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.

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