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.

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