blob: 0fc6945b5c26de34b30db2fa2f3878a52d4d9e74 [file] [log] [blame]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00001# Copyright (c) 1998-2002 John Aycock
Tim Peters536cf992005-12-25 23:18:31 +00002#
Jeremy Hylton3e0055f2005-10-20 19:59:25 +00003# Permission is hereby granted, free of charge, to any person obtaining
4# a copy of this software and associated documentation files (the
5# "Software"), to deal in the Software without restriction, including
6# without limitation the rights to use, copy, modify, merge, publish,
7# distribute, sublicense, and/or sell copies of the Software, and to
8# permit persons to whom the Software is furnished to do so, subject to
9# the following conditions:
Tim Peters536cf992005-12-25 23:18:31 +000010#
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000011# The above copyright notice and this permission notice shall be
12# included in all copies or substantial portions of the Software.
Tim Peters536cf992005-12-25 23:18:31 +000013#
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000014# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
18# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
19# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
20# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22__version__ = 'SPARK-0.7 (pre-alpha-5)'
23
24import re
25import sys
Guido van Rossum805365e2007-05-07 22:24:25 +000026
27# Compatability with older pythons.
28def output(string='', end='\n'):
29 sys.stdout.write(string + end)
30
31try:
32 sorted
33except NameError:
34 def sorted(seq):
35 seq2 = seq[:]
36 seq2.sort()
37 return seq2
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000038
39def _namelist(instance):
Tim Peters536cf992005-12-25 23:18:31 +000040 namelist, namedict, classlist = [], {}, [instance.__class__]
41 for c in classlist:
42 for b in c.__bases__:
43 classlist.append(b)
44 for name in c.__dict__.keys():
Fred Drake34e4f522006-12-29 04:42:48 +000045 if name not in namedict:
Tim Peters536cf992005-12-25 23:18:31 +000046 namelist.append(name)
47 namedict[name] = 1
48 return namelist
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000049
50class GenericScanner:
Tim Peters536cf992005-12-25 23:18:31 +000051 def __init__(self, flags=0):
52 pattern = self.reflect()
53 self.re = re.compile(pattern, re.VERBOSE|flags)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000054
Tim Peters536cf992005-12-25 23:18:31 +000055 self.index2func = {}
56 for name, number in self.re.groupindex.items():
57 self.index2func[number-1] = getattr(self, 't_' + name)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000058
Tim Peters536cf992005-12-25 23:18:31 +000059 def makeRE(self, name):
60 doc = getattr(self, name).__doc__
61 rv = '(?P<%s>%s)' % (name[2:], doc)
62 return rv
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000063
Tim Peters536cf992005-12-25 23:18:31 +000064 def reflect(self):
65 rv = []
66 for name in _namelist(self):
67 if name[:2] == 't_' and name != 't_default':
68 rv.append(self.makeRE(name))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000069
Tim Peters536cf992005-12-25 23:18:31 +000070 rv.append(self.makeRE('t_default'))
Guido van Rossum805365e2007-05-07 22:24:25 +000071 return '|'.join(rv)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000072
Tim Peters536cf992005-12-25 23:18:31 +000073 def error(self, s, pos):
Guido van Rossum805365e2007-05-07 22:24:25 +000074 output("Lexical error at position %s" % pos)
Tim Peters536cf992005-12-25 23:18:31 +000075 raise SystemExit
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000076
Tim Peters536cf992005-12-25 23:18:31 +000077 def tokenize(self, s):
78 pos = 0
79 n = len(s)
80 while pos < n:
81 m = self.re.match(s, pos)
82 if m is None:
83 self.error(s, pos)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000084
Tim Peters536cf992005-12-25 23:18:31 +000085 groups = m.groups()
86 for i in range(len(groups)):
Fred Drake34e4f522006-12-29 04:42:48 +000087 if groups[i] and i in self.index2func:
Tim Peters536cf992005-12-25 23:18:31 +000088 self.index2func[i](groups[i])
89 pos = m.end()
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000090
Tim Peters536cf992005-12-25 23:18:31 +000091 def t_default(self, s):
92 r'( . | \n )+'
Guido van Rossum805365e2007-05-07 22:24:25 +000093 output("Specification error: unmatched input")
Tim Peters536cf992005-12-25 23:18:31 +000094 raise SystemExit
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000095
96#
97# Extracted from GenericParser and made global so that [un]picking works.
98#
99class _State:
Tim Peters536cf992005-12-25 23:18:31 +0000100 def __init__(self, stateno, items):
101 self.T, self.complete, self.items = [], [], items
102 self.stateno = stateno
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000103
104class GenericParser:
Tim Peters536cf992005-12-25 23:18:31 +0000105 #
106 # An Earley parser, as per J. Earley, "An Efficient Context-Free
107 # Parsing Algorithm", CACM 13(2), pp. 94-102. Also J. C. Earley,
108 # "An Efficient Context-Free Parsing Algorithm", Ph.D. thesis,
109 # Carnegie-Mellon University, August 1968. New formulation of
110 # the parser according to J. Aycock, "Practical Earley Parsing
111 # and the SPARK Toolkit", Ph.D. thesis, University of Victoria,
112 # 2001, and J. Aycock and R. N. Horspool, "Practical Earley
113 # Parsing", unpublished paper, 2001.
114 #
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000115
Tim Peters536cf992005-12-25 23:18:31 +0000116 def __init__(self, start):
117 self.rules = {}
118 self.rule2func = {}
119 self.rule2name = {}
120 self.collectRules()
121 self.augment(start)
122 self.ruleschanged = 1
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000123
Tim Peters536cf992005-12-25 23:18:31 +0000124 _NULLABLE = '\e_'
125 _START = 'START'
126 _BOF = '|-'
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000127
Tim Peters536cf992005-12-25 23:18:31 +0000128 #
129 # When pickling, take the time to generate the full state machine;
130 # some information is then extraneous, too. Unfortunately we
131 # can't save the rule2func map.
132 #
133 def __getstate__(self):
134 if self.ruleschanged:
135 #
136 # XXX - duplicated from parse()
137 #
138 self.computeNull()
139 self.newrules = {}
140 self.new2old = {}
141 self.makeNewRules()
142 self.ruleschanged = 0
143 self.edges, self.cores = {}, {}
144 self.states = { 0: self.makeState0() }
145 self.makeState(0, self._BOF)
146 #
147 # XXX - should find a better way to do this..
148 #
149 changes = 1
150 while changes:
151 changes = 0
152 for k, v in self.edges.items():
153 if v is None:
154 state, sym = k
Fred Drake34e4f522006-12-29 04:42:48 +0000155 if state in self.states:
Tim Peters536cf992005-12-25 23:18:31 +0000156 self.goto(state, sym)
157 changes = 1
158 rv = self.__dict__.copy()
159 for s in self.states.values():
160 del s.items
161 del rv['rule2func']
162 del rv['nullable']
163 del rv['cores']
164 return rv
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000165
Tim Peters536cf992005-12-25 23:18:31 +0000166 def __setstate__(self, D):
167 self.rules = {}
168 self.rule2func = {}
169 self.rule2name = {}
170 self.collectRules()
171 start = D['rules'][self._START][0][1][1] # Blech.
172 self.augment(start)
173 D['rule2func'] = self.rule2func
174 D['makeSet'] = self.makeSet_fast
175 self.__dict__ = D
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000176
Tim Peters536cf992005-12-25 23:18:31 +0000177 #
178 # A hook for GenericASTBuilder and GenericASTMatcher. Mess
179 # thee not with this; nor shall thee toucheth the _preprocess
180 # argument to addRule.
181 #
182 def preprocess(self, rule, func): return rule, func
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000183
Tim Peters536cf992005-12-25 23:18:31 +0000184 def addRule(self, doc, func, _preprocess=1):
185 fn = func
Guido van Rossum805365e2007-05-07 22:24:25 +0000186 rules = doc.split()
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000187
Tim Peters536cf992005-12-25 23:18:31 +0000188 index = []
189 for i in range(len(rules)):
190 if rules[i] == '::=':
191 index.append(i-1)
192 index.append(len(rules))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000193
Tim Peters536cf992005-12-25 23:18:31 +0000194 for i in range(len(index)-1):
195 lhs = rules[index[i]]
196 rhs = rules[index[i]+2:index[i+1]]
197 rule = (lhs, tuple(rhs))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000198
Tim Peters536cf992005-12-25 23:18:31 +0000199 if _preprocess:
200 rule, fn = self.preprocess(rule, func)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000201
Fred Drake34e4f522006-12-29 04:42:48 +0000202 if lhs in self.rules:
Tim Peters536cf992005-12-25 23:18:31 +0000203 self.rules[lhs].append(rule)
204 else:
205 self.rules[lhs] = [ rule ]
206 self.rule2func[rule] = fn
207 self.rule2name[rule] = func.__name__[2:]
208 self.ruleschanged = 1
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000209
Tim Peters536cf992005-12-25 23:18:31 +0000210 def collectRules(self):
211 for name in _namelist(self):
212 if name[:2] == 'p_':
213 func = getattr(self, name)
214 doc = func.__doc__
215 self.addRule(doc, func)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000216
Tim Peters536cf992005-12-25 23:18:31 +0000217 def augment(self, start):
218 rule = '%s ::= %s %s' % (self._START, self._BOF, start)
219 self.addRule(rule, lambda args: args[1], 0)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000220
Tim Peters536cf992005-12-25 23:18:31 +0000221 def computeNull(self):
222 self.nullable = {}
223 tbd = []
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000224
Tim Peters536cf992005-12-25 23:18:31 +0000225 for rulelist in self.rules.values():
226 lhs = rulelist[0][0]
227 self.nullable[lhs] = 0
228 for rule in rulelist:
229 rhs = rule[1]
230 if len(rhs) == 0:
231 self.nullable[lhs] = 1
232 continue
233 #
234 # We only need to consider rules which
235 # consist entirely of nonterminal symbols.
236 # This should be a savings on typical
237 # grammars.
238 #
239 for sym in rhs:
Fred Drake34e4f522006-12-29 04:42:48 +0000240 if sym not in self.rules:
Tim Peters536cf992005-12-25 23:18:31 +0000241 break
242 else:
243 tbd.append(rule)
244 changes = 1
245 while changes:
246 changes = 0
247 for lhs, rhs in tbd:
248 if self.nullable[lhs]:
249 continue
250 for sym in rhs:
251 if not self.nullable[sym]:
252 break
253 else:
254 self.nullable[lhs] = 1
255 changes = 1
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000256
Tim Peters536cf992005-12-25 23:18:31 +0000257 def makeState0(self):
258 s0 = _State(0, [])
259 for rule in self.newrules[self._START]:
260 s0.items.append((rule, 0))
261 return s0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000262
Tim Peters536cf992005-12-25 23:18:31 +0000263 def finalState(self, tokens):
264 #
265 # Yuck.
266 #
267 if len(self.newrules[self._START]) == 2 and len(tokens) == 0:
268 return 1
269 start = self.rules[self._START][0][1][1]
270 return self.goto(1, start)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000271
Tim Peters536cf992005-12-25 23:18:31 +0000272 def makeNewRules(self):
273 worklist = []
274 for rulelist in self.rules.values():
275 for rule in rulelist:
276 worklist.append((rule, 0, 1, rule))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000277
Tim Peters536cf992005-12-25 23:18:31 +0000278 for rule, i, candidate, oldrule in worklist:
279 lhs, rhs = rule
280 n = len(rhs)
281 while i < n:
282 sym = rhs[i]
Fred Drake34e4f522006-12-29 04:42:48 +0000283 if sym not in self.rules or \
Tim Peters536cf992005-12-25 23:18:31 +0000284 not self.nullable[sym]:
285 candidate = 0
286 i = i + 1
287 continue
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000288
Tim Peters536cf992005-12-25 23:18:31 +0000289 newrhs = list(rhs)
290 newrhs[i] = self._NULLABLE+sym
291 newrule = (lhs, tuple(newrhs))
292 worklist.append((newrule, i+1,
293 candidate, oldrule))
294 candidate = 0
295 i = i + 1
296 else:
297 if candidate:
298 lhs = self._NULLABLE+lhs
299 rule = (lhs, rhs)
Fred Drake34e4f522006-12-29 04:42:48 +0000300 if lhs in self.newrules:
Tim Peters536cf992005-12-25 23:18:31 +0000301 self.newrules[lhs].append(rule)
302 else:
303 self.newrules[lhs] = [ rule ]
304 self.new2old[rule] = oldrule
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000305
Tim Peters536cf992005-12-25 23:18:31 +0000306 def typestring(self, token):
307 return None
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000308
Tim Peters536cf992005-12-25 23:18:31 +0000309 def error(self, token):
Guido van Rossum805365e2007-05-07 22:24:25 +0000310 output("Syntax error at or near `%s' token" % token)
Tim Peters536cf992005-12-25 23:18:31 +0000311 raise SystemExit
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000312
Tim Peters536cf992005-12-25 23:18:31 +0000313 def parse(self, tokens):
314 sets = [ [(1,0), (2,0)] ]
315 self.links = {}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000316
Tim Peters536cf992005-12-25 23:18:31 +0000317 if self.ruleschanged:
318 self.computeNull()
319 self.newrules = {}
320 self.new2old = {}
321 self.makeNewRules()
322 self.ruleschanged = 0
323 self.edges, self.cores = {}, {}
324 self.states = { 0: self.makeState0() }
325 self.makeState(0, self._BOF)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000326
Guido van Rossum805365e2007-05-07 22:24:25 +0000327 for i in range(len(tokens)):
Tim Peters536cf992005-12-25 23:18:31 +0000328 sets.append([])
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000329
Tim Peters536cf992005-12-25 23:18:31 +0000330 if sets[i] == []:
331 break
332 self.makeSet(tokens[i], sets, i)
333 else:
334 sets.append([])
335 self.makeSet(None, sets, len(tokens))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000336
Tim Peters536cf992005-12-25 23:18:31 +0000337 #_dump(tokens, sets, self.states)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000338
Tim Peters536cf992005-12-25 23:18:31 +0000339 finalitem = (self.finalState(tokens), 0)
340 if finalitem not in sets[-2]:
341 if len(tokens) > 0:
342 self.error(tokens[i-1])
343 else:
344 self.error(None)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000345
Tim Peters536cf992005-12-25 23:18:31 +0000346 return self.buildTree(self._START, finalitem,
347 tokens, len(sets)-2)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000348
Tim Peters536cf992005-12-25 23:18:31 +0000349 def isnullable(self, sym):
350 #
351 # For symbols in G_e only. If we weren't supporting 1.5,
352 # could just use sym.startswith().
353 #
354 return self._NULLABLE == sym[0:len(self._NULLABLE)]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000355
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000356 def skip(self, hs, pos=0):
357 n = len(hs[1])
Tim Peters536cf992005-12-25 23:18:31 +0000358 while pos < n:
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000359 if not self.isnullable(hs[1][pos]):
Tim Peters536cf992005-12-25 23:18:31 +0000360 break
361 pos = pos + 1
362 return pos
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000363
Tim Peters536cf992005-12-25 23:18:31 +0000364 def makeState(self, state, sym):
365 assert sym is not None
366 #
367 # Compute \epsilon-kernel state's core and see if
368 # it exists already.
369 #
370 kitems = []
371 for rule, pos in self.states[state].items:
372 lhs, rhs = rule
373 if rhs[pos:pos+1] == (sym,):
374 kitems.append((rule, self.skip(rule, pos+1)))
375 core = kitems
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000376
Tim Peters536cf992005-12-25 23:18:31 +0000377 core.sort()
378 tcore = tuple(core)
Fred Drake34e4f522006-12-29 04:42:48 +0000379 if tcore in self.cores:
Tim Peters536cf992005-12-25 23:18:31 +0000380 return self.cores[tcore]
381 #
382 # Nope, doesn't exist. Compute it and the associated
383 # \epsilon-nonkernel state together; we'll need it right away.
384 #
385 k = self.cores[tcore] = len(self.states)
386 K, NK = _State(k, kitems), _State(k+1, [])
387 self.states[k] = K
388 predicted = {}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000389
Tim Peters536cf992005-12-25 23:18:31 +0000390 edges = self.edges
391 rules = self.newrules
392 for X in K, NK:
393 worklist = X.items
394 for item in worklist:
395 rule, pos = item
396 lhs, rhs = rule
397 if pos == len(rhs):
398 X.complete.append(rule)
399 continue
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000400
Tim Peters536cf992005-12-25 23:18:31 +0000401 nextSym = rhs[pos]
402 key = (X.stateno, nextSym)
Fred Drake34e4f522006-12-29 04:42:48 +0000403 if nextSym not in rules:
404 if key not in edges:
Tim Peters536cf992005-12-25 23:18:31 +0000405 edges[key] = None
406 X.T.append(nextSym)
407 else:
408 edges[key] = None
Fred Drake34e4f522006-12-29 04:42:48 +0000409 if nextSym not in predicted:
Tim Peters536cf992005-12-25 23:18:31 +0000410 predicted[nextSym] = 1
411 for prule in rules[nextSym]:
412 ppos = self.skip(prule)
413 new = (prule, ppos)
414 NK.items.append(new)
415 #
416 # Problem: we know K needs generating, but we
417 # don't yet know about NK. Can't commit anything
418 # regarding NK to self.edges until we're sure. Should
419 # we delay committing on both K and NK to avoid this
420 # hacky code? This creates other problems..
421 #
422 if X is K:
423 edges = {}
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000424
Tim Peters536cf992005-12-25 23:18:31 +0000425 if NK.items == []:
426 return k
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000427
Tim Peters536cf992005-12-25 23:18:31 +0000428 #
429 # Check for \epsilon-nonkernel's core. Unfortunately we
430 # need to know the entire set of predicted nonterminals
431 # to do this without accidentally duplicating states.
432 #
Guido van Rossum805365e2007-05-07 22:24:25 +0000433 core = sorted(predicted.keys())
Tim Peters536cf992005-12-25 23:18:31 +0000434 tcore = tuple(core)
Fred Drake34e4f522006-12-29 04:42:48 +0000435 if tcore in self.cores:
Tim Peters536cf992005-12-25 23:18:31 +0000436 self.edges[(k, None)] = self.cores[tcore]
437 return k
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000438
Tim Peters536cf992005-12-25 23:18:31 +0000439 nk = self.cores[tcore] = self.edges[(k, None)] = NK.stateno
440 self.edges.update(edges)
441 self.states[nk] = NK
442 return k
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000443
Tim Peters536cf992005-12-25 23:18:31 +0000444 def goto(self, state, sym):
445 key = (state, sym)
Fred Drake34e4f522006-12-29 04:42:48 +0000446 if key not in self.edges:
Tim Peters536cf992005-12-25 23:18:31 +0000447 #
448 # No transitions from state on sym.
449 #
450 return None
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000451
Tim Peters536cf992005-12-25 23:18:31 +0000452 rv = self.edges[key]
453 if rv is None:
454 #
455 # Target state isn't generated yet. Remedy this.
456 #
457 rv = self.makeState(state, sym)
458 self.edges[key] = rv
459 return rv
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000460
Tim Peters536cf992005-12-25 23:18:31 +0000461 def gotoT(self, state, t):
462 return [self.goto(state, t)]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000463
Tim Peters536cf992005-12-25 23:18:31 +0000464 def gotoST(self, state, st):
465 rv = []
466 for t in self.states[state].T:
467 if st == t:
468 rv.append(self.goto(state, t))
469 return rv
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000470
Tim Peters536cf992005-12-25 23:18:31 +0000471 def add(self, set, item, i=None, predecessor=None, causal=None):
472 if predecessor is None:
473 if item not in set:
474 set.append(item)
475 else:
476 key = (item, i)
477 if item not in set:
478 self.links[key] = []
479 set.append(item)
480 self.links[key].append((predecessor, causal))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000481
Tim Peters536cf992005-12-25 23:18:31 +0000482 def makeSet(self, token, sets, i):
483 cur, next = sets[i], sets[i+1]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000484
Tim Peters536cf992005-12-25 23:18:31 +0000485 ttype = token is not None and self.typestring(token) or None
486 if ttype is not None:
487 fn, arg = self.gotoT, ttype
488 else:
489 fn, arg = self.gotoST, token
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000490
Tim Peters536cf992005-12-25 23:18:31 +0000491 for item in cur:
492 ptr = (item, i)
493 state, parent = item
494 add = fn(state, arg)
495 for k in add:
496 if k is not None:
497 self.add(next, (k, parent), i+1, ptr)
498 nk = self.goto(k, None)
499 if nk is not None:
500 self.add(next, (nk, i+1))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000501
Tim Peters536cf992005-12-25 23:18:31 +0000502 if parent == i:
503 continue
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000504
Tim Peters536cf992005-12-25 23:18:31 +0000505 for rule in self.states[state].complete:
506 lhs, rhs = rule
507 for pitem in sets[parent]:
508 pstate, pparent = pitem
509 k = self.goto(pstate, lhs)
510 if k is not None:
511 why = (item, i, rule)
512 pptr = (pitem, parent)
513 self.add(cur, (k, pparent),
514 i, pptr, why)
515 nk = self.goto(k, None)
516 if nk is not None:
517 self.add(cur, (nk, i))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000518
Tim Peters536cf992005-12-25 23:18:31 +0000519 def makeSet_fast(self, token, sets, i):
520 #
521 # Call *only* when the entire state machine has been built!
522 # It relies on self.edges being filled in completely, and
523 # then duplicates and inlines code to boost speed at the
524 # cost of extreme ugliness.
525 #
526 cur, next = sets[i], sets[i+1]
527 ttype = token is not None and self.typestring(token) or None
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000528
Tim Peters536cf992005-12-25 23:18:31 +0000529 for item in cur:
530 ptr = (item, i)
531 state, parent = item
532 if ttype is not None:
533 k = self.edges.get((state, ttype), None)
534 if k is not None:
535 #self.add(next, (k, parent), i+1, ptr)
536 #INLINED --v
537 new = (k, parent)
538 key = (new, i+1)
539 if new not in next:
540 self.links[key] = []
541 next.append(new)
542 self.links[key].append((ptr, None))
543 #INLINED --^
544 #nk = self.goto(k, None)
545 nk = self.edges.get((k, None), None)
546 if nk is not None:
547 #self.add(next, (nk, i+1))
548 #INLINED --v
549 new = (nk, i+1)
550 if new not in next:
551 next.append(new)
552 #INLINED --^
553 else:
554 add = self.gotoST(state, token)
555 for k in add:
556 if k is not None:
557 self.add(next, (k, parent), i+1, ptr)
558 #nk = self.goto(k, None)
559 nk = self.edges.get((k, None), None)
560 if nk is not None:
561 self.add(next, (nk, i+1))
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000562
Tim Peters536cf992005-12-25 23:18:31 +0000563 if parent == i:
564 continue
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000565
Tim Peters536cf992005-12-25 23:18:31 +0000566 for rule in self.states[state].complete:
567 lhs, rhs = rule
568 for pitem in sets[parent]:
569 pstate, pparent = pitem
570 #k = self.goto(pstate, lhs)
571 k = self.edges.get((pstate, lhs), None)
572 if k is not None:
573 why = (item, i, rule)
574 pptr = (pitem, parent)
575 #self.add(cur, (k, pparent),
576 # i, pptr, why)
577 #INLINED --v
578 new = (k, pparent)
579 key = (new, i)
580 if new not in cur:
581 self.links[key] = []
582 cur.append(new)
583 self.links[key].append((pptr, why))
584 #INLINED --^
585 #nk = self.goto(k, None)
586 nk = self.edges.get((k, None), None)
587 if nk is not None:
588 #self.add(cur, (nk, i))
589 #INLINED --v
590 new = (nk, i)
591 if new not in cur:
592 cur.append(new)
593 #INLINED --^
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000594
Tim Peters536cf992005-12-25 23:18:31 +0000595 def predecessor(self, key, causal):
596 for p, c in self.links[key]:
597 if c == causal:
598 return p
599 assert 0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000600
Tim Peters536cf992005-12-25 23:18:31 +0000601 def causal(self, key):
602 links = self.links[key]
603 if len(links) == 1:
604 return links[0][1]
605 choices = []
606 rule2cause = {}
607 for p, c in links:
608 rule = c[2]
609 choices.append(rule)
610 rule2cause[rule] = c
611 return rule2cause[self.ambiguity(choices)]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000612
Tim Peters536cf992005-12-25 23:18:31 +0000613 def deriveEpsilon(self, nt):
614 if len(self.newrules[nt]) > 1:
615 rule = self.ambiguity(self.newrules[nt])
616 else:
617 rule = self.newrules[nt][0]
Guido van Rossum805365e2007-05-07 22:24:25 +0000618 #output(rule)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000619
Tim Peters536cf992005-12-25 23:18:31 +0000620 rhs = rule[1]
621 attr = [None] * len(rhs)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000622
Tim Peters536cf992005-12-25 23:18:31 +0000623 for i in range(len(rhs)-1, -1, -1):
624 attr[i] = self.deriveEpsilon(rhs[i])
625 return self.rule2func[self.new2old[rule]](attr)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000626
Tim Peters536cf992005-12-25 23:18:31 +0000627 def buildTree(self, nt, item, tokens, k):
628 state, parent = item
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000629
Tim Peters536cf992005-12-25 23:18:31 +0000630 choices = []
631 for rule in self.states[state].complete:
632 if rule[0] == nt:
633 choices.append(rule)
634 rule = choices[0]
635 if len(choices) > 1:
636 rule = self.ambiguity(choices)
Guido van Rossum805365e2007-05-07 22:24:25 +0000637 #output(rule)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000638
Tim Peters536cf992005-12-25 23:18:31 +0000639 rhs = rule[1]
640 attr = [None] * len(rhs)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000641
Tim Peters536cf992005-12-25 23:18:31 +0000642 for i in range(len(rhs)-1, -1, -1):
643 sym = rhs[i]
Fred Drake34e4f522006-12-29 04:42:48 +0000644 if sym not in self.newrules:
Tim Peters536cf992005-12-25 23:18:31 +0000645 if sym != self._BOF:
646 attr[i] = tokens[k-1]
647 key = (item, k)
648 item, k = self.predecessor(key, None)
649 #elif self.isnullable(sym):
650 elif self._NULLABLE == sym[0:len(self._NULLABLE)]:
651 attr[i] = self.deriveEpsilon(sym)
652 else:
653 key = (item, k)
654 why = self.causal(key)
655 attr[i] = self.buildTree(sym, why[0],
656 tokens, why[1])
657 item, k = self.predecessor(key, why)
658 return self.rule2func[self.new2old[rule]](attr)
659
660 def ambiguity(self, rules):
661 #
662 # XXX - problem here and in collectRules() if the same rule
663 # appears in >1 method. Also undefined results if rules
664 # causing the ambiguity appear in the same method.
665 #
666 sortlist = []
667 name2index = {}
668 for i in range(len(rules)):
669 lhs, rhs = rule = rules[i]
670 name = self.rule2name[self.new2old[rule]]
671 sortlist.append((len(rhs), name))
672 name2index[name] = i
673 sortlist.sort()
Guido van Rossum1bc535d2007-05-15 18:46:22 +0000674 list = [b for a, b in sortlist]
Tim Peters536cf992005-12-25 23:18:31 +0000675 return rules[name2index[self.resolve(list)]]
676
677 def resolve(self, list):
678 #
679 # Resolve ambiguity in favor of the shortest RHS.
680 # Since we walk the tree from the top down, this
681 # should effectively resolve in favor of a "shift".
682 #
683 return list[0]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000684
685#
686# GenericASTBuilder automagically constructs a concrete/abstract syntax tree
687# for a given input. The extra argument is a class (not an instance!)
688# which supports the "__setslice__" and "__len__" methods.
689#
690# XXX - silently overrides any user code in methods.
691#
692
693class GenericASTBuilder(GenericParser):
Tim Peters536cf992005-12-25 23:18:31 +0000694 def __init__(self, AST, start):
695 GenericParser.__init__(self, start)
696 self.AST = AST
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000697
Tim Peters536cf992005-12-25 23:18:31 +0000698 def preprocess(self, rule, func):
699 rebind = lambda lhs, self=self: \
700 lambda args, lhs=lhs, self=self: \
701 self.buildASTNode(args, lhs)
702 lhs, rhs = rule
703 return rule, rebind(lhs)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000704
Tim Peters536cf992005-12-25 23:18:31 +0000705 def buildASTNode(self, args, lhs):
706 children = []
707 for arg in args:
708 if isinstance(arg, self.AST):
709 children.append(arg)
710 else:
711 children.append(self.terminal(arg))
712 return self.nonterminal(lhs, children)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000713
Tim Peters536cf992005-12-25 23:18:31 +0000714 def terminal(self, token): return token
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000715
Tim Peters536cf992005-12-25 23:18:31 +0000716 def nonterminal(self, type, args):
717 rv = self.AST(type)
718 rv[:len(args)] = args
719 return rv
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000720
721#
722# GenericASTTraversal is a Visitor pattern according to Design Patterns. For
723# each node it attempts to invoke the method n_<node type>, falling
724# back onto the default() method if the n_* can't be found. The preorder
725# traversal also looks for an exit hook named n_<node type>_exit (no default
726# routine is called if it's not found). To prematurely halt traversal
727# of a subtree, call the prune() method -- this only makes sense for a
728# preorder traversal. Node type is determined via the typestring() method.
729#
730
731class GenericASTTraversalPruningException:
Tim Peters536cf992005-12-25 23:18:31 +0000732 pass
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000733
734class GenericASTTraversal:
Tim Peters536cf992005-12-25 23:18:31 +0000735 def __init__(self, ast):
736 self.ast = ast
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000737
Tim Peters536cf992005-12-25 23:18:31 +0000738 def typestring(self, node):
739 return node.type
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000740
Tim Peters536cf992005-12-25 23:18:31 +0000741 def prune(self):
742 raise GenericASTTraversalPruningException
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000743
Tim Peters536cf992005-12-25 23:18:31 +0000744 def preorder(self, node=None):
745 if node is None:
746 node = self.ast
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000747
Tim Peters536cf992005-12-25 23:18:31 +0000748 try:
749 name = 'n_' + self.typestring(node)
750 if hasattr(self, name):
751 func = getattr(self, name)
752 func(node)
753 else:
754 self.default(node)
755 except GenericASTTraversalPruningException:
756 return
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000757
Tim Peters536cf992005-12-25 23:18:31 +0000758 for kid in node:
759 self.preorder(kid)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000760
Tim Peters536cf992005-12-25 23:18:31 +0000761 name = name + '_exit'
762 if hasattr(self, name):
763 func = getattr(self, name)
764 func(node)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000765
Tim Peters536cf992005-12-25 23:18:31 +0000766 def postorder(self, node=None):
767 if node is None:
768 node = self.ast
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000769
Tim Peters536cf992005-12-25 23:18:31 +0000770 for kid in node:
771 self.postorder(kid)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000772
Tim Peters536cf992005-12-25 23:18:31 +0000773 name = 'n_' + self.typestring(node)
774 if hasattr(self, name):
775 func = getattr(self, name)
776 func(node)
777 else:
778 self.default(node)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000779
780
Tim Peters536cf992005-12-25 23:18:31 +0000781 def default(self, node):
782 pass
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000783
784#
785# GenericASTMatcher. AST nodes must have "__getitem__" and "__cmp__"
786# implemented.
787#
788# XXX - makes assumptions about how GenericParser walks the parse tree.
789#
790
791class GenericASTMatcher(GenericParser):
Tim Peters536cf992005-12-25 23:18:31 +0000792 def __init__(self, start, ast):
793 GenericParser.__init__(self, start)
794 self.ast = ast
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000795
Tim Peters536cf992005-12-25 23:18:31 +0000796 def preprocess(self, rule, func):
797 rebind = lambda func, self=self: \
798 lambda args, func=func, self=self: \
799 self.foundMatch(args, func)
800 lhs, rhs = rule
801 rhslist = list(rhs)
802 rhslist.reverse()
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000803
Tim Peters536cf992005-12-25 23:18:31 +0000804 return (lhs, tuple(rhslist)), rebind(func)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000805
Tim Peters536cf992005-12-25 23:18:31 +0000806 def foundMatch(self, args, func):
807 func(args[-1])
808 return args[-1]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000809
Tim Peters536cf992005-12-25 23:18:31 +0000810 def match_r(self, node):
811 self.input.insert(0, node)
812 children = 0
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000813
Tim Peters536cf992005-12-25 23:18:31 +0000814 for child in node:
815 if children == 0:
816 self.input.insert(0, '(')
817 children = children + 1
818 self.match_r(child)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000819
Tim Peters536cf992005-12-25 23:18:31 +0000820 if children > 0:
821 self.input.insert(0, ')')
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000822
Tim Peters536cf992005-12-25 23:18:31 +0000823 def match(self, ast=None):
824 if ast is None:
825 ast = self.ast
826 self.input = []
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000827
Tim Peters536cf992005-12-25 23:18:31 +0000828 self.match_r(ast)
829 self.parse(self.input)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000830
Tim Peters536cf992005-12-25 23:18:31 +0000831 def resolve(self, list):
832 #
833 # Resolve ambiguity in favor of the longest RHS.
834 #
835 return list[-1]
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000836
837def _dump(tokens, sets, states):
Tim Peters536cf992005-12-25 23:18:31 +0000838 for i in range(len(sets)):
Guido van Rossum805365e2007-05-07 22:24:25 +0000839 output('set %d' % i)
Tim Peters536cf992005-12-25 23:18:31 +0000840 for item in sets[i]:
Guido van Rossum805365e2007-05-07 22:24:25 +0000841 output('\t', item)
Tim Peters536cf992005-12-25 23:18:31 +0000842 for (lhs, rhs), pos in states[item[0]].items:
Guido van Rossum805365e2007-05-07 22:24:25 +0000843 output('\t\t', lhs, '::=', end='')
844 output(' '.join(rhs[:pos]), end='')
845 output('.', end='')
846 output(' '.join(rhs[pos:]))
Tim Peters536cf992005-12-25 23:18:31 +0000847 if i < len(tokens):
Guido van Rossum805365e2007-05-07 22:24:25 +0000848 output()
849 output('token %s' % str(tokens[i]))
850 output()