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.

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