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.

652 lines
24 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 functools import partial
  13. from ..parse_tree_builder import AmbiguousIntermediateExpander
  14. from ..visitors import Discard
  15. from ..lexer import Token
  16. from ..utils import logger
  17. from ..tree import Tree
  18. class ForestNode(object):
  19. pass
  20. class SymbolNode(ForestNode):
  21. """
  22. A Symbol Node represents a symbol (or Intermediate LR0).
  23. Symbol nodes are keyed by the symbol (s). For intermediate nodes
  24. s will be an LR0, stored as a tuple of (rule, ptr). For completed symbol
  25. nodes, s will be a string representing the non-terminal origin (i.e.
  26. the left hand side of the rule).
  27. The children of a Symbol or Intermediate Node will always be Packed Nodes;
  28. with each Packed Node child representing a single derivation of a production.
  29. Hence a Symbol Node with a single child is unambiguous.
  30. """
  31. __slots__ = ('s', 'start', 'end', '_children', 'paths', 'paths_loaded', 'priority', 'is_intermediate', '_hash')
  32. def __init__(self, s, start, end):
  33. self.s = s
  34. self.start = start
  35. self.end = end
  36. self._children = set()
  37. self.paths = set()
  38. self.paths_loaded = False
  39. ### We use inf here as it can be safely negated without resorting to conditionals,
  40. # unlike None or float('NaN'), and sorts appropriately.
  41. self.priority = float('-inf')
  42. self.is_intermediate = isinstance(s, tuple)
  43. self._hash = hash((self.s, self.start, self.end))
  44. def add_family(self, lr0, rule, start, left, right):
  45. self._children.add(PackedNode(self, lr0, rule, start, left, right))
  46. def add_path(self, transitive, node):
  47. self.paths.add((transitive, node))
  48. def load_paths(self):
  49. for transitive, node in self.paths:
  50. if transitive.next_titem is not None:
  51. vn = SymbolNode(transitive.next_titem.s, transitive.next_titem.start, self.end)
  52. vn.add_path(transitive.next_titem, node)
  53. self.add_family(transitive.reduction.rule.origin, transitive.reduction.rule, transitive.reduction.start, transitive.reduction.node, vn)
  54. else:
  55. self.add_family(transitive.reduction.rule.origin, transitive.reduction.rule, transitive.reduction.start, transitive.reduction.node, node)
  56. self.paths_loaded = True
  57. @property
  58. def is_ambiguous(self):
  59. return len(self.children) > 1
  60. @property
  61. def children(self):
  62. if not self.paths_loaded: self.load_paths()
  63. return sorted(self._children, key=attrgetter('sort_key'))
  64. def __iter__(self):
  65. return iter(self._children)
  66. def __eq__(self, other):
  67. if not isinstance(other, SymbolNode):
  68. return False
  69. 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)
  70. def __hash__(self):
  71. return self._hash
  72. def __repr__(self):
  73. if self.is_intermediate:
  74. rule = self.s[0]
  75. ptr = self.s[1]
  76. before = ( expansion.name for expansion in rule.expansion[:ptr] )
  77. after = ( expansion.name for expansion in rule.expansion[ptr:] )
  78. symbol = "{} ::= {}* {}".format(rule.origin.name, ' '.join(before), ' '.join(after))
  79. else:
  80. symbol = self.s.name
  81. return "({}, {}, {}, {})".format(symbol, self.start, self.end, self.priority)
  82. class PackedNode(ForestNode):
  83. """
  84. A Packed Node represents a single derivation in a symbol node.
  85. """
  86. __slots__ = ('parent', 's', 'rule', 'start', 'left', 'right', 'priority', '_hash')
  87. def __init__(self, parent, s, rule, start, left, right):
  88. self.parent = parent
  89. self.s = s
  90. self.start = start
  91. self.rule = rule
  92. self.left = left
  93. self.right = right
  94. self.priority = float('-inf')
  95. self._hash = hash((self.left, self.right))
  96. @property
  97. def is_empty(self):
  98. return self.left is None and self.right is None
  99. @property
  100. def sort_key(self):
  101. """
  102. Used to sort PackedNode children of SymbolNodes.
  103. A SymbolNode has multiple PackedNodes if it matched
  104. ambiguously. Hence, we use the sort order to identify
  105. the order in which ambiguous children should be considered.
  106. """
  107. return self.is_empty, -self.priority, self.rule.order
  108. @property
  109. def children(self):
  110. return [x for x in [self.left, self.right] if x is not None]
  111. def __iter__(self):
  112. return iter([self.left, self.right])
  113. def __eq__(self, other):
  114. if not isinstance(other, PackedNode):
  115. return False
  116. return self is other or (self.left == other.left and self.right == other.right)
  117. def __hash__(self):
  118. return self._hash
  119. def __repr__(self):
  120. if isinstance(self.s, tuple):
  121. rule = self.s[0]
  122. ptr = self.s[1]
  123. before = ( expansion.name for expansion in rule.expansion[:ptr] )
  124. after = ( expansion.name for expansion in rule.expansion[ptr:] )
  125. symbol = "{} ::= {}* {}".format(rule.origin.name, ' '.join(before), ' '.join(after))
  126. else:
  127. symbol = self.s.name
  128. return "({}, {}, {}, {})".format(symbol, self.start, self.priority, self.rule.order)
  129. class ForestVisitor(object):
  130. """
  131. An abstract base class for building forest visitors.
  132. Use this as a base when you need to walk the forest.
  133. """
  134. def visit_token_node(self, node): pass
  135. def visit_symbol_node_in(self, node): pass
  136. def visit_symbol_node_out(self, node): pass
  137. def visit_packed_node_in(self, node): pass
  138. def visit_packed_node_out(self, node): pass
  139. def on_cycle(self, node, get_path): pass
  140. def visit(self, root):
  141. def make_get_path(node):
  142. """Create a function that will return a path from `node` to
  143. the last visited node. Used for the `on_cycle` callback."""
  144. def get_path():
  145. index = len(path) - 1
  146. while id(path[index]) != id(node):
  147. index -= 1
  148. return path[index:]
  149. return get_path
  150. # Visiting is a list of IDs of all symbol/intermediate nodes currently in
  151. # the stack. It serves two purposes: to detect when we 'recurse' in and out
  152. # of a symbol/intermediate so that we can process both up and down. Also,
  153. # since the SPPF can have cycles it allows us to detect if we're trying
  154. # to recurse into a node that's already on the stack (infinite recursion).
  155. visiting = set()
  156. # a list of nodes that are currently being visited
  157. # used for the `on_cycle` callback
  158. path = list()
  159. # We do not use recursion here to walk the Forest due to the limited
  160. # stack size in python. Therefore input_stack is essentially our stack.
  161. input_stack = deque([root])
  162. # It is much faster to cache these as locals since they are called
  163. # many times in large parses.
  164. vpno = getattr(self, 'visit_packed_node_out')
  165. vpni = getattr(self, 'visit_packed_node_in')
  166. vsno = getattr(self, 'visit_symbol_node_out')
  167. vsni = getattr(self, 'visit_symbol_node_in')
  168. vino = getattr(self, 'visit_intermediate_node_out', vsno)
  169. vini = getattr(self, 'visit_intermediate_node_in', vsni)
  170. vtn = getattr(self, 'visit_token_node')
  171. oc = getattr(self, 'on_cycle')
  172. while input_stack:
  173. current = next(reversed(input_stack))
  174. try:
  175. next_node = next(current)
  176. except StopIteration:
  177. input_stack.pop()
  178. continue
  179. except TypeError:
  180. ### If the current object is not an iterator, pass through to Token/SymbolNode
  181. pass
  182. else:
  183. if next_node is None:
  184. continue
  185. if id(next_node) in visiting:
  186. oc(next_node, make_get_path(next_node))
  187. continue
  188. input_stack.append(next_node)
  189. continue
  190. if not isinstance(current, ForestNode):
  191. vtn(current)
  192. input_stack.pop()
  193. continue
  194. current_id = id(current)
  195. if current_id in visiting:
  196. if isinstance(current, PackedNode):
  197. vpno(current)
  198. elif current.is_intermediate:
  199. vino(current)
  200. else:
  201. vsno(current)
  202. input_stack.pop()
  203. path.pop()
  204. visiting.remove(current_id)
  205. continue
  206. else:
  207. visiting.add(current_id)
  208. path.append(current)
  209. if isinstance(current, PackedNode):
  210. next_node = vpni(current)
  211. elif current.is_intermediate:
  212. next_node = vini(current)
  213. else:
  214. next_node = vsni(current)
  215. if next_node is None:
  216. continue
  217. if not isinstance(next_node, ForestNode) and \
  218. not isinstance(next_node, Token):
  219. next_node = iter(next_node)
  220. elif id(next_node) in visiting:
  221. oc(next_node, make_get_path(next_node))
  222. continue
  223. input_stack.append(next_node)
  224. continue
  225. class ForestTransformer(ForestVisitor):
  226. """The base class for a bottom-up forest transformation.
  227. Transformations are applied via inheritance and overriding of the
  228. following methods:
  229. transform_symbol_node
  230. transform_intermediate_node
  231. transform_packed_node
  232. transform_token_node
  233. `transform_token_node` receives a Token as an argument.
  234. All other methods receive the node that is being transformed and
  235. a list of the results of the transformations of that node's children.
  236. The return value of these methods are the resulting transformations.
  237. If `Discard` is raised in a transformation, no data from that node
  238. will be passed to its parent's transformation.
  239. """
  240. def __init__(self):
  241. # results of transformations
  242. self.data = dict()
  243. # used to track parent nodes
  244. self.node_stack = deque()
  245. def transform(self, root):
  246. """Perform a transformation on a Forest."""
  247. self.node_stack.append('result')
  248. self.data['result'] = []
  249. self.visit(root)
  250. assert len(self.data['result']) <= 1
  251. if self.data['result']:
  252. return self.data['result'][0]
  253. def transform_symbol_node(self, node, data):
  254. return node
  255. def transform_intermediate_node(self, node, data):
  256. return node
  257. def transform_packed_node(self, node, data):
  258. return node
  259. def transform_token_node(self, node):
  260. return node
  261. def visit_symbol_node_in(self, node):
  262. self.node_stack.append(id(node))
  263. self.data[id(node)] = []
  264. return node.children
  265. def visit_packed_node_in(self, node):
  266. self.node_stack.append(id(node))
  267. self.data[id(node)] = []
  268. return node.children
  269. def visit_token_node(self, node):
  270. try:
  271. transformed = self.transform_token_node(node)
  272. except Discard:
  273. pass
  274. else:
  275. self.data[self.node_stack[-1]].append(transformed)
  276. def visit_symbol_node_out(self, node):
  277. self.node_stack.pop()
  278. try:
  279. transformed = self.transform_symbol_node(node, self.data[id(node)])
  280. except Discard:
  281. pass
  282. else:
  283. self.data[self.node_stack[-1]].append(transformed)
  284. finally:
  285. del self.data[id(node)]
  286. def visit_intermediate_node_out(self, node):
  287. self.node_stack.pop()
  288. try:
  289. transformed = self.transform_intermediate_node(node, self.data[id(node)])
  290. except Discard:
  291. pass
  292. else:
  293. self.data[self.node_stack[-1]].append(transformed)
  294. finally:
  295. del self.data[id(node)]
  296. def visit_packed_node_out(self, node):
  297. self.node_stack.pop()
  298. try:
  299. transformed = self.transform_packed_node(node, self.data[id(node)])
  300. except Discard:
  301. pass
  302. else:
  303. self.data[self.node_stack[-1]].append(transformed)
  304. finally:
  305. del self.data[id(node)]
  306. class ForestSumVisitor(ForestVisitor):
  307. """
  308. A visitor for prioritizing ambiguous parts of the Forest.
  309. This visitor is used when support for explicit priorities on
  310. rules is requested (whether normal, or invert). It walks the
  311. forest (or subsets thereof) and cascades properties upwards
  312. from the leaves.
  313. It would be ideal to do this during parsing, however this would
  314. require processing each Earley item multiple times. That's
  315. a big performance drawback; so running a forest walk is the
  316. lesser of two evils: there can be significantly more Earley
  317. items created during parsing than there are SPPF nodes in the
  318. final tree.
  319. """
  320. def visit_packed_node_in(self, node):
  321. return iter([node.left, node.right])
  322. def visit_symbol_node_in(self, node):
  323. return iter(node.children)
  324. def visit_packed_node_out(self, node):
  325. priority = node.rule.options.priority if not node.parent.is_intermediate and node.rule.options.priority else 0
  326. priority += getattr(node.right, 'priority', 0)
  327. priority += getattr(node.left, 'priority', 0)
  328. node.priority = priority
  329. def visit_symbol_node_out(self, node):
  330. node.priority = max(child.priority for child in node.children)
  331. class ForestToParseTree(ForestTransformer):
  332. """Used by the earley parser when ambiguity equals 'resolve' or
  333. 'explicit'. Transforms an SPPF into an (ambiguous) parse tree.
  334. tree_class: The Tree class to use for construction
  335. callbacks: A dictionary of rules to functions that output a tree
  336. prioritizer: A ForestVisitor that manipulates the priorities of
  337. ForestNodes
  338. resolve_ambiguity: If True, ambiguities will be resolved based on
  339. priorities. Otherwise, `_ambig` nodes will be in the resulting
  340. tree.
  341. """
  342. def __init__(self, tree_class=Tree, callbacks=dict(), prioritizer=ForestSumVisitor(), resolve_ambiguity=True):
  343. super(ForestToParseTree, self).__init__()
  344. self.tree_class = tree_class
  345. self.callbacks = callbacks
  346. self.prioritizer = prioritizer
  347. self.resolve_ambiguity = resolve_ambiguity
  348. self._on_cycle_retreat = False
  349. def on_cycle(self, node, get_path):
  350. logger.warning("Cycle encountered in the SPPF at node: %s. "
  351. "As infinite ambiguities cannot be represented in a tree, "
  352. "this family of derivations will be discarded.", node)
  353. if self.resolve_ambiguity:
  354. # TODO: choose a different path if cycle is encountered
  355. logger.warning("At this time, using ambiguity resolution for SPPFs "
  356. "with cycles may result in None being returned.")
  357. self._on_cycle_retreat = True
  358. def _check_cycle(self, node):
  359. if self._on_cycle_retreat:
  360. raise Discard
  361. def _collapse_ambig(self, children):
  362. new_children = []
  363. for child in children:
  364. if hasattr(child, 'data') and child.data == '_ambig':
  365. new_children += child.children
  366. else:
  367. new_children.append(child)
  368. return new_children
  369. def _call_rule_func(self, node, data):
  370. # called when transforming children of symbol nodes
  371. # data is a list of trees or tokens that correspond to the
  372. # symbol's rule expansion
  373. return self.callbacks[node.rule](data)
  374. def _call_ambig_func(self, node, data):
  375. # called when transforming a symbol node
  376. # data is a list of trees where each tree's data is
  377. # equal to the name of the symbol or one of its aliases.
  378. if len(data) > 1:
  379. return self.tree_class('_ambig', data)
  380. elif data:
  381. return data[0]
  382. raise Discard
  383. def transform_symbol_node(self, node, data):
  384. self._check_cycle(node)
  385. data = self._collapse_ambig(data)
  386. return self._call_ambig_func(node, data)
  387. def transform_intermediate_node(self, node, data):
  388. self._check_cycle(node)
  389. if len(data) > 1:
  390. children = [self.tree_class('_inter', c) for c in data]
  391. return self.tree_class('_iambig', children)
  392. return data[0]
  393. def transform_packed_node(self, node, data):
  394. self._check_cycle(node)
  395. children = list()
  396. assert len(data) <= 2
  397. if node.left:
  398. if node.left.is_intermediate and isinstance(data[0], list):
  399. children += data[0]
  400. else:
  401. children.append(data[0])
  402. if len(data) > 1:
  403. children.append(data[1])
  404. elif data:
  405. children.append(data[0])
  406. if node.parent.is_intermediate:
  407. return children
  408. return self._call_rule_func(node, children)
  409. def visit_symbol_node_in(self, node):
  410. self._on_cycle_retreat = False
  411. super(ForestToParseTree, self).visit_symbol_node_in(node)
  412. if self.prioritizer and node.is_ambiguous and isinf(node.priority):
  413. self.prioritizer.visit(node)
  414. if self.resolve_ambiguity:
  415. return node.children[0]
  416. return node.children
  417. def visit_packed_node_in(self, node):
  418. self._on_cycle_retreat = False
  419. return super(ForestToParseTree, self).visit_packed_node_in(node)
  420. def visit_token_node(self, node):
  421. self._on_cycle_retreat = False
  422. return super(ForestToParseTree, self).visit_token_node(node)
  423. def handles_ambiguity(func):
  424. """Decorator for methods of subclasses of TreeForestTransformer.
  425. Denotes that the method should receive a list of transformed derivations."""
  426. func.handles_ambiguity = True
  427. return func
  428. class TreeForestTransformer(ForestToParseTree):
  429. """A ForestTransformer with a tree-Transformer-like interface.
  430. By default, it will construct a tree.
  431. Methods provided via inheritance are called based on the rule/symbol
  432. names of nodes in the forest.
  433. Methods that act on rules will receive a list of the results of the
  434. transformations of the rule's children. By default, trees and tokens.
  435. Methods that act on tokens will receive a Token.
  436. Alternatively, methods that act on rules may be annotated with
  437. `handles_ambiguity`. In this case, the function will receive a list
  438. of all the transformations of all the derivations of the rule.
  439. By default, a list of trees where each tree.data is equal to the
  440. rule name or one of its aliases.
  441. Non-tree transformations are made possible by override of
  442. `__default__`, `__default_token__`, and `__default_ambig__`.
  443. """
  444. def __init__(self, tree_class=Tree, prioritizer=ForestSumVisitor(), resolve_ambiguity=True):
  445. super(TreeForestTransformer, self).__init__(tree_class, dict(), prioritizer, resolve_ambiguity)
  446. def __default__(self, name, data):
  447. """Default operation on tree (for override).
  448. Returns a tree with name with data as children.
  449. """
  450. return self.tree_class(name, data)
  451. def __default_ambig__(self, name, data):
  452. """Default operation on ambiguous rule (for override).
  453. Wraps data in an '_ambig_ node if it contains more than
  454. one element.'
  455. """
  456. if len(data) > 1:
  457. return self.tree_class('_ambig', data)
  458. elif data:
  459. return data[0]
  460. raise Discard
  461. def __default_token__(self, node):
  462. """Default operation on Token (for override).
  463. Returns node
  464. """
  465. return node
  466. def transform_token_node(self, node):
  467. return getattr(self, node.type, self.__default_token__)(node)
  468. def _call_rule_func(self, node, data):
  469. name = node.rule.alias or node.rule.options.template_source or node.rule.origin.name
  470. user_func = getattr(self, name, self.__default__)
  471. if user_func == self.__default__ or hasattr(user_func, 'handles_ambiguity'):
  472. user_func = partial(self.__default__, name)
  473. if not self.resolve_ambiguity:
  474. wrapper = partial(AmbiguousIntermediateExpander, self.tree_class)
  475. user_func = wrapper(user_func)
  476. return user_func(data)
  477. def _call_ambig_func(self, node, data):
  478. name = node.s.name
  479. user_func = getattr(self, name, self.__default_ambig__)
  480. if user_func == self.__default_ambig__ or not hasattr(user_func, 'handles_ambiguity'):
  481. user_func = partial(self.__default_ambig__, name)
  482. return user_func(data)
  483. class ForestToPyDotVisitor(ForestVisitor):
  484. """
  485. A Forest visitor which writes the SPPF to a PNG.
  486. The SPPF can get really large, really quickly because
  487. of the amount of meta-data it stores, so this is probably
  488. only useful for trivial trees and learning how the SPPF
  489. is structured.
  490. """
  491. def __init__(self, rankdir="TB"):
  492. self.pydot = import_module('pydot')
  493. self.graph = self.pydot.Dot(graph_type='digraph', rankdir=rankdir)
  494. def visit(self, root, filename):
  495. super(ForestToPyDotVisitor, self).visit(root)
  496. self.graph.write_png(filename)
  497. def visit_token_node(self, node):
  498. graph_node_id = str(id(node))
  499. graph_node_label = "\"{}\"".format(node.value.replace('"', '\\"'))
  500. graph_node_color = 0x808080
  501. graph_node_style = "\"filled,rounded\""
  502. graph_node_shape = "diamond"
  503. 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)
  504. self.graph.add_node(graph_node)
  505. def visit_packed_node_in(self, node):
  506. graph_node_id = str(id(node))
  507. graph_node_label = repr(node)
  508. graph_node_color = 0x808080
  509. graph_node_style = "filled"
  510. graph_node_shape = "diamond"
  511. 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)
  512. self.graph.add_node(graph_node)
  513. return iter([node.left, node.right])
  514. def visit_packed_node_out(self, node):
  515. graph_node_id = str(id(node))
  516. graph_node = self.graph.get_node(graph_node_id)[0]
  517. for child in [node.left, node.right]:
  518. if child is not None:
  519. child_graph_node_id = str(id(child))
  520. child_graph_node = self.graph.get_node(child_graph_node_id)[0]
  521. self.graph.add_edge(self.pydot.Edge(graph_node, child_graph_node))
  522. else:
  523. #### Try and be above the Python object ID range; probably impl. specific, but maybe this is okay.
  524. child_graph_node_id = str(randint(100000000000000000000000000000,123456789012345678901234567890))
  525. child_graph_node_style = "invis"
  526. child_graph_node = self.pydot.Node(child_graph_node_id, style=child_graph_node_style, label="None")
  527. child_edge_style = "invis"
  528. self.graph.add_node(child_graph_node)
  529. self.graph.add_edge(self.pydot.Edge(graph_node, child_graph_node, style=child_edge_style))
  530. def visit_symbol_node_in(self, node):
  531. graph_node_id = str(id(node))
  532. graph_node_label = repr(node)
  533. graph_node_color = 0x808080
  534. graph_node_style = "\"filled\""
  535. if node.is_intermediate:
  536. graph_node_shape = "ellipse"
  537. else:
  538. graph_node_shape = "rectangle"
  539. 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)
  540. self.graph.add_node(graph_node)
  541. return iter(node.children)
  542. def visit_symbol_node_out(self, node):
  543. graph_node_id = str(id(node))
  544. graph_node = self.graph.get_node(graph_node_id)[0]
  545. for child in node.children:
  546. child_graph_node_id = str(id(child))
  547. child_graph_node = self.graph.get_node(child_graph_node_id)[0]
  548. self.graph.add_edge(self.pydot.Edge(graph_node, child_graph_node))