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.

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