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.

262 lines
8.8 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 self.__class__(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 Item_JoinDerivations(Item):
  54. __eq__ = Item.similar
  55. __hash__ = Item.__hash__
  56. class NewsList(list):
  57. "Keeps track of newly added items (append-only)"
  58. def __init__(self, initial=None):
  59. list.__init__(self, initial or [])
  60. self.last_iter = 0
  61. def get_news(self):
  62. i = self.last_iter
  63. self.last_iter = len(self)
  64. return self[i:]
  65. class Column:
  66. "An entry in the table, aka Earley Chart. Contains lists of items."
  67. def __init__(self, i):
  68. self.i = i
  69. self.to_reduce = NewsList()
  70. self.to_predict = NewsList()
  71. self.to_scan = NewsList()
  72. self.item_count = 0
  73. self.added = set()
  74. self.completed = {}
  75. def add(self, items):
  76. """Sort items into scan/predict/reduce newslists
  77. Makes sure only unique items are added.
  78. """
  79. for item in items:
  80. if item.is_complete:
  81. # XXX Potential bug: What happens if there's ambiguity in an empty rule?
  82. if item.rule.expansion and item in self.completed:
  83. old_tree = self.completed[item].tree
  84. if old_tree.data != '_ambig':
  85. new_tree = old_tree.copy()
  86. new_tree.rule = old_tree.rule
  87. old_tree.set('_ambig', [new_tree])
  88. old_tree.rule = None # No longer a 'drv' node
  89. if item.tree.children[0] is old_tree: # XXX a little hacky!
  90. raise ParseError("Infinite recursion in grammar! (Rule %s)" % item.rule)
  91. old_tree.children.append(item.tree)
  92. else:
  93. self.completed[item] = item
  94. self.to_reduce.append(item)
  95. else:
  96. if item not in self.added:
  97. self.added.add(item)
  98. if isinstance(item.expect, Terminal):
  99. self.to_scan.append(item)
  100. else:
  101. self.to_predict.append(item)
  102. self.item_count += 1 # Only count if actually added
  103. def __nonzero__(self):
  104. return bool(self.item_count)
  105. class Parser:
  106. def __init__(self, rules, start_symbol, callback, resolve_ambiguity=None, all_derivations=True):
  107. """
  108. all_derivations:
  109. True = Try every rule combination, and every possible derivation of each rule. (default)
  110. False = Try every rule combination, but not every derivation of the same rule.
  111. """
  112. self.analysis = GrammarAnalyzer(rules, start_symbol)
  113. self.start_symbol = start_symbol
  114. self.resolve_ambiguity = resolve_ambiguity
  115. self.all_derivations = all_derivations
  116. self.postprocess = {}
  117. self.predictions = {}
  118. for rule in self.analysis.rules:
  119. if rule.origin != '$root': # XXX kinda ugly
  120. a = rule.alias
  121. self.postprocess[rule] = a if callable(a) else (a and getattr(callback, a))
  122. self.predictions[rule.origin] = [x.rule for x in self.analysis.expand_rule(rule.origin)]
  123. def parse(self, stream, start_symbol=None):
  124. # Define parser functions
  125. start_symbol = start_symbol or self.start_symbol
  126. _Item = Item if self.all_derivations else Item_JoinDerivations
  127. def predict(nonterm, column):
  128. assert not isinstance(nonterm, Terminal), nonterm
  129. return [_Item(rule, 0, column, None) for rule in self.predictions[nonterm]]
  130. def complete(item):
  131. name = item.rule.origin
  132. return [i.advance(item.tree) for i in item.start.to_predict if i.expect == name]
  133. def predict_and_complete(column):
  134. while True:
  135. to_predict = {x.expect for x in column.to_predict.get_news()
  136. if x.ptr} # if not part of an already predicted batch
  137. to_reduce = column.to_reduce.get_news()
  138. if not (to_predict or to_reduce):
  139. break
  140. for nonterm in to_predict:
  141. column.add( predict(nonterm, column) )
  142. for item in to_reduce:
  143. new_items = list(complete(item))
  144. for new_item in new_items:
  145. if new_item.similar(item):
  146. raise ParseError('Infinite recursion detected! (rule %s)' % new_item.rule)
  147. column.add(new_items)
  148. def scan(i, token, column):
  149. to_scan = column.to_scan.get_news()
  150. next_set = Column(i)
  151. next_set.add(item.advance(token) for item in to_scan if item.expect.match(token))
  152. if not next_set:
  153. expect = {i.expect for i in column.to_scan}
  154. raise UnexpectedToken(token, expect, stream, i)
  155. return next_set
  156. # Main loop starts
  157. column0 = Column(0)
  158. column0.add(predict(start_symbol, column0))
  159. column = column0
  160. for i, token in enumerate(stream):
  161. predict_and_complete(column)
  162. column = scan(i, token, column)
  163. predict_and_complete(column)
  164. # Parse ended. Now build a parse tree
  165. solutions = [n.tree for n in column.to_reduce
  166. if n.rule.origin==start_symbol and n.start is column0]
  167. if not solutions:
  168. raise ParseError('Incomplete parse: Could not find a solution to input')
  169. elif len(solutions) == 1:
  170. tree = solutions[0]
  171. else:
  172. tree = Tree('_ambig', solutions)
  173. if self.resolve_ambiguity:
  174. tree = self.resolve_ambiguity(tree)
  175. return ApplyCallbacks(self.postprocess).transform(tree)
  176. class ApplyCallbacks(Transformer_NoRecurse):
  177. def __init__(self, postprocess):
  178. self.postprocess = postprocess
  179. def drv(self, tree):
  180. children = tree.children
  181. callback = self.postprocess[tree.rule]
  182. if callback:
  183. return callback(children)
  184. else:
  185. return Tree(rule.origin, children)
  186. # RULES = [
  187. # ('a', ['d']),
  188. # ('d', ['b']),
  189. # ('b', ['C']),
  190. # ('b', ['b', 'C']),
  191. # ('b', ['C', 'b']),
  192. # ]
  193. # p = Parser(RULES, 'a')
  194. # for x in p.parse('CC'):
  195. # print x.pretty()
  196. #---------------
  197. # RULES = [
  198. # ('s', ['a', 'a']),
  199. # ('a', ['b', 'b']),
  200. # ('b', ['C'], lambda (x,): x),
  201. # ('b', ['b', 'C']),
  202. # ]
  203. # p = Parser(RULES, 's', {})
  204. # print p.parse('CCCCC').pretty()