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.

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