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.

329 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. from collections import deque
  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 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. 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, stream, 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))
  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. i = 0
  217. for token in stream:
  218. self.predict_and_complete(i, to_scan, columns, transitives)
  219. to_scan = scan(i, token, to_scan)
  220. i += 1
  221. self.predict_and_complete(i, to_scan, columns, transitives)
  222. ## Column is now the final column in the parse.
  223. assert i == len(columns)-1
  224. return to_scan
  225. def parse(self, stream, start):
  226. assert start, start
  227. start_symbol = NonTerminal(start)
  228. columns = [set()]
  229. to_scan = set() # The scan buffer. 'Q' in E.Scott's paper.
  230. ## Predict for the start_symbol.
  231. # Add predicted items to the first Earley set (for the predictor) if they
  232. # result in a non-terminal, or the scanner if they result in a terminal.
  233. for rule in self.predictions[start_symbol]:
  234. item = Item(rule, 0, 0)
  235. if item.expect in self.TERMINALS:
  236. to_scan.add(item)
  237. else:
  238. columns[0].add(item)
  239. to_scan = self._parse(stream, columns, to_scan, start_symbol)
  240. # If the parse was successful, the start
  241. # symbol should have been completed in the last step of the Earley cycle, and will be in
  242. # this column. Find the item for the start_symbol, which is the root of the SPPF tree.
  243. 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]
  244. if self.debug:
  245. from .earley_forest import ForestToPyDotVisitor
  246. try:
  247. debug_walker = ForestToPyDotVisitor()
  248. except ImportError:
  249. logger.warning("Cannot find dependency 'pydot', will not generate sppf debug image")
  250. else:
  251. debug_walker.visit(solutions[0], "sppf.png")
  252. if not solutions:
  253. expected_tokens = [t.expect for t in to_scan]
  254. raise UnexpectedEOF(expected_tokens)
  255. elif len(solutions) > 1:
  256. assert False, 'Earley should not generate multiple start symbol items!'
  257. # Perform our SPPF -> AST conversion using the right ForestVisitor.
  258. forest_tree_visitor_cls = ForestToTreeVisitor if self.resolve_ambiguity else ForestToAmbiguousTreeVisitor
  259. forest_tree_visitor = forest_tree_visitor_cls(self.callbacks, self.forest_sum_visitor and self.forest_sum_visitor())
  260. return forest_tree_visitor.visit(solutions[0])
  261. class ApplyCallbacks(Transformer_InPlace):
  262. def __init__(self, postprocess):
  263. self.postprocess = postprocess
  264. @v_args(meta=True)
  265. def drv(self, children, meta):
  266. return self.postprocess[meta.rule](children)