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.

259 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. static = isinstance(cls.__dict__[name], (staticmethod, classmethod))
  58. setattr(cls, name, decorator(value, static=static, **kwargs))
  59. return cls
  60. class InlineTransformer(Transformer): # XXX Deprecated
  61. def _call_userfunc(self, tree, new_children=None):
  62. # Assumes tree is already transformed
  63. children = new_children if new_children is not None else tree.children
  64. try:
  65. f = getattr(self, tree.data)
  66. except AttributeError:
  67. return self.__default__(tree.data, children, tree.meta)
  68. else:
  69. return f(*children)
  70. class TransformerChain(object):
  71. def __init__(self, *transformers):
  72. self.transformers = transformers
  73. def transform(self, tree):
  74. for t in self.transformers:
  75. tree = t.transform(tree)
  76. return tree
  77. def __mul__(self, other):
  78. return TransformerChain(*self.transformers + (other,))
  79. class Transformer_InPlace(Transformer):
  80. "Non-recursive. Changes the tree in-place instead of returning new instances"
  81. def _transform_tree(self, tree): # Cancel recursion
  82. return self._call_userfunc(tree)
  83. def transform(self, tree):
  84. for subtree in tree.iter_subtrees():
  85. subtree.children = list(self._transform_children(subtree.children))
  86. return self._transform_tree(tree)
  87. class Transformer_InPlaceRecursive(Transformer):
  88. "Recursive. Changes the tree in-place instead of returning new instances"
  89. def _transform_tree(self, tree):
  90. tree.children = list(self._transform_children(tree.children))
  91. return self._call_userfunc(tree)
  92. # Visitors
  93. class VisitorBase:
  94. def _call_userfunc(self, tree):
  95. return getattr(self, tree.data, self.__default__)(tree)
  96. def __default__(self, tree):
  97. "Default operation on tree (for override)"
  98. return tree
  99. class Visitor(VisitorBase):
  100. """Bottom-up visitor, non-recursive
  101. Visits the tree, starting with the leaves and finally the root (bottom-up)
  102. Calls its methods (provided by user via inheritance) according to tree.data
  103. """
  104. def visit(self, tree):
  105. for subtree in tree.iter_subtrees():
  106. self._call_userfunc(subtree)
  107. return tree
  108. class Visitor_Recursive(VisitorBase):
  109. """Bottom-up visitor, recursive
  110. Visits the tree, starting with the leaves and finally the root (bottom-up)
  111. Calls its methods (provided by user via inheritance) according to tree.data
  112. """
  113. def visit(self, tree):
  114. for child in tree.children:
  115. if isinstance(child, Tree):
  116. self.visit(child)
  117. f = getattr(self, tree.data, self.__default__)
  118. f(tree)
  119. return tree
  120. def visit_children_decor(func):
  121. "See Interpreter"
  122. @wraps(func)
  123. def inner(cls, tree):
  124. values = cls.visit_children(tree)
  125. return func(cls, values)
  126. return inner
  127. class Interpreter:
  128. """Top-down visitor, recursive
  129. Visits the tree, starting with the root and finally the leaves (top-down)
  130. Calls its methods (provided by user via inheritance) according to tree.data
  131. Unlike Transformer and Visitor, the Interpreter doesn't automatically visit its sub-branches.
  132. The user has to explicitly call visit_children, or use the @visit_children_decor
  133. """
  134. def visit(self, tree):
  135. return getattr(self, tree.data)(tree)
  136. def visit_children(self, tree):
  137. return [self.visit(child) if isinstance(child, Tree) else child
  138. for child in tree.children]
  139. def __getattr__(self, name):
  140. return self.__default__
  141. def __default__(self, tree):
  142. return self.visit_children(tree)
  143. # Decorators
  144. def _apply_decorator(obj, decorator, **kwargs):
  145. try:
  146. _apply = obj._apply_decorator
  147. except AttributeError:
  148. return decorator(obj, **kwargs)
  149. else:
  150. return _apply(decorator, **kwargs)
  151. def _inline_args__func(func):
  152. @wraps(func)
  153. def create_decorator(_f, with_self):
  154. if with_self:
  155. def f(self, children):
  156. return _f(self, *children)
  157. else:
  158. def f(self, children):
  159. return _f(*children)
  160. return f
  161. return smart_decorator(func, create_decorator)
  162. def inline_args(obj): # XXX Deprecated
  163. return _apply_decorator(obj, _inline_args__func)
  164. def _visitor_args_func_dec(func, inline=False, meta=False, whole_tree=False, static=False):
  165. assert [whole_tree, meta, inline].count(True) <= 1
  166. def create_decorator(_f, with_self):
  167. if with_self:
  168. def f(self, *args, **kwargs):
  169. return _f(self, *args, **kwargs)
  170. else:
  171. def f(self, *args, **kwargs):
  172. return _f(*args, **kwargs)
  173. return f
  174. if static:
  175. f = wraps(func)(create_decorator(func, False))
  176. else:
  177. f = smart_decorator(func, create_decorator)
  178. f.inline = inline
  179. f.meta = meta
  180. f.whole_tree = whole_tree
  181. return f
  182. def v_args(inline=False, meta=False, tree=False):
  183. "A convenience decorator factory, for modifying the behavior of user-supplied visitor methods"
  184. if [tree, meta, inline].count(True) > 1:
  185. raise ValueError("Visitor functions can either accept tree, or meta, or be inlined. These cannot be combined.")
  186. def _visitor_args_dec(obj):
  187. return _apply_decorator(obj, _visitor_args_func_dec, inline=inline, meta=meta, whole_tree=tree)
  188. return _visitor_args_dec
  189. ###}