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.

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