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.

90 lines
2.5 KiB

  1. from copy import deepcopy
  2. from .utils import inline_args
  3. class Tree(object):
  4. def __init__(self, data, children):
  5. self.data = data
  6. self.children = list(children)
  7. def __repr__(self):
  8. return 'Tree(%s, %s)' % (self.data, self.children)
  9. def _pretty(self, level, indent_str):
  10. if len(self.children) == 1 and not isinstance(self.children[0], Tree):
  11. return [ indent_str*level, self.data, '\t', '%s' % self.children[0], '\n']
  12. l = [ indent_str*level, self.data, '\n' ]
  13. for n in self.children:
  14. if isinstance(n, Tree):
  15. l += n._pretty(level+1, indent_str)
  16. else:
  17. l += [ indent_str*(level+1), '%s' % n, '\n' ]
  18. return l
  19. def pretty(self, indent_str=' '):
  20. return ''.join(self._pretty(0, indent_str))
  21. def expand_kids_by_index(self, *indices):
  22. for i in sorted(indices, reverse=True): # reverse so that changing tail won't affect indices
  23. kid = self.children[i]
  24. self.children[i:i+1] = kid.children
  25. def __eq__(self, other):
  26. return self.data == other.data and self.children == other.children
  27. def __hash__(self):
  28. return hash((self.data, tuple(self.children)))
  29. def find_pred(self, pred):
  30. if pred(self):
  31. yield self
  32. else:
  33. for c in self.children:
  34. if isinstance(c, Tree):
  35. for t in c.find_pred(pred):
  36. yield t
  37. def find_data(self, data):
  38. return self.find_pred(lambda t: t.data == data)
  39. def __deepcopy__(self, memo):
  40. return type(self)(self.data, deepcopy(self.children, memo))
  41. class Transformer(object):
  42. def _get_func(self, name):
  43. return getattr(self, name)
  44. def transform(self, tree):
  45. items = [self.transform(c) if isinstance(c, Tree) else c for c in tree.children]
  46. try:
  47. f = self._get_func(tree.data)
  48. except AttributeError:
  49. return self.__default__(tree.data, items)
  50. else:
  51. return f(items)
  52. def __default__(self, data, children):
  53. return Tree(data, children)
  54. class InlineTransformer(Transformer):
  55. def _get_func(self, name):
  56. return inline_args(getattr(self, name)).__get__(self)
  57. class Visitor(object):
  58. def visit(self, tree):
  59. for child in tree.children:
  60. if isinstance(child, Tree):
  61. self.visit(child)
  62. f = getattr(self, tree.data, self.__default__)
  63. f(tree)
  64. return tree
  65. def __default__(self, tree):
  66. pass