This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

471 lines
16 KiB

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