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.

250 lines
8.3 KiB

  1. "This module implements an Earley Parser"
  2. # The parser uses a parse-forest to keep track of derivations and ambiguations.
  3. # When the parse ends successfully, a disambiguation stage resolves all ambiguity
  4. # (right now ambiguity resolution is not developed beyond the needs of lark)
  5. # Afterwards the parse tree is reduced (transformed) according to user callbacks.
  6. # I use the no-recursion version of Transformer and Visitor, because the tree might be
  7. # deeper than Python's recursion limit (a bit absurd, but that's life)
  8. #
  9. # The algorithm keeps track of each state set, using a corresponding Column instance.
  10. # Column keeps track of new items using NewsList instances.
  11. #
  12. # Author: Erez Shinan (2017)
  13. # Email : erezshin@gmail.com
  14. from ..common import ParseError, UnexpectedToken, Terminal
  15. from ..tree import Tree, Visitor_NoRecurse, Transformer_NoRecurse
  16. from .grammar_analysis import GrammarAnalyzer
  17. class EndToken:
  18. type = '$end'
  19. class Derivation(Tree):
  20. def __init__(self, rule, items=None):
  21. Tree.__init__(self, 'drv', items or [])
  22. self.rule = rule
  23. def _pretty_label(self): # Nicer pretty for debugging the parser
  24. return self.rule.origin if self.rule else self.data
  25. END_TOKEN = EndToken()
  26. class Item(object):
  27. "An Earley Item, the atom of the algorithm."
  28. def __init__(self, rule, ptr, start, tree):
  29. self.rule = rule
  30. self.ptr = ptr
  31. self.start = start
  32. self.tree = tree if tree is not None else Derivation(self.rule)
  33. @property
  34. def expect(self):
  35. return self.rule.expansion[self.ptr]
  36. @property
  37. def is_complete(self):
  38. return self.ptr == len(self.rule.expansion)
  39. def advance(self, tree):
  40. assert self.tree.data == 'drv'
  41. new_tree = Derivation(self.rule, self.tree.children + [tree])
  42. return Item(self.rule, self.ptr+1, self.start, new_tree)
  43. def similar(self, other):
  44. return self.start is other.start and self.ptr == other.ptr and self.rule == other.rule
  45. def __eq__(self, other):
  46. return self.similar(other) and (self.tree is other.tree or self.tree == other.tree)
  47. def __hash__(self):
  48. return hash((self.rule, self.ptr, id(self.start)))
  49. def __repr__(self):
  50. before = list(map(str, self.rule.expansion[:self.ptr]))
  51. after = list(map(str, self.rule.expansion[self.ptr:]))
  52. return '<(%d) %s : %s * %s>' % (id(self.start), self.rule.origin, ' '.join(before), ' '.join(after))
  53. class NewsList(list):
  54. "Keeps track of newly added items (append-only)"
  55. def __init__(self, initial=None):
  56. list.__init__(self, initial or [])
  57. self.last_iter = 0
  58. def get_news(self):
  59. i = self.last_iter
  60. self.last_iter = len(self)
  61. return self[i:]
  62. class Column:
  63. "An entry in the table, aka Earley Chart. Contains lists of items."
  64. def __init__(self, i):
  65. self.i = i
  66. self.to_reduce = NewsList()
  67. self.to_predict = NewsList()
  68. self.to_scan = NewsList()
  69. self.item_count = 0
  70. self.added = set()
  71. self.completed = {}
  72. def add(self, items):
  73. """Sort items into scan/predict/reduce newslists
  74. Makes sure only unique items are added.
  75. """
  76. for item in items:
  77. if item.is_complete:
  78. # XXX Potential bug: What happens if there's ambiguity in an empty rule?
  79. if item.rule.expansion and item in self.completed:
  80. old_tree = self.completed[item].tree
  81. if old_tree.data != '_ambig':
  82. new_tree = old_tree.copy()
  83. new_tree.rule = old_tree.rule
  84. old_tree.set('_ambig', [new_tree])
  85. old_tree.rule = None # No longer a 'drv' node
  86. if item.tree.children[0] is old_tree: # XXX a little hacky!
  87. raise ParseError("Infinite recursion in grammar! (Rule %s)" % item.rule)
  88. old_tree.children.append(item.tree)
  89. else:
  90. self.completed[item] = item
  91. self.to_reduce.append(item)
  92. else:
  93. if item not in self.added:
  94. self.added.add(item)
  95. if isinstance(item.expect, Terminal):
  96. self.to_scan.append(item)
  97. else:
  98. self.to_predict.append(item)
  99. self.item_count += 1 # Only count if actually added
  100. def __nonzero__(self):
  101. return bool(self.item_count)
  102. class Parser:
  103. def __init__(self, rules, start_symbol, callback, resolve_ambiguity=None):
  104. self.analysis = GrammarAnalyzer(rules, start_symbol)
  105. self.start_symbol = start_symbol
  106. self.resolve_ambiguity = resolve_ambiguity
  107. self.postprocess = {}
  108. self.predictions = {}
  109. for rule in self.analysis.rules:
  110. if rule.origin != '$root': # XXX kinda ugly
  111. a = rule.alias
  112. self.postprocess[rule] = a if callable(a) else (a and getattr(callback, a))
  113. self.predictions[rule.origin] = [x.rule for x in self.analysis.expand_rule(rule.origin)]
  114. def parse(self, stream, start_symbol=None):
  115. # Define parser functions
  116. start_symbol = start_symbol or self.start_symbol
  117. def predict(nonterm, column):
  118. assert not isinstance(nonterm, Terminal), nonterm
  119. return [Item(rule, 0, column, None) for rule in self.predictions[nonterm]]
  120. def complete(item):
  121. name = item.rule.origin
  122. return [i.advance(item.tree) for i in item.start.to_predict if i.expect == name]
  123. def predict_and_complete(column):
  124. while True:
  125. to_predict = {x.expect for x in column.to_predict.get_news()
  126. if x.ptr} # if not part of an already predicted batch
  127. to_reduce = column.to_reduce.get_news()
  128. if not (to_predict or to_reduce):
  129. break
  130. for nonterm in to_predict:
  131. column.add( predict(nonterm, column) )
  132. for item in to_reduce:
  133. new_items = list(complete(item))
  134. for new_item in new_items:
  135. if new_item.similar(item):
  136. raise ParseError('Infinite recursion detected! (rule %s)' % new_item.rule)
  137. column.add(new_items)
  138. def scan(i, token, column):
  139. to_scan = column.to_scan.get_news()
  140. next_set = Column(i)
  141. next_set.add(item.advance(token) for item in to_scan if item.expect.match(token))
  142. if not next_set:
  143. expect = {i.expect for i in column.to_scan}
  144. raise UnexpectedToken(token, expect, stream, i)
  145. return next_set
  146. # Main loop starts
  147. column0 = Column(0)
  148. column0.add(predict(start_symbol, column0))
  149. column = column0
  150. for i, token in enumerate(stream):
  151. predict_and_complete(column)
  152. column = scan(i, token, column)
  153. predict_and_complete(column)
  154. # Parse ended. Now build a parse tree
  155. solutions = [n.tree for n in column.to_reduce
  156. if n.rule.origin==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. tree = solutions[0]
  161. else:
  162. tree = Tree('_ambig', solutions)
  163. if self.resolve_ambiguity:
  164. tree = self.resolve_ambiguity(tree)
  165. return ApplyCallbacks(self.postprocess).transform(tree)
  166. class ApplyCallbacks(Transformer_NoRecurse):
  167. def __init__(self, postprocess):
  168. self.postprocess = postprocess
  169. def drv(self, tree):
  170. children = tree.children
  171. callback = self.postprocess[tree.rule]
  172. if callback:
  173. return callback(children)
  174. else:
  175. return Tree(rule.origin, children)
  176. # RULES = [
  177. # ('a', ['d']),
  178. # ('d', ['b']),
  179. # ('b', ['C']),
  180. # ('b', ['b', 'C']),
  181. # ('b', ['C', 'b']),
  182. # ]
  183. # p = Parser(RULES, 'a')
  184. # for x in p.parse('CC'):
  185. # print x.pretty()
  186. #---------------
  187. # RULES = [
  188. # ('s', ['a', 'a']),
  189. # ('a', ['b', 'b']),
  190. # ('b', ['C'], lambda (x,): x),
  191. # ('b', ['b', 'C']),
  192. # ]
  193. # p = Parser(RULES, 's', {})
  194. # print p.parse('CCCCC').pretty()