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.

270 lines
8.0 KiB

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