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.

253 lines
7.4 KiB

  1. from inspect import isclass, getmembers, getmro
  2. from functools import wraps
  3. from .utils import smart_decorator
  4. from .tree import Tree
  5. class Discard(Exception):
  6. pass
  7. # Transformers
  8. class Transformer:
  9. """Visits the tree recursively, starting with the leaves and finally the root (bottom-up)
  10. Calls its methods (provided by user via inheritance) according to tree.data
  11. The returned value replaces the old one in the structure.
  12. Can be used to implement map or reduce.
  13. """
  14. def _call_userfunc(self, tree, new_children=None):
  15. # Assumes tree is already transformed
  16. children = new_children if new_children is not None else tree.children
  17. try:
  18. f = getattr(self, tree.data)
  19. except AttributeError:
  20. return self.__default__(tree.data, children, tree.meta)
  21. else:
  22. if getattr(f, 'meta', False):
  23. return f(children, tree.meta)
  24. elif getattr(f, 'inline', False):
  25. return f(*children)
  26. elif getattr(f, 'whole_tree', False):
  27. if new_children is not None:
  28. raise NotImplementedError("Doesn't work with the base Transformer class")
  29. return f(tree)
  30. else:
  31. return f(children)
  32. def _transform_children(self, children):
  33. for c in children:
  34. try:
  35. yield self._transform_tree(c) if isinstance(c, Tree) else c
  36. except Discard:
  37. pass
  38. def _transform_tree(self, tree):
  39. children = list(self._transform_children(tree.children))
  40. return self._call_userfunc(tree, children)
  41. def transform(self, tree):
  42. return self._transform_tree(tree)
  43. def __mul__(self, other):
  44. return TransformerChain(self, other)
  45. def __default__(self, data, children, meta):
  46. "Default operation on tree (for override)"
  47. return Tree(data, children, meta)
  48. @classmethod
  49. def _apply_decorator(cls, decorator, **kwargs):
  50. mro = getmro(cls)
  51. assert mro[0] is cls
  52. libmembers = {name for _cls in mro[1:] for name, _ in getmembers(_cls)}
  53. for name, value in getmembers(cls):
  54. if name.startswith('_') or name in libmembers:
  55. continue
  56. setattr(cls, name, decorator(value, **kwargs))
  57. return cls
  58. class InlineTransformer(Transformer): # XXX Deprecated
  59. def _call_userfunc(self, tree, new_children=None):
  60. # Assumes tree is already transformed
  61. children = new_children if new_children is not None else tree.children
  62. try:
  63. f = getattr(self, tree.data)
  64. except AttributeError:
  65. return self.__default__(tree.data, children, tree.meta)
  66. else:
  67. return f(*children)
  68. class TransformerChain(object):
  69. def __init__(self, *transformers):
  70. self.transformers = transformers
  71. def transform(self, tree):
  72. for t in self.transformers:
  73. tree = t.transform(tree)
  74. return tree
  75. def __mul__(self, other):
  76. return TransformerChain(*self.transformers + (other,))
  77. class Transformer_InPlace(Transformer):
  78. "Non-recursive. Changes the tree in-place instead of returning new instances"
  79. def _transform_tree(self, tree): # Cancel recursion
  80. return self._call_userfunc(tree)
  81. def transform(self, tree):
  82. for subtree in tree.iter_subtrees():
  83. subtree.children = list(self._transform_children(subtree.children))
  84. return self._transform_tree(tree)
  85. class Transformer_InPlaceRecursive(Transformer):
  86. "Recursive. Changes the tree in-place instead of returning new instances"
  87. def _transform_tree(self, tree):
  88. tree.children = list(self._transform_children(tree.children))
  89. return self._call_userfunc(tree)
  90. # Visitors
  91. class VisitorBase:
  92. def _call_userfunc(self, tree):
  93. return getattr(self, tree.data, self.__default__)(tree)
  94. def __default__(self, tree):
  95. "Default operation on tree (for override)"
  96. return tree
  97. class Visitor(VisitorBase):
  98. """Bottom-up visitor, non-recursive
  99. Visits the tree, starting with the leaves and finally the root (bottom-up)
  100. Calls its methods (provided by user via inheritance) according to tree.data
  101. """
  102. def visit(self, tree):
  103. for subtree in tree.iter_subtrees():
  104. self._call_userfunc(subtree)
  105. return tree
  106. class Visitor_Recursive(VisitorBase):
  107. """Bottom-up visitor, recursive
  108. Visits the tree, starting with the leaves and finally the root (bottom-up)
  109. Calls its methods (provided by user via inheritance) according to tree.data
  110. """
  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 visit_children_decor(func):
  119. "See Interpreter"
  120. @wraps(func)
  121. def inner(cls, tree):
  122. values = cls.visit_children(tree)
  123. return func(cls, values)
  124. return inner
  125. class Interpreter:
  126. """Top-down visitor, recursive
  127. Visits the tree, starting with the root and finally the leaves (top-down)
  128. Calls its methods (provided by user via inheritance) according to tree.data
  129. Unlike Transformer and Visitor, the Interpreter doesn't automatically visit its sub-branches.
  130. The user has to explicitly call visit_children, or use the @visit_children_decor
  131. """
  132. def visit(self, tree):
  133. return getattr(self, tree.data)(tree)
  134. def visit_children(self, tree):
  135. return [self.visit(child) if isinstance(child, Tree) else child
  136. for child in tree.children]
  137. def __getattr__(self, name):
  138. return self.__default__
  139. def __default__(self, tree):
  140. return self.visit_children(tree)
  141. # Decorators
  142. def _apply_decorator(obj, decorator, **kwargs):
  143. try:
  144. _apply = obj._apply_decorator
  145. except AttributeError:
  146. return decorator(obj, **kwargs)
  147. else:
  148. return _apply(decorator, **kwargs)
  149. def _inline_args__func(func):
  150. @wraps(func)
  151. def create_decorator(_f, with_self):
  152. if with_self:
  153. def f(self, children):
  154. return _f(self, *children)
  155. else:
  156. def f(self, children):
  157. return _f(*children)
  158. return f
  159. return smart_decorator(func, create_decorator)
  160. def inline_args(obj): # XXX Deprecated
  161. return _apply_decorator(obj, _inline_args__func)
  162. def _visitor_args_func_dec(func, inline=False, meta=False, whole_tree=False):
  163. assert [whole_tree, meta, inline].count(True) <= 1
  164. def create_decorator(_f, with_self):
  165. if with_self:
  166. def f(self, *args, **kwargs):
  167. return _f(self, *args, **kwargs)
  168. else:
  169. def f(self, *args, **kwargs):
  170. return _f(*args, **kwargs)
  171. return f
  172. f = smart_decorator(func, create_decorator)
  173. f.inline = inline
  174. f.meta = meta
  175. f.whole_tree = whole_tree
  176. return f
  177. def v_args(inline=False, meta=False, tree=False):
  178. "A convenience decorator factory, for modifying the behavior of user-supplied visitor methods"
  179. if [tree, meta, inline].count(True) > 1:
  180. raise ValueError("Visitor functions can either accept tree, or meta, or be inlined. These cannot be combined.")
  181. def _visitor_args_dec(obj):
  182. return _apply_decorator(obj, _visitor_args_func_dec, inline=inline, meta=meta, whole_tree=tree)
  183. return _visitor_args_dec