This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

541 linhas
18 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. Methods are provided by the user via inheritance, and called according to ``tree.data``.
  38. The returned value from each method replaces the node in the tree structure.
  39. Transformers 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.
  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 (bool, optional): Should the transformer visit tokens in addition to rules.
  50. Setting this to ``False`` is slightly faster. Defaults to ``True``.
  51. (For processing ignored tokens, use the ``lexer_callbacks`` options)
  52. NOTE: A transformer without methods essentially performs a non-memoized partial deepcopy.
  53. """
  54. __visit_tokens__ = True # For backwards compatibility
  55. def __init__(self, visit_tokens=True):
  56. self.__visit_tokens__ = visit_tokens
  57. def _call_userfunc(self, tree, new_children=None):
  58. # Assumes tree is already transformed
  59. children = new_children if new_children is not None else tree.children
  60. try:
  61. f = getattr(self, tree.data)
  62. except AttributeError:
  63. return self.__default__(tree.data, children, tree.meta)
  64. else:
  65. try:
  66. wrapper = getattr(f, 'visit_wrapper', None)
  67. if wrapper is not None:
  68. return f.visit_wrapper(f, tree.data, children, tree.meta)
  69. else:
  70. return f(children)
  71. except (GrammarError, Discard):
  72. raise
  73. except Exception as e:
  74. raise VisitError(tree.data, tree, e)
  75. def _call_userfunc_token(self, token):
  76. try:
  77. f = getattr(self, token.type)
  78. except AttributeError:
  79. return self.__default_token__(token)
  80. else:
  81. try:
  82. return f(token)
  83. except (GrammarError, Discard):
  84. raise
  85. except Exception as e:
  86. raise VisitError(token.type, token, e)
  87. def _transform_children(self, children):
  88. for c in children:
  89. try:
  90. if isinstance(c, Tree):
  91. yield self._transform_tree(c)
  92. elif self.__visit_tokens__ and isinstance(c, Token):
  93. yield self._call_userfunc_token(c)
  94. else:
  95. yield c
  96. except Discard:
  97. pass
  98. def _transform_tree(self, tree):
  99. children = list(self._transform_children(tree.children))
  100. return self._call_userfunc(tree, children)
  101. def transform(self, tree):
  102. "Transform the given tree, and return the final result"
  103. return self._transform_tree(tree)
  104. def __mul__(self, other):
  105. """Chain two transformers together, returning a new transformer.
  106. """
  107. return TransformerChain(self, other)
  108. def __default__(self, data, children, meta):
  109. """Default function that is called if there is no attribute matching ``data``
  110. Can be overridden. Defaults to creating a new copy of the tree node (i.e. ``return Tree(data, children, meta)``)
  111. """
  112. return Tree(data, children, meta)
  113. def __default_token__(self, token):
  114. """Default function that is called if there is no attribute matching ``token.type``
  115. Can be overridden. Defaults to returning the token as-is.
  116. """
  117. return token
  118. def merge_transformers(base_transformer=None, **kwargs):
  119. """
  120. Paramaters:
  121. :param base_transformer: Transformer that all other transformers will be added to.
  122. :param \**kwargs: Key-value arguments providing the prefix for the methods of the transformer and the Transformers themselves.
  123. Compose a new transformer from a base and the in the `**kwargs` provided Transformer instances.
  124. The key should match the grammar file that the Transformer is supposed to manipulate.
  125. This method is meant to aid the composing of large transformers that
  126. manipulate grammars that cross multiple lark files.
  127. Example:
  128. ```python
  129. class T1(Transformer):
  130. def method_on_main_grammar(self, children):
  131. # Do something
  132. pass
  133. def imported_grammar__method(self, children):
  134. # Do something else
  135. pass
  136. class TMain(Transformer):
  137. def method_on_main_grammar(self, children):
  138. # Do something
  139. pass
  140. class TImportedGrammar(Transformer):
  141. def method(self, children):
  142. # Do something else
  143. pass
  144. regular_transformer = T1()
  145. composed_transformer = merge_transformers(TMain(),
  146. imported_grammar=TImportedGrammar())
  147. ```
  148. In the above code block `regular_transformer` and `composed_transformer`
  149. should behave identically.
  150. """
  151. infix = "__"
  152. if base_transformer is None:
  153. base_transformer = Transformer()
  154. for prefix, transformer in kwargs.items():
  155. prefix += infix
  156. for method_name in dir(transformer):
  157. method = getattr(transformer, method_name)
  158. if not callable(method):
  159. continue
  160. if method_name.startswith("_") or method_name == "transform":
  161. continue
  162. new_method_name = prefix + method_name
  163. if prefix + method_name in dir(base_transformer):
  164. raise AttributeError(
  165. ("Method '{new_method_name}' already present in base "
  166. "transformer").format(new_method_name=new_method_name))
  167. setattr(base_transformer, new_method_name, method)
  168. return base_transformer
  169. class InlineTransformer(Transformer): # XXX Deprecated
  170. def _call_userfunc(self, tree, new_children=None):
  171. # Assumes tree is already transformed
  172. children = new_children if new_children is not None else tree.children
  173. try:
  174. f = getattr(self, tree.data)
  175. except AttributeError:
  176. return self.__default__(tree.data, children, tree.meta)
  177. else:
  178. return f(*children)
  179. class TransformerChain(object):
  180. def __init__(self, *transformers):
  181. self.transformers = transformers
  182. def transform(self, tree):
  183. for t in self.transformers:
  184. tree = t.transform(tree)
  185. return tree
  186. def __mul__(self, other):
  187. return TransformerChain(*self.transformers + (other,))
  188. class Transformer_InPlace(Transformer):
  189. """Same as Transformer, but non-recursive, and changes the tree in-place instead of returning new instances
  190. Useful for huge trees. Conservative in memory.
  191. """
  192. def _transform_tree(self, tree): # Cancel recursion
  193. return self._call_userfunc(tree)
  194. def transform(self, tree):
  195. for subtree in tree.iter_subtrees():
  196. subtree.children = list(self._transform_children(subtree.children))
  197. return self._transform_tree(tree)
  198. class Transformer_NonRecursive(Transformer):
  199. """Same as Transformer but non-recursive.
  200. Like Transformer, it doesn't change the original tree.
  201. Useful for huge trees.
  202. """
  203. def transform(self, tree):
  204. # Tree to postfix
  205. rev_postfix = []
  206. q = [tree]
  207. while q:
  208. t = q.pop()
  209. rev_postfix.append(t)
  210. if isinstance(t, Tree):
  211. q += t.children
  212. # Postfix to tree
  213. stack = []
  214. for x in reversed(rev_postfix):
  215. if isinstance(x, Tree):
  216. size = len(x.children)
  217. if size:
  218. args = stack[-size:]
  219. del stack[-size:]
  220. else:
  221. args = []
  222. stack.append(self._call_userfunc(x, args))
  223. elif self.__visit_tokens__ and isinstance(x, Token):
  224. stack.append(self._call_userfunc_token(x))
  225. else:
  226. stack.append(x)
  227. t ,= stack # We should have only one tree remaining
  228. return t
  229. class Transformer_InPlaceRecursive(Transformer):
  230. "Same as Transformer, recursive, but changes the tree in-place instead of returning new instances"
  231. def _transform_tree(self, tree):
  232. tree.children = list(self._transform_children(tree.children))
  233. return self._call_userfunc(tree)
  234. # Visitors
  235. class VisitorBase:
  236. def _call_userfunc(self, tree):
  237. return getattr(self, tree.data, self.__default__)(tree)
  238. def __default__(self, tree):
  239. """Default function that is called if there is no attribute matching ``tree.data``
  240. Can be overridden. Defaults to doing nothing.
  241. """
  242. return tree
  243. def __class_getitem__(cls, _):
  244. return cls
  245. class Visitor(VisitorBase):
  246. """Tree visitor, non-recursive (can handle huge trees).
  247. Visiting a node calls its methods (provided by the user via inheritance) according to ``tree.data``
  248. """
  249. def visit(self, tree):
  250. "Visits the tree, starting with the leaves and finally the root (bottom-up)"
  251. for subtree in tree.iter_subtrees():
  252. self._call_userfunc(subtree)
  253. return tree
  254. def visit_topdown(self,tree):
  255. "Visit the tree, starting at the root, and ending at the leaves (top-down)"
  256. for subtree in tree.iter_subtrees_topdown():
  257. self._call_userfunc(subtree)
  258. return tree
  259. class Visitor_Recursive(VisitorBase):
  260. """Bottom-up visitor, recursive.
  261. Visiting a node calls its methods (provided by the user via inheritance) according to ``tree.data``
  262. Slightly faster than the non-recursive version.
  263. """
  264. def visit(self, tree):
  265. "Visits the tree, starting with the leaves and finally the root (bottom-up)"
  266. for child in tree.children:
  267. if isinstance(child, Tree):
  268. self.visit(child)
  269. self._call_userfunc(tree)
  270. return tree
  271. def visit_topdown(self,tree):
  272. "Visit the tree, starting at the root, and ending at the leaves (top-down)"
  273. self._call_userfunc(tree)
  274. for child in tree.children:
  275. if isinstance(child, Tree):
  276. self.visit_topdown(child)
  277. return tree
  278. def visit_children_decor(func):
  279. "See Interpreter"
  280. @wraps(func)
  281. def inner(cls, tree):
  282. values = cls.visit_children(tree)
  283. return func(cls, values)
  284. return inner
  285. class Interpreter(_Decoratable):
  286. """Interpreter walks the tree starting at the root.
  287. Visits the tree, starting with the root and finally the leaves (top-down)
  288. For each tree node, it calls its methods (provided by user via inheritance) according to ``tree.data``.
  289. Unlike ``Transformer`` and ``Visitor``, the Interpreter doesn't automatically visit its sub-branches.
  290. The user has to explicitly call ``visit``, ``visit_children``, or use the ``@visit_children_decor``.
  291. This allows the user to implement branching and loops.
  292. """
  293. def visit(self, tree):
  294. f = getattr(self, tree.data)
  295. wrapper = getattr(f, 'visit_wrapper', None)
  296. if wrapper is not None:
  297. return f.visit_wrapper(f, tree.data, tree.children, tree.meta)
  298. else:
  299. return f(tree)
  300. def visit_children(self, tree):
  301. return [self.visit(child) if isinstance(child, Tree) else child
  302. for child in tree.children]
  303. def __getattr__(self, name):
  304. return self.__default__
  305. def __default__(self, tree):
  306. return self.visit_children(tree)
  307. # Decorators
  308. def _apply_decorator(obj, decorator, **kwargs):
  309. try:
  310. _apply = obj._apply_decorator
  311. except AttributeError:
  312. return decorator(obj, **kwargs)
  313. else:
  314. return _apply(decorator, **kwargs)
  315. def _inline_args__func(func):
  316. @wraps(func)
  317. def create_decorator(_f, with_self):
  318. if with_self:
  319. def f(self, children):
  320. return _f(self, *children)
  321. else:
  322. def f(self, children):
  323. return _f(*children)
  324. return f
  325. return smart_decorator(func, create_decorator)
  326. def inline_args(obj): # XXX Deprecated
  327. return _apply_decorator(obj, _inline_args__func)
  328. def _visitor_args_func_dec(func, visit_wrapper=None, static=False):
  329. def create_decorator(_f, with_self):
  330. if with_self:
  331. def f(self, *args, **kwargs):
  332. return _f(self, *args, **kwargs)
  333. else:
  334. def f(self, *args, **kwargs):
  335. return _f(*args, **kwargs)
  336. return f
  337. if static:
  338. f = wraps(func)(create_decorator(func, False))
  339. else:
  340. f = smart_decorator(func, create_decorator)
  341. f.vargs_applied = True
  342. f.visit_wrapper = visit_wrapper
  343. return f
  344. def _vargs_inline(f, _data, children, _meta):
  345. return f(*children)
  346. def _vargs_meta_inline(f, _data, children, meta):
  347. return f(meta, *children)
  348. def _vargs_meta(f, _data, children, meta):
  349. return f(children, meta) # TODO swap these for consistency? Backwards incompatible!
  350. def _vargs_tree(f, data, children, meta):
  351. return f(Tree(data, children, meta))
  352. def v_args(inline=False, meta=False, tree=False, wrapper=None):
  353. """A convenience decorator factory for modifying the behavior of user-supplied visitor methods.
  354. By default, callback methods of transformers/visitors accept one argument - a list of the node's children.
  355. ``v_args`` can modify this behavior. When used on a transformer/visitor class definition,
  356. it applies to all the callback methods inside it.
  357. ``v_args`` can be applied to a single method, or to an entire class. When applied to both,
  358. the options given to the method take precedence.
  359. Parameters:
  360. inline (bool, optional): Children are provided as ``*args`` instead of a list argument (not recommended for very long lists).
  361. meta (bool, optional): Provides two arguments: ``children`` and ``meta`` (instead of just the first)
  362. tree (bool, optional): Provides the entire tree as the argument, instead of the children.
  363. wrapper (function, optional): Provide a function to decorate all methods.
  364. Example:
  365. ::
  366. @v_args(inline=True)
  367. class SolveArith(Transformer):
  368. def add(self, left, right):
  369. return left + right
  370. class ReverseNotation(Transformer_InPlace):
  371. @v_args(tree=True)
  372. def tree_node(self, tree):
  373. tree.children = tree.children[::-1]
  374. """
  375. if tree and (meta or inline):
  376. raise ValueError("Visitor functions cannot combine 'tree' with 'meta' or 'inline'.")
  377. func = None
  378. if meta:
  379. if inline:
  380. func = _vargs_meta_inline
  381. else:
  382. func = _vargs_meta
  383. elif inline:
  384. func = _vargs_inline
  385. elif tree:
  386. func = _vargs_tree
  387. if wrapper is not None:
  388. if func is not None:
  389. raise ValueError("Cannot use 'wrapper' along with 'tree', 'meta' or 'inline'.")
  390. func = wrapper
  391. def _visitor_args_dec(obj):
  392. return _apply_decorator(obj, _visitor_args_func_dec, visit_wrapper=func)
  393. return _visitor_args_dec
  394. ###}
  395. # --- Visitor Utilities ---
  396. class CollapseAmbiguities(Transformer):
  397. """
  398. Transforms a tree that contains any number of _ambig nodes into a list of trees,
  399. each one containing an unambiguous tree.
  400. The length of the resulting list is the product of the length of all _ambig nodes.
  401. Warning: This may quickly explode for highly ambiguous trees.
  402. """
  403. def _ambig(self, options):
  404. return sum(options, [])
  405. def __default__(self, data, children_lists, meta):
  406. return [Tree(data, children, meta) for children in combine_alternatives(children_lists)]
  407. def __default_token__(self, t):
  408. return [t]