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.

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