Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/astroid/transforms.py: 84%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
2# For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE
3# Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt
5from __future__ import annotations
7import warnings
8from collections import defaultdict
9from collections.abc import Callable, Sequence
10from typing import TYPE_CHECKING, TypeVar, Union, cast, overload
12from astroid.context import _invalidate_cache
13from astroid.typing import SuccessfulInferenceResult, TransformFn
15if TYPE_CHECKING:
16 from astroid import nodes
18 _SuccessfulInferenceResultT = TypeVar(
19 "_SuccessfulInferenceResultT", bound=SuccessfulInferenceResult
20 )
21 _Predicate = Callable[[_SuccessfulInferenceResultT], bool] | None
23# pylint: disable-next=consider-alternative-union-syntax
24_Vistables = Union[
25 "nodes.NodeNG", list["nodes.NodeNG"], tuple["nodes.NodeNG", ...], str, None
26]
27_VisitReturns = (
28 SuccessfulInferenceResult | Sequence[SuccessfulInferenceResult] | str | None
29)
32class TransformVisitor:
33 """A visitor for handling transforms.
35 The standard approach of using it is to call
36 :meth:`~visit` with an *astroid* module and the class
37 will take care of the rest, walking the tree and running the
38 transforms for each encountered node.
40 Based on its usage in AstroidManager.brain, it should not be reinstantiated.
41 """
43 def __init__(self) -> None:
44 # The typing here is incorrect, but it's the best we can do
45 # Refer to register_transform and unregister_transform for the correct types
46 self.transforms: defaultdict[
47 type[SuccessfulInferenceResult],
48 list[
49 tuple[
50 TransformFn[SuccessfulInferenceResult],
51 _Predicate[SuccessfulInferenceResult],
52 ]
53 ],
54 ] = defaultdict(list)
56 def _transform(self, node: SuccessfulInferenceResult) -> SuccessfulInferenceResult:
57 """Call matching transforms for the given node if any and return the
58 transformed node.
59 """
60 cls = node.__class__
62 for transform_func, predicate in self.transforms[cls]:
63 if predicate is None or predicate(node):
64 ret = transform_func(node)
65 # if the transformation function returns something, it's
66 # expected to be a replacement for the node
67 if ret is not None:
68 _invalidate_cache()
69 node = ret
70 if ret.__class__ != cls:
71 # Can no longer apply the rest of the transforms.
72 break
73 return node
75 def _visit(self, node: nodes.NodeNG) -> SuccessfulInferenceResult:
76 for name in node._astroid_fields:
77 value = getattr(node, name)
78 if TYPE_CHECKING:
79 value = cast(_Vistables, value)
81 visited = self._visit_generic(value)
82 if visited != value:
83 setattr(node, name, visited)
84 return self._transform(node)
86 @overload
87 def _visit_generic(self, node: None) -> None: ...
89 @overload
90 def _visit_generic(self, node: str) -> str: ...
92 @overload
93 def _visit_generic(
94 self, node: list[nodes.NodeNG]
95 ) -> list[SuccessfulInferenceResult]: ...
97 @overload
98 def _visit_generic(
99 self, node: tuple[nodes.NodeNG, ...]
100 ) -> tuple[SuccessfulInferenceResult, ...]: ...
102 @overload
103 def _visit_generic(self, node: nodes.NodeNG) -> SuccessfulInferenceResult: ...
105 def _visit_generic(self, node: _Vistables) -> _VisitReturns:
106 if not node:
107 return node
108 if isinstance(node, list):
109 return [self._visit_generic(child) for child in node]
110 if isinstance(node, tuple):
111 return tuple(self._visit_generic(child) for child in node)
112 if isinstance(node, str):
113 return node
115 try:
116 return self._visit(node)
117 except RecursionError:
118 # Returning the node untransformed is better than giving up.
119 warnings.warn(
120 f"Astroid was unable to transform {node}.\n"
121 "Some functionality will be missing unless the system recursion limit is lifted.\n"
122 "From pylint, try: --init-hook='import sys; sys.setrecursionlimit(2000)' or higher.",
123 UserWarning,
124 stacklevel=0,
125 )
126 return node
128 def register_transform(
129 self,
130 node_class: type[_SuccessfulInferenceResultT],
131 transform: TransformFn[_SuccessfulInferenceResultT],
132 predicate: _Predicate[_SuccessfulInferenceResultT] | None = None,
133 ) -> None:
134 """Register `transform(node)` function to be applied on the given node.
136 The transform will only be applied if `predicate` is None or returns true
137 when called with the node as argument.
139 The transform function may return a value which is then used to
140 substitute the original node in the tree.
141 """
142 self.transforms[node_class].append((transform, predicate)) # type: ignore[index, arg-type]
144 def unregister_transform(
145 self,
146 node_class: type[_SuccessfulInferenceResultT],
147 transform: TransformFn[_SuccessfulInferenceResultT],
148 predicate: _Predicate[_SuccessfulInferenceResultT] | None = None,
149 ) -> None:
150 """Unregister the given transform."""
151 self.transforms[node_class].remove((transform, predicate)) # type: ignore[index, arg-type]
153 def visit(self, node: nodes.NodeNG) -> SuccessfulInferenceResult:
154 """Walk the given astroid *tree* and transform each encountered node.
156 Only the nodes which have transforms registered will actually
157 be replaced or changed.
158 """
159 return self._visit(node)