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.

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