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.

461 lines
14 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. """When raising the Discard exception in a transformer callback,
  10. that node is discarded and won't appear in the parent.
  11. """
  12. pass
  13. # Transformers
  14. class _Decoratable:
  15. "Provides support for decorating methods with @v_args"
  16. @classmethod
  17. def _apply_decorator(cls, decorator, **kwargs):
  18. mro = getmro(cls)
  19. assert mro[0] is cls
  20. libmembers = {name for _cls in mro[1:] for name, _ in getmembers(_cls)}
  21. for name, value in getmembers(cls):
  22. # Make sure the function isn't inherited (unless it's overwritten)
  23. if name.startswith('_') or (name in libmembers and name not in cls.__dict__):
  24. continue
  25. if not callable(value):
  26. continue
  27. # Skip if v_args already applied (at the function level)
  28. if hasattr(cls.__dict__[name], 'vargs_applied') or hasattr(value, 'vargs_applied'):
  29. continue
  30. static = isinstance(cls.__dict__[name], (staticmethod, classmethod))
  31. setattr(cls, name, decorator(value, static=static, **kwargs))
  32. return cls
  33. def __class_getitem__(cls, _):
  34. return cls
  35. class Transformer(_Decoratable):
  36. """Transformers visit each node of the tree, and run the appropriate method on it according to the node's data.
  37. Calls its methods (provided by user via inheritance) according to ``tree.data``.
  38. The returned value replaces the old one in the structure.
  39. They work bottom-up (or depth-first), starting with the leaves and ending at the root of the tree.
  40. Transformers can be used to implement map & reduce patterns. Because nodes are reduced from leaf to root,
  41. at any point the callbacks may assume the children have already been transformed (if applicable).
  42. ``Transformer`` can do anything ``Visitor`` can do, but because it reconstructs the tree,
  43. it is slightly less efficient. It can be used to implement map or reduce patterns.
  44. All these classes implement the transformer interface:
  45. - ``Transformer`` - Recursively transforms the tree. This is the one you probably want.
  46. - ``Transformer_InPlace`` - Non-recursive. Changes the tree in-place instead of returning new instances
  47. - ``Transformer_InPlaceRecursive`` - Recursive. Changes the tree in-place instead of returning new instances
  48. Parameters:
  49. visit_tokens: By default, transformers only visit rules.
  50. visit_tokens=True will tell ``Transformer`` to visit tokens
  51. as well. This is a slightly slower alternative to lexer_callbacks
  52. but it's easier to maintain and works for all algorithms
  53. (even when there isn't a lexer).
  54. """
  55. __visit_tokens__ = True # For backwards compatibility
  56. def __init__(self, visit_tokens=True):
  57. self.__visit_tokens__ = visit_tokens
  58. def _call_userfunc(self, tree, new_children=None):
  59. # Assumes tree is already transformed
  60. children = new_children if new_children is not None else tree.children
  61. try:
  62. f = getattr(self, tree.data)
  63. except AttributeError:
  64. return self.__default__(tree.data, children, tree.meta)
  65. else:
  66. try:
  67. wrapper = getattr(f, 'visit_wrapper', None)
  68. if wrapper is not None:
  69. return f.visit_wrapper(f, tree.data, children, tree.meta)
  70. else:
  71. return f(children)
  72. except (GrammarError, Discard):
  73. raise
  74. except Exception as e:
  75. raise VisitError(tree.data, tree, e)
  76. def _call_userfunc_token(self, token):
  77. try:
  78. f = getattr(self, token.type)
  79. except AttributeError:
  80. return self.__default_token__(token)
  81. else:
  82. try:
  83. return f(token)
  84. except (GrammarError, Discard):
  85. raise
  86. except Exception as e:
  87. raise VisitError(token.type, token, e)
  88. def _transform_children(self, children):
  89. for c in children:
  90. try:
  91. if isinstance(c, Tree):
  92. yield self._transform_tree(c)
  93. elif self.__visit_tokens__ and isinstance(c, Token):
  94. yield self._call_userfunc_token(c)
  95. else:
  96. yield c
  97. except Discard:
  98. pass
  99. def _transform_tree(self, tree):
  100. children = list(self._transform_children(tree.children))
  101. return self._call_userfunc(tree, children)
  102. def transform(self, tree):
  103. return self._transform_tree(tree)
  104. def __mul__(self, other):
  105. return TransformerChain(self, other)
  106. def __default__(self, data, children, meta):
  107. """Default operation on tree (for override)
  108. Function that is called on if a function with a corresponding name has not been found.
  109. Defaults to reconstruct the Tree.
  110. """
  111. return Tree(data, children, meta)
  112. def __default_token__(self, token):
  113. """Default operation on token (for override)
  114. Function that is called on if a function with a corresponding name has not been found.
  115. Defaults to just return the argument.
  116. """
  117. return token
  118. class InlineTransformer(Transformer): # XXX Deprecated
  119. def _call_userfunc(self, tree, new_children=None):
  120. # Assumes tree is already transformed
  121. children = new_children if new_children is not None else tree.children
  122. try:
  123. f = getattr(self, tree.data)
  124. except AttributeError:
  125. return self.__default__(tree.data, children, tree.meta)
  126. else:
  127. return f(*children)
  128. class TransformerChain(object):
  129. def __init__(self, *transformers):
  130. self.transformers = transformers
  131. def transform(self, tree):
  132. for t in self.transformers:
  133. tree = t.transform(tree)
  134. return tree
  135. def __mul__(self, other):
  136. return TransformerChain(*self.transformers + (other,))
  137. class Transformer_InPlace(Transformer):
  138. "Non-recursive. Changes the tree in-place instead of returning new instances"
  139. def _transform_tree(self, tree): # Cancel recursion
  140. return self._call_userfunc(tree)
  141. def transform(self, tree):
  142. for subtree in tree.iter_subtrees():
  143. subtree.children = list(self._transform_children(subtree.children))
  144. return self._transform_tree(tree)
  145. class Transformer_NonRecursive(Transformer):
  146. "Non-recursive. Doesn't change the original tree."
  147. def transform(self, tree):
  148. # Tree to postfix
  149. rev_postfix = []
  150. q = [tree]
  151. while q:
  152. t = q.pop()
  153. rev_postfix.append( t )
  154. if isinstance(t, Tree):
  155. q += t.children
  156. # Postfix to tree
  157. stack = []
  158. for x in reversed(rev_postfix):
  159. if isinstance(x, Tree):
  160. size = len(x.children)
  161. if size:
  162. args = stack[-size:]
  163. del stack[-size:]
  164. else:
  165. args = []
  166. stack.append(self._call_userfunc(x, args))
  167. else:
  168. stack.append(x)
  169. t ,= stack # We should have only one tree remaining
  170. return t
  171. class Transformer_InPlaceRecursive(Transformer):
  172. "Recursive. Changes the tree in-place instead of returning new instances"
  173. def _transform_tree(self, tree):
  174. tree.children = list(self._transform_children(tree.children))
  175. return self._call_userfunc(tree)
  176. # Visitors
  177. class VisitorBase:
  178. def _call_userfunc(self, tree):
  179. return getattr(self, tree.data, self.__default__)(tree)
  180. def __default__(self, tree):
  181. "Default operation on tree (for override)"
  182. return tree
  183. def __class_getitem__(cls, _):
  184. return cls
  185. class Visitor(VisitorBase):
  186. """Bottom-up visitor, non-recursive.
  187. Visits the tree, starting with the leaves and finally the root (bottom-up)
  188. Calls its methods (provided by user via inheritance) according to ``tree.data``
  189. """
  190. def visit(self, tree):
  191. for subtree in tree.iter_subtrees():
  192. self._call_userfunc(subtree)
  193. return tree
  194. def visit_topdown(self,tree):
  195. for subtree in tree.iter_subtrees_topdown():
  196. self._call_userfunc(subtree)
  197. return tree
  198. class Visitor_Recursive(VisitorBase):
  199. """Bottom-up visitor, recursive.
  200. Visits the tree, starting with the leaves and finally the root (bottom-up)
  201. Calls its methods (provided by user via inheritance) according to ``tree.data``
  202. """
  203. def visit(self, tree):
  204. for child in tree.children:
  205. if isinstance(child, Tree):
  206. self.visit(child)
  207. self._call_userfunc(tree)
  208. return tree
  209. def visit_topdown(self,tree):
  210. self._call_userfunc(tree)
  211. for child in tree.children:
  212. if isinstance(child, Tree):
  213. self.visit_topdown(child)
  214. return tree
  215. def visit_children_decor(func):
  216. "See Interpreter"
  217. @wraps(func)
  218. def inner(cls, tree):
  219. values = cls.visit_children(tree)
  220. return func(cls, values)
  221. return inner
  222. class Interpreter(_Decoratable):
  223. """Interpreter walks the tree starting at the root.
  224. Visits the tree, starting with the root and finally the leaves (top-down)
  225. For each tree node, it calls its methods (provided by user via inheritance) according to ``tree.data``.
  226. Unlike ``Transformer`` and ``Visitor``, the Interpreter doesn't automatically visit its sub-branches.
  227. The user has to explicitly call ``visit``, ``visit_children``, or use the ``@visit_children_decor``.
  228. This allows the user to implement branching and loops.
  229. """
  230. def visit(self, tree):
  231. f = getattr(self, tree.data)
  232. wrapper = getattr(f, 'visit_wrapper', None)
  233. if wrapper is not None:
  234. return f.visit_wrapper(f, tree.data, tree.children, tree.meta)
  235. else:
  236. return f(tree)
  237. def visit_children(self, tree):
  238. return [self.visit(child) if isinstance(child, Tree) else child
  239. for child in tree.children]
  240. def __getattr__(self, name):
  241. return self.__default__
  242. def __default__(self, tree):
  243. return self.visit_children(tree)
  244. # Decorators
  245. def _apply_decorator(obj, decorator, **kwargs):
  246. try:
  247. _apply = obj._apply_decorator
  248. except AttributeError:
  249. return decorator(obj, **kwargs)
  250. else:
  251. return _apply(decorator, **kwargs)
  252. def _inline_args__func(func):
  253. @wraps(func)
  254. def create_decorator(_f, with_self):
  255. if with_self:
  256. def f(self, children):
  257. return _f(self, *children)
  258. else:
  259. def f(self, children):
  260. return _f(*children)
  261. return f
  262. return smart_decorator(func, create_decorator)
  263. def inline_args(obj): # XXX Deprecated
  264. return _apply_decorator(obj, _inline_args__func)
  265. def _visitor_args_func_dec(func, visit_wrapper=None, static=False):
  266. def create_decorator(_f, with_self):
  267. if with_self:
  268. def f(self, *args, **kwargs):
  269. return _f(self, *args, **kwargs)
  270. else:
  271. def f(self, *args, **kwargs):
  272. return _f(*args, **kwargs)
  273. return f
  274. if static:
  275. f = wraps(func)(create_decorator(func, False))
  276. else:
  277. f = smart_decorator(func, create_decorator)
  278. f.vargs_applied = True
  279. f.visit_wrapper = visit_wrapper
  280. return f
  281. def _vargs_inline(f, data, children, meta):
  282. return f(*children)
  283. def _vargs_meta_inline(f, data, children, meta):
  284. return f(meta, *children)
  285. def _vargs_meta(f, data, children, meta):
  286. return f(children, meta) # TODO swap these for consistency? Backwards incompatible!
  287. def _vargs_tree(f, data, children, meta):
  288. return f(Tree(data, children, meta))
  289. def v_args(inline=False, meta=False, tree=False, wrapper=None):
  290. """A convenience decorator factory for modifying the behavior of user-supplied visitor methods.
  291. By default, callback methods of transformers/visitors accept one argument - a list of the node's children.
  292. ``v_args`` can modify this behavior. When used on a transformer/visitor class definition,
  293. it applies to all the callback methods inside it.
  294. Parameters:
  295. inline: Children are provided as ``*args`` instead of a list argument (not recommended for very long lists).
  296. meta: Provides two arguments: ``children`` and ``meta`` (instead of just the first)
  297. tree: Provides the entire tree as the argument, instead of the children.
  298. Example:
  299. ::
  300. @v_args(inline=True)
  301. class SolveArith(Transformer):
  302. def add(self, left, right):
  303. return left + right
  304. class ReverseNotation(Transformer_InPlace):
  305. @v_args(tree=True)
  306. def tree_node(self, tree):
  307. tree.children = tree.children[::-1]
  308. """
  309. if tree and (meta or inline):
  310. raise ValueError("Visitor functions cannot combine 'tree' with 'meta' or 'inline'.")
  311. func = None
  312. if meta:
  313. if inline:
  314. func = _vargs_meta_inline
  315. else:
  316. func = _vargs_meta
  317. elif inline:
  318. func = _vargs_inline
  319. elif tree:
  320. func = _vargs_tree
  321. if wrapper is not None:
  322. if func is not None:
  323. raise ValueError("Cannot use 'wrapper' along with 'tree', 'meta' or 'inline'.")
  324. func = wrapper
  325. def _visitor_args_dec(obj):
  326. return _apply_decorator(obj, _visitor_args_func_dec, visit_wrapper=func)
  327. return _visitor_args_dec
  328. ###}
  329. #--- Visitor Utilities ---
  330. class CollapseAmbiguities(Transformer):
  331. """
  332. Transforms a tree that contains any number of _ambig nodes into a list of trees,
  333. each one containing an unambiguous tree.
  334. The length of the resulting list is the product of the length of all _ambig nodes.
  335. Warning: This may quickly explode for highly ambiguous trees.
  336. """
  337. def _ambig(self, options):
  338. return sum(options, [])
  339. def __default__(self, data, children_lists, meta):
  340. return [Tree(data, children, meta) for children in combine_alternatives(children_lists)]
  341. def __default_token__(self, t):
  342. return [t]