PageRenderTime 56ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/pypy/interpreter/astcompiler/tools/spark.py

https://bitbucket.org/evelyn559/pypy
Python | 839 lines | 581 code | 108 blank | 150 comment | 154 complexity | 2de21da9d72dca8e132ce15164bda51b MD5 | raw file
  1. # Copyright (c) 1998-2002 John Aycock
  2. #
  3. # 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:
  10. #
  11. # The above copyright notice and this permission notice shall be
  12. # included in all copies or substantial portions of the Software.
  13. #
  14. # 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. __version__ = 'SPARK-0.7 (pre-alpha-5)'
  22. import re
  23. import string
  24. def _namelist(instance):
  25. namelist, namedict, classlist = [], {}, [instance.__class__]
  26. for c in classlist:
  27. for b in c.__bases__:
  28. classlist.append(b)
  29. for name in c.__dict__.keys():
  30. if not namedict.has_key(name):
  31. namelist.append(name)
  32. namedict[name] = 1
  33. return namelist
  34. class GenericScanner:
  35. def __init__(self, flags=0):
  36. pattern = self.reflect()
  37. self.re = re.compile(pattern, re.VERBOSE|flags)
  38. self.index2func = {}
  39. for name, number in self.re.groupindex.items():
  40. self.index2func[number-1] = getattr(self, 't_' + name)
  41. def makeRE(self, name):
  42. doc = getattr(self, name).__doc__
  43. rv = '(?P<%s>%s)' % (name[2:], doc)
  44. return rv
  45. def reflect(self):
  46. rv = []
  47. for name in _namelist(self):
  48. if name[:2] == 't_' and name != 't_default':
  49. rv.append(self.makeRE(name))
  50. rv.append(self.makeRE('t_default'))
  51. return string.join(rv, '|')
  52. def error(self, s, pos):
  53. print "Lexical error at position %s" % pos
  54. raise SystemExit
  55. def tokenize(self, s):
  56. pos = 0
  57. n = len(s)
  58. while pos < n:
  59. m = self.re.match(s, pos)
  60. if m is None:
  61. self.error(s, pos)
  62. groups = m.groups()
  63. for i in range(len(groups)):
  64. if groups[i] and self.index2func.has_key(i):
  65. self.index2func[i](groups[i])
  66. pos = m.end()
  67. def t_default(self, s):
  68. r'( . | \n )+'
  69. print "Specification error: unmatched input"
  70. raise SystemExit
  71. #
  72. # Extracted from GenericParser and made global so that [un]picking works.
  73. #
  74. class _State:
  75. def __init__(self, stateno, items):
  76. self.T, self.complete, self.items = [], [], items
  77. self.stateno = stateno
  78. class GenericParser:
  79. #
  80. # An Earley parser, as per J. Earley, "An Efficient Context-Free
  81. # Parsing Algorithm", CACM 13(2), pp. 94-102. Also J. C. Earley,
  82. # "An Efficient Context-Free Parsing Algorithm", Ph.D. thesis,
  83. # Carnegie-Mellon University, August 1968. New formulation of
  84. # the parser according to J. Aycock, "Practical Earley Parsing
  85. # and the SPARK Toolkit", Ph.D. thesis, University of Victoria,
  86. # 2001, and J. Aycock and R. N. Horspool, "Practical Earley
  87. # Parsing", unpublished paper, 2001.
  88. #
  89. def __init__(self, start):
  90. self.rules = {}
  91. self.rule2func = {}
  92. self.rule2name = {}
  93. self.collectRules()
  94. self.augment(start)
  95. self.ruleschanged = 1
  96. _NULLABLE = '\e_'
  97. _START = 'START'
  98. _BOF = '|-'
  99. #
  100. # When pickling, take the time to generate the full state machine;
  101. # some information is then extraneous, too. Unfortunately we
  102. # can't save the rule2func map.
  103. #
  104. def __getstate__(self):
  105. if self.ruleschanged:
  106. #
  107. # XXX - duplicated from parse()
  108. #
  109. self.computeNull()
  110. self.newrules = {}
  111. self.new2old = {}
  112. self.makeNewRules()
  113. self.ruleschanged = 0
  114. self.edges, self.cores = {}, {}
  115. self.states = { 0: self.makeState0() }
  116. self.makeState(0, self._BOF)
  117. #
  118. # XXX - should find a better way to do this..
  119. #
  120. changes = 1
  121. while changes:
  122. changes = 0
  123. for k, v in self.edges.items():
  124. if v is None:
  125. state, sym = k
  126. if self.states.has_key(state):
  127. self.goto(state, sym)
  128. changes = 1
  129. rv = self.__dict__.copy()
  130. for s in self.states.values():
  131. del s.items
  132. del rv['rule2func']
  133. del rv['nullable']
  134. del rv['cores']
  135. return rv
  136. def __setstate__(self, D):
  137. self.rules = {}
  138. self.rule2func = {}
  139. self.rule2name = {}
  140. self.collectRules()
  141. start = D['rules'][self._START][0][1][1] # Blech.
  142. self.augment(start)
  143. D['rule2func'] = self.rule2func
  144. D['makeSet'] = self.makeSet_fast
  145. self.__dict__ = D
  146. #
  147. # A hook for GenericASTBuilder and GenericASTMatcher. Mess
  148. # thee not with this; nor shall thee toucheth the _preprocess
  149. # argument to addRule.
  150. #
  151. def preprocess(self, rule, func): return rule, func
  152. def addRule(self, doc, func, _preprocess=1):
  153. fn = func
  154. rules = string.split(doc)
  155. index = []
  156. for i in range(len(rules)):
  157. if rules[i] == '::=':
  158. index.append(i-1)
  159. index.append(len(rules))
  160. for i in range(len(index)-1):
  161. lhs = rules[index[i]]
  162. rhs = rules[index[i]+2:index[i+1]]
  163. rule = (lhs, tuple(rhs))
  164. if _preprocess:
  165. rule, fn = self.preprocess(rule, func)
  166. if self.rules.has_key(lhs):
  167. self.rules[lhs].append(rule)
  168. else:
  169. self.rules[lhs] = [ rule ]
  170. self.rule2func[rule] = fn
  171. self.rule2name[rule] = func.__name__[2:]
  172. self.ruleschanged = 1
  173. def collectRules(self):
  174. for name in _namelist(self):
  175. if name[:2] == 'p_':
  176. func = getattr(self, name)
  177. doc = func.__doc__
  178. self.addRule(doc, func)
  179. def augment(self, start):
  180. rule = '%s ::= %s %s' % (self._START, self._BOF, start)
  181. self.addRule(rule, lambda args: args[1], 0)
  182. def computeNull(self):
  183. self.nullable = {}
  184. tbd = []
  185. for rulelist in self.rules.values():
  186. lhs = rulelist[0][0]
  187. self.nullable[lhs] = 0
  188. for rule in rulelist:
  189. rhs = rule[1]
  190. if len(rhs) == 0:
  191. self.nullable[lhs] = 1
  192. continue
  193. #
  194. # We only need to consider rules which
  195. # consist entirely of nonterminal symbols.
  196. # This should be a savings on typical
  197. # grammars.
  198. #
  199. for sym in rhs:
  200. if not self.rules.has_key(sym):
  201. break
  202. else:
  203. tbd.append(rule)
  204. changes = 1
  205. while changes:
  206. changes = 0
  207. for lhs, rhs in tbd:
  208. if self.nullable[lhs]:
  209. continue
  210. for sym in rhs:
  211. if not self.nullable[sym]:
  212. break
  213. else:
  214. self.nullable[lhs] = 1
  215. changes = 1
  216. def makeState0(self):
  217. s0 = _State(0, [])
  218. for rule in self.newrules[self._START]:
  219. s0.items.append((rule, 0))
  220. return s0
  221. def finalState(self, tokens):
  222. #
  223. # Yuck.
  224. #
  225. if len(self.newrules[self._START]) == 2 and len(tokens) == 0:
  226. return 1
  227. start = self.rules[self._START][0][1][1]
  228. return self.goto(1, start)
  229. def makeNewRules(self):
  230. worklist = []
  231. for rulelist in self.rules.values():
  232. for rule in rulelist:
  233. worklist.append((rule, 0, 1, rule))
  234. for rule, i, candidate, oldrule in worklist:
  235. lhs, rhs = rule
  236. n = len(rhs)
  237. while i < n:
  238. sym = rhs[i]
  239. if not self.rules.has_key(sym) or \
  240. not self.nullable[sym]:
  241. candidate = 0
  242. i = i + 1
  243. continue
  244. newrhs = list(rhs)
  245. newrhs[i] = self._NULLABLE+sym
  246. newrule = (lhs, tuple(newrhs))
  247. worklist.append((newrule, i+1,
  248. candidate, oldrule))
  249. candidate = 0
  250. i = i + 1
  251. else:
  252. if candidate:
  253. lhs = self._NULLABLE+lhs
  254. rule = (lhs, rhs)
  255. if self.newrules.has_key(lhs):
  256. self.newrules[lhs].append(rule)
  257. else:
  258. self.newrules[lhs] = [ rule ]
  259. self.new2old[rule] = oldrule
  260. def typestring(self, token):
  261. return None
  262. def error(self, token):
  263. print "Syntax error at or near `%s' token" % token
  264. raise SystemExit
  265. def parse(self, tokens):
  266. sets = [ [(1,0), (2,0)] ]
  267. self.links = {}
  268. if self.ruleschanged:
  269. self.computeNull()
  270. self.newrules = {}
  271. self.new2old = {}
  272. self.makeNewRules()
  273. self.ruleschanged = 0
  274. self.edges, self.cores = {}, {}
  275. self.states = { 0: self.makeState0() }
  276. self.makeState(0, self._BOF)
  277. for i in xrange(len(tokens)):
  278. sets.append([])
  279. if sets[i] == []:
  280. break
  281. self.makeSet(tokens[i], sets, i)
  282. else:
  283. sets.append([])
  284. self.makeSet(None, sets, len(tokens))
  285. #_dump(tokens, sets, self.states)
  286. finalitem = (self.finalState(tokens), 0)
  287. if finalitem not in sets[-2]:
  288. if len(tokens) > 0:
  289. self.error(tokens[i-1])
  290. else:
  291. self.error(None)
  292. return self.buildTree(self._START, finalitem,
  293. tokens, len(sets)-2)
  294. def isnullable(self, sym):
  295. #
  296. # For symbols in G_e only. If we weren't supporting 1.5,
  297. # could just use sym.startswith().
  298. #
  299. return self._NULLABLE == sym[0:len(self._NULLABLE)]
  300. def skip(self, (lhs, rhs), pos=0):
  301. n = len(rhs)
  302. while pos < n:
  303. if not self.isnullable(rhs[pos]):
  304. break
  305. pos = pos + 1
  306. return pos
  307. def makeState(self, state, sym):
  308. assert sym is not None
  309. #
  310. # Compute \epsilon-kernel state's core and see if
  311. # it exists already.
  312. #
  313. kitems = []
  314. for rule, pos in self.states[state].items:
  315. lhs, rhs = rule
  316. if rhs[pos:pos+1] == (sym,):
  317. kitems.append((rule, self.skip(rule, pos+1)))
  318. core = kitems
  319. core.sort()
  320. tcore = tuple(core)
  321. if self.cores.has_key(tcore):
  322. return self.cores[tcore]
  323. #
  324. # Nope, doesn't exist. Compute it and the associated
  325. # \epsilon-nonkernel state together; we'll need it right away.
  326. #
  327. k = self.cores[tcore] = len(self.states)
  328. K, NK = _State(k, kitems), _State(k+1, [])
  329. self.states[k] = K
  330. predicted = {}
  331. edges = self.edges
  332. rules = self.newrules
  333. for X in K, NK:
  334. worklist = X.items
  335. for item in worklist:
  336. rule, pos = item
  337. lhs, rhs = rule
  338. if pos == len(rhs):
  339. X.complete.append(rule)
  340. continue
  341. nextSym = rhs[pos]
  342. key = (X.stateno, nextSym)
  343. if not rules.has_key(nextSym):
  344. if not edges.has_key(key):
  345. edges[key] = None
  346. X.T.append(nextSym)
  347. else:
  348. edges[key] = None
  349. if not predicted.has_key(nextSym):
  350. predicted[nextSym] = 1
  351. for prule in rules[nextSym]:
  352. ppos = self.skip(prule)
  353. new = (prule, ppos)
  354. NK.items.append(new)
  355. #
  356. # Problem: we know K needs generating, but we
  357. # don't yet know about NK. Can't commit anything
  358. # regarding NK to self.edges until we're sure. Should
  359. # we delay committing on both K and NK to avoid this
  360. # hacky code? This creates other problems..
  361. #
  362. if X is K:
  363. edges = {}
  364. if NK.items == []:
  365. return k
  366. #
  367. # Check for \epsilon-nonkernel's core. Unfortunately we
  368. # need to know the entire set of predicted nonterminals
  369. # to do this without accidentally duplicating states.
  370. #
  371. core = predicted.keys()
  372. core.sort()
  373. tcore = tuple(core)
  374. if self.cores.has_key(tcore):
  375. self.edges[(k, None)] = self.cores[tcore]
  376. return k
  377. nk = self.cores[tcore] = self.edges[(k, None)] = NK.stateno
  378. self.edges.update(edges)
  379. self.states[nk] = NK
  380. return k
  381. def goto(self, state, sym):
  382. key = (state, sym)
  383. if not self.edges.has_key(key):
  384. #
  385. # No transitions from state on sym.
  386. #
  387. return None
  388. rv = self.edges[key]
  389. if rv is None:
  390. #
  391. # Target state isn't generated yet. Remedy this.
  392. #
  393. rv = self.makeState(state, sym)
  394. self.edges[key] = rv
  395. return rv
  396. def gotoT(self, state, t):
  397. return [self.goto(state, t)]
  398. def gotoST(self, state, st):
  399. rv = []
  400. for t in self.states[state].T:
  401. if st == t:
  402. rv.append(self.goto(state, t))
  403. return rv
  404. def add(self, set, item, i=None, predecessor=None, causal=None):
  405. if predecessor is None:
  406. if item not in set:
  407. set.append(item)
  408. else:
  409. key = (item, i)
  410. if item not in set:
  411. self.links[key] = []
  412. set.append(item)
  413. self.links[key].append((predecessor, causal))
  414. def makeSet(self, token, sets, i):
  415. cur, next = sets[i], sets[i+1]
  416. ttype = token is not None and self.typestring(token) or None
  417. if ttype is not None:
  418. fn, arg = self.gotoT, ttype
  419. else:
  420. fn, arg = self.gotoST, token
  421. for item in cur:
  422. ptr = (item, i)
  423. state, parent = item
  424. add = fn(state, arg)
  425. for k in add:
  426. if k is not None:
  427. self.add(next, (k, parent), i+1, ptr)
  428. nk = self.goto(k, None)
  429. if nk is not None:
  430. self.add(next, (nk, i+1))
  431. if parent == i:
  432. continue
  433. for rule in self.states[state].complete:
  434. lhs, rhs = rule
  435. for pitem in sets[parent]:
  436. pstate, pparent = pitem
  437. k = self.goto(pstate, lhs)
  438. if k is not None:
  439. why = (item, i, rule)
  440. pptr = (pitem, parent)
  441. self.add(cur, (k, pparent),
  442. i, pptr, why)
  443. nk = self.goto(k, None)
  444. if nk is not None:
  445. self.add(cur, (nk, i))
  446. def makeSet_fast(self, token, sets, i):
  447. #
  448. # Call *only* when the entire state machine has been built!
  449. # It relies on self.edges being filled in completely, and
  450. # then duplicates and inlines code to boost speed at the
  451. # cost of extreme ugliness.
  452. #
  453. cur, next = sets[i], sets[i+1]
  454. ttype = token is not None and self.typestring(token) or None
  455. for item in cur:
  456. ptr = (item, i)
  457. state, parent = item
  458. if ttype is not None:
  459. k = self.edges.get((state, ttype), None)
  460. if k is not None:
  461. #self.add(next, (k, parent), i+1, ptr)
  462. #INLINED --v
  463. new = (k, parent)
  464. key = (new, i+1)
  465. if new not in next:
  466. self.links[key] = []
  467. next.append(new)
  468. self.links[key].append((ptr, None))
  469. #INLINED --^
  470. #nk = self.goto(k, None)
  471. nk = self.edges.get((k, None), None)
  472. if nk is not None:
  473. #self.add(next, (nk, i+1))
  474. #INLINED --v
  475. new = (nk, i+1)
  476. if new not in next:
  477. next.append(new)
  478. #INLINED --^
  479. else:
  480. add = self.gotoST(state, token)
  481. for k in add:
  482. if k is not None:
  483. self.add(next, (k, parent), i+1, ptr)
  484. #nk = self.goto(k, None)
  485. nk = self.edges.get((k, None), None)
  486. if nk is not None:
  487. self.add(next, (nk, i+1))
  488. if parent == i:
  489. continue
  490. for rule in self.states[state].complete:
  491. lhs, rhs = rule
  492. for pitem in sets[parent]:
  493. pstate, pparent = pitem
  494. #k = self.goto(pstate, lhs)
  495. k = self.edges.get((pstate, lhs), None)
  496. if k is not None:
  497. why = (item, i, rule)
  498. pptr = (pitem, parent)
  499. #self.add(cur, (k, pparent),
  500. # i, pptr, why)
  501. #INLINED --v
  502. new = (k, pparent)
  503. key = (new, i)
  504. if new not in cur:
  505. self.links[key] = []
  506. cur.append(new)
  507. self.links[key].append((pptr, why))
  508. #INLINED --^
  509. #nk = self.goto(k, None)
  510. nk = self.edges.get((k, None), None)
  511. if nk is not None:
  512. #self.add(cur, (nk, i))
  513. #INLINED --v
  514. new = (nk, i)
  515. if new not in cur:
  516. cur.append(new)
  517. #INLINED --^
  518. def predecessor(self, key, causal):
  519. for p, c in self.links[key]:
  520. if c == causal:
  521. return p
  522. assert 0
  523. def causal(self, key):
  524. links = self.links[key]
  525. if len(links) == 1:
  526. return links[0][1]
  527. choices = []
  528. rule2cause = {}
  529. for p, c in links:
  530. rule = c[2]
  531. choices.append(rule)
  532. rule2cause[rule] = c
  533. return rule2cause[self.ambiguity(choices)]
  534. def deriveEpsilon(self, nt):
  535. if len(self.newrules[nt]) > 1:
  536. rule = self.ambiguity(self.newrules[nt])
  537. else:
  538. rule = self.newrules[nt][0]
  539. #print rule
  540. rhs = rule[1]
  541. attr = [None] * len(rhs)
  542. for i in range(len(rhs)-1, -1, -1):
  543. attr[i] = self.deriveEpsilon(rhs[i])
  544. return self.rule2func[self.new2old[rule]](attr)
  545. def buildTree(self, nt, item, tokens, k):
  546. state, parent = item
  547. choices = []
  548. for rule in self.states[state].complete:
  549. if rule[0] == nt:
  550. choices.append(rule)
  551. rule = choices[0]
  552. if len(choices) > 1:
  553. rule = self.ambiguity(choices)
  554. #print rule
  555. rhs = rule[1]
  556. attr = [None] * len(rhs)
  557. for i in range(len(rhs)-1, -1, -1):
  558. sym = rhs[i]
  559. if not self.newrules.has_key(sym):
  560. if sym != self._BOF:
  561. attr[i] = tokens[k-1]
  562. key = (item, k)
  563. item, k = self.predecessor(key, None)
  564. #elif self.isnullable(sym):
  565. elif self._NULLABLE == sym[0:len(self._NULLABLE)]:
  566. attr[i] = self.deriveEpsilon(sym)
  567. else:
  568. key = (item, k)
  569. why = self.causal(key)
  570. attr[i] = self.buildTree(sym, why[0],
  571. tokens, why[1])
  572. item, k = self.predecessor(key, why)
  573. return self.rule2func[self.new2old[rule]](attr)
  574. def ambiguity(self, rules):
  575. #
  576. # XXX - problem here and in collectRules() if the same rule
  577. # appears in >1 method. Also undefined results if rules
  578. # causing the ambiguity appear in the same method.
  579. #
  580. sortlist = []
  581. name2index = {}
  582. for i in range(len(rules)):
  583. lhs, rhs = rule = rules[i]
  584. name = self.rule2name[self.new2old[rule]]
  585. sortlist.append((len(rhs), name))
  586. name2index[name] = i
  587. sortlist.sort()
  588. list = map(lambda (a,b): b, sortlist)
  589. return rules[name2index[self.resolve(list)]]
  590. def resolve(self, list):
  591. #
  592. # Resolve ambiguity in favor of the shortest RHS.
  593. # Since we walk the tree from the top down, this
  594. # should effectively resolve in favor of a "shift".
  595. #
  596. return list[0]
  597. #
  598. # GenericASTBuilder automagically constructs a concrete/abstract syntax tree
  599. # for a given input. The extra argument is a class (not an instance!)
  600. # which supports the "__setslice__" and "__len__" methods.
  601. #
  602. # XXX - silently overrides any user code in methods.
  603. #
  604. class GenericASTBuilder(GenericParser):
  605. def __init__(self, AST, start):
  606. GenericParser.__init__(self, start)
  607. self.AST = AST
  608. def preprocess(self, rule, func):
  609. rebind = lambda lhs, self=self: \
  610. lambda args, lhs=lhs, self=self: \
  611. self.buildASTNode(args, lhs)
  612. lhs, rhs = rule
  613. return rule, rebind(lhs)
  614. def buildASTNode(self, args, lhs):
  615. children = []
  616. for arg in args:
  617. if isinstance(arg, self.AST):
  618. children.append(arg)
  619. else:
  620. children.append(self.terminal(arg))
  621. return self.nonterminal(lhs, children)
  622. def terminal(self, token): return token
  623. def nonterminal(self, type, args):
  624. rv = self.AST(type)
  625. rv[:len(args)] = args
  626. return rv
  627. #
  628. # GenericASTTraversal is a Visitor pattern according to Design Patterns. For
  629. # each node it attempts to invoke the method n_<node type>, falling
  630. # back onto the default() method if the n_* can't be found. The preorder
  631. # traversal also looks for an exit hook named n_<node type>_exit (no default
  632. # routine is called if it's not found). To prematurely halt traversal
  633. # of a subtree, call the prune() method -- this only makes sense for a
  634. # preorder traversal. Node type is determined via the typestring() method.
  635. #
  636. class GenericASTTraversalPruningException:
  637. pass
  638. class GenericASTTraversal:
  639. def __init__(self, ast):
  640. self.ast = ast
  641. def typestring(self, node):
  642. return node.type
  643. def prune(self):
  644. raise GenericASTTraversalPruningException
  645. def preorder(self, node=None):
  646. if node is None:
  647. node = self.ast
  648. try:
  649. name = 'n_' + self.typestring(node)
  650. if hasattr(self, name):
  651. func = getattr(self, name)
  652. func(node)
  653. else:
  654. self.default(node)
  655. except GenericASTTraversalPruningException:
  656. return
  657. for kid in node:
  658. self.preorder(kid)
  659. name = name + '_exit'
  660. if hasattr(self, name):
  661. func = getattr(self, name)
  662. func(node)
  663. def postorder(self, node=None):
  664. if node is None:
  665. node = self.ast
  666. for kid in node:
  667. self.postorder(kid)
  668. name = 'n_' + self.typestring(node)
  669. if hasattr(self, name):
  670. func = getattr(self, name)
  671. func(node)
  672. else:
  673. self.default(node)
  674. def default(self, node):
  675. pass
  676. #
  677. # GenericASTMatcher. AST nodes must have "__getitem__" and "__cmp__"
  678. # implemented.
  679. #
  680. # XXX - makes assumptions about how GenericParser walks the parse tree.
  681. #
  682. class GenericASTMatcher(GenericParser):
  683. def __init__(self, start, ast):
  684. GenericParser.__init__(self, start)
  685. self.ast = ast
  686. def preprocess(self, rule, func):
  687. rebind = lambda func, self=self: \
  688. lambda args, func=func, self=self: \
  689. self.foundMatch(args, func)
  690. lhs, rhs = rule
  691. rhslist = list(rhs)
  692. rhslist.reverse()
  693. return (lhs, tuple(rhslist)), rebind(func)
  694. def foundMatch(self, args, func):
  695. func(args[-1])
  696. return args[-1]
  697. def match_r(self, node):
  698. self.input.insert(0, node)
  699. children = 0
  700. for child in node:
  701. if children == 0:
  702. self.input.insert(0, '(')
  703. children = children + 1
  704. self.match_r(child)
  705. if children > 0:
  706. self.input.insert(0, ')')
  707. def match(self, ast=None):
  708. if ast is None:
  709. ast = self.ast
  710. self.input = []
  711. self.match_r(ast)
  712. self.parse(self.input)
  713. def resolve(self, list):
  714. #
  715. # Resolve ambiguity in favor of the longest RHS.
  716. #
  717. return list[-1]
  718. def _dump(tokens, sets, states):
  719. for i in range(len(sets)):
  720. print 'set', i
  721. for item in sets[i]:
  722. print '\t', item
  723. for (lhs, rhs), pos in states[item[0]].items:
  724. print '\t\t', lhs, '::=',
  725. print string.join(rhs[:pos]),
  726. print '.',
  727. print string.join(rhs[pos:])
  728. if i < len(tokens):
  729. print
  730. print 'token', str(tokens[i])
  731. print