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.

224 lines
9.9 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. # Author: Erez Shinan (2017)
  10. # Email : erezshin@gmail.com
  11. from ..visitors import Transformer_InPlace, v_args
  12. from ..exceptions import ParseError, UnexpectedToken
  13. from .grammar_analysis import GrammarAnalyzer
  14. from ..grammar import NonTerminal
  15. from .earley_common import Item
  16. from .earley_forest import ForestToTreeVisitor, ForestSumVisitor, SymbolNode
  17. from collections import deque, defaultdict
  18. class Parser:
  19. def __init__(self, parser_conf, term_matcher, resolve_ambiguity=True, forest_sum_visitor = ForestSumVisitor):
  20. analysis = GrammarAnalyzer(parser_conf)
  21. self.parser_conf = parser_conf
  22. self.resolve_ambiguity = resolve_ambiguity
  23. self.FIRST = analysis.FIRST
  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. def make_symbol_node(s, start, end):
  46. label = (s, start, end)
  47. if label in node_cache:
  48. node = node_cache[label]
  49. else:
  50. node = node_cache[label] = SymbolNode(s, start, end)
  51. return node
  52. def predict_and_complete(i, to_scan):
  53. """The core Earley Predictor and Completer.
  54. At each stage of the input, we handling any completed items (things
  55. that matched on the last cycle) and use those to predict what should
  56. come next in the input stream. The completions and any predicted
  57. non-terminals are recursively processed until we reach a set of,
  58. which can be added to the scan list for the next scanner cycle."""
  59. held_completions.clear()
  60. column = columns[i]
  61. # R (items) = Ei (column.items)
  62. items = deque(column)
  63. while items:
  64. item = items.pop() # remove an element, A say, from R
  65. ### The Earley completer
  66. if item.is_complete: ### (item.s == string)
  67. if item.node is None:
  68. item.node = make_symbol_node(item.s, item.start, i)
  69. item.node.add_family(item.s, item.rule, item.start, None, None)
  70. # Empty has 0 length. If we complete an empty symbol in a particular
  71. # parse step, we need to be able to use that same empty symbol to complete
  72. # any predictions that result, that themselves require empty. Avoids
  73. # infinite recursion on empty symbols.
  74. # held_completions is 'H' in E.Scott's paper.
  75. is_empty_item = item.start == i
  76. if is_empty_item:
  77. held_completions[item.rule.origin] = item.node
  78. originators = [originator for originator in columns[item.start] if originator.expect is not None and originator.expect == item.s]
  79. for originator in originators:
  80. new_item = originator.advance()
  81. new_item.node = make_symbol_node(new_item.s, originator.start, i)
  82. new_item.node.add_family(new_item.s, new_item.rule, new_item.start, originator.node, item.node)
  83. if new_item.expect in self.TERMINALS:
  84. # Add (B :: aC.B, h, y) to Q
  85. to_scan.add(new_item)
  86. elif new_item not in column:
  87. # Add (B :: aC.B, h, y) to Ei and R
  88. column.add(new_item)
  89. items.append(new_item)
  90. ### The Earley predictor
  91. elif item.expect in self.NON_TERMINALS: ### (item.s == lr0)
  92. new_items = []
  93. for rule in self.predictions[item.expect]:
  94. new_item = Item(rule, 0, i)
  95. new_items.append(new_item)
  96. # Process any held completions (H).
  97. if item.expect in held_completions:
  98. new_item = item.advance()
  99. new_item.node = make_symbol_node(new_item.s, item.start, i)
  100. new_item.node.add_family(new_item.s, new_item.rule, new_item.start, item.node, held_completions[item.expect])
  101. new_items.append(new_item)
  102. for new_item in new_items:
  103. if new_item.expect in self.TERMINALS:
  104. to_scan.add(new_item)
  105. elif new_item not in column:
  106. column.add(new_item)
  107. items.append(new_item)
  108. def scan(i, token, to_scan):
  109. """The core Earley Scanner.
  110. This is a custom implementation of the scanner that uses the
  111. Lark lexer to match tokens. The scan list is built by the
  112. Earley predictor, based on the previously completed tokens.
  113. This ensures that at each phase of the parse we have a custom
  114. lexer context, allowing for more complex ambiguities."""
  115. next_to_scan = set()
  116. next_set = set()
  117. columns.append(next_set)
  118. for item in set(to_scan):
  119. if match(item.expect, token):
  120. new_item = item.advance()
  121. new_item.node = make_symbol_node(new_item.s, new_item.start, i)
  122. new_item.node.add_family(new_item.s, item.rule, new_item.start, item.node, token)
  123. if new_item.expect in self.TERMINALS:
  124. # add (B ::= Aai+1.B, h, y) to Q'
  125. next_to_scan.add(new_item)
  126. else:
  127. # add (B ::= Aa+1.B, h, y) to Ei+1
  128. next_set.add(new_item)
  129. if not next_set and not next_to_scan:
  130. expect = {i.expect.name for i in to_scan}
  131. raise UnexpectedToken(token, expect, considered_rules = set(to_scan))
  132. return next_to_scan
  133. # Main loop starts
  134. columns.append(set())
  135. ## The scan buffer. 'Q' in E.Scott's paper.
  136. to_scan = set()
  137. ## Predict for the start_symbol.
  138. # Add predicted items to the first Earley set (for the predictor) if they
  139. # result in a non-terminal, or the scanner if they result in a terminal.
  140. for rule in self.predictions[start_symbol]:
  141. item = Item(rule, 0, 0)
  142. if item.expect in self.TERMINALS:
  143. to_scan.add(item)
  144. else:
  145. columns[0].add(item)
  146. ## The main Earley loop.
  147. # Run the Prediction/Completion cycle for any Items in the current Earley set.
  148. # Completions will be added to the SPPF tree, and predictions will be recursively
  149. # processed down to terminals/empty nodes to be added to the scanner for the next
  150. # step.
  151. i = 0
  152. for token in stream:
  153. predict_and_complete(i, to_scan)
  154. # Clear the node_cache and token_cache, which are only relevant for each
  155. # step in the Earley pass.
  156. node_cache.clear()
  157. token_cache.clear()
  158. to_scan = scan(i, token, to_scan)
  159. i += 1
  160. predict_and_complete(i, to_scan)
  161. ## Column is now the final column in the parse. If the parse was successful, the start
  162. # symbol should have been completed in the last step of the Earley cycle, and will be in
  163. # this column. Find the item for the start_symbol, which is the root of the SPPF tree.
  164. 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]
  165. if not solutions:
  166. raise ParseError('Incomplete parse: Could not find a solution to input')
  167. elif len(solutions) > 1:
  168. raise ParseError('Earley should not generate multiple start symbol items!')
  169. ## If we're not resolving ambiguity, we just return the root of the SPPF tree to the caller.
  170. # This means the caller can work directly with the SPPF tree.
  171. if not self.resolve_ambiguity:
  172. return solutions[0]
  173. # ... otherwise, disambiguate and convert the SPPF to an AST, removing any ambiguities
  174. # according to the rules.
  175. return self.forest_tree_visitor.go(solutions[0])
  176. class ApplyCallbacks(Transformer_InPlace):
  177. def __init__(self, postprocess):
  178. self.postprocess = postprocess
  179. @v_args(meta=True)
  180. def drv(self, children, meta):
  181. return self.postprocess[meta.rule](children)