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.

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