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.

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