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.

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