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.

335 lines
9.7 KiB

  1. from functools import wraps
  2. from .utils import smart_decorator
  3. from .tree import Tree
  4. from .exceptions import VisitError, GrammarError
  5. from .lexer import Token
  6. ###{standalone
  7. from inspect import getmembers, getmro
  8. class Discard(Exception):
  9. pass
  10. # Transformers
  11. class Transformer:
  12. """Visits the tree recursively, starting with the leaves and finally the root (bottom-up)
  13. Calls its methods (provided by user via inheritance) according to tree.data
  14. The returned value replaces the old one in the structure.
  15. Can be used to implement map or reduce.
  16. """
  17. __visit_tokens__ = True # For backwards compatibility
  18. def __init__(self, visit_tokens=True):
  19. self.__visit_tokens__ = visit_tokens
  20. def _call_userfunc(self, tree, new_children=None):
  21. # Assumes tree is already transformed
  22. children = new_children if new_children is not None else tree.children
  23. try:
  24. f = getattr(self, tree.data)
  25. except AttributeError:
  26. return self.__default__(tree.data, children, tree.meta)
  27. else:
  28. try:
  29. wrapper = getattr(f, 'visit_wrapper', None)
  30. if wrapper is not None:
  31. return f.visit_wrapper(f, tree.data, children, tree.meta)
  32. else:
  33. return f(children)
  34. except (GrammarError, Discard):
  35. raise
  36. except Exception as e:
  37. raise VisitError(tree.data, tree, e)
  38. def _call_userfunc_token(self, token):
  39. try:
  40. f = getattr(self, token.type)
  41. except AttributeError:
  42. return self.__default_token__(token)
  43. else:
  44. try:
  45. return f(token)
  46. except (GrammarError, Discard):
  47. raise
  48. except Exception as e:
  49. raise VisitError(token.type, token, e)
  50. def _transform_children(self, children):
  51. for c in children:
  52. try:
  53. if isinstance(c, Tree):
  54. yield self._transform_tree(c)
  55. elif self.__visit_tokens__ and isinstance(c, Token):
  56. yield self._call_userfunc_token(c)
  57. else:
  58. yield c
  59. except Discard:
  60. pass
  61. def _transform_tree(self, tree):
  62. children = list(self._transform_children(tree.children))
  63. return self._call_userfunc(tree, children)
  64. def transform(self, tree):
  65. return self._transform_tree(tree)
  66. def __mul__(self, other):
  67. return TransformerChain(self, other)
  68. def __default__(self, data, children, meta):
  69. "Default operation on tree (for override)"
  70. return Tree(data, children, meta)
  71. def __default_token__(self, token):
  72. "Default operation on token (for override)"
  73. return token
  74. @classmethod
  75. def _apply_decorator(cls, decorator, **kwargs):
  76. mro = getmro(cls)
  77. assert mro[0] is cls
  78. libmembers = {name for _cls in mro[1:] for name, _ in getmembers(_cls)}
  79. for name, value in getmembers(cls):
  80. # Make sure the function isn't inherited (unless it's overwritten)
  81. if name.startswith('_') or (name in libmembers and name not in cls.__dict__):
  82. continue
  83. if not callable(cls.__dict__[name]):
  84. continue
  85. # Skip if v_args already applied (at the function level)
  86. if hasattr(cls.__dict__[name], 'vargs_applied'):
  87. continue
  88. static = isinstance(cls.__dict__[name], (staticmethod, classmethod))
  89. setattr(cls, name, decorator(value, static=static, **kwargs))
  90. return cls
  91. class InlineTransformer(Transformer): # XXX Deprecated
  92. def _call_userfunc(self, tree, new_children=None):
  93. # Assumes tree is already transformed
  94. children = new_children if new_children is not None else tree.children
  95. try:
  96. f = getattr(self, tree.data)
  97. except AttributeError:
  98. return self.__default__(tree.data, children, tree.meta)
  99. else:
  100. return f(*children)
  101. class TransformerChain(object):
  102. def __init__(self, *transformers):
  103. self.transformers = transformers
  104. def transform(self, tree):
  105. for t in self.transformers:
  106. tree = t.transform(tree)
  107. return tree
  108. def __mul__(self, other):
  109. return TransformerChain(*self.transformers + (other,))
  110. class Transformer_InPlace(Transformer):
  111. "Non-recursive. Changes the tree in-place instead of returning new instances"
  112. def _transform_tree(self, tree): # Cancel recursion
  113. return self._call_userfunc(tree)
  114. def transform(self, tree):
  115. for subtree in tree.iter_subtrees():
  116. subtree.children = list(self._transform_children(subtree.children))
  117. return self._transform_tree(tree)
  118. class Transformer_InPlaceRecursive(Transformer):
  119. "Recursive. Changes the tree in-place instead of returning new instances"
  120. def _transform_tree(self, tree):
  121. tree.children = list(self._transform_children(tree.children))
  122. return self._call_userfunc(tree)
  123. # Visitors
  124. class VisitorBase:
  125. def _call_userfunc(self, tree):
  126. return getattr(self, tree.data, self.__default__)(tree)
  127. def __default__(self, tree):
  128. "Default operation on tree (for override)"
  129. return tree
  130. class Visitor(VisitorBase):
  131. """Bottom-up visitor, non-recursive
  132. Visits the tree, starting with the leaves and finally the root (bottom-up)
  133. Calls its methods (provided by user via inheritance) according to tree.data
  134. """
  135. def visit(self, tree):
  136. for subtree in tree.iter_subtrees():
  137. self._call_userfunc(subtree)
  138. return tree
  139. def visit_topdown(self,tree):
  140. for subtree in tree.iter_subtrees_topdown():
  141. self._call_userfunc(subtree)
  142. return tree
  143. class Visitor_Recursive(VisitorBase):
  144. """Bottom-up visitor, recursive
  145. Visits the tree, starting with the leaves and finally the root (bottom-up)
  146. Calls its methods (provided by user via inheritance) according to tree.data
  147. """
  148. def visit(self, tree):
  149. for child in tree.children:
  150. if isinstance(child, Tree):
  151. self.visit(child)
  152. self._call_userfunc(tree)
  153. return tree
  154. def visit_topdown(self,tree):
  155. self._call_userfunc(tree)
  156. for child in tree.children:
  157. if isinstance(child, Tree):
  158. self.visit_topdown(child)
  159. return tree
  160. def visit_children_decor(func):
  161. "See Interpreter"
  162. @wraps(func)
  163. def inner(cls, tree):
  164. values = cls.visit_children(tree)
  165. return func(cls, values)
  166. return inner
  167. class Interpreter:
  168. """Top-down visitor, recursive
  169. Visits the tree, starting with the root and finally the leaves (top-down)
  170. Calls its methods (provided by user via inheritance) according to tree.data
  171. Unlike Transformer and Visitor, the Interpreter doesn't automatically visit its sub-branches.
  172. The user has to explicitly call visit_children, or use the @visit_children_decor
  173. """
  174. def visit(self, tree):
  175. return getattr(self, tree.data)(tree)
  176. def visit_children(self, tree):
  177. return [self.visit(child) if isinstance(child, Tree) else child
  178. for child in tree.children]
  179. def __getattr__(self, name):
  180. return self.__default__
  181. def __default__(self, tree):
  182. return self.visit_children(tree)
  183. # Decorators
  184. def _apply_decorator(obj, decorator, **kwargs):
  185. try:
  186. _apply = obj._apply_decorator
  187. except AttributeError:
  188. return decorator(obj, **kwargs)
  189. else:
  190. return _apply(decorator, **kwargs)
  191. def _inline_args__func(func):
  192. @wraps(func)
  193. def create_decorator(_f, with_self):
  194. if with_self:
  195. def f(self, children):
  196. return _f(self, *children)
  197. else:
  198. def f(self, children):
  199. return _f(*children)
  200. return f
  201. return smart_decorator(func, create_decorator)
  202. def inline_args(obj): # XXX Deprecated
  203. return _apply_decorator(obj, _inline_args__func)
  204. def _visitor_args_func_dec(func, visit_wrapper=None, static=False):
  205. def create_decorator(_f, with_self):
  206. if with_self:
  207. def f(self, *args, **kwargs):
  208. return _f(self, *args, **kwargs)
  209. else:
  210. def f(self, *args, **kwargs):
  211. return _f(*args, **kwargs)
  212. return f
  213. if static:
  214. f = wraps(func)(create_decorator(func, False))
  215. else:
  216. f = smart_decorator(func, create_decorator)
  217. f.vargs_applied = True
  218. f.visit_wrapper = visit_wrapper
  219. return f
  220. def _vargs_inline(f, data, children, meta):
  221. return f(*children)
  222. def _vargs_meta_inline(f, data, children, meta):
  223. return f(meta, *children)
  224. def _vargs_meta(f, data, children, meta):
  225. return f(children, meta) # TODO swap these for consistency? Backwards incompatible!
  226. def _vargs_tree(f, data, children, meta):
  227. return f(Tree(data, children, meta))
  228. def v_args(inline=False, meta=False, tree=False, wrapper=None):
  229. "A convenience decorator factory, for modifying the behavior of user-supplied visitor methods"
  230. if tree and (meta or inline):
  231. raise ValueError("Visitor functions cannot combine 'tree' with 'meta' or 'inline'.")
  232. func = None
  233. if meta:
  234. if inline:
  235. func = _vargs_meta_inline
  236. else:
  237. func = _vargs_meta
  238. elif inline:
  239. func = _vargs_inline
  240. elif tree:
  241. func = _vargs_tree
  242. if wrapper is not None:
  243. if func is not None:
  244. raise ValueError("Cannot use 'wrapper' along with 'tree', 'meta' or 'inline'.")
  245. func = wrapper
  246. def _visitor_args_dec(obj):
  247. return _apply_decorator(obj, _visitor_args_func_dec, visit_wrapper=func)
  248. return _visitor_args_dec
  249. ###}