All patches and comments are welcome. Please squash your changes to logical
commits before using git-format-patch and git-send-email to
patches@git.madduck.net.
If you'd read over the Git project's submission guidelines and adhered to them,
I'd be especially grateful.
1 # Copyright 2004-2005 Elemental Security, Inc. All Rights Reserved.
2 # Licensed to PSF under a Contributor Agreement.
4 """Parser engine for the grammar tables generated by pgen.
6 The grammar table must be loaded first.
8 See Parser/parser.c in the Python distribution for additional info on
9 how this parsing engine works.
17 class ParseError(Exception):
18 """Exception to signal the parser is stuck."""
20 def __init__(self, msg, type, value, context):
22 self, "%s: type=%r, value=%r, context=%r" % (msg, type, value, context)
27 self.context = context
33 The proper usage sequence is:
35 p = Parser(grammar, [converter]) # create instance
36 p.setup([start]) # prepare for parsing
37 <for each input token>:
38 if p.addtoken(...): # parse a token; may raise ParseError
40 root = p.rootnode # root of abstract syntax tree
42 A Parser instance may be reused by calling setup() repeatedly.
44 A Parser instance contains state pertaining to the current token
45 sequence, and should not be used concurrently by different threads
46 to parse separate token sequences.
48 See driver.py for how to get input tokens by tokenizing a file or
51 Parsing is complete when addtoken() returns True; the root of the
52 abstract syntax tree can then be retrieved from the rootnode
53 instance variable. When a syntax error occurs, addtoken() raises
54 the ParseError exception. There is no error recovery; the parser
55 cannot be used after a syntax error was reported (but it can be
56 reinitialized by calling setup()).
60 def __init__(self, grammar, convert=None):
63 The grammar argument is a grammar.Grammar instance; see the
64 grammar module for more information.
66 The parser is not ready yet for parsing; you must call the
67 setup() method to get it started.
69 The optional convert argument is a function mapping concrete
70 syntax tree nodes to abstract syntax tree nodes. If not
71 given, no conversion is done and the syntax tree produced is
72 the concrete syntax tree. If given, it must be a function of
73 two arguments, the first being the grammar (a grammar.Grammar
74 instance), and the second being the concrete syntax tree node
75 to be converted. The syntax tree is converted from the bottom
78 A concrete syntax tree node is a (type, value, context, nodes)
79 tuple, where type is the node type (a token or symbol number),
80 value is None for symbols and a string for tokens, context is
81 None or an opaque value used for error reporting (typically a
82 (lineno, offset) pair), and nodes is a list of children for
83 symbols, and None for tokens.
85 An abstract syntax tree node may be anything; this is entirely
86 up to the converter function.
89 self.grammar = grammar
90 self.convert = convert or (lambda grammar, node: node)
92 def setup(self, start=None):
93 """Prepare for parsing.
95 This *must* be called before starting to parse.
97 The optional argument is an alternative start symbol; it
98 defaults to the grammar's start symbol.
100 You can use a Parser instance to parse any number of programs;
101 each time you call setup() the parser is reset to an initial
102 state determined by the (implicit or explicit) start symbol.
106 start = self.grammar.start
107 # Each stack entry is a tuple: (dfa, state, node).
108 # A node is a tuple: (type, value, context, children),
109 # where children is a list of nodes or None, and context may be None.
110 newnode = (start, None, None, [])
111 stackentry = (self.grammar.dfas[start], 0, newnode)
112 self.stack = [stackentry]
114 self.used_names = set() # Aliased to self.rootnode.used_names in pop()
116 def addtoken(self, type, value, context):
117 """Add a token; return True iff this is the end of the program."""
118 # Map from token to label
119 ilabel = self.classify(type, value, context)
120 # Loop until the token is shifted; may raise exceptions
122 dfa, state, node = self.stack[-1]
125 # Look for a state with this label
126 for i, newstate in arcs:
127 t, v = self.grammar.labels[i]
129 # Look it up in the list of labels
131 # Shift a token; we're done with it
132 self.shift(type, value, newstate, context)
133 # Pop while we are in an accept-only state
135 while states[state] == [(0, state)]:
140 dfa, state, node = self.stack[-1]
142 # Done with this token
145 # See if it's a symbol and if we're in its first set
146 itsdfa = self.grammar.dfas[t]
147 itsstates, itsfirst = itsdfa
148 if ilabel in itsfirst:
150 self.push(t, self.grammar.dfas[t], newstate, context)
151 break # To continue the outer while loop
153 if (0, state) in arcs:
154 # An accepting state, pop it and try something else
157 # Done parsing, but another token is input
158 raise ParseError("too much input", type, value, context)
160 # No success finding a transition
161 raise ParseError("bad input", type, value, context)
163 def classify(self, type, value, context):
164 """Turn a token into a label. (Internal)"""
165 if type == token.NAME:
166 # Keep a listing of all used names
167 self.used_names.add(value)
168 # Check for reserved words
169 ilabel = self.grammar.keywords.get(value)
170 if ilabel is not None:
172 ilabel = self.grammar.tokens.get(type)
174 raise ParseError("bad token", type, value, context)
177 def shift(self, type, value, newstate, context):
178 """Shift a token. (Internal)"""
179 dfa, state, node = self.stack[-1]
180 newnode = (type, value, context, None)
181 newnode = self.convert(self.grammar, newnode)
182 if newnode is not None:
183 node[-1].append(newnode)
184 self.stack[-1] = (dfa, newstate, node)
186 def push(self, type, newdfa, newstate, context):
187 """Push a nonterminal. (Internal)"""
188 dfa, state, node = self.stack[-1]
189 newnode = (type, None, context, [])
190 self.stack[-1] = (dfa, newstate, node)
191 self.stack.append((newdfa, 0, newnode))
194 """Pop a nonterminal. (Internal)"""
195 popdfa, popstate, popnode = self.stack.pop()
196 newnode = self.convert(self.grammar, popnode)
197 if newnode is not None:
199 dfa, state, node = self.stack[-1]
200 node[-1].append(newnode)
202 self.rootnode = newnode
203 self.rootnode.used_names = self.used_names