This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

530 рядки
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, **transformers_to_merge):
  119. """Merge a collection of transformers into the base_transformer, each into its own 'namespace'.
  120. When called, it will collect the methods from each transformer, and assign them to base_transformer,
  121. with their name prefixed with the given keyword, as ``prefix__methodname``.
  122. This function is especially useful for processing grammars that import other grammars,
  123. thereby creating some of their rules in a 'namespace'. (i.e with a consistent name prefix).
  124. In this case, the key for the transformer should match the name of the imported grammar.
  125. Parameters:
  126. base_transformer (Transformer, optional): The transformer that all other transformers will be added to.
  127. **transformers_to_merge: Keyword arguments, in the form of ``name_prefix = transformer``.
  128. Raises:
  129. AttributeError: In case of a name collision in the merged methods
  130. Example:
  131. ::
  132. class TBase(Transformer):
  133. def start(self, children):
  134. return children[0] + 'bar'
  135. class TImportedGrammar(Transformer):
  136. def foo(self, children):
  137. return "foo"
  138. composed_transformer = merge_transformers(TBase(), imported=TImportedGrammar())
  139. t = Tree('start', [ Tree('imported__foo', []) ])
  140. assert composed_transformer.transform(t) == 'foobar'
  141. """
  142. if base_transformer is None:
  143. base_transformer = Transformer()
  144. for prefix, transformer in transformers_to_merge.items():
  145. for method_name in dir(transformer):
  146. method = getattr(transformer, method_name)
  147. if not callable(method):
  148. continue
  149. if method_name.startswith("_") or method_name == "transform":
  150. continue
  151. prefixed_method = prefix + "__" + method_name
  152. if hasattr(base_transformer, prefixed_method):
  153. raise AttributeError("Cannot merge: method '%s' appears more than once" % prefixed_method)
  154. setattr(base_transformer, prefixed_method, method)
  155. return base_transformer
  156. class InlineTransformer(Transformer): # XXX Deprecated
  157. def _call_userfunc(self, tree, new_children=None):
  158. # Assumes tree is already transformed
  159. children = new_children if new_children is not None else tree.children
  160. try:
  161. f = getattr(self, tree.data)
  162. except AttributeError:
  163. return self.__default__(tree.data, children, tree.meta)
  164. else:
  165. return f(*children)
  166. class TransformerChain(object):
  167. def __init__(self, *transformers):
  168. self.transformers = transformers
  169. def transform(self, tree):
  170. for t in self.transformers:
  171. tree = t.transform(tree)
  172. return tree
  173. def __mul__(self, other):
  174. return TransformerChain(*self.transformers + (other,))
  175. class Transformer_InPlace(Transformer):
  176. """Same as Transformer, but non-recursive, and changes the tree in-place instead of returning new instances
  177. Useful for huge trees. Conservative in memory.
  178. """
  179. def _transform_tree(self, tree): # Cancel recursion
  180. return self._call_userfunc(tree)
  181. def transform(self, tree):
  182. for subtree in tree.iter_subtrees():
  183. subtree.children = list(self._transform_children(subtree.children))
  184. return self._transform_tree(tree)
  185. class Transformer_NonRecursive(Transformer):
  186. """Same as Transformer but non-recursive.
  187. Like Transformer, it doesn't change the original tree.
  188. Useful for huge trees.
  189. """
  190. def transform(self, tree):
  191. # Tree to postfix
  192. rev_postfix = []
  193. q = [tree]
  194. while q:
  195. t = q.pop()
  196. rev_postfix.append(t)
  197. if isinstance(t, Tree):
  198. q += t.children
  199. # Postfix to tree
  200. stack = []
  201. for x in reversed(rev_postfix):
  202. if isinstance(x, Tree):
  203. size = len(x.children)
  204. if size:
  205. args = stack[-size:]
  206. del stack[-size:]
  207. else:
  208. args = []
  209. stack.append(self._call_userfunc(x, args))
  210. elif self.__visit_tokens__ and isinstance(x, Token):
  211. stack.append(self._call_userfunc_token(x))
  212. else:
  213. stack.append(x)
  214. t ,= stack # We should have only one tree remaining
  215. return t
  216. class Transformer_InPlaceRecursive(Transformer):
  217. "Same as Transformer, recursive, but changes the tree in-place instead of returning new instances"
  218. def _transform_tree(self, tree):
  219. tree.children = list(self._transform_children(tree.children))
  220. return self._call_userfunc(tree)
  221. # Visitors
  222. class VisitorBase:
  223. def _call_userfunc(self, tree):
  224. return getattr(self, tree.data, self.__default__)(tree)
  225. def __default__(self, tree):
  226. """Default function that is called if there is no attribute matching ``tree.data``
  227. Can be overridden. Defaults to doing nothing.
  228. """
  229. return tree
  230. def __class_getitem__(cls, _):
  231. return cls
  232. class Visitor(VisitorBase):
  233. """Tree visitor, non-recursive (can handle huge trees).
  234. Visiting a node calls its methods (provided by the user via inheritance) according to ``tree.data``
  235. """
  236. def visit(self, tree):
  237. "Visits the tree, starting with the leaves and finally the root (bottom-up)"
  238. for subtree in tree.iter_subtrees():
  239. self._call_userfunc(subtree)
  240. return tree
  241. def visit_topdown(self,tree):
  242. "Visit the tree, starting at the root, and ending at the leaves (top-down)"
  243. for subtree in tree.iter_subtrees_topdown():
  244. self._call_userfunc(subtree)
  245. return tree
  246. class Visitor_Recursive(VisitorBase):
  247. """Bottom-up visitor, recursive.
  248. Visiting a node calls its methods (provided by the user via inheritance) according to ``tree.data``
  249. Slightly faster than the non-recursive version.
  250. """
  251. def visit(self, tree):
  252. "Visits the tree, starting with the leaves and finally the root (bottom-up)"
  253. for child in tree.children:
  254. if isinstance(child, Tree):
  255. self.visit(child)
  256. self._call_userfunc(tree)
  257. return tree
  258. def visit_topdown(self,tree):
  259. "Visit the tree, starting at the root, and ending at the leaves (top-down)"
  260. self._call_userfunc(tree)
  261. for child in tree.children:
  262. if isinstance(child, Tree):
  263. self.visit_topdown(child)
  264. return tree
  265. def visit_children_decor(func):
  266. "See Interpreter"
  267. @wraps(func)
  268. def inner(cls, tree):
  269. values = cls.visit_children(tree)
  270. return func(cls, values)
  271. return inner
  272. class Interpreter(_Decoratable):
  273. """Interpreter walks the tree starting at the root.
  274. Visits the tree, starting with the root and finally the leaves (top-down)
  275. For each tree node, it calls its methods (provided by user via inheritance) according to ``tree.data``.
  276. Unlike ``Transformer`` and ``Visitor``, the Interpreter doesn't automatically visit its sub-branches.
  277. The user has to explicitly call ``visit``, ``visit_children``, or use the ``@visit_children_decor``.
  278. This allows the user to implement branching and loops.
  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 user-supplied visitor methods.
  341. By default, callback methods of transformers/visitors accept one argument - a list of the node's children.
  342. ``v_args`` can modify this behavior. When used on a transformer/visitor class definition,
  343. it applies to all the callback methods inside it.
  344. ``v_args`` can be applied to a single method, or to an entire class. When applied to both,
  345. the options given to the method take precedence.
  346. Parameters:
  347. inline (bool, optional): Children are provided as ``*args`` instead of a list argument (not recommended for very long lists).
  348. meta (bool, optional): Provides two arguments: ``children`` and ``meta`` (instead of just the first)
  349. tree (bool, optional): Provides the entire tree as the argument, instead of the children.
  350. wrapper (function, optional): Provide a function to decorate all methods.
  351. Example:
  352. ::
  353. @v_args(inline=True)
  354. class SolveArith(Transformer):
  355. def add(self, left, right):
  356. return left + right
  357. class ReverseNotation(Transformer_InPlace):
  358. @v_args(tree=True)
  359. def tree_node(self, tree):
  360. tree.children = tree.children[::-1]
  361. """
  362. if tree and (meta or inline):
  363. raise ValueError("Visitor functions cannot combine 'tree' with 'meta' or 'inline'.")
  364. func = None
  365. if meta:
  366. if inline:
  367. func = _vargs_meta_inline
  368. else:
  369. func = _vargs_meta
  370. elif inline:
  371. func = _vargs_inline
  372. elif tree:
  373. func = _vargs_tree
  374. if wrapper is not None:
  375. if func is not None:
  376. raise ValueError("Cannot use 'wrapper' along with 'tree', 'meta' or 'inline'.")
  377. func = wrapper
  378. def _visitor_args_dec(obj):
  379. return _apply_decorator(obj, _visitor_args_func_dec, visit_wrapper=func)
  380. return _visitor_args_dec
  381. ###}
  382. # --- Visitor Utilities ---
  383. class CollapseAmbiguities(Transformer):
  384. """
  385. Transforms a tree that contains any number of _ambig nodes into a list of trees,
  386. each one containing an unambiguous tree.
  387. The length of the resulting list is the product of the length of all _ambig nodes.
  388. Warning: This may quickly explode for highly ambiguous trees.
  389. """
  390. def _ambig(self, options):
  391. return sum(options, [])
  392. def __default__(self, data, children_lists, meta):
  393. return [Tree(data, children, meta) for children in combine_alternatives(children_lists)]
  394. def __default_token__(self, t):
  395. return [t]