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.

367 lines
17 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 .grammar_analysis import GrammarAnalyzer
  18. from ..grammar import NonTerminal, Terminal
  19. from .earley import ApplyCallbacks
  20. from .earley_common import Item, TransitiveItem
  21. from .earley_forest import ForestToTreeVisitor, ForestSumVisitor, SymbolNode, ForestToAmbiguousTreeVisitor
  22. class Parser:
  23. def __init__(self, parser_conf, term_matcher, resolve_ambiguity=True, forest_sum_visitor = ForestSumVisitor, ignore = (), complete_lex = False):
  24. analysis = GrammarAnalyzer(parser_conf)
  25. self.parser_conf = parser_conf
  26. self.resolve_ambiguity = resolve_ambiguity
  27. self.ignore = [Terminal(t) for t in ignore]
  28. self.complete_lex = complete_lex
  29. self.FIRST = analysis.FIRST
  30. self.NULLABLE = analysis.NULLABLE
  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.forest_tree_visitor = ForestToTreeVisitor(forest_sum_visitor, self.callbacks)
  41. self.term_matcher = term_matcher
  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. columns = []
  52. transitives = []
  53. text_line = 1
  54. text_column = 1
  55. def is_quasi_complete(item):
  56. if item.is_complete:
  57. return True
  58. quasi = item.advance()
  59. while not quasi.is_complete:
  60. symbol = quasi.expect
  61. if symbol not in self.NULLABLE:
  62. return False
  63. if quasi.rule.origin == start_symbol and symbol == start_symbol:
  64. return False
  65. quasi = quasi.advance()
  66. return True
  67. def create_leo_transitives(item, trule, previous, visited = None):
  68. if visited is None:
  69. visited = set()
  70. if item.rule.origin in transitives[item.start]:
  71. previous = trule = transitives[item.start][item.rule.origin]
  72. return trule, previous
  73. is_empty_rule = not self.FIRST[item.rule.origin]
  74. if is_empty_rule:
  75. return trule, previous
  76. originator = None
  77. for key in columns[item.start]:
  78. if key.expect is not None and key.expect == item.rule.origin:
  79. if originator is not None:
  80. return trule, previous
  81. originator = key
  82. if originator is None:
  83. return trule, previous
  84. if originator in visited:
  85. return trule, previous
  86. visited.add(originator)
  87. if not is_quasi_complete(originator):
  88. return trule, previous
  89. trule = originator.advance()
  90. if originator.start != item.start:
  91. visited.clear()
  92. trule, previous = create_leo_transitives(originator, trule, previous, visited)
  93. if trule is None:
  94. return trule, previous
  95. titem = None
  96. if previous is not None:
  97. titem = TransitiveItem(item.rule.origin, trule, originator, previous.column)
  98. previous.next_titem = titem
  99. else:
  100. titem = TransitiveItem(item.rule.origin, trule, originator, item.start)
  101. previous = transitives[item.start][item.rule.origin] = titem
  102. return trule, previous
  103. def predict_and_complete(i, to_scan):
  104. """The core Earley Predictor and Completer.
  105. At each stage of the input, we handling any completed items (things
  106. that matched on the last cycle) and use those to predict what should
  107. come next in the input stream. The completions and any predicted
  108. non-terminals are recursively processed until we reach a set of,
  109. which can be added to the scan list for the next scanner cycle."""
  110. held_completions.clear()
  111. column = columns[i]
  112. # R (items) = Ei (column.items)
  113. items = deque(column)
  114. while items:
  115. item = items.pop() # remove an element, A say, from R
  116. ### The Earley completer
  117. if item.is_complete: ### (item.s == string)
  118. if item.node is None:
  119. label = (item.s, item.start, i)
  120. item.node = node_cache[label] if label in node_cache else node_cache.setdefault(label, SymbolNode(*label))
  121. item.node.add_family(item.s, item.rule, item.start, None, None)
  122. create_leo_transitives(item, None, None)
  123. ###R Joop Leo right recursion Completer
  124. if item.rule.origin in transitives[item.start]:
  125. transitive = transitives[item.start][item.s]
  126. if transitive.previous in transitives[transitive.column]:
  127. root_transitive = transitives[transitive.column][transitive.previous]
  128. else:
  129. root_transitive = transitive
  130. label = (root_transitive.s, root_transitive.start, i)
  131. node = vn = node_cache[label] if label in node_cache else node_cache.setdefault(label, SymbolNode(*label))
  132. vn.add_path(root_transitive, item.node)
  133. new_item = Item(transitive.rule, transitive.ptr, transitive.start)
  134. new_item.node = vn
  135. if new_item.expect in self.TERMINALS:
  136. # Add (B :: aC.B, h, y) to Q
  137. to_scan.add(new_item)
  138. elif new_item not in column:
  139. # Add (B :: aC.B, h, y) to Ei and R
  140. column.add(new_item)
  141. items.append(new_item)
  142. ###R Regular Earley completer
  143. else:
  144. # Empty has 0 length. If we complete an empty symbol in a particular
  145. # parse step, we need to be able to use that same empty symbol to complete
  146. # any predictions that result, that themselves require empty. Avoids
  147. # infinite recursion on empty symbols.
  148. # held_completions is 'H' in E.Scott's paper.
  149. is_empty_item = item.start == i
  150. if is_empty_item:
  151. held_completions[item.rule.origin] = item.node
  152. originators = [originator for originator in columns[item.start] if originator.expect is not None and originator.expect == item.s]
  153. for originator in originators:
  154. new_item = originator.advance()
  155. label = (new_item.s, originator.start, i)
  156. new_item.node = node_cache[label] if label in node_cache else node_cache.setdefault(label, SymbolNode(*label))
  157. new_item.node.add_family(new_item.s, new_item.rule, i, originator.node, item.node)
  158. if new_item.expect in self.TERMINALS:
  159. # Add (B :: aC.B, h, y) to Q
  160. to_scan.add(new_item)
  161. elif new_item not in column:
  162. # Add (B :: aC.B, h, y) to Ei and R
  163. column.add(new_item)
  164. items.append(new_item)
  165. ### The Earley predictor
  166. elif item.expect in self.NON_TERMINALS: ### (item.s == lr0)
  167. new_items = []
  168. for rule in self.predictions[item.expect]:
  169. new_item = Item(rule, 0, i)
  170. new_items.append(new_item)
  171. # Process any held completions (H).
  172. if item.expect in held_completions:
  173. new_item = item.advance()
  174. label = (new_item.s, item.start, i)
  175. new_item.node = node_cache[label] if label in node_cache else node_cache.setdefault(label, SymbolNode(*label))
  176. new_item.node.add_family(new_item.s, new_item.rule, new_item.start, item.node, held_completions[item.expect])
  177. new_items.append(new_item)
  178. for new_item in new_items:
  179. if new_item.expect in self.TERMINALS:
  180. to_scan.add(new_item)
  181. elif new_item not in column:
  182. column.add(new_item)
  183. items.append(new_item)
  184. def scan(i, to_scan):
  185. """The core Earley Scanner.
  186. This is a custom implementation of the scanner that uses the
  187. Lark lexer to match tokens. The scan list is built by the
  188. Earley predictor, based on the previously completed tokens.
  189. This ensures that at each phase of the parse we have a custom
  190. lexer context, allowing for more complex ambiguities."""
  191. # 1) Loop the expectations and ask the lexer to match.
  192. # Since regexp is forward looking on the input stream, and we only
  193. # want to process tokens when we hit the point in the stream at which
  194. # they complete, we push all tokens into a buffer (delayed_matches), to
  195. # be held possibly for a later parse step when we reach the point in the
  196. # input stream at which they complete.
  197. for item in set(to_scan):
  198. m = match(item.expect, stream, i)
  199. if m:
  200. t = Token(item.expect.name, m.group(0), i, text_line, text_column)
  201. delayed_matches[m.end()].append( (item, i, t) )
  202. if self.complete_lex:
  203. s = m.group(0)
  204. for j in range(1, len(s)):
  205. m = match(item.expect, s[:-j])
  206. if m:
  207. t = Token(item.expect.name, m.group(0), i, text_line, text_column)
  208. delayed_matches[i+m.end()].append( (item, i, t) )
  209. # Remove any items that successfully matched in this pass from the to_scan buffer.
  210. # This ensures we don't carry over tokens that already matched, if we're ignoring below.
  211. to_scan.remove(item)
  212. # 3) Process any ignores. This is typically used for e.g. whitespace.
  213. # We carry over any unmatched items from the to_scan buffer to be matched again after
  214. # the ignore. This should allow us to use ignored symbols in non-terminals to implement
  215. # e.g. mandatory spacing.
  216. for x in self.ignore:
  217. m = match(x, stream, i)
  218. if m:
  219. # Carry over any items still in the scan buffer, to past the end of the ignored items.
  220. delayed_matches[m.end()].extend([(item, i, None) for item in to_scan ])
  221. # If we're ignoring up to the end of the file, # carry over the start symbol if it already completed.
  222. delayed_matches[m.end()].extend([(item, i, None) for item in columns[i] if item.is_complete and item.s == start_symbol])
  223. next_to_scan = set()
  224. next_set = set()
  225. columns.append(next_set)
  226. next_transitives = dict()
  227. transitives.append(next_transitives)
  228. ## 4) Process Tokens from delayed_matches.
  229. # This is the core of the Earley scanner. Create an SPPF node for each Token,
  230. # and create the symbol node in the SPPF tree. Advance the item that completed,
  231. # and add the resulting new item to either the Earley set (for processing by the
  232. # completer/predictor) or the to_scan buffer for the next parse step.
  233. for item, start, token in delayed_matches[i+1]:
  234. if token is not None:
  235. new_item = item.advance()
  236. label = (new_item.s, new_item.start, i)
  237. new_item.node = node_cache[label] if label in node_cache else node_cache.setdefault(label, SymbolNode(*label))
  238. new_item.node.add_family(new_item.s, item.rule, new_item.start, item.node, token)
  239. else:
  240. new_item = item
  241. if new_item.expect in self.TERMINALS:
  242. # add (B ::= Aai+1.B, h, y) to Q'
  243. next_to_scan.add(new_item)
  244. else:
  245. # add (B ::= Aa+1.B, h, y) to Ei+1
  246. next_set.add(new_item)
  247. del delayed_matches[i+1] # No longer needed, so unburden memory
  248. if not next_set and not delayed_matches and not next_to_scan:
  249. raise UnexpectedCharacters(stream, i, text_line, text_column, {item.expect for item in to_scan}, set(to_scan))
  250. return next_to_scan
  251. # Main loop starts
  252. columns.append(set())
  253. transitives.append(dict())
  254. ## The scan buffer. 'Q' in E.Scott's paper.
  255. to_scan = set()
  256. ## Predict for the start_symbol.
  257. # Add predicted items to the first Earley set (for the predictor) if they
  258. # result in a non-terminal, or the scanner if they result in a terminal.
  259. for rule in self.predictions[start_symbol]:
  260. item = Item(rule, 0, 0)
  261. if item.expect in self.TERMINALS:
  262. to_scan.add(item)
  263. else:
  264. columns[0].add(item)
  265. ## The main Earley loop.
  266. # Run the Prediction/Completion cycle for any Items in the current Earley set.
  267. # Completions will be added to the SPPF tree, and predictions will be recursively
  268. # processed down to terminals/empty nodes to be added to the scanner for the next
  269. # step.
  270. i = 0
  271. for token in stream:
  272. predict_and_complete(i, to_scan)
  273. # Clear the node_cache and token_cache, which are only relevant for each
  274. # step in the Earley pass.
  275. node_cache.clear()
  276. token_cache.clear()
  277. node_cache.clear()
  278. to_scan = scan(i, to_scan)
  279. if token == '\n':
  280. text_line += 1
  281. text_column = 1
  282. else:
  283. text_column += 1
  284. i += 1
  285. predict_and_complete(i, to_scan)
  286. ## Column is now the final column in the parse. If the parse was successful, the start
  287. # symbol should have been completed in the last step of the Earley cycle, and will be in
  288. # this column. Find the item for the start_symbol, which is the root of the SPPF tree.
  289. 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]
  290. if not solutions:
  291. expected_tokens = [t.expect for t in to_scan]
  292. raise ParseError('Unexpected end of input! Expecting a terminal of: %s' % expected_tokens)
  293. elif len(solutions) > 1:
  294. raise Exception('Earley should not generate more than one start symbol - bug')
  295. ## If we're not resolving ambiguity, we just return the root of the SPPF tree to the caller.
  296. # This means the caller can work directly with the SPPF tree.
  297. if not self.resolve_ambiguity:
  298. return ForestToAmbiguousTreeVisitor(self.callbacks).go(solutions[0])
  299. # ... otherwise, disambiguate and convert the SPPF to an AST, removing any ambiguities
  300. # according to the rules.
  301. return self.forest_tree_visitor.go(solutions[0])