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.

347 lines
13 KiB

  1. """"This module implements an SPPF implementation
  2. This is used as the primary output mechanism for the Earley parser
  3. in order to store complex ambiguities.
  4. Full reference and more details is here:
  5. http://www.bramvandersanden.com/post/2014/06/shared-packed-parse-forest/
  6. """
  7. from ..tree import Tree
  8. from ..exceptions import ParseError
  9. from ..lexer import Token
  10. from ..utils import Str
  11. from ..grammar import NonTerminal, Terminal
  12. from .earley_common import Column, Derivation
  13. from collections import deque
  14. class SymbolNode(object):
  15. """
  16. A Symbol Node represents a symbol (or Intermediate LR0).
  17. Symbol nodes are keyed by the symbol (s). For intermediate nodes
  18. s will be an LR0, stored as a tuple of (rule, ptr). For completed symbol
  19. nodes, s will be a string representing the non-terminal origin (i.e.
  20. the left hand side of the rule).
  21. The children of a Symbol or Intermediate Node will always be Packed Nodes;
  22. with each Packed Node child representing a single derivation of a production.
  23. Hence a Symbol Node with a single child is unambiguous.
  24. """
  25. __slots__ = ('s', 'start', 'end', 'children', 'priority', 'is_intermediate')
  26. def __init__(self, s, start, end):
  27. self.s = s
  28. self.start = start
  29. self.end = end
  30. self.children = set()
  31. self.priority = None
  32. self.is_intermediate = isinstance(s, tuple)
  33. def add_family(self, lr0, rule, start, left, right):
  34. self.children.add(PackedNode(self, lr0, rule, start, left, right))
  35. @property
  36. def is_ambiguous(self):
  37. return len(self.children) > 1
  38. def __iter__(self):
  39. return iter(self.children)
  40. def __eq__(self, other):
  41. if not isinstance(other, SymbolNode):
  42. return False
  43. return self is other or (self.s == other.s and self.start == other.start and self.end is other.end)
  44. def __hash__(self):
  45. return hash((self.s, self.start.i, self.end.i))
  46. def __repr__(self):
  47. symbol = self.s.name if isinstance(self.s, (NonTerminal, Terminal)) else self.s[0].origin.name
  48. return "(%s, %d, %d, %d)" % (symbol, self.start.i, self.end.i, self.priority if self.priority is not None else 0)
  49. class PackedNode(object):
  50. """
  51. A Packed Node represents a single derivation in a symbol node.
  52. """
  53. __slots__ = ('parent', 's', 'rule', 'start', 'left', 'right', 'priority', '_hash')
  54. def __init__(self, parent, s, rule, start, left, right):
  55. self.parent = parent
  56. self.s = s
  57. self.start = start
  58. self.rule = rule
  59. self.left = left
  60. self.right = right
  61. self.priority = None
  62. self._hash = hash((self.s, self.start.i, self.left, self.right))
  63. @property
  64. def is_empty(self):
  65. return self.left is None and self.right is None
  66. def __iter__(self):
  67. return iter([self.left, self.right])
  68. def __lt__(self, other):
  69. if self.is_empty and not other.is_empty: return True
  70. if self.priority < other.priority: return True
  71. return False
  72. def __gt__(self, other):
  73. if self.is_empty and not other.is_empty: return True
  74. if self.priority > other.priority: return True
  75. return False
  76. def __eq__(self, other):
  77. if not isinstance(other, PackedNode):
  78. return False
  79. return self is other or (self.s == other.s and self.start == other.start and self.left == other.left and self.right == other.right)
  80. def __hash__(self):
  81. return self._hash
  82. def __repr__(self):
  83. symbol = self.s.name if isinstance(self.s, (NonTerminal, Terminal)) else self.s[0].origin.name
  84. return "{%s, %d, %s, %s, %s}" % (symbol, self.start.i, self.left, self.right, self.priority if self.priority is not None else 0)
  85. class ForestVisitor(object):
  86. """
  87. An abstract base class for building forest visitors.
  88. Use this as a base when you need to walk the forest.
  89. """
  90. def __init__(self, root):
  91. self.root = root
  92. self.result = None
  93. def visit_token_node(self, node): pass
  94. def visit_symbol_node_in(self, node): pass
  95. def visit_symbol_node_out(self, node): pass
  96. def visit_packed_node_in(self, node): pass
  97. def visit_packed_node_out(self, node): pass
  98. def go(self):
  99. # Visiting is a list of IDs of all symbol/intermediate nodes currently in
  100. # the stack. It serves two purposes: to detect when we 'recurse' in and out
  101. # of a symbol/intermediate so that we can process both up and down. Also,
  102. # since the SPPF can have cycles it allows us to detect if we're trying
  103. # to recurse into a node that's already on the stack (infinite recursion).
  104. visiting = set()
  105. # We do not use recursion here to walk the Forest due to the limited
  106. # stack size in python. Therefore input_stack is essentially our stack.
  107. input_stack = deque([self.root])
  108. # It is much faster to cache these as locals since they are called
  109. # many times in large parses.
  110. vpno = getattr(self, 'visit_packed_node_out')
  111. vpni = getattr(self, 'visit_packed_node_in')
  112. vsno = getattr(self, 'visit_symbol_node_out')
  113. vsni = getattr(self, 'visit_symbol_node_in')
  114. vtn = getattr(self, 'visit_token_node')
  115. while input_stack:
  116. current = next(reversed(input_stack))
  117. try:
  118. next_node = next(current)
  119. except StopIteration:
  120. input_stack.pop()
  121. continue
  122. except TypeError:
  123. ### If the current object is not an iterator, pass through to Token/SymbolNode
  124. pass
  125. else:
  126. if next_node is None:
  127. continue
  128. if id(next_node) in visiting:
  129. raise ParseError("Infinite recursion in grammar!")
  130. input_stack.append(next_node)
  131. continue
  132. if isinstance(current, Str):
  133. vtn(current)
  134. input_stack.pop()
  135. continue
  136. current_id = id(current)
  137. if current_id in visiting:
  138. if isinstance(current, PackedNode): vpno(current)
  139. else: vsno(current)
  140. input_stack.pop()
  141. visiting.remove(current_id)
  142. continue
  143. else:
  144. visiting.add(current_id)
  145. if isinstance(current, PackedNode): next_node = vpni(current)
  146. else: next_node = vsni(current)
  147. if next_node is None:
  148. continue
  149. if id(next_node) in visiting:
  150. raise ParseError("Infinite recursion in grammar!")
  151. input_stack.append(next_node)
  152. continue
  153. return self.result
  154. class ForestSumVisitor(ForestVisitor):
  155. """
  156. A visitor for prioritizing ambiguous parts of the Forest.
  157. This visitor is the default when resolving ambiguity. It pushes the priorities
  158. from the rules into the SPPF nodes; and then sorts the packed node children
  159. of ambiguous symbol or intermediate node according to the priorities.
  160. This relies on the custom sort function provided in PackedNode.__lt__; which
  161. uses these properties (and other factors) to sort the ambiguous packed nodes.
  162. """
  163. def visit_packed_node_in(self, node):
  164. return iter([node.left, node.right])
  165. def visit_symbol_node_in(self, node):
  166. return iter(node.children)
  167. def visit_packed_node_out(self, node):
  168. node.priority = 0
  169. if node.rule.options and node.rule.options.priority: node.priority += node.rule.options.priority
  170. if node.right is not None and hasattr(node.right, 'priority'): node.priority += node.right.priority
  171. if node.left is not None and hasattr(node.left, 'priority'): node.priority += node.left.priority
  172. def visit_symbol_node_out(self, node):
  173. node.priority = max(child.priority for child in node.children)
  174. node.children = sorted(node.children, reverse = True)
  175. class ForestAntiscoreSumVisitor(ForestSumVisitor):
  176. """
  177. A visitor for prioritizing ambiguous parts of the Forest.
  178. This visitor is used when resolve_ambiguity == 'resolve__antiscore_sum'.
  179. It pushes the priorities from the rules into the SPPF nodes, and implements
  180. a 'least cost' mechanism for resolving ambiguity (reverse of the default
  181. priority mechanism). It uses a custom __lt__ comparator key for sorting
  182. the packed node children.
  183. """
  184. def visit_symbol_node_out(self, node):
  185. node.priority = min(child.priority for child in node.children)
  186. node.children = sorted(node.children, key=AntiscoreSumComparator, reverse = True)
  187. class AntiscoreSumComparator(object):
  188. """
  189. An antiscore-sum comparator for PackedNode objects.
  190. This allows 'sorting' an iterable of PackedNode objects so that they
  191. are arranged lowest priority first.
  192. """
  193. __slots__ = ['obj']
  194. def __init__(self, obj, *args):
  195. self.obj = obj
  196. def __lt__(self, other):
  197. if self.obj.is_empty and not other.obj.is_empty: return True
  198. if self.obj.priority > other.obj.priority: return True
  199. return False
  200. def __gt__(self, other):
  201. if self.obj.is_empty and not other.obj.is_empty: return True
  202. if self.obj.priority < other.obj.priority: return True
  203. return False
  204. class ForestToTreeVisitor(ForestVisitor):
  205. """
  206. A Forest visitor which converts an SPPF forest to an unambiguous AST.
  207. The implementation in this visitor walks only the first ambiguous child
  208. of each symbol node. When it finds an ambiguous symbol node it first
  209. calls the forest_sum_visitor implementation to sort the children
  210. into preference order using the algorithms defined there; so the first
  211. child should always be the highest preference. The forest_sum_visitor
  212. implementation should be another ForestVisitor which sorts the children
  213. according to some priority mechanism.
  214. """
  215. def __init__(self, root, forest_sum_visitor = ForestSumVisitor, callbacks = None):
  216. super(ForestToTreeVisitor, self).__init__(root)
  217. self.forest_sum_visitor = forest_sum_visitor
  218. self.output_stack = deque()
  219. self.callbacks = callbacks
  220. self.result = None
  221. def visit_token_node(self, node):
  222. self.output_stack[-1].append(node)
  223. def visit_symbol_node_in(self, node):
  224. if node.is_ambiguous and node.priority is None:
  225. self.forest_sum_visitor(node).go()
  226. return next(iter(node.children))
  227. def visit_packed_node_in(self, node):
  228. if not node.parent.is_intermediate:
  229. self.output_stack.append([])
  230. return iter([node.left, node.right])
  231. def visit_packed_node_out(self, node):
  232. if not node.parent.is_intermediate:
  233. result = self.callbacks[node.rule](self.output_stack.pop())
  234. if self.output_stack:
  235. self.output_stack[-1].append(result)
  236. else:
  237. self.result = result
  238. class ForestToAmbiguousTreeVisitor(ForestVisitor):
  239. """
  240. A Forest visitor which converts an SPPF forest to an ambiguous AST.
  241. Because of the fundamental disparity between what can be stored in
  242. an SPPF and what can be stored in a Tree; this implementation is not
  243. complete. It correctly deals with ambiguities that occur on symbol nodes only,
  244. and cannot deal with ambiguities that occur on intermediate nodes.
  245. Usually, most parsers can be rewritten to avoid intermediate node
  246. ambiguities. Also, this implementation could be fixed, however
  247. the code to handle intermediate node ambiguities is messy and
  248. would not be performant. It is much better not to use this and
  249. instead to correctly disambiguate the forest and only store unambiguous
  250. parses in Trees. It is here just to provide some parity with the
  251. old ambiguity='explicit'.
  252. This is mainly used by the test framework, to make it simpler to write
  253. tests ensuring the SPPF contains the right results.
  254. """
  255. def __init__(self, root, callbacks):
  256. super(ForestToAmbiguousTreeVisitor, self).__init__(root)
  257. self.output_stack = deque()
  258. self.callbacks = callbacks
  259. self.result = None
  260. def visit_token_node(self, node):
  261. self.output_stack[-1].children.append(node)
  262. def visit_symbol_node_in(self, node):
  263. if not node.is_intermediate and node.is_ambiguous:
  264. self.output_stack.append(Tree('_ambig', []))
  265. return iter(node.children)
  266. def visit_symbol_node_out(self, node):
  267. if node.is_ambiguous:
  268. result = self.output_stack.pop()
  269. if self.output_stack:
  270. self.output_stack[-1].children.append(result)
  271. else:
  272. self.result = result
  273. def visit_packed_node_in(self, node):
  274. #### NOTE:
  275. ## When an intermediate node (node.parent.s == tuple) has ambiguous children this
  276. ## forest visitor will break.
  277. if not node.parent.is_intermediate:
  278. self.output_stack.append(Tree('drv', []))
  279. return iter([node.left, node.right])
  280. def visit_packed_node_out(self, node):
  281. if not node.parent.is_intermediate:
  282. result = self.callbacks[node.rule](self.output_stack.pop().children)
  283. if self.output_stack:
  284. self.output_stack[-1].children.append(result)
  285. else:
  286. self.result = result