Debian Codegraph @

src/_pytest/_code/source.py

raw
1 # mypy: allow-untyped-defs
2 from __future__ import annotations
3
4 import ast
5 from bisect import bisect_right
6 from collections.abc import Iterable
7 from collections.abc import Iterator
8 import inspect
9 import textwrap
10 import tokenize
11 import types
12 from typing import overload
13 import warnings
14
15
16 class Source:
17 """An immutable object holding a source code fragment.
18
19 When using Source(...), the source lines are deindented.
20 """
21
22 def __init__(self, obj: object = None) -> None:
23 if not obj:
24 self.lines: list[str] = []
25 self.raw_lines: list[str] = []
26 elif isinstance(obj, Source):
27 self.lines = obj.lines
28 self.raw_lines = obj.raw_lines
29 elif isinstance(obj, tuple | list):
30 self.lines = deindent(x.rstrip("\n") for x in obj)
31 self.raw_lines = list(x.rstrip("\n") for x in obj)
32 elif isinstance(obj, str):
33 self.lines = deindent(obj.split("\n"))
34 self.raw_lines = obj.split("\n")
35 else:
36 try:
37 rawcode = getrawcode(obj)
38 src = inspect.getsource(rawcode)
39 except TypeError:
40 src = inspect.getsource(obj) # type: ignore[arg-type]
41 self.lines = deindent(src.split("\n"))
42 self.raw_lines = src.split("\n")
43
44 def __eq__(self, other: object) -> bool:
45 if not isinstance(other, Source):
46 return NotImplemented
47 return self.lines == other.lines
48
49 # Ignore type because of https://github.com/python/mypy/issues/4266.
50 __hash__ = None # type: ignore
51
52 @overload
53 def __getitem__(self, key: int) -> str: ...
54
55 @overload
56 def __getitem__(self, key: slice) -> Source: ...
57
58 def __getitem__(self, key: int | slice) -> str | Source:
59 if isinstance(key, int):
60 return self.lines[key]
61 else:
62 if key.step not in (None, 1):
63 raise IndexError("cannot slice a Source with a step")
64 newsource = Source()
65 newsource.lines = self.lines[key.start : key.stop]
66 newsource.raw_lines = self.raw_lines[key.start : key.stop]
67 return newsource
68
69 def __iter__(self) -> Iterator[str]:
70 return iter(self.lines)
71
72 def __len__(self) -> int:
73 return len(self.lines)
74
75 def strip(self) -> Source:
76 """Return new Source object with trailing and leading blank lines removed."""
77 start, end = 0, len(self)
78 while start < end and not self.lines[start].strip():
79 start += 1
80 while end > start and not self.lines[end - 1].strip():
81 end -= 1
82 source = Source()
83 source.raw_lines = self.raw_lines
84 source.lines[:] = self.lines[start:end]
85 return source
86
87 def indent(self, indent: str = " " * 4) -> Source:
88 """Return a copy of the source object with all lines indented by the
89 given indent-string."""
90 newsource = Source()
91 newsource.raw_lines = self.raw_lines
92 newsource.lines = [(indent + line) for line in self.lines]
93 return newsource
94
95 def getstatement(self, lineno: int) -> Source:
96 """Return Source statement which contains the given linenumber
97 (counted from 0)."""
98 start, end = self.getstatementrange(lineno)
99 return self[start:end]
100
101 def getstatementrange(self, lineno: int) -> tuple[int, int]:
102 """Return (start, end) tuple which spans the minimal statement region
103 which containing the given lineno."""
104 if not (0 <= lineno < len(self)):
105 raise IndexError("lineno out of range")
106 _ast, start, end = getstatementrange_ast(lineno, self)
107 return start, end
108
109 def deindent(self) -> Source:
110 """Return a new Source object deindented."""
111 newsource = Source()
112 newsource.lines[:] = deindent(self.lines)
113 newsource.raw_lines = self.raw_lines
114 return newsource
115
116 def __str__(self) -> str:
117 return "\n".join(self.lines)
118
119
120 #
121 # helper functions
122 #
123
124
125 def findsource(obj) -> tuple[Source | None, int]:
126 try:
127 sourcelines, lineno = inspect.findsource(obj)
128 except Exception:
129 return None, -1
130 source = Source()
131 source.lines = [line.rstrip() for line in sourcelines]
132 source.raw_lines = sourcelines
133 return source, lineno
134
135
136 def getrawcode(obj: object, trycall: bool = True) -> types.CodeType:
137 """Return code object for given function."""
138 try:
139 return obj.__code__ # type: ignore[attr-defined,no-any-return]
140 except AttributeError:
141 pass
142 if trycall:
143 call = getattr(obj, "__call__", None)
144 if call and not isinstance(obj, type):
145 return getrawcode(call, trycall=False)
146 raise TypeError(f"could not get code object for {obj!r}")
147
148
149 def deindent(lines: Iterable[str]) -> list[str]:
150 return textwrap.dedent("\n".join(lines)).splitlines()
151
152
153 def get_statement_startend2(lineno: int, node: ast.AST) -> tuple[int, int | None]:
154 # Flatten all statements and except handlers into one lineno-list.
155 # AST's line numbers start indexing at 1.
156 values: list[int] = []
157 for x in ast.walk(node):
158 if isinstance(x, ast.stmt | ast.ExceptHandler):
159 # The lineno points to the class/def, so need to include the decorators.
160 if isinstance(x, ast.ClassDef | ast.FunctionDef | ast.AsyncFunctionDef):
161 for d in x.decorator_list:
162 values.append(d.lineno - 1)
163 values.append(x.lineno - 1)
164 for name in ("finalbody", "orelse"):
165 val: list[ast.stmt] | None = getattr(x, name, None)
166 if val:
167 # Treat the finally/orelse part as its own statement.
168 values.append(val[0].lineno - 1 - 1)
169 values.sort()
170 insert_index = bisect_right(values, lineno)
171 if insert_index == 0:
172 return 0, None
173 start = values[insert_index - 1]
174 if insert_index >= len(values):
175 end = None
176 else:
177 end = values[insert_index]
178 return start, end
179
180
181 def getstatementrange_ast(
182 lineno: int,
183 source: Source,
184 assertion: bool = False,
185 astnode: ast.AST | None = None,
186 ) -> tuple[ast.AST, int, int]:
187 if astnode is None:
188 content = str(source)
189 # See #4260:
190 # Don't produce duplicate warnings when compiling source to find AST.
191 with warnings.catch_warnings():
192 warnings.simplefilter("ignore")
193 astnode = ast.parse(content, "source", "exec")
194
195 start, end = get_statement_startend2(lineno, astnode)
196 # We need to correct the end:
197 # - ast-parsing strips comments
198 # - there might be empty lines
199 # - we might have lesser indented code blocks at the end
200 if end is None:
201 end = len(source.lines)
202
203 if end > start + 1:
204 # Make sure we don't span differently indented code blocks
205 # by using the BlockFinder helper used which inspect.getsource() uses itself.
206 block_finder = inspect.BlockFinder()
207 # If we start with an indented line, put blockfinder to "started" mode.
208 block_finder.started = (
209 bool(source.lines[start]) and source.lines[start][0].isspace()
210 )
211 it = ((x + "\n") for x in source.lines[start:end])
212 try:
213 for tok in tokenize.generate_tokens(lambda: next(it)):
214 block_finder.tokeneater(*tok)
215 except (inspect.EndOfBlock, IndentationError):
216 end = block_finder.last + start
217 except Exception:
218 pass
219
220 # The end might still point to a comment or empty line, correct it.
221 end = min(end, len(source.lines))
222 while end:
223 line = source.lines[end - 1].lstrip()
224 if line.startswith("#") or not line:
225 end -= 1
226 else:
227 break
228 return astnode, start, end