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.

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