This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

336 lines
15 KiB

  1. """This module implements an Earley parser.
  2. The core Earley algorithm used here is based on Elizabeth Scott's implementation, here:
  3. https://www.sciencedirect.com/science/article/pii/S1571066108001497
  4. That is probably the best reference for understanding the algorithm here.
  5. The Earley parser outputs an SPPF-tree as per that document. The SPPF tree format
  6. is explained here: https://lark-parser.readthedocs.io/en/latest/_static/sppf/sppf.html
  7. """
  8. from collections import deque
  9. from ..tree import Tree
  10. from ..visitors import Transformer_InPlace, v_args
  11. from ..exceptions import UnexpectedEOF, UnexpectedToken
  12. from ..utils import logger
  13. from .grammar_analysis import GrammarAnalyzer
  14. from ..grammar import NonTerminal
  15. from .earley_common import Item, TransitiveItem
  16. from .earley_forest import ForestSumVisitor, SymbolNode, ForestToParseTree
  17. class Parser:
  18. def __init__(self, parser_conf, term_matcher, resolve_ambiguity=True, debug=False, tree_class=Tree):
  19. analysis = GrammarAnalyzer(parser_conf)
  20. self.parser_conf = parser_conf
  21. self.resolve_ambiguity = resolve_ambiguity
  22. self.debug = debug
  23. self.tree_class = tree_class
  24. self.FIRST = analysis.FIRST
  25. self.NULLABLE = analysis.NULLABLE
  26. self.callbacks = parser_conf.callbacks
  27. self.predictions = {}
  28. ## These could be moved to the grammar analyzer. Pre-computing these is *much* faster than
  29. # the slow 'isupper' in is_terminal.
  30. self.TERMINALS = { sym for r in parser_conf.rules for sym in r.expansion if sym.is_term }
  31. self.NON_TERMINALS = { sym for r in parser_conf.rules for sym in r.expansion if not sym.is_term }
  32. self.forest_sum_visitor = None
  33. for rule in parser_conf.rules:
  34. if rule.origin not in self.predictions:
  35. self.predictions[rule.origin] = [x.rule for x in analysis.expand_rule(rule.origin)]
  36. ## Detect if any rules have priorities set. If the user specified priority = "none" then
  37. # the priorities will be stripped from all rules before they reach us, allowing us to
  38. # skip the extra tree walk. We'll also skip this if the user just didn't specify priorities
  39. # on any rules.
  40. if self.forest_sum_visitor is None and rule.options.priority is not None:
  41. self.forest_sum_visitor = ForestSumVisitor
  42. self.term_matcher = term_matcher
  43. def predict_and_complete(self, i, to_scan, columns, transitives):
  44. """The core Earley Predictor and Completer.
  45. At each stage of the input, we handling any completed items (things
  46. that matched on the last cycle) and use those to predict what should
  47. come next in the input stream. The completions and any predicted
  48. non-terminals are recursively processed until we reach a set of,
  49. which can be added to the scan list for the next scanner cycle."""
  50. # Held Completions (H in E.Scotts paper).
  51. node_cache = {}
  52. held_completions = {}
  53. column = columns[i]
  54. # R (items) = Ei (column.items)
  55. items = deque(column)
  56. while items:
  57. item = items.pop() # remove an element, A say, from R
  58. ### The Earley completer
  59. if item.is_complete: ### (item.s == string)
  60. if item.node is None:
  61. label = (item.s, item.start, i)
  62. item.node = node_cache[label] if label in node_cache else node_cache.setdefault(label, SymbolNode(*label))
  63. item.node.add_family(item.s, item.rule, item.start, None, None)
  64. # create_leo_transitives(item.rule.origin, item.start)
  65. ###R Joop Leo right recursion Completer
  66. if item.rule.origin in transitives[item.start]:
  67. transitive = transitives[item.start][item.s]
  68. if transitive.previous in transitives[transitive.column]:
  69. root_transitive = transitives[transitive.column][transitive.previous]
  70. else:
  71. root_transitive = transitive
  72. new_item = Item(transitive.rule, transitive.ptr, transitive.start)
  73. label = (root_transitive.s, root_transitive.start, i)
  74. new_item.node = node_cache[label] if label in node_cache else node_cache.setdefault(label, SymbolNode(*label))
  75. new_item.node.add_path(root_transitive, item.node)
  76. if new_item.expect in self.TERMINALS:
  77. # Add (B :: aC.B, h, y) to Q
  78. to_scan.add(new_item)
  79. elif new_item not in column:
  80. # Add (B :: aC.B, h, y) to Ei and R
  81. column.add(new_item)
  82. items.append(new_item)
  83. ###R Regular Earley completer
  84. else:
  85. # Empty has 0 length. If we complete an empty symbol in a particular
  86. # parse step, we need to be able to use that same empty symbol to complete
  87. # any predictions that result, that themselves require empty. Avoids
  88. # infinite recursion on empty symbols.
  89. # held_completions is 'H' in E.Scott's paper.
  90. is_empty_item = item.start == i
  91. if is_empty_item:
  92. held_completions[item.rule.origin] = item.node
  93. originators = [originator for originator in columns[item.start] if originator.expect is not None and originator.expect == item.s]
  94. for originator in originators:
  95. new_item = originator.advance()
  96. label = (new_item.s, originator.start, i)
  97. new_item.node = node_cache[label] if label in node_cache else node_cache.setdefault(label, SymbolNode(*label))
  98. new_item.node.add_family(new_item.s, new_item.rule, i, originator.node, item.node)
  99. if new_item.expect in self.TERMINALS:
  100. # Add (B :: aC.B, h, y) to Q
  101. to_scan.add(new_item)
  102. elif new_item not in column:
  103. # Add (B :: aC.B, h, y) to Ei and R
  104. column.add(new_item)
  105. items.append(new_item)
  106. ### The Earley predictor
  107. elif item.expect in self.NON_TERMINALS: ### (item.s == lr0)
  108. new_items = []
  109. for rule in self.predictions[item.expect]:
  110. new_item = Item(rule, 0, i)
  111. new_items.append(new_item)
  112. # Process any held completions (H).
  113. if item.expect in held_completions:
  114. new_item = item.advance()
  115. label = (new_item.s, item.start, i)
  116. new_item.node = node_cache[label] if label in node_cache else node_cache.setdefault(label, SymbolNode(*label))
  117. new_item.node.add_family(new_item.s, new_item.rule, new_item.start, item.node, held_completions[item.expect])
  118. new_items.append(new_item)
  119. for new_item in new_items:
  120. if new_item.expect in self.TERMINALS:
  121. to_scan.add(new_item)
  122. elif new_item not in column:
  123. column.add(new_item)
  124. items.append(new_item)
  125. def _parse(self, lexer, columns, to_scan, start_symbol=None):
  126. def is_quasi_complete(item):
  127. if item.is_complete:
  128. return True
  129. quasi = item.advance()
  130. while not quasi.is_complete:
  131. if quasi.expect not in self.NULLABLE:
  132. return False
  133. if quasi.rule.origin == start_symbol and quasi.expect == start_symbol:
  134. return False
  135. quasi = quasi.advance()
  136. return True
  137. def create_leo_transitives(origin, start):
  138. visited = set()
  139. to_create = []
  140. trule = None
  141. previous = None
  142. ### Recursively walk backwards through the Earley sets until we find the
  143. # first transitive candidate. If this is done continuously, we shouldn't
  144. # have to walk more than 1 hop.
  145. while True:
  146. if origin in transitives[start]:
  147. previous = trule = transitives[start][origin]
  148. break
  149. is_empty_rule = not self.FIRST[origin]
  150. if is_empty_rule:
  151. break
  152. candidates = [ candidate for candidate in columns[start] if candidate.expect is not None and origin == candidate.expect ]
  153. if len(candidates) != 1:
  154. break
  155. originator = next(iter(candidates))
  156. if originator is None or originator in visited:
  157. break
  158. visited.add(originator)
  159. if not is_quasi_complete(originator):
  160. break
  161. trule = originator.advance()
  162. if originator.start != start:
  163. visited.clear()
  164. to_create.append((origin, start, originator))
  165. origin = originator.rule.origin
  166. start = originator.start
  167. # If a suitable Transitive candidate is not found, bail.
  168. if trule is None:
  169. return
  170. #### Now walk forwards and create Transitive Items in each set we walked through; and link
  171. # each transitive item to the next set forwards.
  172. while to_create:
  173. origin, start, originator = to_create.pop()
  174. titem = None
  175. if previous is not None:
  176. titem = previous.next_titem = TransitiveItem(origin, trule, originator, previous.column)
  177. else:
  178. titem = TransitiveItem(origin, trule, originator, start)
  179. previous = transitives[start][origin] = titem
  180. def scan(i, token, to_scan):
  181. """The core Earley Scanner.
  182. This is a custom implementation of the scanner that uses the
  183. Lark lexer to match tokens. The scan list is built by the
  184. Earley predictor, based on the previously completed tokens.
  185. This ensures that at each phase of the parse we have a custom
  186. lexer context, allowing for more complex ambiguities."""
  187. next_to_scan = set()
  188. next_set = set()
  189. columns.append(next_set)
  190. transitives.append({})
  191. node_cache = {}
  192. for item in set(to_scan):
  193. if match(item.expect, token):
  194. new_item = item.advance()
  195. label = (new_item.s, new_item.start, i)
  196. new_item.node = node_cache[label] if label in node_cache else node_cache.setdefault(label, SymbolNode(*label))
  197. new_item.node.add_family(new_item.s, item.rule, new_item.start, item.node, token)
  198. if new_item.expect in self.TERMINALS:
  199. # add (B ::= Aai+1.B, h, y) to Q'
  200. next_to_scan.add(new_item)
  201. else:
  202. # add (B ::= Aa+1.B, h, y) to Ei+1
  203. next_set.add(new_item)
  204. if not next_set and not next_to_scan:
  205. expect = {i.expect.name for i in to_scan}
  206. raise UnexpectedToken(token, expect, considered_rules=set(to_scan), state=frozenset(i.s for i in to_scan))
  207. return next_to_scan
  208. # Define parser functions
  209. match = self.term_matcher
  210. # Cache for nodes & tokens created in a particular parse step.
  211. transitives = [{}]
  212. ## The main Earley loop.
  213. # Run the Prediction/Completion cycle for any Items in the current Earley set.
  214. # Completions will be added to the SPPF tree, and predictions will be recursively
  215. # processed down to terminals/empty nodes to be added to the scanner for the next
  216. # step.
  217. expects = {i.expect for i in to_scan}
  218. i = 0
  219. for token in lexer.lex(expects):
  220. self.predict_and_complete(i, to_scan, columns, transitives)
  221. to_scan = scan(i, token, to_scan)
  222. i += 1
  223. expects.clear()
  224. expects |= {i.expect for i in to_scan}
  225. self.predict_and_complete(i, to_scan, columns, transitives)
  226. ## Column is now the final column in the parse.
  227. assert i == len(columns)-1
  228. return to_scan
  229. def parse(self, lexer, start):
  230. assert start, start
  231. start_symbol = NonTerminal(start)
  232. columns = [set()]
  233. to_scan = set() # The scan buffer. 'Q' in E.Scott's paper.
  234. ## Predict for the start_symbol.
  235. # Add predicted items to the first Earley set (for the predictor) if they
  236. # result in a non-terminal, or the scanner if they result in a terminal.
  237. for rule in self.predictions[start_symbol]:
  238. item = Item(rule, 0, 0)
  239. if item.expect in self.TERMINALS:
  240. to_scan.add(item)
  241. else:
  242. columns[0].add(item)
  243. to_scan = self._parse(lexer, columns, to_scan, start_symbol)
  244. # If the parse was successful, the start
  245. # symbol should have been completed in the last step of the Earley cycle, and will be in
  246. # this column. Find the item for the start_symbol, which is the root of the SPPF tree.
  247. solutions = [n.node for n in columns[-1] if n.is_complete and n.node is not None and n.s == start_symbol and n.start == 0]
  248. if not solutions:
  249. expected_terminals = [t.expect.name for t in to_scan]
  250. raise UnexpectedEOF(expected_terminals, state=frozenset(i.s for i in to_scan))
  251. if self.debug:
  252. from .earley_forest import ForestToPyDotVisitor
  253. try:
  254. debug_walker = ForestToPyDotVisitor()
  255. except ImportError:
  256. logger.warning("Cannot find dependency 'pydot', will not generate sppf debug image")
  257. else:
  258. debug_walker.visit(solutions[0], "sppf.png")
  259. if len(solutions) > 1:
  260. assert False, 'Earley should not generate multiple start symbol items!'
  261. if self.tree_class is not None:
  262. # Perform our SPPF -> AST conversion
  263. transformer = ForestToParseTree(self.tree_class, self.callbacks, self.forest_sum_visitor and self.forest_sum_visitor(), self.resolve_ambiguity)
  264. return transformer.transform(solutions[0])
  265. # return the root of the SPPF
  266. return solutions[0]
  267. class ApplyCallbacks(Transformer_InPlace):
  268. def __init__(self, postprocess):
  269. self.postprocess = postprocess
  270. @v_args(meta=True)
  271. def drv(self, children, meta):
  272. return self.postprocess[meta.rule](children)