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.

400 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. @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(value):
  22. continue
  23. # Skip if v_args already applied (at the function level)
  24. if hasattr(cls.__dict__[name], 'vargs_applied') or hasattr(value, '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. def __class_getitem__(cls, _):
  30. return cls
  31. class Transformer(_Decoratable):
  32. """Visits the tree recursively, starting with the leaves and finally the root (bottom-up)
  33. Calls its methods (provided by user via inheritance) according to tree.data
  34. The returned value replaces the old one in the structure.
  35. Can be used to implement map or reduce.
  36. """
  37. __visit_tokens__ = True # For backwards compatibility
  38. def __init__(self, visit_tokens=True):
  39. self.__visit_tokens__ = visit_tokens
  40. def _call_userfunc(self, tree, new_children=None):
  41. # Assumes tree is already transformed
  42. children = new_children if new_children is not None else tree.children
  43. try:
  44. f = getattr(self, tree.data)
  45. except AttributeError:
  46. return self.__default__(tree.data, children, tree.meta)
  47. else:
  48. try:
  49. wrapper = getattr(f, 'visit_wrapper', None)
  50. if wrapper is not None:
  51. return f.visit_wrapper(f, tree.data, children, tree.meta)
  52. else:
  53. return f(children)
  54. except (GrammarError, Discard):
  55. raise
  56. except Exception as e:
  57. raise VisitError(tree.data, tree, e)
  58. def _call_userfunc_token(self, token):
  59. try:
  60. f = getattr(self, token.type)
  61. except AttributeError:
  62. return self.__default_token__(token)
  63. else:
  64. try:
  65. return f(token)
  66. except (GrammarError, Discard):
  67. raise
  68. except Exception as e:
  69. raise VisitError(token.type, token, e)
  70. def _transform_children(self, children):
  71. for c in children:
  72. try:
  73. if isinstance(c, Tree):
  74. yield self._transform_tree(c)
  75. elif self.__visit_tokens__ and isinstance(c, Token):
  76. yield self._call_userfunc_token(c)
  77. else:
  78. yield c
  79. except Discard:
  80. pass
  81. def _transform_tree(self, tree):
  82. children = list(self._transform_children(tree.children))
  83. return self._call_userfunc(tree, children)
  84. def transform(self, tree):
  85. return self._transform_tree(tree)
  86. def __mul__(self, other):
  87. return TransformerChain(self, other)
  88. def __default__(self, data, children, meta):
  89. "Default operation on tree (for override)"
  90. return Tree(data, children, meta)
  91. def __default_token__(self, token):
  92. "Default operation on token (for override)"
  93. return token
  94. class InlineTransformer(Transformer): # XXX Deprecated
  95. def _call_userfunc(self, tree, new_children=None):
  96. # Assumes tree is already transformed
  97. children = new_children if new_children is not None else tree.children
  98. try:
  99. f = getattr(self, tree.data)
  100. except AttributeError:
  101. return self.__default__(tree.data, children, tree.meta)
  102. else:
  103. return f(*children)
  104. class TransformerChain(object):
  105. def __init__(self, *transformers):
  106. self.transformers = transformers
  107. def transform(self, tree):
  108. for t in self.transformers:
  109. tree = t.transform(tree)
  110. return tree
  111. def __mul__(self, other):
  112. return TransformerChain(*self.transformers + (other,))
  113. class Transformer_InPlace(Transformer):
  114. "Non-recursive. Changes the tree in-place instead of returning new instances"
  115. def _transform_tree(self, tree): # Cancel recursion
  116. return self._call_userfunc(tree)
  117. def transform(self, tree):
  118. for subtree in tree.iter_subtrees():
  119. subtree.children = list(self._transform_children(subtree.children))
  120. return self._transform_tree(tree)
  121. class Transformer_NonRecursive(Transformer):
  122. "Non-recursive. Doesn't change the original tree."
  123. def transform(self, tree):
  124. # Tree to postfix
  125. rev_postfix = []
  126. q = [tree]
  127. while q:
  128. t = q.pop()
  129. rev_postfix.append( t )
  130. if isinstance(t, Tree):
  131. q += t.children
  132. # Postfix to tree
  133. stack = []
  134. for x in reversed(rev_postfix):
  135. if isinstance(x, Tree):
  136. size = len(x.children)
  137. if size:
  138. args = stack[-size:]
  139. del stack[-size:]
  140. else:
  141. args = []
  142. stack.append(self._call_userfunc(x, args))
  143. else:
  144. stack.append(x)
  145. t ,= stack # We should have only one tree remaining
  146. return t
  147. class Transformer_InPlaceRecursive(Transformer):
  148. "Recursive. Changes the tree in-place instead of returning new instances"
  149. def _transform_tree(self, tree):
  150. tree.children = list(self._transform_children(tree.children))
  151. return self._call_userfunc(tree)
  152. # Visitors
  153. class VisitorBase:
  154. def _call_userfunc(self, tree):
  155. return getattr(self, tree.data, self.__default__)(tree)
  156. def __default__(self, tree):
  157. "Default operation on tree (for override)"
  158. return tree
  159. def __class_getitem__(cls, _):
  160. return cls
  161. class Visitor(VisitorBase):
  162. """Bottom-up visitor, non-recursive
  163. Visits the tree, starting with the leaves and finally the root (bottom-up)
  164. Calls its methods (provided by user via inheritance) according to tree.data
  165. """
  166. def visit(self, tree):
  167. for subtree in tree.iter_subtrees():
  168. self._call_userfunc(subtree)
  169. return tree
  170. def visit_topdown(self,tree):
  171. for subtree in tree.iter_subtrees_topdown():
  172. self._call_userfunc(subtree)
  173. return tree
  174. class Visitor_Recursive(VisitorBase):
  175. """Bottom-up visitor, recursive
  176. Visits the tree, starting with the leaves and finally the root (bottom-up)
  177. Calls its methods (provided by user via inheritance) according to tree.data
  178. """
  179. def visit(self, tree):
  180. for child in tree.children:
  181. if isinstance(child, Tree):
  182. self.visit(child)
  183. self._call_userfunc(tree)
  184. return tree
  185. def visit_topdown(self,tree):
  186. self._call_userfunc(tree)
  187. for child in tree.children:
  188. if isinstance(child, Tree):
  189. self.visit_topdown(child)
  190. return tree
  191. def visit_children_decor(func):
  192. "See Interpreter"
  193. @wraps(func)
  194. def inner(cls, tree):
  195. values = cls.visit_children(tree)
  196. return func(cls, values)
  197. return inner
  198. class Interpreter(_Decoratable):
  199. """Top-down visitor, recursive
  200. Visits the tree, starting with the root and finally the leaves (top-down)
  201. Calls its methods (provided by user via inheritance) according to tree.data
  202. Unlike Transformer and Visitor, the Interpreter doesn't automatically visit its sub-branches.
  203. The user has to explicitly call visit_children, or use the @visit_children_decor
  204. """
  205. def visit(self, tree):
  206. f = getattr(self, tree.data)
  207. wrapper = getattr(f, 'visit_wrapper', None)
  208. if wrapper is not None:
  209. return f.visit_wrapper(f, tree.data, tree.children, tree.meta)
  210. else:
  211. return f(tree)
  212. def visit_children(self, tree):
  213. return [self.visit(child) if isinstance(child, Tree) else child
  214. for child in tree.children]
  215. def __getattr__(self, name):
  216. return self.__default__
  217. def __default__(self, tree):
  218. return self.visit_children(tree)
  219. # Decorators
  220. def _apply_decorator(obj, decorator, **kwargs):
  221. try:
  222. _apply = obj._apply_decorator
  223. except AttributeError:
  224. return decorator(obj, **kwargs)
  225. else:
  226. return _apply(decorator, **kwargs)
  227. def _inline_args__func(func):
  228. @wraps(func)
  229. def create_decorator(_f, with_self):
  230. if with_self:
  231. def f(self, children):
  232. return _f(self, *children)
  233. else:
  234. def f(self, children):
  235. return _f(*children)
  236. return f
  237. return smart_decorator(func, create_decorator)
  238. def inline_args(obj): # XXX Deprecated
  239. return _apply_decorator(obj, _inline_args__func)
  240. def _visitor_args_func_dec(func, visit_wrapper=None, static=False):
  241. def create_decorator(_f, with_self):
  242. if with_self:
  243. def f(self, *args, **kwargs):
  244. return _f(self, *args, **kwargs)
  245. else:
  246. def f(self, *args, **kwargs):
  247. return _f(*args, **kwargs)
  248. return f
  249. if static:
  250. f = wraps(func)(create_decorator(func, False))
  251. else:
  252. f = smart_decorator(func, create_decorator)
  253. f.vargs_applied = True
  254. f.visit_wrapper = visit_wrapper
  255. return f
  256. def _vargs_inline(f, data, children, meta):
  257. return f(*children)
  258. def _vargs_meta_inline(f, data, children, meta):
  259. return f(meta, *children)
  260. def _vargs_meta(f, data, children, meta):
  261. return f(children, meta) # TODO swap these for consistency? Backwards incompatible!
  262. def _vargs_tree(f, data, children, meta):
  263. return f(Tree(data, children, meta))
  264. def v_args(inline=False, meta=False, tree=False, wrapper=None):
  265. "A convenience decorator factory, for modifying the behavior of user-supplied visitor methods"
  266. if tree and (meta or inline):
  267. raise ValueError("Visitor functions cannot combine 'tree' with 'meta' or 'inline'.")
  268. func = None
  269. if meta:
  270. if inline:
  271. func = _vargs_meta_inline
  272. else:
  273. func = _vargs_meta
  274. elif inline:
  275. func = _vargs_inline
  276. elif tree:
  277. func = _vargs_tree
  278. if wrapper is not None:
  279. if func is not None:
  280. raise ValueError("Cannot use 'wrapper' along with 'tree', 'meta' or 'inline'.")
  281. func = wrapper
  282. def _visitor_args_dec(obj):
  283. return _apply_decorator(obj, _visitor_args_func_dec, visit_wrapper=func)
  284. return _visitor_args_dec
  285. ###}
  286. #--- Visitor Utilities ---
  287. class CollapseAmbiguities(Transformer):
  288. """
  289. Transforms a tree that contains any number of _ambig nodes into a list of trees,
  290. each one containing an unambiguous tree.
  291. The length of the resulting list is the product of the length of all _ambig nodes.
  292. Warning: This may quickly explode for highly ambiguous trees.
  293. """
  294. def _ambig(self, options):
  295. return sum(options, [])
  296. def __default__(self, data, children_lists, meta):
  297. return [Tree(data, children, meta) for children in combine_alternatives(children_lists)]
  298. def __default_token__(self, t):
  299. return [t]