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.

230 lines
5.9 KiB

  1. try:
  2. from future_builtins import filter
  3. except ImportError:
  4. pass
  5. from copy import deepcopy
  6. from .utils import inline_args
  7. class Tree(object):
  8. def __init__(self, data, children):
  9. self.data = data
  10. self.children = list(children)
  11. def __repr__(self):
  12. return 'Tree(%s, %s)' % (self.data, self.children)
  13. def _pretty_label(self):
  14. return self.data
  15. def _pretty(self, level, indent_str):
  16. if len(self.children) == 1 and not isinstance(self.children[0], Tree):
  17. return [ indent_str*level, self._pretty_label(), '\t', '%s' % self.children[0], '\n']
  18. l = [ indent_str*level, self._pretty_label(), '\n' ]
  19. for n in self.children:
  20. if isinstance(n, Tree):
  21. l += n._pretty(level+1, indent_str)
  22. else:
  23. l += [ indent_str*(level+1), '%s' % n, '\n' ]
  24. return l
  25. def pretty(self, indent_str=' '):
  26. return ''.join(self._pretty(0, indent_str))
  27. def expand_kids_by_index(self, *indices):
  28. for i in sorted(indices, reverse=True): # reverse so that changing tail won't affect indices
  29. kid = self.children[i]
  30. self.children[i:i+1] = kid.children
  31. def __eq__(self, other):
  32. try:
  33. return self.data == other.data and self.children == other.children
  34. except AttributeError:
  35. return False
  36. def __ne__(self, other):
  37. return not (self == other)
  38. def __hash__(self):
  39. return hash((self.data, tuple(self.children)))
  40. def find_pred(self, pred):
  41. return filter(pred, self.iter_subtrees())
  42. def find_data(self, data):
  43. return self.find_pred(lambda t: t.data == data)
  44. def scan_values(self, pred):
  45. for c in self.children:
  46. if isinstance(c, Tree):
  47. for t in c.scan_values(pred):
  48. yield t
  49. else:
  50. if pred(c):
  51. yield c
  52. def iter_subtrees(self):
  53. # TODO: Re-write as a more efficient version
  54. visited = set()
  55. q = [self]
  56. l = []
  57. while q:
  58. subtree = q.pop()
  59. l.append( subtree )
  60. if id(subtree) in visited:
  61. continue # already been here from another branch
  62. visited.add(id(subtree))
  63. q += [c for c in subtree.children if isinstance(c, Tree)]
  64. seen = set()
  65. for x in reversed(l):
  66. if id(x) not in seen:
  67. yield x
  68. seen.add(id(x))
  69. def __deepcopy__(self, memo):
  70. return type(self)(self.data, deepcopy(self.children, memo))
  71. def copy(self):
  72. return type(self)(self.data, self.children)
  73. def set(self, data, children):
  74. self.data = data
  75. self.children = children
  76. class Transformer(object):
  77. def _get_func(self, name):
  78. return getattr(self, name)
  79. def transform(self, tree):
  80. items = []
  81. for c in tree.children:
  82. try:
  83. items.append(self.transform(c) if isinstance(c, Tree) else c)
  84. except Discard:
  85. pass
  86. try:
  87. f = self._get_func(tree.data)
  88. except AttributeError:
  89. return self.__default__(tree.data, items)
  90. else:
  91. return f(items)
  92. def __default__(self, data, children):
  93. return Tree(data, children)
  94. def __mul__(self, other):
  95. return TransformerChain(self, other)
  96. class Discard(Exception):
  97. pass
  98. class TransformerChain(object):
  99. def __init__(self, *transformers):
  100. self.transformers = transformers
  101. def transform(self, tree):
  102. for t in self.transformers:
  103. tree = t.transform(tree)
  104. return tree
  105. def __mul__(self, other):
  106. return TransformerChain(*self.transformers + (other,))
  107. class InlineTransformer(Transformer):
  108. def _get_func(self, name): # use super()._get_func
  109. return inline_args(getattr(self, name)).__get__(self)
  110. class Visitor(object):
  111. def visit(self, tree):
  112. for child in tree.children:
  113. if isinstance(child, Tree):
  114. self.visit(child)
  115. f = getattr(self, tree.data, self.__default__)
  116. f(tree)
  117. return tree
  118. def __default__(self, tree):
  119. pass
  120. class Visitor_NoRecurse(Visitor):
  121. def visit(self, tree):
  122. subtrees = list(tree.iter_subtrees())
  123. for subtree in (subtrees):
  124. getattr(self, subtree.data, self.__default__)(subtree)
  125. return tree
  126. class Transformer_NoRecurse(Transformer):
  127. def transform(self, tree):
  128. subtrees = list(tree.iter_subtrees())
  129. def _t(t):
  130. # Assumes t is already transformed
  131. try:
  132. f = self._get_func(t.data)
  133. except AttributeError:
  134. return self.__default__(t)
  135. else:
  136. return f(t)
  137. for subtree in subtrees:
  138. children = []
  139. for c in subtree.children:
  140. try:
  141. children.append(_t(c) if isinstance(c, Tree) else c)
  142. except Discard:
  143. pass
  144. subtree.children = children
  145. return _t(tree)
  146. def __default__(self, t):
  147. return t
  148. def pydot__tree_to_png(tree, filename):
  149. import pydot
  150. graph = pydot.Dot(graph_type='digraph', rankdir="LR")
  151. i = [0]
  152. def new_leaf(leaf):
  153. node = pydot.Node(i[0], label=repr(leaf))
  154. i[0] += 1
  155. graph.add_node(node)
  156. return node
  157. def _to_pydot(subtree):
  158. color = hash(subtree.data) & 0xffffff
  159. color |= 0x808080
  160. subnodes = [_to_pydot(child) if isinstance(child, Tree) else new_leaf(child)
  161. for child in subtree.children]
  162. node = pydot.Node(i[0], style="filled", fillcolor="#%x"%color, label=subtree.data)
  163. i[0] += 1
  164. graph.add_node(node)
  165. for subnode in subnodes:
  166. graph.add_edge(pydot.Edge(node, subnode))
  167. return node
  168. _to_pydot(tree)
  169. graph.write_png(filename)