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.

260 lines
7.6 KiB

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