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.

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