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.

433 lines
17 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 random import randint
  8. from ..tree import Tree
  9. from ..exceptions import ParseError
  10. from ..lexer import Token
  11. from ..utils import Str
  12. from ..grammar import NonTerminal, Terminal, Symbol
  13. from math import isinf
  14. from collections import deque
  15. from operator import attrgetter
  16. from importlib import import_module
  17. class ForestNode(object):
  18. pass
  19. class SymbolNode(ForestNode):
  20. """
  21. A Symbol Node represents a symbol (or Intermediate LR0).
  22. Symbol nodes are keyed by the symbol (s). For intermediate nodes
  23. s will be an LR0, stored as a tuple of (rule, ptr). For completed symbol
  24. nodes, s will be a string representing the non-terminal origin (i.e.
  25. the left hand side of the rule).
  26. The children of a Symbol or Intermediate Node will always be Packed Nodes;
  27. with each Packed Node child representing a single derivation of a production.
  28. Hence a Symbol Node with a single child is unambiguous.
  29. """
  30. __slots__ = ('s', 'start', 'end', '_children', 'paths', 'paths_loaded', 'priority', 'is_intermediate', '_hash')
  31. def __init__(self, s, start, end):
  32. self.s = s
  33. self.start = start
  34. self.end = end
  35. self._children = set()
  36. self.paths = set()
  37. self.paths_loaded = False
  38. ### We use inf here as it can be safely negated without resorting to conditionals,
  39. # unlike None or float('NaN'), and sorts appropriately.
  40. self.priority = float('-inf')
  41. self.is_intermediate = isinstance(s, tuple)
  42. self._hash = hash((self.s, self.start, self.end))
  43. def add_family(self, lr0, rule, start, left, right):
  44. self._children.add(PackedNode(self, lr0, rule, start, left, right))
  45. def add_path(self, transitive, node):
  46. self.paths.add((transitive, node))
  47. def load_paths(self):
  48. for transitive, node in self.paths:
  49. if transitive.next_titem is not None:
  50. vn = SymbolNode(transitive.next_titem.s, transitive.next_titem.start, self.end)
  51. vn.add_path(transitive.next_titem, node)
  52. self.add_family(transitive.reduction.rule.origin, transitive.reduction.rule, transitive.reduction.start, transitive.reduction.node, vn)
  53. else:
  54. self.add_family(transitive.reduction.rule.origin, transitive.reduction.rule, transitive.reduction.start, transitive.reduction.node, node)
  55. self.paths_loaded = True
  56. @property
  57. def is_ambiguous(self):
  58. return len(self.children) > 1
  59. @property
  60. def children(self):
  61. if not self.paths_loaded: self.load_paths()
  62. return sorted(self._children, key=attrgetter('sort_key'))
  63. def __iter__(self):
  64. return iter(self._children)
  65. def __eq__(self, other):
  66. if not isinstance(other, SymbolNode):
  67. return False
  68. return self is other or (type(self.s) == type(other.s) and self.s == other.s and self.start == other.start and self.end is other.end)
  69. def __hash__(self):
  70. return self._hash
  71. def __repr__(self):
  72. if self.is_intermediate:
  73. rule = self.s[0]
  74. ptr = self.s[1]
  75. before = ( expansion.name for expansion in rule.expansion[:ptr] )
  76. after = ( expansion.name for expansion in rule.expansion[ptr:] )
  77. symbol = "{} ::= {}* {}".format(rule.origin.name, ' '.join(before), ' '.join(after))
  78. else:
  79. symbol = self.s.name
  80. return "({}, {}, {}, {})".format(symbol, self.start, self.end, self.priority)
  81. class PackedNode(ForestNode):
  82. """
  83. A Packed Node represents a single derivation in a symbol node.
  84. """
  85. __slots__ = ('parent', 's', 'rule', 'start', 'left', 'right', 'priority', '_hash')
  86. def __init__(self, parent, s, rule, start, left, right):
  87. self.parent = parent
  88. self.s = s
  89. self.start = start
  90. self.rule = rule
  91. self.left = left
  92. self.right = right
  93. self.priority = float('-inf')
  94. self._hash = hash((self.left, self.right))
  95. @property
  96. def is_empty(self):
  97. return self.left is None and self.right is None
  98. @property
  99. def sort_key(self):
  100. """
  101. Used to sort PackedNode children of SymbolNodes.
  102. A SymbolNode has multiple PackedNodes if it matched
  103. ambiguously. Hence, we use the sort order to identify
  104. the order in which ambiguous children should be considered.
  105. """
  106. return self.is_empty, -self.priority, -self.rule.order
  107. def __iter__(self):
  108. return iter([self.left, self.right])
  109. def __eq__(self, other):
  110. if not isinstance(other, PackedNode):
  111. return False
  112. return self is other or (self.left == other.left and self.right == other.right)
  113. def __hash__(self):
  114. return self._hash
  115. def __repr__(self):
  116. if isinstance(self.s, tuple):
  117. rule = self.s[0]
  118. ptr = self.s[1]
  119. before = ( expansion.name for expansion in rule.expansion[:ptr] )
  120. after = ( expansion.name for expansion in rule.expansion[ptr:] )
  121. symbol = "{} ::= {}* {}".format(rule.origin.name, ' '.join(before), ' '.join(after))
  122. else:
  123. symbol = self.s.name
  124. return "({}, {}, {}, {})".format(symbol, self.start, self.priority, self.rule.order)
  125. class ForestVisitor(object):
  126. """
  127. An abstract base class for building forest visitors.
  128. Use this as a base when you need to walk the forest.
  129. """
  130. __slots__ = ['result']
  131. def visit_token_node(self, node): pass
  132. def visit_symbol_node_in(self, node): pass
  133. def visit_symbol_node_out(self, node): pass
  134. def visit_packed_node_in(self, node): pass
  135. def visit_packed_node_out(self, node): pass
  136. def go(self, root):
  137. self.result = None
  138. # Visiting is a list of IDs of all symbol/intermediate nodes currently in
  139. # the stack. It serves two purposes: to detect when we 'recurse' in and out
  140. # of a symbol/intermediate so that we can process both up and down. Also,
  141. # since the SPPF can have cycles it allows us to detect if we're trying
  142. # to recurse into a node that's already on the stack (infinite recursion).
  143. visiting = set()
  144. # We do not use recursion here to walk the Forest due to the limited
  145. # stack size in python. Therefore input_stack is essentially our stack.
  146. input_stack = deque([root])
  147. # It is much faster to cache these as locals since they are called
  148. # many times in large parses.
  149. vpno = getattr(self, 'visit_packed_node_out')
  150. vpni = getattr(self, 'visit_packed_node_in')
  151. vsno = getattr(self, 'visit_symbol_node_out')
  152. vsni = getattr(self, 'visit_symbol_node_in')
  153. vtn = getattr(self, 'visit_token_node')
  154. while input_stack:
  155. current = next(reversed(input_stack))
  156. try:
  157. next_node = next(current)
  158. except StopIteration:
  159. input_stack.pop()
  160. continue
  161. except TypeError:
  162. ### If the current object is not an iterator, pass through to Token/SymbolNode
  163. pass
  164. else:
  165. if next_node is None:
  166. continue
  167. if id(next_node) in visiting:
  168. raise ParseError("Infinite recursion in grammar!")
  169. input_stack.append(next_node)
  170. continue
  171. if not isinstance(current, ForestNode):
  172. vtn(current)
  173. input_stack.pop()
  174. continue
  175. current_id = id(current)
  176. if current_id in visiting:
  177. if isinstance(current, PackedNode): vpno(current)
  178. else: vsno(current)
  179. input_stack.pop()
  180. visiting.remove(current_id)
  181. continue
  182. else:
  183. visiting.add(current_id)
  184. if isinstance(current, PackedNode): next_node = vpni(current)
  185. else: next_node = vsni(current)
  186. if next_node is None:
  187. continue
  188. if id(next_node) in visiting:
  189. raise ParseError("Infinite recursion in grammar!")
  190. input_stack.append(next_node)
  191. continue
  192. return self.result
  193. class ForestSumVisitor(ForestVisitor):
  194. """
  195. A visitor for prioritizing ambiguous parts of the Forest.
  196. This visitor is used when support for explicit priorities on
  197. rules is requested (whether normal, or invert). It walks the
  198. forest (or subsets thereof) and cascades properties upwards
  199. from the leaves.
  200. It would be ideal to do this during parsing, however this would
  201. require processing each Earley item multiple times. That's
  202. a big performance drawback; so running a forest walk is the
  203. lesser of two evils: there can be significantly more Earley
  204. items created during parsing than there are SPPF nodes in the
  205. final tree.
  206. """
  207. def visit_packed_node_in(self, node):
  208. return iter([node.left, node.right])
  209. def visit_symbol_node_in(self, node):
  210. return iter(node.children)
  211. def visit_packed_node_out(self, node):
  212. priority = node.rule.options.priority if not node.parent.is_intermediate and node.rule.options and node.rule.options.priority else 0
  213. priority += getattr(node.right, 'priority', 0)
  214. priority += getattr(node.left, 'priority', 0)
  215. node.priority = priority
  216. def visit_symbol_node_out(self, node):
  217. node.priority = max(child.priority for child in node.children)
  218. class ForestToTreeVisitor(ForestVisitor):
  219. """
  220. A Forest visitor which converts an SPPF forest to an unambiguous AST.
  221. The implementation in this visitor walks only the first ambiguous child
  222. of each symbol node. When it finds an ambiguous symbol node it first
  223. calls the forest_sum_visitor implementation to sort the children
  224. into preference order using the algorithms defined there; so the first
  225. child should always be the highest preference. The forest_sum_visitor
  226. implementation should be another ForestVisitor which sorts the children
  227. according to some priority mechanism.
  228. """
  229. __slots__ = ['forest_sum_visitor', 'callbacks', 'output_stack']
  230. def __init__(self, callbacks = None, forest_sum_visitor = None):
  231. self.forest_sum_visitor = forest_sum_visitor
  232. self.callbacks = callbacks
  233. def go(self, root):
  234. self.output_stack = deque()
  235. return super(ForestToTreeVisitor, self).go(root)
  236. def visit_token_node(self, node):
  237. self.output_stack[-1].append(node)
  238. def visit_symbol_node_in(self, node):
  239. if self.forest_sum_visitor and node.is_ambiguous and isinf(node.priority):
  240. self.forest_sum_visitor.go(node)
  241. return next(iter(node.children))
  242. def visit_packed_node_in(self, node):
  243. if not node.parent.is_intermediate:
  244. self.output_stack.append([])
  245. return iter([node.left, node.right])
  246. def visit_packed_node_out(self, node):
  247. if not node.parent.is_intermediate:
  248. result = self.callbacks[node.rule](self.output_stack.pop())
  249. if self.output_stack:
  250. self.output_stack[-1].append(result)
  251. else:
  252. self.result = result
  253. class ForestToAmbiguousTreeVisitor(ForestToTreeVisitor):
  254. """
  255. A Forest visitor which converts an SPPF forest to an ambiguous AST.
  256. Because of the fundamental disparity between what can be stored in
  257. an SPPF and what can be stored in a Tree; this implementation is not
  258. complete. It correctly deals with ambiguities that occur on symbol nodes only,
  259. and cannot deal with ambiguities that occur on intermediate nodes.
  260. Usually, most parsers can be rewritten to avoid intermediate node
  261. ambiguities. Also, this implementation could be fixed, however
  262. the code to handle intermediate node ambiguities is messy and
  263. would not be performant. It is much better not to use this and
  264. instead to correctly disambiguate the forest and only store unambiguous
  265. parses in Trees. It is here just to provide some parity with the
  266. old ambiguity='explicit'.
  267. This is mainly used by the test framework, to make it simpler to write
  268. tests ensuring the SPPF contains the right results.
  269. """
  270. def __init__(self, callbacks, forest_sum_visitor = ForestSumVisitor):
  271. super(ForestToAmbiguousTreeVisitor, self).__init__(callbacks, forest_sum_visitor)
  272. def visit_token_node(self, node):
  273. self.output_stack[-1].children.append(node)
  274. def visit_symbol_node_in(self, node):
  275. if self.forest_sum_visitor and node.is_ambiguous and isinf(node.priority):
  276. self.forest_sum_visitor.go(node)
  277. if not node.is_intermediate and node.is_ambiguous:
  278. self.output_stack.append(Tree('_ambig', []))
  279. return iter(node.children)
  280. def visit_symbol_node_out(self, node):
  281. if not node.is_intermediate and node.is_ambiguous:
  282. result = self.output_stack.pop()
  283. if self.output_stack:
  284. self.output_stack[-1].children.append(result)
  285. else:
  286. self.result = result
  287. def visit_packed_node_in(self, node):
  288. if not node.parent.is_intermediate:
  289. self.output_stack.append(Tree('drv', []))
  290. return iter([node.left, node.right])
  291. def visit_packed_node_out(self, node):
  292. if not node.parent.is_intermediate:
  293. result = self.callbacks[node.rule](self.output_stack.pop().children)
  294. if self.output_stack:
  295. self.output_stack[-1].children.append(result)
  296. else:
  297. self.result = result
  298. class ForestToPyDotVisitor(ForestVisitor):
  299. """
  300. A Forest visitor which writes the SPPF to a PNG.
  301. The SPPF can get really large, really quickly because
  302. of the amount of meta-data it stores, so this is probably
  303. only useful for trivial trees and learning how the SPPF
  304. is structured.
  305. """
  306. def __init__(self, rankdir="TB"):
  307. self.pydot = import_module('pydot')
  308. self.graph = self.pydot.Dot(graph_type='digraph', rankdir=rankdir)
  309. def go(self, root, filename):
  310. super(ForestToPyDotVisitor, self).go(root)
  311. self.graph.write_png(filename)
  312. def visit_token_node(self, node):
  313. graph_node_id = str(id(node))
  314. graph_node_label = "\"{}\"".format(node.value.replace('"', '\\"'))
  315. graph_node_color = 0x808080
  316. graph_node_style = "\"filled,rounded\""
  317. graph_node_shape = "diamond"
  318. graph_node = self.pydot.Node(graph_node_id, style=graph_node_style, fillcolor="#{:06x}".format(graph_node_color), shape=graph_node_shape, label=graph_node_label)
  319. self.graph.add_node(graph_node)
  320. def visit_packed_node_in(self, node):
  321. graph_node_id = str(id(node))
  322. graph_node_label = repr(node)
  323. graph_node_color = 0x808080
  324. graph_node_style = "filled"
  325. graph_node_shape = "diamond"
  326. graph_node = self.pydot.Node(graph_node_id, style=graph_node_style, fillcolor="#{:06x}".format(graph_node_color), shape=graph_node_shape, label=graph_node_label)
  327. self.graph.add_node(graph_node)
  328. return iter([node.left, node.right])
  329. def visit_packed_node_out(self, node):
  330. graph_node_id = str(id(node))
  331. graph_node = self.graph.get_node(graph_node_id)[0]
  332. for child in [node.left, node.right]:
  333. if child is not None:
  334. child_graph_node_id = str(id(child))
  335. child_graph_node = self.graph.get_node(child_graph_node_id)[0]
  336. self.graph.add_edge(self.pydot.Edge(graph_node, child_graph_node))
  337. else:
  338. #### Try and be above the Python object ID range; probably impl. specific, but maybe this is okay.
  339. child_graph_node_id = str(randint(100000000000000000000000000000,123456789012345678901234567890))
  340. child_graph_node_style = "invis"
  341. child_graph_node = self.pydot.Node(child_graph_node_id, style=child_graph_node_style, label="None")
  342. child_edge_style = "invis"
  343. self.graph.add_node(child_graph_node)
  344. self.graph.add_edge(self.pydot.Edge(graph_node, child_graph_node, style=child_edge_style))
  345. def visit_symbol_node_in(self, node):
  346. graph_node_id = str(id(node))
  347. graph_node_label = repr(node)
  348. graph_node_color = 0x808080
  349. graph_node_style = "\"filled\""
  350. if node.is_intermediate:
  351. graph_node_shape = "ellipse"
  352. else:
  353. graph_node_shape = "rectangle"
  354. graph_node = self.pydot.Node(graph_node_id, style=graph_node_style, fillcolor="#{:06x}".format(graph_node_color), shape=graph_node_shape, label=graph_node_label)
  355. self.graph.add_node(graph_node)
  356. return iter(node.children)
  357. def visit_symbol_node_out(self, node):
  358. graph_node_id = str(id(node))
  359. graph_node = self.graph.get_node(graph_node_id)[0]
  360. for child in node.children:
  361. child_graph_node_id = str(id(child))
  362. child_graph_node = self.graph.get_node(child_graph_node_id)[0]
  363. self.graph.add_edge(self.pydot.Edge(graph_node, child_graph_node))