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.

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