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.

275 lines
13 KiB

  1. """This module implements an experimental Earley parser with a dynamic lexer
  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. Instead of running a lexer beforehand, or using a costy char-by-char method, this parser
  9. uses regular expressions by necessity, achieving high-performance while maintaining all of
  10. Earley's power in parsing any CFG.
  11. """
  12. # Author: Erez Shinan (2017)
  13. # Email : erezshin@gmail.com
  14. from collections import defaultdict, deque
  15. from ..exceptions import ParseError, UnexpectedCharacters
  16. from ..lexer import Token
  17. from ..tree import Tree
  18. from .grammar_analysis import GrammarAnalyzer
  19. from ..grammar import NonTerminal, Terminal
  20. from .earley import ApplyCallbacks
  21. from .earley_common import Column, Item
  22. from .earley_forest import ForestToTreeVisitor, ForestSumVisitor, SymbolNode
  23. class Parser:
  24. def __init__(self, parser_conf, term_matcher, resolve_ambiguity=True, forest_sum_visitor = ForestSumVisitor, ignore = (), complete_lex = False):
  25. analysis = GrammarAnalyzer(parser_conf)
  26. self.parser_conf = parser_conf
  27. self.resolve_ambiguity = resolve_ambiguity
  28. self.ignore = [Terminal(t) for t in ignore]
  29. self.complete_lex = complete_lex
  30. self.FIRST = analysis.FIRST
  31. self.callbacks = {}
  32. self.predictions = {}
  33. ## These could be moved to the grammar analyzer. Pre-computing these is *much* faster than
  34. # the slow 'isupper' in is_terminal.
  35. self.TERMINALS = { sym for r in parser_conf.rules for sym in r.expansion if sym.is_term }
  36. self.NON_TERMINALS = { sym for r in parser_conf.rules for sym in r.expansion if not sym.is_term }
  37. for rule in parser_conf.rules:
  38. self.callbacks[rule] = getattr(parser_conf.callback, rule.alias or rule.origin, None)
  39. self.predictions[rule.origin] = [x.rule for x in analysis.expand_rule(rule.origin)]
  40. self.term_matcher = term_matcher
  41. self.forest_tree_visitor = ForestToTreeVisitor(forest_sum_visitor, self.callbacks)
  42. def parse(self, stream, start_symbol=None):
  43. start_symbol = NonTerminal(start_symbol or self.parser_conf.start)
  44. delayed_matches = defaultdict(list)
  45. match = self.term_matcher
  46. # Held Completions (H in E.Scotts paper).
  47. held_completions = {}
  48. # Cache for nodes & tokens created in a particular parse step.
  49. node_cache = {}
  50. token_cache = {}
  51. text_line = 1
  52. text_column = 1
  53. def make_symbol_node(s, start, end):
  54. label = (s, start.i, end.i)
  55. if label in node_cache:
  56. node = node_cache[label]
  57. else:
  58. node = node_cache[label] = SymbolNode(s, start, end)
  59. return node
  60. def predict_and_complete(column, to_scan):
  61. """The core Earley Predictor and Completer.
  62. At each stage of the input, we handling any completed items (things
  63. that matched on the last cycle) and use those to predict what should
  64. come next in the input stream. The completions and any predicted
  65. non-terminals are recursively processed until we reach a set of,
  66. which can be added to the scan list for the next scanner cycle."""
  67. held_completions.clear()
  68. # R (items) = Ei (column.items)
  69. items = deque(column.items)
  70. while items:
  71. item = items.pop() # remove an element, A say, from R
  72. ### The Earley completer
  73. if item.is_complete: ### (item.s == string)
  74. if item.node is None:
  75. item.node = make_symbol_node(item.s, item.start, column)
  76. item.node.add_family(item.s, item.rule, item.start, None, None)
  77. # Empty has 0 length. If we complete an empty symbol in a particular
  78. # parse step, we need to be able to use that same empty symbol to complete
  79. # any predictions that result, that themselves require empty. Avoids
  80. # infinite recursion on empty symbols.
  81. # held_completions is 'H' in E.Scott's paper.
  82. is_empty_item = item.start.i == column.i
  83. if is_empty_item:
  84. held_completions[item.rule.origin] = item.node
  85. originators = [originator for originator in item.start.items if originator.expect is not None and originator.expect == item.s]
  86. for originator in originators:
  87. new_item = originator.advance()
  88. new_item.node = make_symbol_node(new_item.s, originator.start, column)
  89. new_item.node.add_family(new_item.s, new_item.rule, new_item.start, originator.node, item.node)
  90. if new_item.expect in self.TERMINALS:
  91. # Add (B :: aC.B, h, y) to Q
  92. to_scan.add(new_item)
  93. elif new_item not in column.items:
  94. # Add (B :: aC.B, h, y) to Ei and R
  95. column.add(new_item)
  96. items.append(new_item)
  97. ### The Earley predictor
  98. elif item.expect in self.NON_TERMINALS: ### (item.s == lr0)
  99. new_items = []
  100. for rule in self.predictions[item.expect]:
  101. new_item = Item(rule, 0, column)
  102. new_items.append(new_item)
  103. # Process any held completions (H).
  104. if item.expect in held_completions:
  105. new_item = item.advance()
  106. new_item.node = make_symbol_node(new_item.s, item.start, column)
  107. new_item.node.add_family(new_item.s, new_item.rule, new_item.start, item.node, held_completions[item.expect])
  108. new_items.append(new_item)
  109. for new_item in new_items:
  110. if new_item.expect in self.TERMINALS:
  111. to_scan.add(new_item)
  112. elif new_item not in column.items:
  113. column.add(new_item)
  114. items.append(new_item)
  115. def scan(i, column, to_scan):
  116. """The core Earley Scanner.
  117. This is a custom implementation of the scanner that uses the
  118. Lark lexer to match tokens. The scan list is built by the
  119. Earley predictor, based on the previously completed tokens.
  120. This ensures that at each phase of the parse we have a custom
  121. lexer context, allowing for more complex ambiguities."""
  122. # 1) Loop the expectations and ask the lexer to match.
  123. # Since regexp is forward looking on the input stream, and we only
  124. # want to process tokens when we hit the point in the stream at which
  125. # they complete, we push all tokens into a buffer (delayed_matches), to
  126. # be held possibly for a later parse step when we reach the point in the
  127. # input stream at which they complete.
  128. for item in set(to_scan):
  129. m = match(item.expect, stream, i)
  130. if m:
  131. t = Token(item.expect.name, m.group(0), i, text_line, text_column)
  132. delayed_matches[m.end()].append( (item, column, t) )
  133. if self.complete_lex:
  134. s = m.group(0)
  135. for j in range(1, len(s)):
  136. m = match(item.expect, s[:-j])
  137. if m:
  138. t = Token(item.expect.name, m.group(0), i, text_line, text_column)
  139. delayed_matches[i+m.end()].append( (item, column, t) )
  140. # Remove any items that successfully matched in this pass from the to_scan buffer.
  141. # This ensures we don't carry over tokens that already matched, if we're ignoring below.
  142. to_scan.remove(item)
  143. # 3) Process any ignores. This is typically used for e.g. whitespace.
  144. # We carry over any unmatched items from the to_scan buffer to be matched again after
  145. # the ignore. This should allow us to use ignored symbols in non-terminals to implement
  146. # e.g. mandatory spacing.
  147. for x in self.ignore:
  148. m = match(x, stream, i)
  149. if m:
  150. # Carry over any items still in the scan buffer, to past the end of the ignored items.
  151. delayed_matches[m.end()].extend([(item, column, None) for item in to_scan ])
  152. # If we're ignoring up to the end of the file, # carry over the start symbol if it already completed.
  153. delayed_matches[m.end()].extend([(item, column, None) for item in column.items if item.is_complete and item.s == start_symbol])
  154. next_set = Column(i + 1, self.FIRST) # Ei+1
  155. next_to_scan = set()
  156. ## 4) Process Tokens from delayed_matches.
  157. # This is the core of the Earley scanner. Create an SPPF node for each Token,
  158. # and create the symbol node in the SPPF tree. Advance the item that completed,
  159. # and add the resulting new item to either the Earley set (for processing by the
  160. # completer/predictor) or the to_scan buffer for the next parse step.
  161. for item, start, token in delayed_matches[i+1]:
  162. if token is not None:
  163. new_item = item.advance()
  164. new_item.node = make_symbol_node(new_item.s, new_item.start, column)
  165. new_item.node.add_family(new_item.s, item.rule, new_item.start, item.node, token)
  166. else:
  167. new_item = item
  168. if new_item.expect in self.TERMINALS:
  169. # add (B ::= Aai+1.B, h, y) to Q'
  170. next_to_scan.add(new_item)
  171. else:
  172. # add (B ::= Aa+1.B, h, y) to Ei+1
  173. next_set.add(new_item)
  174. del delayed_matches[i+1] # No longer needed, so unburden memory
  175. if not next_set and not delayed_matches and not next_to_scan:
  176. raise UnexpectedCharacters(stream, i, text_line, text_column, {item.expect for item in to_scan}, set(to_scan))
  177. return next_set, next_to_scan
  178. # Main loop starts
  179. column0 = Column(0, self.FIRST)
  180. column = column0
  181. ## The scan buffer. 'Q' in E.Scott's paper.
  182. to_scan = set()
  183. ## Predict for the start_symbol.
  184. # Add predicted items to the first Earley set (for the predictor) if they
  185. # result in a non-terminal, or the scanner if they result in a terminal.
  186. for rule in self.predictions[start_symbol]:
  187. item = Item(rule, 0, column0)
  188. if item.expect in self.TERMINALS:
  189. to_scan.add(item)
  190. else:
  191. column.add(item)
  192. ## The main Earley loop.
  193. # Run the Prediction/Completion cycle for any Items in the current Earley set.
  194. # Completions will be added to the SPPF tree, and predictions will be recursively
  195. # processed down to terminals/empty nodes to be added to the scanner for the next
  196. # step.
  197. for i, token in enumerate(stream):
  198. predict_and_complete(column, to_scan)
  199. # Clear the node_cache and token_cache, which are only relevant for each
  200. # step in the Earley pass.
  201. node_cache.clear()
  202. token_cache.clear()
  203. column, to_scan = scan(i, column, to_scan)
  204. if token == '\n':
  205. text_line += 1
  206. text_column = 1
  207. else:
  208. text_column += 1
  209. predict_and_complete(column, to_scan)
  210. ## Column is now the final column in the parse. If the parse was successful, the start
  211. # symbol should have been completed in the last step of the Earley cycle, and will be in
  212. # this column. Find the item for the start_symbol, which is the root of the SPPF tree.
  213. 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]
  214. if not solutions:
  215. expected_tokens = [t.expect for t in to_scan]
  216. raise ParseError('Unexpected end of input! Expecting a terminal of: %s' % expected_tokens)
  217. elif len(solutions) > 1:
  218. raise Exception('Earley should not generate more than one start symbol - bug')
  219. ## If we're not resolving ambiguity, we just return the root of the SPPF tree to the caller.
  220. # This means the caller can work directly with the SPPF tree.
  221. if not self.resolve_ambiguity:
  222. return solutions[0]
  223. # ... otherwise, disambiguate and convert the SPPF to an AST, removing any ambiguities
  224. # according to the rules.
  225. return self.forest_tree_visitor.go(solutions[0])