Debian Codegraph @

tools/wraptypes/yacc.py

raw symbols SCIP
1 from __future__ import print_function
2 #-----------------------------------------------------------------------------
3 # ply: yacc.py
4 #
5 # Author(s): David M. Beazley ([email protected])
6 # Modifications for pyglet by Alex Holkner ([email protected]) (<ah>)
7 #
8 # Copyright (C) 2001-2006, David M. Beazley
9 #
10 # This library is free software; you can redistribute it and/or
11 # modify it under the terms of the GNU Lesser General Public
12 # License as published by the Free Software Foundation; either
13 # version 2.1 of the License, or (at your option) any later version.
14 #
15 # This library is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 # Lesser General Public License for more details.
19 #
20 # You should have received a copy of the GNU Lesser General Public
21 # License along with this library; if not, write to the Free Software
22 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 #
24 # See the file COPYING for a complete copy of the LGPL.
25 #
26 #
27 # This implements an LR parser that is constructed from grammar rules defined
28 # as Python functions. The grammer is specified by supplying the BNF inside
29 # Python documentation strings. The inspiration for this technique was borrowed
30 # from John Aycock's Spark parsing system. PLY might be viewed as cross between
31 # Spark and the GNU bison utility.
32 #
33 # The current implementation is only somewhat object-oriented. The
34 # LR parser itself is defined in terms of an object (which allows multiple
35 # parsers to co-exist). However, most of the variables used during table
36 # construction are defined in terms of global variables. Users shouldn't
37 # notice unless they are trying to define multiple parsers at the same
38 # time using threads (in which case they should have their head examined).
39 #
40 # This implementation supports both SLR and LALR(1) parsing. LALR(1)
41 # support was originally implemented by Elias Ioup ([email protected]),
42 # using the algorithm found in Aho, Sethi, and Ullman "Compilers: Principles,
43 # Techniques, and Tools" (The Dragon Book). LALR(1) has since been replaced
44 # by the more efficient DeRemer and Pennello algorithm.
45 #
46 # :::::::: WARNING :::::::
47 #
48 # Construction of LR parsing tables is fairly complicated and expensive.
49 # To make this module run fast, a *LOT* of work has been put into
50 # optimization---often at the expensive of readability and what might
51 # consider to be good Python "coding style." Modify the code at your
52 # own risk!
53 # ----------------------------------------------------------------------------
54
55 __version__ = "2.2"
56
57 #-----------------------------------------------------------------------------
58 # === User configurable parameters ===
59 #
60 # Change these to modify the default behavior of yacc (if you wish)
61 #-----------------------------------------------------------------------------
62
63 yaccdebug = 1 # Debugging mode. If set, yacc generates a
64 # a 'parser.out' file in the current directory
65
66 debug_file = 'parser.out' # Default name of the debugging file
67 tab_module = 'parsetab' # Default name of the table module
68 default_lr = 'LALR' # Default LR table generation method
69
70 error_count = 3 # Number of symbols that must be shifted to leave recovery mode
71
72 import re, types, sys, cStringIO, md5, os.path
73
74 # Exception raised for yacc-related errors
75 class YaccError(Exception): pass
76
77 #-----------------------------------------------------------------------------
78 # === LR Parsing Engine ===
79 #
80 # The following classes are used for the LR parser itself. These are not
81 # used during table construction and are independent of the actual LR
82 # table generation algorithm
83 #-----------------------------------------------------------------------------
84
85 # This class is used to hold non-terminal grammar symbols during parsing.
86 # It normally has the following attributes set:
87 # .type = Grammar symbol type
88 # .value = Symbol value
89 # .lineno = Starting line number
90 # .endlineno = Ending line number (optional, set automatically)
91 # .lexpos = Starting lex position
92 # .endlexpos = Ending lex position (optional, set automatically)
93
94 class YaccSymbol:
95 filename = '' # <ah>
96 def __str__(self): return self.type
97 def __repr__(self): return str(self)
98
99 # This class is a wrapper around the objects actually passed to each
100 # grammar rule. Index lookup and assignment actually assign the
101 # .value attribute of the underlying YaccSymbol object.
102 # The lineno() method returns the line number of a given
103 # item (or 0 if not defined). The linespan() method returns
104 # a tuple of (startline,endline) representing the range of lines
105 # for a symbol. The lexspan() method returns a tuple (lexpos,endlexpos)
106 # representing the range of positional information for a symbol.
107
108 class YaccProduction:
109 def __init__(self,s,stack=None):
110 self.slice = s
111 self.pbstack = []
112 self.stack = stack
113
114 def __getitem__(self,n):
115 if type(n) == types.IntType:
116 if n >= 0: return self.slice[n].value
117 else: return self.stack[n].value
118 else:
119 return [s.value for s in self.slice[n.start:n.stop:n.step]]
120
121 def __setitem__(self,n,v):
122 self.slice[n].value = v
123
124 def __len__(self):
125 return len(self.slice)
126
127 def lineno(self,n):
128 return getattr(self.slice[n],"lineno",0)
129
130 def linespan(self,n):
131 startline = getattr(self.slice[n],"lineno",0)
132 endline = getattr(self.slice[n],"endlineno",startline)
133 return startline,endline
134
135 def lexpos(self,n):
136 return getattr(self.slice[n],"lexpos",0)
137
138 def lexspan(self,n):
139 startpos = getattr(self.slice[n],"lexpos",0)
140 endpos = getattr(self.slice[n],"endlexpos",startpos)
141 return startpos,endpos
142
143 def pushback(self,n):
144 if n <= 0:
145 raise ValueError("Expected a positive value")
146 if n > (len(self.slice)-1):
147 raise ValueError("Can't push %d tokens. Only %d are available." % (n,len(self.slice)-1))
148 for i in range(0,n):
149 self.pbstack.append(self.slice[-i-1])
150
151 # The LR Parsing engine. This is defined as a class so that multiple parsers
152 # can exist in the same process. A user never instantiates this directly.
153 # Instead, the global yacc() function should be used to create a suitable Parser
154 # object.
155
156 class Parser:
157 # <ah> Remove magic (use ParserPrototype)
158 def __init__(self):
159 # Reset internal state
160 self.productions = None # List of productions
161 self.errorfunc = None # Error handling function
162 self.action = { } # LR Action table
163 self.goto = { } # LR goto table
164 self.require = { } # Attribute require table
165 self.method = "Unknown LR" # Table construction method used
166
167 # <ah> 25 Jan 2007
168 self.statestackstack = []
169 self.symstackstack = []
170
171 def errok(self):
172 self.errorcount = 0
173
174 def restart(self):
175 del self.statestack[:]
176 del self.symstack[:]
177 sym = YaccSymbol()
178 sym.type = '$end'
179 self.symstack.append(sym)
180 self.statestack.append(0)
181
182 def push_state(self):
183 '''Save parser state and restart it.'''
184 # <ah> 25 Jan 2007
185 self.statestackstack.append(self.statestack[:])
186 self.symstackstack.append(self.symstack[:])
187 self.restart()
188
189 def pop_state(self):
190 '''Restore saved parser state.'''
191 # <ah> 25 Jan 2007
192 self.statestack[:] = self.statestackstack.pop()
193 self.symstack[:] = self.symstackstack.pop()
194
195 def parse(self,input=None,lexer=None,debug=0):
196 lookahead = None # Current lookahead symbol
197 lookaheadstack = [ ] # Stack of lookahead symbols
198 actions = self.action # Local reference to action table
199 goto = self.goto # Local reference to goto table
200 prod = self.productions # Local reference to production list
201 pslice = YaccProduction(None) # Production object passed to grammar rules
202 pslice.parser = self # Parser object
203 self.errorcount = 0 # Used during error recovery
204
205 # If no lexer was given, we will try to use the lex module
206 if not lexer:
207 import lex
208 lexer = lex.lexer
209
210 pslice.lexer = lexer
211
212 # If input was supplied, pass to lexer
213 if input:
214 lexer.input(input)
215
216 # Tokenize function
217 get_token = lexer.token
218
219 statestack = [ ] # Stack of parsing states
220 self.statestack = statestack
221 symstack = [ ] # Stack of grammar symbols
222 self.symstack = symstack
223
224 pslice.stack = symstack # Put in the production
225 errtoken = None # Err token
226
227 # The start state is assumed to be (0,$end)
228 statestack.append(0)
229 sym = YaccSymbol()
230 sym.type = '$end'
231 symstack.append(sym)
232
233 while 1:
234 # Get the next symbol on the input. If a lookahead symbol
235 # is already set, we just use that. Otherwise, we'll pull
236 # the next token off of the lookaheadstack or from the lexer
237 if debug > 1:
238 print('state', statestack[-1])
239 if not lookahead:
240 if not lookaheadstack:
241 lookahead = get_token() # Get the next token
242 else:
243 lookahead = lookaheadstack.pop()
244 if not lookahead:
245 lookahead = YaccSymbol()
246 lookahead.type = '$end'
247 if debug:
248 errorlead = ("%s . %s" % (" ".join([xx.type for xx in symstack][1:]), str(lookahead))).lstrip()
249
250 # Check the action table
251 s = statestack[-1]
252 ltype = lookahead.type
253 t = actions.get((s,ltype),None)
254
255 if debug > 1:
256 print('action', t)
257 if t is not None:
258 if t > 0:
259 # shift a symbol on the stack
260 if ltype == '$end':
261 # Error, end of input
262 sys.stderr.write("yacc: Parse error. EOF\n")
263 return
264 statestack.append(t)
265 if debug > 1:
266 sys.stderr.write("%-60s shift state %s\n" % (errorlead, t))
267 symstack.append(lookahead)
268 lookahead = None
269
270 # Decrease error count on successful shift
271 if self.errorcount > 0:
272 self.errorcount -= 1
273
274 continue
275
276 if t < 0:
277 # reduce a symbol on the stack, emit a production
278 p = prod[-t]
279 pname = p.name
280 plen = p.len
281
282 # Get production function
283 sym = YaccSymbol()
284 sym.type = pname # Production name
285 sym.value = None
286 if debug > 1:
287 sys.stderr.write("%-60s reduce %d\n" % (errorlead, -t))
288
289 if plen:
290 targ = symstack[-plen-1:]
291 targ[0] = sym
292 try:
293 sym.lineno = targ[1].lineno
294 sym.filename = targ[1].filename
295 sym.endlineno = getattr(targ[-1],"endlineno",targ[-1].lineno)
296 sym.lexpos = targ[1].lexpos
297 sym.endlexpos = getattr(targ[-1],"endlexpos",targ[-1].lexpos)
298 except AttributeError:
299 sym.lineno = 0
300 del symstack[-plen:]
301 del statestack[-plen:]
302 else:
303 sym.lineno = 0
304 targ = [ sym ]
305 pslice.slice = targ
306 pslice.pbstack = []
307 # Call the grammar rule with our special slice object
308 p.func(pslice)
309
310 # If there was a pushback, put that on the stack
311 if pslice.pbstack:
312 lookaheadstack.append(lookahead)
313 for _t in pslice.pbstack:
314 lookaheadstack.append(_t)
315 lookahead = None
316
317 symstack.append(sym)
318 statestack.append(goto[statestack[-1],pname])
319 continue
320
321 if t == 0:
322 n = symstack[-1]
323 return getattr(n,"value",None)
324 sys.stderr.write(errorlead, "\n")
325
326 if t == None:
327 if debug:
328 sys.stderr.write(errorlead + "\n")
329 # We have some kind of parsing error here. To handle
330 # this, we are going to push the current token onto
331 # the tokenstack and replace it with an 'error' token.
332 # If there are any synchronization rules, they may
333 # catch it.
334 #
335 # In addition to pushing the error token, we call call
336 # the user defined p_error() function if this is the
337 # first syntax error. This function is only called if
338 # errorcount == 0.
339 if not self.errorcount:
340 self.errorcount = error_count
341 errtoken = lookahead
342 if errtoken.type == '$end':
343 errtoken = None # End of file!
344 if self.errorfunc:
345 global errok,token,restart
346 errok = self.errok # Set some special functions available in error recovery
347 token = get_token
348 restart = self.restart
349 tok = self.errorfunc(errtoken)
350 del errok, token, restart # Delete special functions
351
352 if not self.errorcount:
353 # User must have done some kind of panic
354 # mode recovery on their own. The
355 # returned token is the next lookahead
356 lookahead = tok
357 errtoken = None
358 continue
359 else:
360 if errtoken:
361 if hasattr(errtoken,"lineno"): lineno = lookahead.lineno
362 else: lineno = 0
363 if lineno:
364 sys.stderr.write("yacc: Syntax error at line %d, token=%s\n" % (lineno, errtoken.type))
365 else:
366 sys.stderr.write("yacc: Syntax error, token=%s" % errtoken.type)
367 else:
368 sys.stderr.write("yacc: Parse error in input. EOF\n")
369 return
370
371 else:
372 self.errorcount = error_count
373
374 # case 1: the statestack only has 1 entry on it. If we're in this state, the
375 # entire parse has been rolled back and we're completely hosed. The token is
376 # discarded and we just keep going.
377
378 if len(statestack) <= 1 and lookahead.type != '$end':
379 lookahead = None
380 errtoken = None
381 # Nuke the pushback stack
382 del lookaheadstack[:]
383 continue
384
385 # case 2: the statestack has a couple of entries on it, but we're
386 # at the end of the file. nuke the top entry and generate an error token
387
388 # Start nuking entries on the stack
389 if lookahead.type == '$end':
390 # Whoa. We're really hosed here. Bail out
391 return
392
393 if lookahead.type != 'error':
394 sym = symstack[-1]
395 if sym.type == 'error':
396 # Hmmm. Error is on top of stack, we'll just nuke input
397 # symbol and continue
398 lookahead = None
399 continue
400 t = YaccSymbol()
401 t.type = 'error'
402 if hasattr(lookahead,"lineno"):
403 t.lineno = lookahead.lineno
404 t.value = lookahead
405 lookaheadstack.append(lookahead)
406 lookahead = t
407 else:
408 symstack.pop()
409 statestack.pop()
410
411 continue
412
413 # Call an error function here
414 raise RuntimeError("yacc: internal parser error!!!\n")
415
416 # -----------------------------------------------------------------------------
417 # === Parser Construction ===
418 #
419 # The following functions and variables are used to implement the yacc() function
420 # itself. This is pretty hairy stuff involving lots of error checking,
421 # construction of LR items, kernels, and so forth. Although a lot of
422 # this work is done using global variables, the resulting Parser object
423 # is completely self contained--meaning that it is safe to repeatedly
424 # call yacc() with different grammars in the same application.
425 # -----------------------------------------------------------------------------
426
427 # -----------------------------------------------------------------------------
428 # validate_file()
429 #
430 # This function checks to see if there are duplicated p_rulename() functions
431 # in the parser module file. Without this function, it is really easy for
432 # users to make mistakes by cutting and pasting code fragments (and it's a real
433 # bugger to try and figure out why the resulting parser doesn't work). Therefore,
434 # we just do a little regular expression pattern matching of def statements
435 # to try and detect duplicates.
436 # -----------------------------------------------------------------------------
437
438 def validate_file(filename):
439 base,ext = os.path.splitext(filename)
440 if ext != '.py': return 1 # No idea. Assume it's okay.
441
442 try:
443 f = open(filename)
444 lines = f.readlines()
445 f.close()
446 except IOError:
447 return 1 # Oh well
448
449 # Match def p_funcname(
450 fre = re.compile(r'\s*def\s+(p_[a-zA-Z_0-9]*)\(')
451 counthash = { }
452 linen = 1
453 noerror = 1
454 for l in lines:
455 m = fre.match(l)
456 if m:
457 name = m.group(1)
458 prev = counthash.get(name)
459 if not prev:
460 counthash[name] = linen
461 else:
462 sys.stderr.write("%s:%d: Function %s redefined. Previously defined on line %d\n" % (filename,linen,name,prev))
463 noerror = 0
464 linen += 1
465 return noerror
466
467 # This function looks for functions that might be grammar rules, but which don't have the proper p_suffix.
468 def validate_dict(d):
469 for n,v in d.items():
470 if n[0:2] == 'p_' and type(v) in (types.FunctionType, types.MethodType): continue
471 if n[0:2] == 't_': continue
472
473 if n[0:2] == 'p_':
474 sys.stderr.write("yacc: Warning. '%s' not defined as a function\n" % n)
475 if 1 and isinstance(v,types.FunctionType) and v.func_code.co_argcount == 1:
476 try:
477 doc = v.__doc__.split(" ")
478 if doc[1] == ':':
479 sys.stderr.write("%s:%d: Warning. Possible grammar rule '%s' defined without p_ prefix.\n" % (v.func_code.co_filename, v.func_code.co_firstlineno,n))
480 except Exception:
481 pass
482
483 # -----------------------------------------------------------------------------
484 # === GRAMMAR FUNCTIONS ===
485 #
486 # The following global variables and functions are used to store, manipulate,
487 # and verify the grammar rules specified by the user.
488 # -----------------------------------------------------------------------------
489
490 # Initialize all of the global variables used during grammar construction
491 def initialize_vars():
492 global Productions, Prodnames, Prodmap, Terminals
493 global Nonterminals, First, Follow, Precedence, LRitems
494 global Errorfunc, Signature, Requires
495
496 Productions = [None] # A list of all of the productions. The first
497 # entry is always reserved for the purpose of
498 # building an augmented grammar
499
500 Prodnames = { } # A dictionary mapping the names of nonterminals to a list of all
501 # productions of that nonterminal.
502
503 Prodmap = { } # A dictionary that is only used to detect duplicate
504 # productions.
505
506 Terminals = { } # A dictionary mapping the names of terminal symbols to a
507 # list of the rules where they are used.
508
509 Nonterminals = { } # A dictionary mapping names of nonterminals to a list
510 # of rule numbers where they are used.
511
512 First = { } # A dictionary of precomputed FIRST(x) symbols
513
514 Follow = { } # A dictionary of precomputed FOLLOW(x) symbols
515
516 Precedence = { } # Precedence rules for each terminal. Contains tuples of the
517 # form ('right',level) or ('nonassoc', level) or ('left',level)
518
519 LRitems = [ ] # A list of all LR items for the grammar. These are the
520 # productions with the "dot" like E -> E . PLUS E
521
522 Errorfunc = None # User defined error handler
523
524 Signature = md5.new() # Digital signature of the grammar rules, precedence
525 # and other information. Used to determined when a
526 # parsing table needs to be regenerated.
527
528 Requires = { } # Requires list
529
530 # File objects used when creating the parser.out debugging file
531 global _vf, _vfc
532 _vf = cStringIO.StringIO()
533 _vfc = cStringIO.StringIO()
534
535 # -----------------------------------------------------------------------------
536 # class Production:
537 #
538 # This class stores the raw information about a single production or grammar rule.
539 # It has a few required attributes:
540 #
541 # name - Name of the production (nonterminal)
542 # prod - A list of symbols making up its production
543 # number - Production number.
544 #
545 # In addition, a few additional attributes are used to help with debugging or
546 # optimization of table generation.
547 #
548 # file - File where production action is defined.
549 # lineno - Line number where action is defined
550 # func - Action function
551 # prec - Precedence level
552 # lr_next - Next LR item. Example, if we are ' E -> E . PLUS E'
553 # then lr_next refers to 'E -> E PLUS . E'
554 # lr_index - LR item index (location of the ".") in the prod list.
555 # lookaheads - LALR lookahead symbols for this item
556 # len - Length of the production (number of symbols on right hand side)
557 # -----------------------------------------------------------------------------
558
559 class Production:
560 def __init__(self,**kw):
561 for k,v in kw.items():
562 setattr(self,k,v)
563 self.lr_index = -1
564 self.lr0_added = 0 # Flag indicating whether or not added to LR0 closure
565 self.lr1_added = 0 # Flag indicating whether or not added to LR1
566 self.usyms = [ ]
567 self.lookaheads = { }
568 self.lk_added = { }
569 self.setnumbers = [ ]
570
571 def __str__(self):
572 if self.prod:
573 s = "%s -> %s" % (self.name," ".join(self.prod))
574 else:
575 s = "%s -> <empty>" % self.name
576 return s
577
578 def __repr__(self):
579 return str(self)
580
581 # Compute lr_items from the production
582 def lr_item(self,n):
583 if n > len(self.prod): return None
584 p = Production()
585 p.name = self.name
586 p.prod = list(self.prod)
587 p.number = self.number
588 p.lr_index = n
589 p.lookaheads = { }
590 p.setnumbers = self.setnumbers
591 p.prod.insert(n,".")
592 p.prod = tuple(p.prod)
593 p.len = len(p.prod)
594 p.usyms = self.usyms
595
596 # Precompute list of productions immediately following
597 try:
598 p.lrafter = Prodnames[p.prod[n+1]]
599 except (IndexError,KeyError) as e:
600 p.lrafter = []
601 try:
602 p.lrbefore = p.prod[n-1]
603 except IndexError:
604 p.lrbefore = None
605
606 return p
607
608 class MiniProduction:
609 pass
610
611 # regex matching identifiers
612 _is_identifier = re.compile(r'^[a-zA-Z0-9_-]+$')
613
614 # -----------------------------------------------------------------------------
615 # add_production()
616 #
617 # Given an action function, this function assembles a production rule.
618 # The production rule is assumed to be found in the function's docstring.
619 # This rule has the general syntax:
620 #
621 # name1 ::= production1
622 # | production2
623 # | production3
624 # ...
625 # | productionn
626 # name2 ::= production1
627 # | production2
628 # ...
629 # -----------------------------------------------------------------------------
630
631 def add_production(f,file,line,prodname,syms):
632
633 if Terminals.has_key(prodname):
634 sys.stderr.write("%s:%d: Illegal rule name '%s'. Already defined as a token.\n" % (file,line,prodname))
635 return -1
636 if prodname == 'error':
637 sys.stderr.write("%s:%d: Illegal rule name '%s'. error is a reserved word.\n" % (file,line,prodname))
638 return -1
639
640 if not _is_identifier.match(prodname):
641 sys.stderr.write("%s:%d: Illegal rule name '%s'\n" % (file,line,prodname))
642 return -1
643
644 for x in range(len(syms)):
645 s = syms[x]
646 if s[0] in "'\"":
647 try:
648 c = eval(s)
649 if (len(c) > 1):
650 sys.stderr.write("%s:%d: Literal token %s in rule '%s' may only be a single character\n" % (file,line,s, prodname))
651 return -1
652 if not Terminals.has_key(c):
653 Terminals[c] = []
654 syms[x] = c
655 continue
656 except SyntaxError:
657 pass
658 if not _is_identifier.match(s) and s != '%prec':
659 sys.stderr.write("%s:%d: Illegal name '%s' in rule '%s'\n" % (file,line,s, prodname))
660 return -1
661
662 # See if the rule is already in the rulemap
663 map = "%s -> %s" % (prodname,syms)
664 if Prodmap.has_key(map):
665 m = Prodmap[map]
666 sys.stderr.write("%s:%d: Duplicate rule %s.\n" % (file,line, m))
667 sys.stderr.write("%s:%d: Previous definition at %s:%d\n" % (file,line, m.file, m.line))
668 return -1
669
670 p = Production()
671 p.name = prodname
672 p.prod = syms
673 p.file = file
674 p.line = line
675 p.func = f
676 p.number = len(Productions)
677
678
679 Productions.append(p)
680 Prodmap[map] = p
681 if not Nonterminals.has_key(prodname):
682 Nonterminals[prodname] = [ ]
683
684 # Add all terminals to Terminals
685 i = 0
686 while i < len(p.prod):
687 t = p.prod[i]
688 if t == '%prec':
689 try:
690 precname = p.prod[i+1]
691 except IndexError:
692 sys.stderr.write("%s:%d: Syntax error. Nothing follows %%prec.\n" % (p.file,p.line))
693 return -1
694
695 prec = Precedence.get(precname,None)
696 if not prec:
697 sys.stderr.write("%s:%d: Nothing known about the precedence of '%s'\n" % (p.file,p.line,precname))
698 return -1
699 else:
700 p.prec = prec
701 del p.prod[i]
702 del p.prod[i]
703 continue
704
705 if Terminals.has_key(t):
706 Terminals[t].append(p.number)
707 # Is a terminal. We'll assign a precedence to p based on this
708 if not hasattr(p,"prec"):
709 p.prec = Precedence.get(t,('right',0))
710 else:
711 if not Nonterminals.has_key(t):
712 Nonterminals[t] = [ ]
713 Nonterminals[t].append(p.number)
714 i += 1
715
716 if not hasattr(p,"prec"):
717 p.prec = ('right',0)
718
719 # Set final length of productions
720 p.len = len(p.prod)
721 p.prod = tuple(p.prod)
722
723 # Calculate unique syms in the production
724 p.usyms = [ ]
725 for s in p.prod:
726 if s not in p.usyms:
727 p.usyms.append(s)
728
729 # Add to the global productions list
730 try:
731 Prodnames[p.name].append(p)
732 except KeyError:
733 Prodnames[p.name] = [ p ]
734 return 0
735
736 # Given a raw rule function, this function rips out its doc string
737 # and adds rules to the grammar
738
739 def add_function(f):
740 line = f.func_code.co_firstlineno
741 file = f.func_code.co_filename
742 error = 0
743
744 if isinstance(f,types.MethodType):
745 reqdargs = 2
746 else:
747 reqdargs = 1
748
749 if f.func_code.co_argcount > reqdargs:
750 sys.stderr.write("%s:%d: Rule '%s' has too many arguments.\n" % (file,line,f.__name__))
751 return -1
752
753 if f.func_code.co_argcount < reqdargs:
754 sys.stderr.write("%s:%d: Rule '%s' requires an argument.\n" % (file,line,f.__name__))
755 return -1
756
757 if f.__doc__:
758 # Split the doc string into lines
759 pstrings = f.__doc__.splitlines()
760 lastp = None
761 dline = line
762 for ps in pstrings:
763 dline += 1
764 p = ps.split()
765 if not p: continue
766 try:
767 if p[0] == '|':
768 # This is a continuation of a previous rule
769 if not lastp:
770 sys.stderr.write("%s:%d: Misplaced '|'.\n" % (file,dline))
771 return -1
772 prodname = lastp
773 if len(p) > 1:
774 syms = p[1:]
775 else:
776 syms = [ ]
777 else:
778 prodname = p[0]
779 lastp = prodname
780 assign = p[1]
781 if len(p) > 2:
782 syms = p[2:]
783 else:
784 syms = [ ]
785 if assign != ':' and assign != '::=':
786 sys.stderr.write("%s:%d: Syntax error. Expected ':'\n" % (file,dline))
787 return -1
788
789
790 e = add_production(f,file,dline,prodname,syms)
791 error += e
792
793
794 except Exception:
795 sys.stderr.write("%s:%d: Syntax error in rule '%s'\n" % (file,dline,ps))
796 error -= 1
797 else:
798 sys.stderr.write("%s:%d: No documentation string specified in function '%s'\n" % (file,line,f.__name__))
799 return error
800
801
802 # Cycle checking code (Michael Dyck)
803
804 def compute_reachable():
805 '''
806 Find each symbol that can be reached from the start symbol.
807 Print a warning for any nonterminals that can't be reached.
808 (Unused terminals have already had their warning.)
809 '''
810 Reachable = { }
811 for s in Terminals.keys() + Nonterminals.keys():
812 Reachable[s] = 0
813
814 mark_reachable_from( Productions[0].prod[0], Reachable )
815
816 for s in Nonterminals.keys():
817 if not Reachable[s]:
818 sys.stderr.write("yacc: Symbol '%s' is unreachable.\n" % s)
819
820 def mark_reachable_from(s, Reachable):
821 '''
822 Mark all symbols that are reachable from symbol s.
823 '''
824 if Reachable[s]:
825 # We've already reached symbol s.
826 return
827 Reachable[s] = 1
828 for p in Prodnames.get(s,[]):
829 for r in p.prod:
830 mark_reachable_from(r, Reachable)
831
832 # -----------------------------------------------------------------------------
833 # compute_terminates()
834 #
835 # This function looks at the various parsing rules and tries to detect
836 # infinite recursion cycles (grammar rules where there is no possible way
837 # to derive a string of only terminals).
838 # -----------------------------------------------------------------------------
839 def compute_terminates():
840 '''
841 Raise an error for any symbols that don't terminate.
842 '''
843 Terminates = {}
844
845 # Terminals:
846 for t in Terminals.keys():
847 Terminates[t] = 1
848
849 Terminates['$end'] = 1
850
851 # Nonterminals:
852
853 # Initialize to false:
854 for n in Nonterminals.keys():
855 Terminates[n] = 0
856
857 # Then propagate termination until no change:
858 while 1:
859 some_change = 0
860 for (n,pl) in Prodnames.items():
861 # Nonterminal n terminates iff any of its productions terminates.
862 for p in pl:
863 # Production p terminates iff all of its rhs symbols terminate.
864 for s in p.prod:
865 if not Terminates[s]:
866 # The symbol s does not terminate,
867 # so production p does not terminate.
868 p_terminates = 0
869 break
870 else:
871 # didn't break from the loop,
872 # so every symbol s terminates
873 # so production p terminates.
874 p_terminates = 1
875
876 if p_terminates:
877 # symbol n terminates!
878 if not Terminates[n]:
879 Terminates[n] = 1
880 some_change = 1
881 # Don't need to consider any more productions for this n.
882 break
883
884 if not some_change:
885 break
886
887 some_error = 0
888 for (s,terminates) in Terminates.items():
889 if not terminates:
890 if not Prodnames.has_key(s) and not Terminals.has_key(s) and s != 'error':
891 # s is used-but-not-defined, and we've already warned of that,
892 # so it would be overkill to say that it's also non-terminating.
893 pass
894 else:
895 sys.stderr.write("yacc: Infinite recursion detected for symbol '%s'.\n" % s)
896 some_error = 1
897
898 return some_error
899
900 # -----------------------------------------------------------------------------
901 # verify_productions()
902 #
903 # This function examines all of the supplied rules to see if they seem valid.
904 # -----------------------------------------------------------------------------
905 def verify_productions(cycle_check=1):
906 error = 0
907 for p in Productions:
908 if not p: continue
909
910 for s in p.prod:
911 if not Prodnames.has_key(s) and not Terminals.has_key(s) and s != 'error':
912 sys.stderr.write("%s:%d: Symbol '%s' used, but not defined as a token or a rule.\n" % (p.file,p.line,s))
913 error = 1
914 continue
915
916 unused_tok = 0
917 # Now verify all of the tokens
918 if yaccdebug:
919 _vf.write("Unused terminals:\n\n")
920 for s,v in Terminals.items():
921 if s != 'error' and not v:
922 sys.stderr.write("yacc: Warning. Token '%s' defined, but not used.\n" % s)
923 if yaccdebug: _vf.write(" %s\n"% s)
924 unused_tok += 1
925
926 # Print out all of the productions
927 if yaccdebug:
928 _vf.write("\nGrammar\n\n")
929 for i in range(1,len(Productions)):
930 _vf.write("Rule %-5d %s\n" % (i, Productions[i]))
931
932 unused_prod = 0
933 # Verify the use of all productions
934 for s,v in Nonterminals.items():
935 if not v:
936 p = Prodnames[s][0]
937 sys.stderr.write("%s:%d: Warning. Rule '%s' defined, but not used.\n" % (p.file,p.line, s))
938 unused_prod += 1
939
940
941 if unused_tok == 1:
942 sys.stderr.write("yacc: Warning. There is 1 unused token.\n")
943 if unused_tok > 1:
944 sys.stderr.write("yacc: Warning. There are %d unused tokens.\n" % unused_tok)
945
946 if unused_prod == 1:
947 sys.stderr.write("yacc: Warning. There is 1 unused rule.\n")
948 if unused_prod > 1:
949 sys.stderr.write("yacc: Warning. There are %d unused rules.\n" % unused_prod)
950
951 if yaccdebug:
952 _vf.write("\nTerminals, with rules where they appear\n\n")
953 ks = Terminals.keys()
954 ks.sort()
955 for k in ks:
956 _vf.write("%-20s : %s\n" % (k, " ".join([str(s) for s in Terminals[k]])))
957 _vf.write("\nNonterminals, with rules where they appear\n\n")
958 ks = Nonterminals.keys()
959 ks.sort()
960 for k in ks:
961 _vf.write("%-20s : %s\n" % (k, " ".join([str(s) for s in Nonterminals[k]])))
962
963 if (cycle_check):
964 compute_reachable()
965 error += compute_terminates()
966 # error += check_cycles()
967 return error
968
969 # -----------------------------------------------------------------------------
970 # build_lritems()
971 #
972 # This function walks the list of productions and builds a complete set of the
973 # LR items. The LR items are stored in two ways: First, they are uniquely
974 # numbered and placed in the list _lritems. Second, a linked list of LR items
975 # is built for each production. For example:
976 #
977 # E -> E PLUS E
978 #
979 # Creates the list
980 #
981 # [E -> . E PLUS E, E -> E . PLUS E, E -> E PLUS . E, E -> E PLUS E . ]
982 # -----------------------------------------------------------------------------
983
984 def build_lritems():
985 for p in Productions:
986 lastlri = p
987 lri = p.lr_item(0)
988 i = 0
989 while 1:
990 lri = p.lr_item(i)
991 lastlri.lr_next = lri
992 if not lri: break
993 lri.lr_num = len(LRitems)
994 LRitems.append(lri)
995 lastlri = lri
996 i += 1
997
998 # In order for the rest of the parser generator to work, we need to
999 # guarantee that no more lritems are generated. Therefore, we nuke
1000 # the p.lr_item method. (Only used in debugging)
1001 # Production.lr_item = None
1002
1003 # -----------------------------------------------------------------------------
1004 # add_precedence()
1005 #
1006 # Given a list of precedence rules, add to the precedence table.
1007 # -----------------------------------------------------------------------------
1008
1009 def add_precedence(plist):
1010 plevel = 0
1011 error = 0
1012 for p in plist:
1013 plevel += 1
1014 try:
1015 prec = p[0]
1016 terms = p[1:]
1017 if prec != 'left' and prec != 'right' and prec != 'nonassoc':
1018 sys.stderr.write("yacc: Invalid precedence '%s'\n" % prec)
1019 return -1
1020 for t in terms:
1021 if Precedence.has_key(t):
1022 sys.stderr.write("yacc: Precedence already specified for terminal '%s'\n" % t)
1023 error += 1
1024 continue
1025 Precedence[t] = (prec,plevel)
1026 except:
1027 sys.stderr.write("yacc: Invalid precedence table.\n")
1028 error += 1
1029
1030 return error
1031
1032 # -----------------------------------------------------------------------------
1033 # augment_grammar()
1034 #
1035 # Compute the augmented grammar. This is just a rule S' -> start where start
1036 # is the starting symbol.
1037 # -----------------------------------------------------------------------------
1038
1039 def augment_grammar(start=None):
1040 if not start:
1041 start = Productions[1].name
1042 Productions[0] = Production(name="S'",prod=[start],number=0,len=1,prec=('right',0),func=None)
1043 Productions[0].usyms = [ start ]
1044 Nonterminals[start].append(0)
1045
1046
1047 # -------------------------------------------------------------------------
1048 # first()
1049 #
1050 # Compute the value of FIRST1(beta) where beta is a tuple of symbols.
1051 #
1052 # During execution of compute_first1, the result may be incomplete.
1053 # Afterward (e.g., when called from compute_follow()), it will be complete.
1054 # -------------------------------------------------------------------------
1055 def first(beta):
1056
1057 # We are computing First(x1,x2,x3,...,xn)
1058 result = [ ]
1059 for x in beta:
1060 x_produces_empty = 0
1061
1062 # Add all the non-<empty> symbols of First[x] to the result.
1063 for f in First[x]:
1064 if f == '<empty>':
1065 x_produces_empty = 1
1066 else:
1067 if f not in result: result.append(f)
1068
1069 if x_produces_empty:
1070 # We have to consider the next x in beta,
1071 # i.e. stay in the loop.
1072 pass
1073 else:
1074 # We don't have to consider any further symbols in beta.
1075 break
1076 else:
1077 # There was no 'break' from the loop,
1078 # so x_produces_empty was true for all x in beta,
1079 # so beta produces empty as well.
1080 result.append('<empty>')
1081
1082 return result
1083
1084
1085 # FOLLOW(x)
1086 # Given a non-terminal. This function computes the set of all symbols
1087 # that might follow it. Dragon book, p. 189.
1088
1089 def compute_follow(start=None):
1090 # Add '$end' to the follow list of the start symbol
1091 for k in Nonterminals.keys():
1092 Follow[k] = [ ]
1093
1094 if not start:
1095 start = Productions[1].name
1096
1097 Follow[start] = [ '$end' ]
1098
1099 while 1:
1100 didadd = 0
1101 for p in Productions[1:]:
1102 # Here is the production set
1103 for i in range(len(p.prod)):
1104 B = p.prod[i]
1105 if Nonterminals.has_key(B):
1106 # Okay. We got a non-terminal in a production
1107 fst = first(p.prod[i+1:])
1108 hasempty = 0
1109 for f in fst:
1110 if f != '<empty>' and f not in Follow[B]:
1111 Follow[B].append(f)
1112 didadd = 1
1113 if f == '<empty>':
1114 hasempty = 1
1115 if hasempty or i == (len(p.prod)-1):
1116 # Add elements of follow(a) to follow(b)
1117 for f in Follow[p.name]:
1118 if f not in Follow[B]:
1119 Follow[B].append(f)
1120 didadd = 1
1121 if not didadd: break
1122
1123 if 0 and yaccdebug:
1124 _vf.write('\nFollow:\n')
1125 for k in Nonterminals.keys():
1126 _vf.write("%-20s : %s\n" % (k, " ".join([str(s) for s in Follow[k]])))
1127
1128 # -------------------------------------------------------------------------
1129 # compute_first1()
1130 #
1131 # Compute the value of FIRST1(X) for all symbols
1132 # -------------------------------------------------------------------------
1133 def compute_first1():
1134
1135 # Terminals:
1136 for t in Terminals.keys():
1137 First[t] = [t]
1138
1139 First['$end'] = ['$end']
1140 First['#'] = ['#'] # what's this for?
1141
1142 # Nonterminals:
1143
1144 # Initialize to the empty set:
1145 for n in Nonterminals.keys():
1146 First[n] = []
1147
1148 # Then propagate symbols until no change:
1149 while 1:
1150 some_change = 0
1151 for n in Nonterminals.keys():
1152 for p in Prodnames[n]:
1153 for f in first(p.prod):
1154 if f not in First[n]:
1155 First[n].append( f )
1156 some_change = 1
1157 if not some_change:
1158 break
1159
1160 if 0 and yaccdebug:
1161 _vf.write('\nFirst:\n')
1162 for k in Nonterminals.keys():
1163 _vf.write("%-20s : %s\n" %
1164 (k, " ".join([str(s) for s in First[k]])))
1165
1166 # -----------------------------------------------------------------------------
1167 # === SLR Generation ===
1168 #
1169 # The following functions are used to construct SLR (Simple LR) parsing tables
1170 # as described on p.221-229 of the dragon book.
1171 # -----------------------------------------------------------------------------
1172
1173 # Global variables for the LR parsing engine
1174 def lr_init_vars():
1175 global _lr_action, _lr_goto, _lr_method
1176 global _lr_goto_cache, _lr0_cidhash
1177
1178 _lr_action = { } # Action table
1179 _lr_goto = { } # Goto table
1180 _lr_method = "Unknown" # LR method used
1181 _lr_goto_cache = { }
1182 _lr0_cidhash = { }
1183
1184
1185 # Compute the LR(0) closure operation on I, where I is a set of LR(0) items.
1186 # prodlist is a list of productions.
1187
1188 _add_count = 0 # Counter used to detect cycles
1189
1190 def lr0_closure(I):
1191 global _add_count
1192
1193 _add_count += 1
1194 prodlist = Productions
1195
1196 # Add everything in I to J
1197 J = I[:]
1198 didadd = 1
1199 while didadd:
1200 didadd = 0
1201 for j in J:
1202 for x in j.lrafter:
1203 if x.lr0_added == _add_count: continue
1204 # Add B --> .G to J
1205 J.append(x.lr_next)
1206 x.lr0_added = _add_count
1207 didadd = 1
1208
1209 return J
1210
1211 # Compute the LR(0) goto function goto(I,X) where I is a set
1212 # of LR(0) items and X is a grammar symbol. This function is written
1213 # in a way that guarantees uniqueness of the generated goto sets
1214 # (i.e. the same goto set will never be returned as two different Python
1215 # objects). With uniqueness, we can later do fast set comparisons using
1216 # id(obj) instead of element-wise comparison.
1217
1218 def lr0_goto(I,x):
1219 # First we look for a previously cached entry
1220 g = _lr_goto_cache.get((id(I),x),None)
1221 if g: return g
1222
1223 # Now we generate the goto set in a way that guarantees uniqueness
1224 # of the result
1225
1226 s = _lr_goto_cache.get(x,None)
1227 if not s:
1228 s = { }
1229 _lr_goto_cache[x] = s
1230
1231 gs = [ ]
1232 for p in I:
1233 n = p.lr_next
1234 if n and n.lrbefore == x:
1235 s1 = s.get(id(n),None)
1236 if not s1:
1237 s1 = { }
1238 s[id(n)] = s1
1239 gs.append(n)
1240 s = s1
1241 g = s.get('$end',None)
1242 if not g:
1243 if gs:
1244 g = lr0_closure(gs)
1245 s['$end'] = g
1246 else:
1247 s['$end'] = gs
1248 _lr_goto_cache[(id(I),x)] = g
1249 return g
1250
1251 _lr0_cidhash = { }
1252
1253 # Compute the LR(0) sets of item function
1254 def lr0_items():
1255
1256 C = [ lr0_closure([Productions[0].lr_next]) ]
1257 i = 0
1258 for I in C:
1259 _lr0_cidhash[id(I)] = i
1260 i += 1
1261
1262 # Loop over the items in C and each grammar symbols
1263 i = 0
1264 while i < len(C):
1265 I = C[i]
1266 i += 1
1267
1268 # Collect all of the symbols that could possibly be in the goto(I,X) sets
1269 asyms = { }
1270 for ii in I:
1271 for s in ii.usyms:
1272 asyms[s] = None
1273
1274 for x in asyms.keys():
1275 g = lr0_goto(I,x)
1276 if not g: continue
1277 if _lr0_cidhash.has_key(id(g)): continue
1278 _lr0_cidhash[id(g)] = len(C)
1279 C.append(g)
1280
1281 return C
1282
1283 # -----------------------------------------------------------------------------
1284 # ==== LALR(1) Parsing ====
1285 #
1286 # LALR(1) parsing is almost exactly the same as SLR except that instead of
1287 # relying upon Follow() sets when performing reductions, a more selective
1288 # lookahead set that incorporates the state of the LR(0) machine is utilized.
1289 # Thus, we mainly just have to focus on calculating the lookahead sets.
1290 #
1291 # The method used here is due to DeRemer and Pennelo (1982).
1292 #
1293 # DeRemer, F. L., and T. J. Pennelo: "Efficient Computation of LALR(1)
1294 # Lookahead Sets", ACM Transactions on Programming Languages and Systems,
1295 # Vol. 4, No. 4, Oct. 1982, pp. 615-649
1296 #
1297 # Further details can also be found in:
1298 #
1299 # J. Tremblay and P. Sorenson, "The Theory and Practice of Compiler Writing",
1300 # McGraw-Hill Book Company, (1985).
1301 #
1302 # Note: This implementation is a complete replacement of the LALR(1)
1303 # implementation in PLY-1.x releases. That version was based on
1304 # a less efficient algorithm and it had bugs in its implementation.
1305 # -----------------------------------------------------------------------------
1306
1307 # -----------------------------------------------------------------------------
1308 # compute_nullable_nonterminals()
1309 #
1310 # Creates a dictionary containing all of the non-terminals that might produce
1311 # an empty production.
1312 # -----------------------------------------------------------------------------
1313
1314 def compute_nullable_nonterminals():
1315 nullable = {}
1316 num_nullable = 0
1317 while 1:
1318 for p in Productions[1:]:
1319 if p.len == 0:
1320 nullable[p.name] = 1
1321 continue
1322 for t in p.prod:
1323 if not nullable.has_key(t): break
1324 else:
1325 nullable[p.name] = 1
1326 if len(nullable) == num_nullable: break
1327 num_nullable = len(nullable)
1328 return nullable
1329
1330 # -----------------------------------------------------------------------------
1331 # find_nonterminal_trans(C)
1332 #
1333 # Given a set of LR(0) items, this functions finds all of the non-terminal
1334 # transitions. These are transitions in which a dot appears immediately before
1335 # a non-terminal. Returns a list of tuples of the form (state,N) where state
1336 # is the state number and N is the nonterminal symbol.
1337 #
1338 # The input C is the set of LR(0) items.
1339 # -----------------------------------------------------------------------------
1340
1341 def find_nonterminal_transitions(C):
1342 trans = []
1343 for state in range(len(C)):
1344 for p in C[state]:
1345 if p.lr_index < p.len - 1:
1346 t = (state,p.prod[p.lr_index+1])
1347 if Nonterminals.has_key(t[1]):
1348 if t not in trans: trans.append(t)
1349 state = state + 1
1350 return trans
1351
1352 # -----------------------------------------------------------------------------
1353 # dr_relation()
1354 #
1355 # Computes the DR(p,A) relationships for non-terminal transitions. The input
1356 # is a tuple (state,N) where state is a number and N is a nonterminal symbol.
1357 #
1358 # Returns a list of terminals.
1359 # -----------------------------------------------------------------------------
1360
1361 def dr_relation(C,trans,nullable):
1362 dr_set = { }
1363 state,N = trans
1364 terms = []
1365
1366 g = lr0_goto(C[state],N)
1367 for p in g:
1368 if p.lr_index < p.len - 1:
1369 a = p.prod[p.lr_index+1]
1370 if Terminals.has_key(a):
1371 if a not in terms: terms.append(a)
1372
1373 # This extra bit is to handle the start state
1374 if state == 0 and N == Productions[0].prod[0]:
1375 terms.append('$end')
1376
1377 return terms
1378
1379 # -----------------------------------------------------------------------------
1380 # reads_relation()
1381 #
1382 # Computes the READS() relation (p,A) READS (t,C).
1383 # -----------------------------------------------------------------------------
1384
1385 def reads_relation(C, trans, empty):
1386 # Look for empty transitions
1387 rel = []
1388 state, N = trans
1389
1390 g = lr0_goto(C[state],N)
1391 j = _lr0_cidhash.get(id(g),-1)
1392 for p in g:
1393 if p.lr_index < p.len - 1:
1394 a = p.prod[p.lr_index + 1]
1395 if empty.has_key(a):
1396 rel.append((j,a))
1397
1398 return rel
1399
1400 # -----------------------------------------------------------------------------
1401 # compute_lookback_includes()
1402 #
1403 # Determines the lookback and includes relations
1404 #
1405 # LOOKBACK:
1406 #
1407 # This relation is determined by running the LR(0) state machine forward.
1408 # For example, starting with a production "N : . A B C", we run it forward
1409 # to obtain "N : A B C ." We then build a relationship between this final
1410 # state and the starting state. These relationships are stored in a dictionary
1411 # lookdict.
1412 #
1413 # INCLUDES:
1414 #
1415 # Computes the INCLUDE() relation (p,A) INCLUDES (p',B).
1416 #
1417 # This relation is used to determine non-terminal transitions that occur
1418 # inside of other non-terminal transition states. (p,A) INCLUDES (p', B)
1419 # if the following holds:
1420 #
1421 # B -> LAT, where T -> epsilon and p' -L-> p
1422 #
1423 # L is essentially a prefix (which may be empty), T is a suffix that must be
1424 # able to derive an empty string. State p' must lead to state p with the string L.
1425 #
1426 # -----------------------------------------------------------------------------
1427
1428 def compute_lookback_includes(C,trans,nullable):
1429
1430 lookdict = {} # Dictionary of lookback relations
1431 includedict = {} # Dictionary of include relations
1432
1433 # Make a dictionary of non-terminal transitions
1434 dtrans = {}
1435 for t in trans:
1436 dtrans[t] = 1
1437
1438 # Loop over all transitions and compute lookbacks and includes
1439 for state,N in trans:
1440 lookb = []
1441 includes = []
1442 for p in C[state]:
1443 if p.name != N: continue
1444
1445 # Okay, we have a name match. We now follow the production all the way
1446 # through the state machine until we get the . on the right hand side
1447
1448 lr_index = p.lr_index
1449 j = state
1450 while lr_index < p.len - 1:
1451 lr_index = lr_index + 1
1452 t = p.prod[lr_index]
1453
1454 # Check to see if this symbol and state are a non-terminal transition
1455 if dtrans.has_key((j,t)):
1456 # Yes. Okay, there is some chance that this is an includes relation
1457 # the only way to know for certain is whether the rest of the
1458 # production derives empty
1459
1460 li = lr_index + 1
1461 while li < p.len:
1462 if Terminals.has_key(p.prod[li]): break # No forget it
1463 if not nullable.has_key(p.prod[li]): break
1464 li = li + 1
1465 else:
1466 # Appears to be a relation between (j,t) and (state,N)
1467 includes.append((j,t))
1468
1469 g = lr0_goto(C[j],t) # Go to next set
1470 j = _lr0_cidhash.get(id(g),-1) # Go to next state
1471
1472 # When we get here, j is the final state, now we have to locate the production
1473 for r in C[j]:
1474 if r.name != p.name: continue
1475 if r.len != p.len: continue
1476 i = 0
1477 # This look is comparing a production ". A B C" with "A B C ."
1478 while i < r.lr_index:
1479 if r.prod[i] != p.prod[i+1]: break
1480 i = i + 1
1481 else:
1482 lookb.append((j,r))
1483 for i in includes:
1484 if not includedict.has_key(i): includedict[i] = []
1485 includedict[i].append((state,N))
1486 lookdict[(state,N)] = lookb
1487
1488 return lookdict,includedict
1489
1490 # -----------------------------------------------------------------------------
1491 # digraph()
1492 # traverse()
1493 #
1494 # The following two functions are used to compute set valued functions
1495 # of the form:
1496 #
1497 # F(x) = F'(x) U U{F(y) | x R y}
1498 #
1499 # This is used to compute the values of Read() sets as well as FOLLOW sets
1500 # in LALR(1) generation.
1501 #
1502 # Inputs: X - An input set
1503 # R - A relation
1504 # FP - Set-valued function
1505 # ------------------------------------------------------------------------------
1506
1507 def digraph(X,R,FP):
1508 N = { }
1509 for x in X:
1510 N[x] = 0
1511 stack = []
1512 F = { }
1513 for x in X:
1514 if N[x] == 0: traverse(x,N,stack,F,X,R,FP)
1515 return F
1516
1517 def traverse(x,N,stack,F,X,R,FP):
1518 stack.append(x)
1519 d = len(stack)
1520 N[x] = d
1521 F[x] = FP(x) # F(X) <- F'(x)
1522
1523 rel = R(x) # Get y's related to x
1524 for y in rel:
1525 if N[y] == 0:
1526 traverse(y,N,stack,F,X,R,FP)
1527 N[x] = min(N[x],N[y])
1528 for a in F.get(y,[]):
1529 if a not in F[x]: F[x].append(a)
1530 if N[x] == d:
1531 N[stack[-1]] = sys.maxint
1532 F[stack[-1]] = F[x]
1533 element = stack.pop()
1534 while element != x:
1535 N[stack[-1]] = sys.maxint
1536 F[stack[-1]] = F[x]
1537 element = stack.pop()
1538
1539 # -----------------------------------------------------------------------------
1540 # compute_read_sets()
1541 #
1542 # Given a set of LR(0) items, this function computes the read sets.
1543 #
1544 # Inputs: C = Set of LR(0) items
1545 # ntrans = Set of nonterminal transitions
1546 # nullable = Set of empty transitions
1547 #
1548 # Returns a set containing the read sets
1549 # -----------------------------------------------------------------------------
1550
1551 def compute_read_sets(C, ntrans, nullable):
1552 FP = lambda x: dr_relation(C,x,nullable)
1553 R = lambda x: reads_relation(C,x,nullable)
1554 F = digraph(ntrans,R,FP)
1555 return F
1556
1557 # -----------------------------------------------------------------------------
1558 # compute_follow_sets()
1559 #
1560 # Given a set of LR(0) items, a set of non-terminal transitions, a readset,
1561 # and an include set, this function computes the follow sets
1562 #
1563 # Follow(p,A) = Read(p,A) U U {Follow(p',B) | (p,A) INCLUDES (p',B)}
1564 #
1565 # Inputs:
1566 # ntrans = Set of nonterminal transitions
1567 # readsets = Readset (previously computed)
1568 # inclsets = Include sets (previously computed)
1569 #
1570 # Returns a set containing the follow sets
1571 # -----------------------------------------------------------------------------
1572
1573 def compute_follow_sets(ntrans,readsets,inclsets):
1574 FP = lambda x: readsets[x]
1575 R = lambda x: inclsets.get(x,[])
1576 F = digraph(ntrans,R,FP)
1577 return F
1578
1579 # -----------------------------------------------------------------------------
1580 # add_lookaheads()
1581 #
1582 # Attaches the lookahead symbols to grammar rules.
1583 #
1584 # Inputs: lookbacks - Set of lookback relations
1585 # followset - Computed follow set
1586 #
1587 # This function directly attaches the lookaheads to productions contained
1588 # in the lookbacks set
1589 # -----------------------------------------------------------------------------
1590
1591 def add_lookaheads(lookbacks,followset):
1592 for trans,lb in lookbacks.items():
1593 # Loop over productions in lookback
1594 for state,p in lb:
1595 if not p.lookaheads.has_key(state):
1596 p.lookaheads[state] = []
1597 f = followset.get(trans,[])
1598 for a in f:
1599 if a not in p.lookaheads[state]: p.lookaheads[state].append(a)
1600
1601 # -----------------------------------------------------------------------------
1602 # add_lalr_lookaheads()
1603 #
1604 # This function does all of the work of adding lookahead information for use
1605 # with LALR parsing
1606 # -----------------------------------------------------------------------------
1607
1608 def add_lalr_lookaheads(C):
1609 # Determine all of the nullable nonterminals
1610 nullable = compute_nullable_nonterminals()
1611
1612 # Find all non-terminal transitions
1613 trans = find_nonterminal_transitions(C)
1614
1615 # Compute read sets
1616 readsets = compute_read_sets(C,trans,nullable)
1617
1618 # Compute lookback/includes relations
1619 lookd, included = compute_lookback_includes(C,trans,nullable)
1620
1621 # Compute LALR FOLLOW sets
1622 followsets = compute_follow_sets(trans,readsets,included)
1623
1624 # Add all of the lookaheads
1625 add_lookaheads(lookd,followsets)
1626
1627 # -----------------------------------------------------------------------------
1628 # lr_parse_table()
1629 #
1630 # This function constructs the parse tables for SLR or LALR
1631 # -----------------------------------------------------------------------------
1632 def lr_parse_table(method):
1633 global _lr_method
1634 goto = _lr_goto # Goto array
1635 action = _lr_action # Action array
1636 actionp = { } # Action production array (temporary)
1637
1638 _lr_method = method
1639
1640 n_srconflict = 0
1641 n_rrconflict = 0
1642
1643 if yaccdebug:
1644 sys.stderr.write("yacc: Generating %s parsing table...\n" % method)
1645 _vf.write("\n\nParsing method: %s\n\n" % method)
1646
1647 # Step 1: Construct C = { I0, I1, ... IN}, collection of LR(0) items
1648 # This determines the number of states
1649
1650 C = lr0_items()
1651
1652 if method == 'LALR':
1653 add_lalr_lookaheads(C)
1654
1655 # Build the parser table, state by state
1656 st = 0
1657 for I in C:
1658 # Loop over each production in I
1659 actlist = [ ] # List of actions
1660
1661 if yaccdebug:
1662 _vf.write("\nstate %d\n\n" % st)
1663 for p in I:
1664 _vf.write(" (%d) %s\n" % (p.number, str(p)))
1665 _vf.write("\n")
1666
1667 for p in I:
1668 try:
1669 if p.prod[-1] == ".":
1670 if p.name == "S'":
1671 # Start symbol. Accept!
1672 action[st,"$end"] = 0
1673 actionp[st,"$end"] = p
1674 else:
1675 # We are at the end of a production. Reduce!
1676 if method == 'LALR':
1677 laheads = p.lookaheads[st]
1678 else:
1679 laheads = Follow[p.name]
1680 for a in laheads:
1681 actlist.append((a,p,"reduce using rule %d (%s)" % (p.number,p)))
1682 r = action.get((st,a),None)
1683 if r is not None:
1684 # Whoa. Have a shift/reduce or reduce/reduce conflict
1685 if r > 0:
1686 # Need to decide on shift or reduce here
1687 # By default we favor shifting. Need to add
1688 # some precedence rules here.
1689 sprec,slevel = Productions[actionp[st,a].number].prec
1690 rprec,rlevel = Precedence.get(a,('right',0))
1691 if (slevel < rlevel) or ((slevel == rlevel) and (rprec == 'left')):
1692 # We really need to reduce here.
1693 action[st,a] = -p.number
1694 actionp[st,a] = p
1695 if not slevel and not rlevel:
1696 _vfc.write("shift/reduce conflict in state %d resolved as reduce.\n" % st)
1697 _vf.write(" ! shift/reduce conflict for %s resolved as reduce.\n" % a)
1698 n_srconflict += 1
1699 elif (slevel == rlevel) and (rprec == 'nonassoc'):
1700 action[st,a] = None
1701 else:
1702 # Hmmm. Guess we'll keep the shift
1703 if not rlevel:
1704 _vfc.write("shift/reduce conflict in state %d resolved as shift.\n" % st)
1705 _vf.write(" ! shift/reduce conflict for %s resolved as shift.\n" % a)
1706 n_srconflict +=1
1707 elif r < 0:
1708 # Reduce/reduce conflict. In this case, we favor the rule
1709 # that was defined first in the grammar file
1710 oldp = Productions[-r]
1711 pp = Productions[p.number]
1712 if oldp.line > pp.line:
1713 action[st,a] = -p.number
1714 actionp[st,a] = p
1715 # sys.stderr.write("Reduce/reduce conflict in state %d\n" % st)
1716 n_rrconflict += 1
1717 _vfc.write("reduce/reduce conflict in state %d resolved using rule %d (%s).\n" % (st, actionp[st,a].number, actionp[st,a]))
1718 _vf.write(" ! reduce/reduce conflict for %s resolved using rule %d (%s).\n" % (a,actionp[st,a].number, actionp[st,a]))
1719 else:
1720 sys.stderr.write("Unknown conflict in state %d\n" % st)
1721 else:
1722 action[st,a] = -p.number
1723 actionp[st,a] = p
1724 else:
1725 i = p.lr_index
1726 a = p.prod[i+1] # Get symbol right after the "."
1727 if Terminals.has_key(a):
1728 g = lr0_goto(I,a)
1729 j = _lr0_cidhash.get(id(g),-1)
1730 if j >= 0:
1731 # We are in a shift state
1732 actlist.append((a,p,"shift and go to state %d" % j))
1733 r = action.get((st,a),None)
1734 if r is not None:
1735 # Whoa have a shift/reduce or shift/shift conflict
1736 if r > 0:
1737 if r != j:
1738 sys.stderr.write("Shift/shift conflict in state %d\n" % st)
1739 elif r < 0:
1740 # Do a precedence check.
1741 # - if precedence of reduce rule is higher, we reduce.
1742 # - if precedence of reduce is same and left assoc, we reduce.
1743 # - otherwise we shift
1744 rprec,rlevel = Productions[actionp[st,a].number].prec
1745 sprec,slevel = Precedence.get(a,('right',0))
1746 if (slevel > rlevel) or ((slevel == rlevel) and (rprec != 'left')):
1747 # We decide to shift here... highest precedence to shift
1748 action[st,a] = j
1749 actionp[st,a] = p
1750 if not rlevel:
1751 n_srconflict += 1
1752 _vfc.write("shift/reduce conflict in state %d resolved as shift.\n" % st)
1753 _vf.write(" ! shift/reduce conflict for %s resolved as shift.\n" % a)
1754 elif (slevel == rlevel) and (rprec == 'nonassoc'):
1755 action[st,a] = None
1756 else:
1757 # Hmmm. Guess we'll keep the reduce
1758 if not slevel and not rlevel:
1759 n_srconflict +=1
1760 _vfc.write("shift/reduce conflict in state %d resolved as reduce.\n" % st)
1761 _vf.write(" ! shift/reduce conflict for %s resolved as reduce.\n" % a)
1762
1763 else:
1764 sys.stderr.write("Unknown conflict in state %d\n" % st)
1765 else:
1766 action[st,a] = j
1767 actionp[st,a] = p
1768
1769 except Exception as e:
1770 raise YaccError("Hosed in lr_parse_table", e)
1771
1772 # Print the actions associated with each terminal
1773 if yaccdebug:
1774 _actprint = { }
1775 for a,p,m in actlist:
1776 if action.has_key((st,a)):
1777 if p is actionp[st,a]:
1778 _vf.write(" %-15s %s\n" % (a,m))
1779 _actprint[(a,m)] = 1
1780 _vf.write("\n")
1781 for a,p,m in actlist:
1782 if action.has_key((st,a)):
1783 if p is not actionp[st,a]:
1784 if not _actprint.has_key((a,m)):
1785 _vf.write(" ! %-15s [ %s ]\n" % (a,m))
1786 _actprint[(a,m)] = 1
1787
1788 # Construct the goto table for this state
1789 if yaccdebug:
1790 _vf.write("\n")
1791 nkeys = { }
1792 for ii in I:
1793 for s in ii.usyms:
1794 if Nonterminals.has_key(s):
1795 nkeys[s] = None
1796 for n in nkeys.keys():
1797 g = lr0_goto(I,n)
1798 j = _lr0_cidhash.get(id(g),-1)
1799 if j >= 0:
1800 goto[st,n] = j
1801 if yaccdebug:
1802 _vf.write(" %-30s shift and go to state %d\n" % (n,j))
1803
1804 st += 1
1805
1806 if yaccdebug:
1807 if n_srconflict == 1:
1808 sys.stderr.write("yacc: %d shift/reduce conflict\n" % n_srconflict)
1809 if n_srconflict > 1:
1810 sys.stderr.write("yacc: %d shift/reduce conflicts\n" % n_srconflict)
1811 if n_rrconflict == 1:
1812 sys.stderr.write("yacc: %d reduce/reduce conflict\n" % n_rrconflict)
1813 if n_rrconflict > 1:
1814 sys.stderr.write("yacc: %d reduce/reduce conflicts\n" % n_rrconflict)
1815
1816 # -----------------------------------------------------------------------------
1817 # ==== LR Utility functions ====
1818 # -----------------------------------------------------------------------------
1819
1820 # -----------------------------------------------------------------------------
1821 # _lr_write_tables()
1822 #
1823 # This function writes the LR parsing tables to a file
1824 # -----------------------------------------------------------------------------
1825
1826 def lr_write_tables(modulename=tab_module,outputdir=''):
1827 filename = os.path.join(outputdir,modulename) + ".py"
1828 try:
1829 f = open(filename,"w")
1830
1831 f.write("""
1832 # %s
1833 # This file is automatically generated. Do not edit.
1834
1835 _lr_method = %s
1836
1837 _lr_signature = %s
1838 """ % (filename, repr(_lr_method), repr(Signature.digest())))
1839
1840 # Change smaller to 0 to go back to original tables
1841 smaller = 1
1842
1843 # Factor out names to try and make smaller
1844 if smaller:
1845 items = { }
1846
1847 for k,v in _lr_action.items():
1848 i = items.get(k[1])
1849 if not i:
1850 i = ([],[])
1851 items[k[1]] = i
1852 i[0].append(k[0])
1853 i[1].append(v)
1854
1855 f.write("\n_lr_action_items = {")
1856 for k,v in items.items():
1857 f.write("%r:([" % k)
1858 for i in v[0]:
1859 f.write("%r," % i)
1860 f.write("],[")
1861 for i in v[1]:
1862 f.write("%r," % i)
1863
1864 f.write("]),")
1865 f.write("}\n")
1866
1867 f.write("""
1868 _lr_action = { }
1869 for _k, _v in _lr_action_items.items():
1870 for _x,_y in zip(_v[0],_v[1]):
1871 _lr_action[(_x,_k)] = _y
1872 del _lr_action_items
1873 """)
1874
1875 else:
1876 f.write("\n_lr_action = { ");
1877 for k,v in _lr_action.items():
1878 f.write("(%r,%r):%r," % (k[0],k[1],v))
1879 f.write("}\n");
1880
1881 if smaller:
1882 # Factor out names to try and make smaller
1883 items = { }
1884
1885 for k,v in _lr_goto.items():
1886 i = items.get(k[1])
1887 if not i:
1888 i = ([],[])
1889 items[k[1]] = i
1890 i[0].append(k[0])
1891 i[1].append(v)
1892
1893 f.write("\n_lr_goto_items = {")
1894 for k,v in items.items():
1895 f.write("%r:([" % k)
1896 for i in v[0]:
1897 f.write("%r," % i)
1898 f.write("],[")
1899 for i in v[1]:
1900 f.write("%r," % i)
1901
1902 f.write("]),")
1903 f.write("}\n")
1904
1905 f.write("""
1906 _lr_goto = { }
1907 for _k, _v in _lr_goto_items.items():
1908 for _x,_y in zip(_v[0],_v[1]):
1909 _lr_goto[(_x,_k)] = _y
1910 del _lr_goto_items
1911 """)
1912 else:
1913 f.write("\n_lr_goto = { ");
1914 for k,v in _lr_goto.items():
1915 f.write("(%r,%r):%r," % (k[0],k[1],v))
1916 f.write("}\n");
1917
1918 # Write production table
1919 f.write("_lr_productions = [\n")
1920 for p in Productions:
1921 if p:
1922 if (p.func):
1923 f.write(" (%r,%d,%r,%r,%d),\n" % (p.name, p.len, p.func.__name__,p.file,p.line))
1924 else:
1925 f.write(" (%r,%d,None,None,None),\n" % (p.name, p.len))
1926 else:
1927 f.write(" None,\n")
1928 f.write("]\n")
1929
1930 f.close()
1931
1932 except IOError as e:
1933 print("Unable to create '%s'" % filename)
1934 print(e)
1935 return
1936
1937 def lr_read_tables(module=tab_module,optimize=0):
1938 global _lr_action, _lr_goto, _lr_productions, _lr_method
1939 try:
1940 exec("import %s as parsetab" % module)
1941 global parsetab # declare the name of the imported module
1942
1943 if (optimize) or (Signature.digest() == parsetab._lr_signature):
1944 _lr_action = parsetab._lr_action
1945 _lr_goto = parsetab._lr_goto
1946 _lr_productions = parsetab._lr_productions
1947 _lr_method = parsetab._lr_method
1948 return 1
1949 else:
1950 return 0
1951
1952 except (ImportError,AttributeError):
1953 return 0
1954
1955
1956 # Available instance types. This is used when parsers are defined by a class.
1957 # it's a little funky because I want to preserve backwards compatibility
1958 # with Python 2.0 where types.ObjectType is undefined.
1959
1960 try:
1961 _INSTANCETYPE = (types.InstanceType, types.ObjectType)
1962 except AttributeError:
1963 _INSTANCETYPE = types.InstanceType
1964
1965 # -----------------------------------------------------------------------------
1966 # yacc(module)
1967 #
1968 # Build the parser module
1969 # -----------------------------------------------------------------------------
1970
1971 # <ah> Add parserclass parameter.
1972 def yacc(method=default_lr, debug=yaccdebug, module=None, tabmodule=tab_module, start=None, check_recursion=1, optimize=0,write_tables=1,debugfile=debug_file,outputdir='', parserclass=Parser):
1973 global yaccdebug
1974 yaccdebug = debug
1975
1976 initialize_vars()
1977 files = { }
1978 error = 0
1979
1980
1981 # Add parsing method to signature
1982 Signature.update(method)
1983
1984 # If a "module" parameter was supplied, extract its dictionary.
1985 # Note: a module may in fact be an instance as well.
1986
1987 if module:
1988 # User supplied a module object.
1989 if isinstance(module, types.ModuleType):
1990 ldict = module.__dict__
1991 elif isinstance(module, _INSTANCETYPE):
1992 _items = [(k,getattr(module,k)) for k in dir(module)]
1993 ldict = { }
1994 for i in _items:
1995 ldict[i[0]] = i[1]
1996 else:
1997 raise ValueError("Expected a module")
1998
1999 else:
2000 # No module given. We might be able to get information from the caller.
2001 # Throw an exception and unwind the traceback to get the globals
2002
2003 try:
2004 raise RuntimeError
2005 except RuntimeError:
2006 e,b,t = sys.exc_info()
2007 f = t.tb_frame
2008 f = f.f_back # Walk out to our calling function
2009 ldict = f.f_globals # Grab its globals dictionary
2010
2011 # Add starting symbol to signature
2012 if not start:
2013 start = ldict.get("start",None)
2014 if start:
2015 Signature.update(start)
2016
2017 # If running in optimized mode. We're going to
2018
2019 if (optimize and lr_read_tables(tabmodule,1)):
2020 # Read parse table
2021 del Productions[:]
2022 for p in _lr_productions:
2023 if not p:
2024 Productions.append(None)
2025 else:
2026 m = MiniProduction()
2027 m.name = p[0]
2028 m.len = p[1]
2029 m.file = p[3]
2030 m.line = p[4]
2031 if p[2]:
2032 m.func = ldict[p[2]]
2033 Productions.append(m)
2034
2035 else:
2036 # Get the tokens map
2037 if (module and isinstance(module,_INSTANCETYPE)):
2038 tokens = getattr(module,"tokens",None)
2039 else:
2040 tokens = ldict.get("tokens",None)
2041
2042 if not tokens:
2043 raise YaccError("module does not define a list 'tokens'")
2044 if not (isinstance(tokens,types.ListType) or isinstance(tokens,types.TupleType)):
2045 raise YaccError("tokens must be a list or tuple.")
2046
2047 # Check to see if a requires dictionary is defined.
2048 requires = ldict.get("require",None)
2049 if requires:
2050 if not (isinstance(requires,types.DictType)):
2051 raise YaccError("require must be a dictionary.")
2052
2053 for r,v in requires.items():
2054 try:
2055 if not (isinstance(v,types.ListType)):
2056 raise TypeError
2057 v1 = [x.split(".") for x in v]
2058 Requires[r] = v1
2059 except Exception:
2060 print("Invalid specification for rule '%s' in require. Expected a list of strings" % r)
2061
2062
2063 # Build the dictionary of terminals. We a record a 0 in the
2064 # dictionary to track whether or not a terminal is actually
2065 # used in the grammar
2066
2067 if 'error' in tokens:
2068 print("yacc: Illegal token 'error'. Is a reserved word.")
2069 raise YaccError("Illegal token name")
2070
2071 for n in tokens:
2072 if Terminals.has_key(n):
2073 print("yacc: Warning. Token '%s' multiply defined." % n)
2074 Terminals[n] = [ ]
2075
2076 Terminals['error'] = [ ]
2077
2078 # Get the precedence map (if any)
2079 prec = ldict.get("precedence",None)
2080 if prec:
2081 if not (isinstance(prec,types.ListType) or isinstance(prec,types.TupleType)):
2082 raise YaccError("precedence must be a list or tuple.")
2083 add_precedence(prec)
2084 Signature.update(repr(prec))
2085
2086 for n in tokens:
2087 if not Precedence.has_key(n):
2088 Precedence[n] = ('right',0) # Default, right associative, 0 precedence
2089
2090 # Look for error handler
2091 ef = ldict.get('p_error',None)
2092 if ef:
2093 if isinstance(ef,types.FunctionType):
2094 ismethod = 0
2095 elif isinstance(ef, types.MethodType):
2096 ismethod = 1
2097 else:
2098 raise YaccError("'p_error' defined, but is not a function or method.")
2099 eline = ef.func_code.co_firstlineno
2100 efile = ef.func_code.co_filename
2101 files[efile] = None
2102
2103 if (ef.func_code.co_argcount != 1+ismethod):
2104 raise YaccError("%s:%d: p_error() requires 1 argument." % (efile,eline))
2105 global Errorfunc
2106 Errorfunc = ef
2107 else:
2108 print("yacc: Warning. no p_error() function is defined.")
2109
2110 # Get the list of built-in functions with p_ prefix
2111 symbols = [ldict[f] for f in ldict.keys()
2112 if (type(ldict[f]) in (types.FunctionType, types.MethodType) and ldict[f].__name__[:2] == 'p_'
2113 and ldict[f].__name__ != 'p_error')]
2114
2115 # Check for non-empty symbols
2116 if len(symbols) == 0:
2117 raise YaccError("no rules of the form p_rulename are defined.")
2118
2119 # Sort the symbols by line number
2120 symbols.sort(key=lambda func: func.__code__.co_firstlineno)
2121
2122 # Add all of the symbols to the grammar
2123 for f in symbols:
2124 if (add_function(f)) < 0:
2125 error += 1
2126 else:
2127 files[f.func_code.co_filename] = None
2128
2129 # Make a signature of the docstrings
2130 for f in symbols:
2131 if f.__doc__:
2132 Signature.update(f.__doc__)
2133
2134 lr_init_vars()
2135
2136 if error:
2137 raise YaccError("Unable to construct parser.")
2138
2139 if not lr_read_tables(tabmodule):
2140
2141 # Validate files
2142 for filename in files.keys():
2143 if not validate_file(filename):
2144 error = 1
2145
2146 # Validate dictionary
2147 validate_dict(ldict)
2148
2149 if start and not Prodnames.has_key(start):
2150 raise YaccError("Bad starting symbol '%s'" % start)
2151
2152 augment_grammar(start)
2153 error = verify_productions(cycle_check=check_recursion)
2154 otherfunc = [ldict[f] for f in ldict.keys()
2155 if (type(f) in (types.FunctionType,types.MethodType) and ldict[f].__name__[:2] != 'p_')]
2156
2157 if error:
2158 raise YaccError("Unable to construct parser.")
2159
2160 build_lritems()
2161 compute_first1()
2162 compute_follow(start)
2163
2164 if method in ['SLR','LALR']:
2165 lr_parse_table(method)
2166 else:
2167 raise YaccError("Unknown parsing method '%s'" % method)
2168
2169 if write_tables:
2170 lr_write_tables(tabmodule,outputdir)
2171
2172 if yaccdebug:
2173 try:
2174 f = open(os.path.join(outputdir,debugfile),"w")
2175 f.write(_vfc.getvalue())
2176 f.write("\n\n")
2177 f.write(_vf.getvalue())
2178 f.close()
2179 except IOError as e:
2180 print("yacc: can't create '%s'" % debugfile,e)
2181
2182 # Made it here. Create a parser object and set up its internal state.
2183 # Set global parse() method to bound method of parser object.
2184
2185 g = ParserPrototype("xyzzy")
2186 g.productions = Productions
2187 g.errorfunc = Errorfunc
2188 g.action = _lr_action
2189 g.goto = _lr_goto
2190 g.method = _lr_method
2191 g.require = Requires
2192
2193 global parser
2194 parser = g.init_parser()
2195
2196 global parse
2197 parse = parser.parse
2198
2199 # Clean up all of the globals we created
2200 if (not optimize):
2201 yacc_cleanup()
2202 return g
2203
2204 # <ah> Allow multiple instances of parser
2205 class ParserPrototype(object):
2206 def __init__(self, magic=None):
2207 if magic != "xyzzy":
2208 raise YaccError('Use yacc()')
2209
2210 def init_parser(self, parser=None):
2211 if not parser:
2212 parser = Parser()
2213 parser.productions = self.productions
2214 parser.errorfunc = self.errorfunc
2215 parser.action = self.action
2216 parser.goto = self.goto
2217 parser.method = self.method
2218 parser.require = self.require
2219 return parser
2220
2221 # yacc_cleanup function. Delete all of the global variables
2222 # used during table construction
2223
2224 def yacc_cleanup():
2225 global _lr_action, _lr_goto, _lr_method, _lr_goto_cache
2226 del _lr_action, _lr_goto, _lr_method, _lr_goto_cache
2227
2228 global Productions, Prodnames, Prodmap, Terminals
2229 global Nonterminals, First, Follow, Precedence, LRitems
2230 global Errorfunc, Signature, Requires
2231
2232 del Productions, Prodnames, Prodmap, Terminals
2233 del Nonterminals, First, Follow, Precedence, LRitems
2234 del Errorfunc, Signature, Requires
2235
2236 global _vf, _vfc
2237 del _vf, _vfc
2238
2239
2240 # Stub that raises an error if parsing is attempted without first calling yacc()
2241 def parse(*args,**kwargs):
2242 raise YaccError("yacc: No parser built with yacc()")
2243