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.

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