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.

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