spark.py 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088
  1. """
  2. Copyright (c) 2015-2017, 2020, 2023 Rocky Bernstein
  3. Copyright (c) 1998-2002 John Aycock
  4. Permission is hereby granted, free of charge, to any person obtaining
  5. a copy of this software and associated documentation files (the
  6. "Software"), to deal in the Software without restriction, including
  7. without limitation the rights to use, copy, modify, merge, publish,
  8. distribute, sublicense, and/or sell copies of the Software, and to
  9. permit persons to whom the Software is furnished to do so, subject to
  10. the following conditions:
  11. The above copyright notice and this permission notice shall be
  12. included in all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  14. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  15. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  16. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  17. CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  18. TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  19. SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  20. """
  21. import os
  22. import pickle
  23. import re
  24. import sys
  25. if sys.version[0:3] <= "2.3":
  26. from sets import Set as set
  27. def sorted(iterable):
  28. temp = [x for x in iterable]
  29. temp.sort()
  30. return temp
  31. def _namelist(instance):
  32. namelist, namedict, classlist = [], {}, [instance.__class__]
  33. for c in classlist:
  34. for b in c.__bases__:
  35. classlist.append(b)
  36. for name in list(c.__dict__.keys()):
  37. if name not in namedict:
  38. namelist.append(name)
  39. namedict[name] = 1
  40. return namelist
  41. def rule2str(rule):
  42. return ("%s ::= %s" % (rule[0], " ".join(rule[1]))).rstrip()
  43. class _State:
  44. """
  45. Extracted from GenericParser and made global so that [un]picking works.
  46. """
  47. def __init__(self, stateno, items):
  48. self.T, self.complete, self.items = [], [], items
  49. self.stateno = stateno
  50. # DEFAULT_DEBUG = {'rules': True, 'transition': True, 'reduce' : True,
  51. # 'errorstack': 'full', 'dups': False }
  52. # DEFAULT_DEBUG = {'rules': False, 'transition': False, 'reduce' : True,
  53. # 'errorstack': 'plain', 'dups': False }
  54. DEFAULT_DEBUG = {
  55. "rules": False,
  56. "transition": False,
  57. "reduce": False,
  58. "errorstack": None,
  59. "context": True,
  60. "dups": False,
  61. }
  62. class GenericParser(object):
  63. """
  64. An Earley parser, as per J. Earley, "An Efficient Context-Free
  65. Parsing Algorithm", CACM 13(2), pp. 94-102. Also J. C. Earley,
  66. "An Efficient Context-Free Parsing Algorithm", Ph.D. thesis,
  67. Carnegie-Mellon University, August 1968. New formulation of
  68. the parser according to J. Aycock, "Practical Earley Parsing
  69. and the SPARK Toolkit", Ph.D. thesis, University of Victoria,
  70. 2001, and J. Aycock and R. N. Horspool, "Practical Earley
  71. Parsing", unpublished paper, 2001.
  72. """
  73. def __init__(self, start, debug=DEFAULT_DEBUG, coverage_path=None):
  74. """_start_ : grammar start symbol;
  75. _debug_ : produce optional parsing debug information
  76. _profile_ : if not None should be a file path to open
  77. with where to store profile is stored
  78. """
  79. self.rules = {}
  80. self.rule2func = {}
  81. self.rule2name = {}
  82. # grammar coverage information
  83. self.coverage_path = coverage_path
  84. if coverage_path:
  85. self.profile_info = {}
  86. if isinstance(coverage_path, str):
  87. if os.path.exists(coverage_path):
  88. self.profile_info = pickle.load(open(coverage_path, "rb"))
  89. else:
  90. self.profile_info = None
  91. # When set, shows additional debug output
  92. self.debug = debug
  93. # Have a place to tag list-like rules. These include rules of the form:
  94. # a ::= x+
  95. # b ::= x*
  96. #
  97. # These kinds of rules, we should create as a list when building a
  98. # parse tree rather than a sequence of nested derivations
  99. self.list_like_nt = set()
  100. self.optional_nt = set()
  101. self.collectRules()
  102. if start not in self.rules:
  103. raise TypeError('Start symbol "%s" is not in LHS of any rule' % start)
  104. self.augment(start)
  105. self.ruleschanged = True
  106. # The key is an LHS non-terminal string. The value
  107. # should be AST if you want to pass an AST to the routine
  108. # to do the checking. The routine called is
  109. # self.reduce_is_invalid and is passed the rule,
  110. # the list of tokens, the current state item,
  111. # and index of the next last token index and
  112. # the first token index for the reduction.
  113. self.check_reduce = {}
  114. _NULLABLE = r"\e_"
  115. _START = "START"
  116. _BOF = "|-"
  117. #
  118. # When pickling, take the time to generate the full state machine;
  119. # some information is then extraneous, too. Unfortunately we
  120. # can't save the rule2func map.
  121. #
  122. def __getstate__(self):
  123. if self.ruleschanged:
  124. #
  125. # XXX - duplicated from parse()
  126. #
  127. self.computeNull()
  128. self.newrules = {}
  129. self.new2old = {}
  130. self.makeNewRules()
  131. self.ruleschanged = False
  132. self.edges, self.cores = {}, {}
  133. self.states = {0: self.makeState0()}
  134. self.makeState(0, self._BOF)
  135. #
  136. # XXX - should find a better way to do this..
  137. #
  138. changes = True
  139. while changes:
  140. changes = False
  141. for k, v in list(self.edges.items()):
  142. if v is None:
  143. state, sym = k
  144. if state in self.states:
  145. self.goto(state, sym)
  146. changes = True
  147. rv = self.__dict__.copy()
  148. for s in list(self.states.values()):
  149. del s.items
  150. del rv["rule2func"]
  151. del rv["nullable"]
  152. del rv["cores"]
  153. return rv
  154. def __setstate__(self, D):
  155. self.rules = {}
  156. self.rule2func = {}
  157. self.rule2name = {}
  158. self.collectRules()
  159. start = D["rules"][self._START][0][1][1] # Blech.
  160. self.augment(start)
  161. D["rule2func"] = self.rule2func
  162. D["makeSet"] = self.makeSet_fast
  163. self.__dict__ = D
  164. #
  165. # A hook for GenericASTBuilder and GenericASTMatcher. Mess
  166. # thee not with this; nor shall thee toucheth the _preprocess
  167. # argument to addRule.
  168. #
  169. def preprocess(self, rule, func):
  170. return rule, func
  171. def addRule(self, doc, func, _preprocess=True):
  172. """Add a grammar rules to _self.rules_, _self.rule2func_,
  173. and _self.rule2name_
  174. Comments, lines starting with # and blank lines are stripped from
  175. doc. We also allow limited form of * and + when there it is of
  176. the RHS has a single item, e.g.
  177. stmts ::= stmt+
  178. """
  179. fn = func
  180. # remove blanks lines and comment lines, e.g. lines starting with "#"
  181. doc = os.linesep.join(
  182. [s for s in doc.splitlines() if s and not re.match(r"^\s*#", s)]
  183. )
  184. rules = doc.split()
  185. index = []
  186. for i in range(len(rules)):
  187. if rules[i] == "::=":
  188. index.append(i - 1)
  189. index.append(len(rules))
  190. for i in range(len(index) - 1):
  191. lhs = rules[index[i]]
  192. rhs = rules[index[i] + 2 : index[i + 1]]
  193. rule = (lhs, tuple(rhs))
  194. if _preprocess:
  195. rule, fn = self.preprocess(rule, func)
  196. # Handle a stripped-down form of *, +, and ?:
  197. # allow only one nonterminal on the right-hand side
  198. if len(rule[1]) == 1:
  199. if rule[1][0] == rule[0]:
  200. raise TypeError("Complete recursive rule %s" % rule2str(rule))
  201. repeat = rule[1][-1][-1]
  202. if repeat in ("*", "+", "?"):
  203. nt = rule[1][-1][:-1]
  204. if repeat == "?":
  205. new_rule_pair = [rule[0], list((nt,))]
  206. self.optional_nt.add(rule[0])
  207. else:
  208. self.list_like_nt.add(rule[0])
  209. new_rule_pair = [rule[0], [rule[0]] + list((nt,))]
  210. new_rule = rule2str(new_rule_pair)
  211. self.addRule(new_rule, func, _preprocess)
  212. if repeat == "+":
  213. second_rule_pair = (lhs, (nt,))
  214. else:
  215. second_rule_pair = (lhs, tuple())
  216. new_rule = rule2str(second_rule_pair)
  217. self.addRule(new_rule, func, _preprocess)
  218. continue
  219. if lhs in self.rules:
  220. if rule in self.rules[lhs]:
  221. if "dups" in self.debug and self.debug["dups"]:
  222. self.duplicate_rule(rule)
  223. continue
  224. self.rules[lhs].append(rule)
  225. else:
  226. self.rules[lhs] = [rule]
  227. self.rule2func[rule] = fn
  228. self.rule2name[rule] = func.__name__[2:]
  229. self.ruleschanged = True
  230. # Note: In empty rules, i.e. len(rule[1] == 0, we don't
  231. # call reductions on explicitly. Instead it is computed
  232. # implicitly.
  233. if self.profile_info is not None and len(rule[1]) > 0:
  234. rule_str = self.reduce_string(rule)
  235. if rule_str not in self.profile_info:
  236. self.profile_info[rule_str] = 0
  237. pass
  238. return
  239. def remove_rules(self, doc):
  240. """Remove a grammar rules from _self.rules_, _self.rule2func_,
  241. and _self.rule2name_
  242. """
  243. # remove blanks lines and comment lines, e.g. lines starting with "#"
  244. doc = os.linesep.join(
  245. [s for s in doc.splitlines() if s and not re.match(r"^\s*#", s)]
  246. )
  247. rules = doc.split()
  248. index = []
  249. for i in range(len(rules)):
  250. if rules[i] == "::=":
  251. index.append(i - 1)
  252. index.append(len(rules))
  253. for i in range(len(index) - 1):
  254. lhs = rules[index[i]]
  255. rhs = rules[index[i] + 2 : index[i + 1]]
  256. rule = (lhs, tuple(rhs))
  257. if lhs not in self.rules:
  258. return
  259. if rule in self.rules[lhs]:
  260. self.rules[lhs].remove(rule)
  261. del self.rule2func[rule]
  262. del self.rule2name[rule]
  263. self.ruleschanged = True
  264. # If we are profiling, remove this rule from that as well
  265. if self.profile_info is not None and len(rule[1]) > 0:
  266. rule_str = self.reduce_string(rule)
  267. if rule_str and rule_str in self.profile_info:
  268. del self.profile_info[rule_str]
  269. pass
  270. pass
  271. pass
  272. return
  273. remove_rule = remove_rules
  274. def collectRules(self):
  275. for name in _namelist(self):
  276. if name[:2] == "p_":
  277. func = getattr(self, name)
  278. doc = func.__doc__
  279. self.addRule(doc, func)
  280. def augment(self, start):
  281. rule = "%s ::= %s %s" % (self._START, self._BOF, start)
  282. self.addRule(rule, lambda args: args[1], False)
  283. def computeNull(self):
  284. self.nullable = {}
  285. tbd = []
  286. for rulelist in list(self.rules.values()):
  287. # FIXME: deleting a rule may leave a null entry.
  288. # Perhaps we should improve deletion so it doesn't leave a trace?
  289. if not rulelist:
  290. continue
  291. lhs = rulelist[0][0]
  292. self.nullable[lhs] = 0
  293. for rule in rulelist:
  294. rhs = rule[1]
  295. if len(rhs) == 0:
  296. self.nullable[lhs] = 1
  297. continue
  298. #
  299. # We only need to consider rules which
  300. # consist entirely of nonterminal symbols.
  301. # This should be a savings on typical
  302. # grammars.
  303. #
  304. for sym in rhs:
  305. if sym not in self.rules:
  306. break
  307. else:
  308. tbd.append(rule)
  309. changes = 1
  310. while changes:
  311. changes = 0
  312. for lhs, rhs in tbd:
  313. if self.nullable[lhs]:
  314. continue
  315. for sym in rhs:
  316. if not self.nullable[sym]:
  317. break
  318. else:
  319. self.nullable[lhs] = 1
  320. changes = 1
  321. def makeState0(self):
  322. s0 = _State(0, [])
  323. for rule in self.newrules[self._START]:
  324. s0.items.append((rule, 0))
  325. return s0
  326. def finalState(self, tokens):
  327. #
  328. # Yuck.
  329. #
  330. if len(self.newrules[self._START]) == 2 and len(tokens) == 0:
  331. return 1
  332. start = self.rules[self._START][0][1][1]
  333. return self.goto(1, start)
  334. def makeNewRules(self):
  335. worklist = []
  336. for rulelist in list(self.rules.values()):
  337. for rule in rulelist:
  338. worklist.append((rule, 0, 1, rule))
  339. for rule, i, candidate, oldrule in worklist:
  340. lhs, rhs = rule
  341. n = len(rhs)
  342. while i < n:
  343. sym = rhs[i]
  344. if sym not in self.rules or not (
  345. sym in self.nullable and self.nullable[sym]
  346. ):
  347. candidate = 0
  348. i += 1
  349. continue
  350. newrhs = list(rhs)
  351. newrhs[i] = self._NULLABLE + sym
  352. newrule = (lhs, tuple(newrhs))
  353. worklist.append((newrule, i + 1, candidate, oldrule))
  354. candidate = 0
  355. i = i + 1
  356. else:
  357. if candidate:
  358. lhs = self._NULLABLE + lhs
  359. rule = (lhs, rhs)
  360. if lhs in self.newrules:
  361. self.newrules[lhs].append(rule)
  362. else:
  363. self.newrules[lhs] = [rule]
  364. self.new2old[rule] = oldrule
  365. def typestring(self, token):
  366. return None
  367. def duplicate_rule(self, rule):
  368. print("Duplicate rule:\n\t%s" % rule2str(rule))
  369. def error(self, tokens, index):
  370. print("Syntax error at or near token %d: `%s'" % (index, tokens[index]))
  371. if "context" in self.debug and self.debug["context"]:
  372. start = index - 2 if index - 2 >= 0 else 0
  373. tokens = [str(tokens[i]) for i in range(start, index + 1)]
  374. print("Token context:\n\t%s" % ("\n\t".join(tokens)))
  375. raise SystemExit
  376. def errorstack(self, tokens, i: int, full=False):
  377. """Show the stacks of completed symbols.
  378. We get this by inspecting the current transitions
  379. possible and from that extracting the set of states
  380. we are in, and from there we look at the set of
  381. symbols before the "dot". If full is True, we
  382. show the entire rule with the dot placement.
  383. Otherwise just the rule up to the dot.
  384. """
  385. print("\n-- Stacks of completed symbols:")
  386. states = [s for s in self.edges.values() if s]
  387. # States now has the set of states we are in
  388. state_stack = set()
  389. for state in states:
  390. # Find rules which can follow, but keep only
  391. # the part before the dot
  392. for rule, dot in self.states[state].items:
  393. lhs, rhs = rule
  394. if dot > 0:
  395. if full:
  396. state_stack.add(
  397. "%s ::= %s . %s"
  398. % (lhs, " ".join(rhs[:dot]), " ".join(rhs[dot:]))
  399. )
  400. else:
  401. state_stack.add("%s ::= %s" % (lhs, " ".join(rhs[:dot])))
  402. pass
  403. pass
  404. pass
  405. for stack in sorted(state_stack):
  406. print(stack)
  407. def parse(self, tokens, debug=None):
  408. """This is the main entry point from outside.
  409. Passing in a debug dictionary changes the default debug
  410. setting.
  411. """
  412. self.tokens = tokens
  413. if debug:
  414. self.debug = debug
  415. sets = [[(1, 0), (2, 0)]]
  416. self.links = {}
  417. if self.ruleschanged:
  418. self.computeNull()
  419. self.newrules = {}
  420. self.new2old = {}
  421. self.makeNewRules()
  422. self.ruleschanged = False
  423. self.edges, self.cores = {}, {}
  424. self.states = {0: self.makeState0()}
  425. self.makeState(0, self._BOF)
  426. i = 0
  427. for i in range(len(tokens)):
  428. sets.append([])
  429. if sets[i] == []:
  430. break
  431. self.makeSet(tokens, sets, i)
  432. else:
  433. sets.append([])
  434. self.makeSet(None, sets, len(tokens))
  435. finalitem = (self.finalState(tokens), 0)
  436. if finalitem not in sets[-2]:
  437. if len(tokens) > 0:
  438. i = min(i, 1)
  439. if self.debug.get("errorstack", False):
  440. self.errorstack(
  441. tokens, i - 1, str(self.debug["errorstack"]) == "full"
  442. )
  443. self.error(tokens, i - 1)
  444. else:
  445. self.error(None, None)
  446. if self.profile_info is not None:
  447. self.dump_profile_info()
  448. return self.buildTree(self._START, finalitem, tokens, len(sets) - 2)
  449. def isnullable(self, sym):
  450. # For symbols in G_e only.
  451. return sym.startswith(self._NULLABLE)
  452. def skip(self, xxx_todo_changeme, pos=0):
  453. _, rhs = xxx_todo_changeme
  454. n = len(rhs)
  455. while pos < n:
  456. if not self.isnullable(rhs[pos]):
  457. break
  458. pos = pos + 1
  459. return pos
  460. def makeState(self, state, sym):
  461. assert sym is not None
  462. # print(sym) # debug
  463. #
  464. # Compute \epsilon-kernel state's core and see if
  465. # it exists already.
  466. #
  467. kitems = []
  468. for rule, pos in self.states[state].items:
  469. lhs, rhs = rule
  470. if rhs[pos : pos + 1] == (sym,):
  471. kitems.append((rule, self.skip(rule, pos + 1)))
  472. tcore = tuple(sorted(kitems))
  473. if tcore in self.cores:
  474. return self.cores[tcore]
  475. #
  476. # Nope, doesn't exist. Compute it and the associated
  477. # \epsilon-nonkernel state together; we'll need it right away.
  478. #
  479. k = self.cores[tcore] = len(self.states)
  480. K, NK = _State(k, kitems), _State(k + 1, [])
  481. self.states[k] = K
  482. predicted = {}
  483. edges = self.edges
  484. rules = self.newrules
  485. for X in K, NK:
  486. worklist = X.items
  487. for item in worklist:
  488. rule, pos = item
  489. lhs, rhs = rule
  490. if pos == len(rhs):
  491. X.complete.append(rule)
  492. continue
  493. nextSym = rhs[pos]
  494. key = (X.stateno, nextSym)
  495. if nextSym not in rules:
  496. if key not in edges:
  497. edges[key] = None
  498. X.T.append(nextSym)
  499. else:
  500. edges[key] = None
  501. if nextSym not in predicted:
  502. predicted[nextSym] = 1
  503. for prule in rules[nextSym]:
  504. ppos = self.skip(prule)
  505. new = (prule, ppos)
  506. NK.items.append(new)
  507. #
  508. # Problem: we know K needs generating, but we
  509. # don't yet know about NK. Can't commit anything
  510. # regarding NK to self.edges until we're sure. Should
  511. # we delay committing on both K and NK to avoid this
  512. # hacky code? This creates other problems..
  513. #
  514. if X is K:
  515. edges = {}
  516. if NK.items == []:
  517. return k
  518. #
  519. # Check for \epsilon-nonkernel's core. Unfortunately we
  520. # need to know the entire set of predicted nonterminals
  521. # to do this without accidentally duplicating states.
  522. #
  523. tcore = tuple(sorted(predicted.keys()))
  524. if tcore in self.cores:
  525. self.edges[(k, None)] = self.cores[tcore]
  526. return k
  527. nk = self.cores[tcore] = self.edges[(k, None)] = NK.stateno
  528. self.edges.update(edges)
  529. self.states[nk] = NK
  530. return k
  531. def goto(self, state, sym):
  532. key = (state, sym)
  533. if key not in self.edges:
  534. #
  535. # No transitions from state on sym.
  536. #
  537. return None
  538. rv = self.edges[key]
  539. if rv is None:
  540. #
  541. # Target state isn't generated yet. Remedy this.
  542. #
  543. rv = self.makeState(state, sym)
  544. self.edges[key] = rv
  545. return rv
  546. def gotoT(self, state, t):
  547. if self.debug["rules"]:
  548. print("Terminal", t, state)
  549. return [self.goto(state, t)]
  550. def gotoST(self, state, st):
  551. if self.debug["transition"]:
  552. print("GotoST", st, state)
  553. rv = []
  554. for t in self.states[state].T:
  555. if st == t:
  556. rv.append(self.goto(state, t))
  557. return rv
  558. def add(self, set, item, i=None, predecessor=None, causal=None):
  559. if predecessor is None:
  560. if item not in set:
  561. set.append(item)
  562. else:
  563. key = (item, i)
  564. if item not in set:
  565. self.links[key] = []
  566. set.append(item)
  567. self.links[key].append((predecessor, causal))
  568. def makeSet(self, tokens, sets, i):
  569. cur, next = sets[i], sets[i + 1]
  570. if tokens is not None:
  571. token = tokens[i]
  572. ttype = self.typestring(token)
  573. else:
  574. ttype = None
  575. token = None
  576. if ttype is not None:
  577. fn, arg = self.gotoT, ttype
  578. else:
  579. fn, arg = self.gotoST, token
  580. for item in cur:
  581. ptr = (item, i)
  582. state, parent = item
  583. add = fn(state, arg)
  584. for k in add:
  585. if k is not None:
  586. self.add(next, (k, parent), i + 1, ptr)
  587. nk = self.goto(k, None)
  588. if nk is not None:
  589. self.add(next, (nk, i + 1))
  590. if parent == i:
  591. continue
  592. for rule in self.states[state].complete:
  593. lhs, rhs = rule
  594. if self.debug["reduce"]:
  595. self.debug_reduce(rule, tokens, parent, i)
  596. if self.profile_info is not None:
  597. self.profile_rule(rule)
  598. if lhs in self.check_reduce:
  599. if self.check_reduce[lhs] == "AST" and (
  600. tokens or hasattr(self, "tokens")
  601. ):
  602. if hasattr(self, "tokens"):
  603. tokens = self.tokens
  604. ast = self.reduce_ast(rule, self.tokens, item, i, sets)
  605. else:
  606. ast = None
  607. invalid = self.reduce_is_invalid(rule, ast, self.tokens, parent, i)
  608. if ast:
  609. del ast
  610. if invalid:
  611. if self.debug["reduce"]:
  612. print("Reduce %s invalid by check" % lhs)
  613. continue
  614. pass
  615. pass
  616. for pitem in sets[parent]:
  617. pstate, pparent = pitem
  618. k = self.goto(pstate, lhs)
  619. if k is not None:
  620. why = (item, i, rule)
  621. pptr = (pitem, parent)
  622. self.add(cur, (k, pparent), i, pptr, why)
  623. nk = self.goto(k, None)
  624. if nk is not None:
  625. self.add(cur, (nk, i))
  626. def makeSet_fast(self, token, sets, i):
  627. #
  628. # Call *only* when the entire state machine has been built!
  629. # It relies on self.edges being filled in completely, and
  630. # then duplicates and inlines code to boost speed at the
  631. # cost of extreme ugliness.
  632. #
  633. cur, next = sets[i], sets[i + 1]
  634. ttype = token is not None and self.typestring(token) or None
  635. for item in cur:
  636. ptr = (item, i)
  637. state, parent = item
  638. if ttype is not None:
  639. k = self.edges.get((state, ttype), None)
  640. if k is not None:
  641. # self.add(next, (k, parent), i+1, ptr)
  642. # INLINED --------v
  643. new = (k, parent)
  644. key = (new, i + 1)
  645. if new not in next:
  646. self.links[key] = []
  647. next.append(new)
  648. self.links[key].append((ptr, None))
  649. # INLINED --------^
  650. # nk = self.goto(k, None)
  651. nk = self.edges.get((k, None), None)
  652. if nk is not None:
  653. # self.add(next, (nk, i+1))
  654. # INLINED -------------v
  655. new = (nk, i + 1)
  656. if new not in next:
  657. next.append(new)
  658. # INLINED ---------------^
  659. else:
  660. add = self.gotoST(state, token)
  661. for k in add:
  662. if k is not None:
  663. self.add(next, (k, parent), i + 1, ptr)
  664. # nk = self.goto(k, None)
  665. nk = self.edges.get((k, None), None)
  666. if nk is not None:
  667. self.add(next, (nk, i + 1))
  668. if parent == i:
  669. continue
  670. for rule in self.states[state].complete:
  671. lhs, rhs = rule
  672. for pitem in sets[parent]:
  673. pstate, pparent = pitem
  674. # k = self.goto(pstate, lhs)
  675. k = self.edges.get((pstate, lhs), None)
  676. if k is not None:
  677. why = (item, i, rule)
  678. pptr = (pitem, parent)
  679. # self.add(cur, (k, pparent), i, pptr, why)
  680. # INLINED ---------v
  681. new = (k, pparent)
  682. key = (new, i)
  683. if new not in cur:
  684. self.links[key] = []
  685. cur.append(new)
  686. self.links[key].append((pptr, why))
  687. # INLINED ----------^
  688. # nk = self.goto(k, None)
  689. nk = self.edges.get((k, None), None)
  690. if nk is not None:
  691. # self.add(cur, (nk, i))
  692. # INLINED ---------v
  693. new = (nk, i)
  694. if new not in cur:
  695. cur.append(new)
  696. # INLINED ----------^
  697. def predecessor(self, key, causal):
  698. for p, c in self.links[key]:
  699. if c == causal:
  700. return p
  701. assert 0
  702. def causal(self, key):
  703. links = self.links[key]
  704. if len(links) == 1:
  705. return links[0][1]
  706. choices = []
  707. rule2cause = {}
  708. for p, c in links:
  709. rule = c[2]
  710. choices.append(rule)
  711. rule2cause[rule] = c
  712. return rule2cause[self.ambiguity(choices)]
  713. def deriveEpsilon(self, nt):
  714. if len(self.newrules[nt]) > 1:
  715. rule = self.ambiguity(self.newrules[nt])
  716. else:
  717. rule = self.newrules[nt][0]
  718. # print(rule) # debug
  719. rhs = rule[1]
  720. attr = [None] * len(rhs)
  721. for i in range(len(rhs) - 1, -1, -1):
  722. attr[i] = self.deriveEpsilon(rhs[i])
  723. return self.rule2func[self.new2old[rule]](attr)
  724. def buildTree(self, nt, item, tokens, k):
  725. # Stack elements: (non-terminal, item, token index, parent index, attributes, rule)
  726. stack = [(nt, item, k, None, [], None)]
  727. while stack:
  728. nt, item, k, parent_idx, attr, rule = stack.pop()
  729. state, parent = item
  730. # Find applicable rules if not already given
  731. if rule is None:
  732. choices = [rule for rule in self.states[state].complete if rule[0] == nt]
  733. rule = choices[0] if len(choices) == 1 else self.ambiguity(choices)
  734. rhs = rule[1]
  735. # Process symbols in reverse order, skipping over those already completed
  736. for i in range(len(rhs) - 1 - len(attr), -1, -1):
  737. sym = rhs[i]
  738. if sym not in self.newrules:
  739. if sym != self._BOF:
  740. attr.append(tokens[k - 1])
  741. key = (item, k)
  742. item, k = self.predecessor(key, None)
  743. else:
  744. attr.append(None)
  745. continue
  746. if self._NULLABLE == sym[0:len(self._NULLABLE)]:
  747. attr.append(self.deriveEpsilon(sym))
  748. continue
  749. key = (item, k)
  750. why = self.causal(key)
  751. if why:
  752. item, k = self.predecessor(key, why)
  753. # Push the current state back onto the stack with updated attributes and rule
  754. stack.append((nt, item, k, parent_idx, attr, rule))
  755. # Push the new state onto the stack
  756. stack.append((sym, why[0], why[1], k, [], None))
  757. break # Break the loop to let the stack process the new state
  758. else:
  759. # If we've processed all symbols, construct the node
  760. node = self.rule2func[self.new2old[rule]](attr[::-1])
  761. if parent_idx is not None: # If there's a parent, update its attributes
  762. parent_attr = stack[-1][-2]
  763. parent_attr.append(node)
  764. continue
  765. # Return the last node in the stack, which should be the first node
  766. return node
  767. def ambiguity(self, rules):
  768. #
  769. # XXX - problem here and in collectRules() if the same rule
  770. # appears in >1 method. Also undefined results if rules
  771. # causing the ambiguity appear in the same method.
  772. #
  773. sortlist = []
  774. name2index = {}
  775. for i in range(len(rules)):
  776. lhs, rhs = rule = rules[i]
  777. name = self.rule2name[self.new2old[rule]]
  778. sortlist.append((len(rhs), name))
  779. name2index[name] = i
  780. sortlist.sort()
  781. list = [a_b[1] for a_b in sortlist]
  782. return rules[name2index[self.resolve(list)]]
  783. def resolve(self, rule: list):
  784. """
  785. Resolve ambiguity in favor of the shortest RHS.
  786. Since we walk the tree from the top down, this
  787. should effectively resolve in favor of a "shift".
  788. """
  789. return rule[0]
  790. def dump_grammar(self, out=sys.stdout):
  791. """
  792. Print grammar rules
  793. """
  794. for rule in sorted(self.rule2name.items()):
  795. out.write("%s\n" % rule2str(rule[0]))
  796. return
  797. def check_grammar(self, ok_start_symbols=set(), out=sys.stderr):
  798. """
  799. Check grammar for:
  800. - unused left-hand side nonterminals that are neither start symbols
  801. or listed in ok_start_symbols
  802. - unused right-hand side nonterminals, i.e. not tokens
  803. - right-recursive rules. These can slow down parsing.
  804. """
  805. warnings = 0
  806. (lhs, rhs, tokens, right_recursive, dup_rhs) = self.check_sets()
  807. if lhs - ok_start_symbols:
  808. warnings += 1
  809. out.write("LHS symbols not used on the RHS:\n")
  810. out.write(" " + (", ".join(sorted(lhs)) + "\n"))
  811. if rhs:
  812. warnings += 1
  813. out.write("RHS symbols not used on the LHS:\n")
  814. out.write((", ".join(sorted(rhs))) + "\n")
  815. if right_recursive:
  816. warnings += 1
  817. out.write("Right recursive rules:\n")
  818. for rule in sorted(right_recursive):
  819. out.write(" %s ::= %s\n" % (rule[0], " ".join(rule[1])))
  820. pass
  821. pass
  822. if dup_rhs:
  823. warnings += 1
  824. out.write("Nonterminals with the same RHS\n")
  825. for rhs in sorted(dup_rhs.keys()):
  826. out.write(" RHS: %s\n" % " ".join(rhs))
  827. out.write(" LHS: %s\n" % ", ".join(dup_rhs[rhs]))
  828. out.write(" ---\n")
  829. pass
  830. pass
  831. return warnings
  832. def check_sets(self):
  833. """
  834. Check grammar
  835. """
  836. lhs_set = set()
  837. rhs_set = set()
  838. rhs_rules_set = {}
  839. token_set = set()
  840. right_recursive = set()
  841. dup_rhs = {}
  842. for lhs in self.rules:
  843. rules_for_lhs = self.rules[lhs]
  844. lhs_set.add(lhs)
  845. for rule in rules_for_lhs:
  846. rhs = rule[1]
  847. if len(rhs) > 0 and rhs in rhs_rules_set:
  848. li = dup_rhs.get(rhs, [])
  849. li.append(lhs)
  850. dup_rhs[rhs] = li
  851. else:
  852. rhs_rules_set[rhs] = lhs
  853. for sym in rhs:
  854. # We assume any symbol starting with an uppercase letter is
  855. # terminal, and anything else is a nonterminal
  856. if re.match("^[A-Z]", sym):
  857. token_set.add(sym)
  858. else:
  859. rhs_set.add(sym)
  860. if len(rhs) > 0 and lhs == rhs[-1]:
  861. right_recursive.add((lhs, rhs))
  862. pass
  863. pass
  864. lhs_set.remove(self._START)
  865. rhs_set.remove(self._BOF)
  866. missing_lhs = lhs_set - rhs_set
  867. missing_rhs = rhs_set - lhs_set
  868. # dup_rhs is missing first entry found, so add that
  869. for rhs in dup_rhs:
  870. dup_rhs[rhs].append(rhs_rules_set[rhs])
  871. pass
  872. return (missing_lhs, missing_rhs, token_set, right_recursive, dup_rhs)
  873. def reduce_string(self, rule, last_token_pos=-1):
  874. if last_token_pos >= 0:
  875. return "%s ::= %s (%d)" % (rule[0], " ".join(rule[1]), last_token_pos)
  876. else:
  877. return "%s ::= %s" % (rule[0], " ".join(rule[1]))
  878. # Note the unused parameters here are used in subclassed
  879. # routines that need more information
  880. def debug_reduce(self, rule, tokens, parent, i):
  881. print(self.reduce_string(rule, i))
  882. def profile_rule(self, rule):
  883. """Bump count of the number of times _rule_ was used"""
  884. rule_str = self.reduce_string(rule)
  885. if rule_str not in self.profile_info:
  886. self.profile_info[rule_str] = 1
  887. else:
  888. self.profile_info[rule_str] += 1
  889. def get_profile_info(self):
  890. """Show the accumulated results of how many times each rule was used"""
  891. return sorted(self.profile_info.items(), key=lambda kv: kv[1], reverse=False)
  892. return
  893. def dump_profile_info(self):
  894. if isinstance(self.coverage_path, str):
  895. with open(self.coverage_path, "wb") as fp:
  896. pickle.dump(self.profile_info, fp)
  897. else:
  898. for rule, count in self.get_profile_info():
  899. self.coverage_path.write("%s -- %d\n" % (rule, count))
  900. pass
  901. self.coverage_path.write("-" * 40 + "\n")
  902. def reduce_ast(self, rule, tokens, item, k, sets):
  903. rhs = rule[1]
  904. ast = [None] * len(rhs)
  905. for i in range(len(rhs) - 1, -1, -1):
  906. sym = rhs[i]
  907. if sym not in self.newrules:
  908. if sym != self._BOF:
  909. ast[i] = tokens[k - 1]
  910. key = (item, k)
  911. item, k = self.predecessor(key, None)
  912. elif self._NULLABLE == sym[0 : len(self._NULLABLE)]:
  913. ast[i] = self.deriveEpsilon(sym)
  914. else:
  915. key = (item, k)
  916. why = self.causal(key)
  917. ast[i] = self.buildTree(sym, why[0], tokens, why[1])
  918. item, k = self.predecessor(key, why)
  919. pass
  920. pass
  921. return ast
  922. #
  923. #
  924. # GenericASTBuilder automagically constructs a concrete/abstract syntax tree
  925. # for a given input. The extra argument is a class (not an instance!)
  926. # which supports the "__setslice__" and "__len__" methods.
  927. #
  928. # XXX - silently overrides any user code in methods.
  929. #
  930. class GenericASTBuilder(GenericParser):
  931. def __init__(self, AST, start, debug=DEFAULT_DEBUG):
  932. if "SPARK_PARSER_COVERAGE" in os.environ:
  933. coverage_path = os.environ["SPARK_PARSER_COVERAGE"]
  934. else:
  935. coverage_path = None
  936. GenericParser.__init__(self, start, debug=debug, coverage_path=coverage_path)
  937. self.AST = AST
  938. def preprocess(self, rule, func):
  939. rebind = (
  940. lambda lhs, self=self: lambda args, lhs=lhs, self=self: self.buildASTNode(
  941. args, lhs
  942. )
  943. )
  944. lhs, rhs = rule
  945. return rule, rebind(lhs)
  946. def buildASTNode(self, args, lhs):
  947. children = []
  948. for arg in args:
  949. if isinstance(arg, self.AST):
  950. children.append(arg)
  951. else:
  952. children.append(self.terminal(arg))
  953. return self.nonterminal(lhs, children)
  954. def terminal(self, token):
  955. return token
  956. def nonterminal(self, type, args):
  957. rv = self.AST(type)
  958. rv[: len(args)] = args
  959. return rv