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.

328 lines
14 KiB

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