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.

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