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.

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