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.

205 lines
5.4 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 __hash__(self):
  37. return hash((self.data, tuple(self.children)))
  38. def find_pred(self, pred):
  39. return filter(pred, self.iter_subtrees())
  40. def find_data(self, data):
  41. return self.find_pred(lambda t: t.data == data)
  42. def scan_values(self, pred):
  43. for c in self.children:
  44. if isinstance(c, Tree):
  45. for t in c.scan_values(pred):
  46. yield t
  47. else:
  48. if pred(c):
  49. yield c
  50. def iter_subtrees(self):
  51. visited = set()
  52. q = [self]
  53. while q:
  54. subtree = q.pop()
  55. if id(subtree) in visited:
  56. continue # already been here from another branch
  57. visited.add(id(subtree))
  58. yield subtree
  59. q += [c for c in subtree.children if isinstance(c, Tree)]
  60. def __deepcopy__(self, memo):
  61. return type(self)(self.data, deepcopy(self.children, memo))
  62. def copy(self):
  63. return type(self)(self.data, self.children)
  64. def set(self, data, children):
  65. self.data = data
  66. self.children = children
  67. class Transformer(object):
  68. def _get_func(self, name):
  69. return getattr(self, name)
  70. def transform(self, tree):
  71. items = [self.transform(c) if isinstance(c, Tree) else c for c in tree.children]
  72. try:
  73. f = self._get_func(tree.data)
  74. except AttributeError:
  75. return self.__default__(tree.data, items)
  76. else:
  77. return f(items)
  78. def __default__(self, data, children):
  79. return Tree(data, children)
  80. def __mul__(self, other):
  81. return TransformerChain(self, other)
  82. class TransformerChain(object):
  83. def __init__(self, *transformers):
  84. self.transformers = transformers
  85. def transform(self, tree):
  86. for t in self.transformers:
  87. tree = t.transform(tree)
  88. return tree
  89. def __mul__(self, other):
  90. return TransformerChain(*self.transformers + (other,))
  91. class InlineTransformer(Transformer):
  92. def _get_func(self, name): # use super()._get_func
  93. return inline_args(getattr(self, name)).__get__(self)
  94. class Visitor(object):
  95. def visit(self, tree):
  96. for child in tree.children:
  97. if isinstance(child, Tree):
  98. self.visit(child)
  99. f = getattr(self, tree.data, self.__default__)
  100. f(tree)
  101. return tree
  102. def __default__(self, tree):
  103. pass
  104. class Visitor_NoRecurse(Visitor):
  105. def visit(self, tree):
  106. subtrees = list(tree.iter_subtrees())
  107. for subtree in reversed(subtrees):
  108. getattr(self, subtree.data, self.__default__)(subtree)
  109. return tree
  110. class Transformer_NoRecurse(Transformer):
  111. def transform(self, tree):
  112. subtrees = list(tree.iter_subtrees())
  113. def _t(t):
  114. # Assumes t is already transformed
  115. try:
  116. f = self._get_func(t.data)
  117. except AttributeError:
  118. return self.__default__(t)
  119. else:
  120. return f(t)
  121. for subtree in reversed(subtrees):
  122. subtree.children = [_t(c) if isinstance(c, Tree) else c for c in subtree.children]
  123. return _t(tree)
  124. def __default__(self, t):
  125. return t
  126. def pydot__tree_to_png(tree, filename):
  127. import pydot
  128. graph = pydot.Dot(graph_type='digraph', rankdir="LR")
  129. i = [0]
  130. def new_leaf(leaf):
  131. node = pydot.Node(i[0], label=repr(leaf))
  132. i[0] += 1
  133. graph.add_node(node)
  134. return node
  135. def _to_pydot(subtree):
  136. color = hash(subtree.data) & 0xffffff
  137. if not (color & 0x808080):
  138. color |= 0x808080
  139. subnodes = [_to_pydot(child) if isinstance(child, Tree) else new_leaf(child)
  140. for child in subtree.children]
  141. node = pydot.Node(i[0], style="filled", fillcolor="#%x"%color, label=subtree.data)
  142. i[0] += 1
  143. graph.add_node(node)
  144. for subnode in subnodes:
  145. graph.add_edge(pydot.Edge(node, subnode))
  146. return node
  147. _to_pydot(tree)
  148. graph.write_png(filename)