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.

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