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.

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