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.

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