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.

402 lines
12 KiB

  1. from functools import wraps
  2. from .utils import smart_decorator, combine_alternatives
  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. "Provides support for decorating methods with @v_args"
  13. @classmethod
  14. def _apply_decorator(cls, decorator, **kwargs):
  15. mro = getmro(cls)
  16. assert mro[0] is cls
  17. libmembers = {name for _cls in mro[1:] for name, _ in getmembers(_cls)}
  18. for name, value in getmembers(cls):
  19. # Make sure the function isn't inherited (unless it's overwritten)
  20. if name.startswith('_') or (name in libmembers and name not in cls.__dict__):
  21. continue
  22. if not callable(value):
  23. continue
  24. # Skip if v_args already applied (at the function level)
  25. if hasattr(cls.__dict__[name], 'vargs_applied') or hasattr(value, 'vargs_applied'):
  26. continue
  27. static = isinstance(cls.__dict__[name], (staticmethod, classmethod))
  28. setattr(cls, name, decorator(value, static=static, **kwargs))
  29. return cls
  30. def __class_getitem__(cls, _):
  31. return cls
  32. class Transformer(_Decoratable):
  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_NonRecursive(Transformer):
  123. "Non-recursive. Doesn't change the original tree."
  124. def transform(self, tree):
  125. # Tree to postfix
  126. rev_postfix = []
  127. q = [tree]
  128. while q:
  129. t = q.pop()
  130. rev_postfix.append( t )
  131. if isinstance(t, Tree):
  132. q += t.children
  133. # Postfix to tree
  134. stack = []
  135. for x in reversed(rev_postfix):
  136. if isinstance(x, Tree):
  137. size = len(x.children)
  138. if size:
  139. args = stack[-size:]
  140. del stack[-size:]
  141. else:
  142. args = []
  143. stack.append(self._call_userfunc(x, args))
  144. else:
  145. stack.append(x)
  146. t ,= stack # We should have only one tree remaining
  147. return t
  148. class Transformer_InPlaceRecursive(Transformer):
  149. "Recursive. Changes the tree in-place instead of returning new instances"
  150. def _transform_tree(self, tree):
  151. tree.children = list(self._transform_children(tree.children))
  152. return self._call_userfunc(tree)
  153. # Visitors
  154. class VisitorBase:
  155. def _call_userfunc(self, tree):
  156. return getattr(self, tree.data, self.__default__)(tree)
  157. def __default__(self, tree):
  158. "Default operation on tree (for override)"
  159. return tree
  160. def __class_getitem__(cls, _):
  161. return cls
  162. class Visitor(VisitorBase):
  163. """Bottom-up visitor, non-recursive
  164. Visits the tree, starting with the leaves and finally the root (bottom-up)
  165. Calls its methods (provided by user via inheritance) according to tree.data
  166. """
  167. def visit(self, tree):
  168. for subtree in tree.iter_subtrees():
  169. self._call_userfunc(subtree)
  170. return tree
  171. def visit_topdown(self,tree):
  172. for subtree in tree.iter_subtrees_topdown():
  173. self._call_userfunc(subtree)
  174. return tree
  175. class Visitor_Recursive(VisitorBase):
  176. """Bottom-up visitor, recursive
  177. Visits the tree, starting with the leaves and finally the root (bottom-up)
  178. Calls its methods (provided by user via inheritance) according to tree.data
  179. """
  180. def visit(self, tree):
  181. for child in tree.children:
  182. if isinstance(child, Tree):
  183. self.visit(child)
  184. self._call_userfunc(tree)
  185. return tree
  186. def visit_topdown(self,tree):
  187. self._call_userfunc(tree)
  188. for child in tree.children:
  189. if isinstance(child, Tree):
  190. self.visit_topdown(child)
  191. return tree
  192. def visit_children_decor(func):
  193. "See Interpreter"
  194. @wraps(func)
  195. def inner(cls, tree):
  196. values = cls.visit_children(tree)
  197. return func(cls, values)
  198. return inner
  199. class Interpreter(_Decoratable):
  200. """Top-down visitor, recursive
  201. Visits the tree, starting with the root and finally the leaves (top-down)
  202. Calls its methods (provided by user via inheritance) according to tree.data
  203. Unlike Transformer and Visitor, the Interpreter doesn't automatically visit its sub-branches.
  204. The user has to explicitly call visit, visit_children, or use the @visit_children_decor
  205. """
  206. def visit(self, tree):
  207. f = getattr(self, tree.data)
  208. wrapper = getattr(f, 'visit_wrapper', None)
  209. if wrapper is not None:
  210. return f.visit_wrapper(f, tree.data, tree.children, tree.meta)
  211. else:
  212. return f(tree)
  213. def visit_children(self, tree):
  214. return [self.visit(child) if isinstance(child, Tree) else child
  215. for child in tree.children]
  216. def __getattr__(self, name):
  217. return self.__default__
  218. def __default__(self, tree):
  219. return self.visit_children(tree)
  220. # Decorators
  221. def _apply_decorator(obj, decorator, **kwargs):
  222. try:
  223. _apply = obj._apply_decorator
  224. except AttributeError:
  225. return decorator(obj, **kwargs)
  226. else:
  227. return _apply(decorator, **kwargs)
  228. def _inline_args__func(func):
  229. @wraps(func)
  230. def create_decorator(_f, with_self):
  231. if with_self:
  232. def f(self, children):
  233. return _f(self, *children)
  234. else:
  235. def f(self, children):
  236. return _f(*children)
  237. return f
  238. return smart_decorator(func, create_decorator)
  239. def inline_args(obj): # XXX Deprecated
  240. return _apply_decorator(obj, _inline_args__func)
  241. def _visitor_args_func_dec(func, visit_wrapper=None, static=False):
  242. def create_decorator(_f, with_self):
  243. if with_self:
  244. def f(self, *args, **kwargs):
  245. return _f(self, *args, **kwargs)
  246. else:
  247. def f(self, *args, **kwargs):
  248. return _f(*args, **kwargs)
  249. return f
  250. if static:
  251. f = wraps(func)(create_decorator(func, False))
  252. else:
  253. f = smart_decorator(func, create_decorator)
  254. f.vargs_applied = True
  255. f.visit_wrapper = visit_wrapper
  256. return f
  257. def _vargs_inline(f, data, children, meta):
  258. return f(*children)
  259. def _vargs_meta_inline(f, data, children, meta):
  260. return f(meta, *children)
  261. def _vargs_meta(f, data, children, meta):
  262. return f(children, meta) # TODO swap these for consistency? Backwards incompatible!
  263. def _vargs_tree(f, data, children, meta):
  264. return f(Tree(data, children, meta))
  265. def v_args(inline=False, meta=False, tree=False, wrapper=None):
  266. "A convenience decorator factory, for modifying the behavior of user-supplied visitor methods"
  267. if tree and (meta or inline):
  268. raise ValueError("Visitor functions cannot combine 'tree' with 'meta' or 'inline'.")
  269. func = None
  270. if meta:
  271. if inline:
  272. func = _vargs_meta_inline
  273. else:
  274. func = _vargs_meta
  275. elif inline:
  276. func = _vargs_inline
  277. elif tree:
  278. func = _vargs_tree
  279. if wrapper is not None:
  280. if func is not None:
  281. raise ValueError("Cannot use 'wrapper' along with 'tree', 'meta' or 'inline'.")
  282. func = wrapper
  283. def _visitor_args_dec(obj):
  284. return _apply_decorator(obj, _visitor_args_func_dec, visit_wrapper=func)
  285. return _visitor_args_dec
  286. ###}
  287. #--- Visitor Utilities ---
  288. class CollapseAmbiguities(Transformer):
  289. """
  290. Transforms a tree that contains any number of _ambig nodes into a list of trees,
  291. each one containing an unambiguous tree.
  292. The length of the resulting list is the product of the length of all _ambig nodes.
  293. Warning: This may quickly explode for highly ambiguous trees.
  294. """
  295. def _ambig(self, options):
  296. return sum(options, [])
  297. def __default__(self, data, children_lists, meta):
  298. return [Tree(data, children, meta) for children in combine_alternatives(children_lists)]
  299. def __default_token__(self, t):
  300. return [t]