• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

alexmojaki / executing / 45790414788

26 Nov 2026 09:18AM UTC coverage: 91.748% (+0.3%) from 91.491%
45790414788

push

github

780 of 846 branches covered (92.2%)

Branch coverage included in aggregate %.

910 of 996 relevant lines covered (91.37%)

4.86 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

93.71
/executing/executing.py
1
"""
2
MIT License
3

4
Copyright (c) 2021 Alex Hall
5

6
Permission is hereby granted, free of charge, to any person obtaining a copy
7
of this software and associated documentation files (the "Software"), to deal
8
in the Software without restriction, including without limitation the rights
9
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
copies of the Software, and to permit persons to whom the Software is
11
furnished to do so, subject to the following conditions:
12

13
The above copyright notice and this permission notice shall be included in all
14
copies or substantial portions of the Software.
15

16
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
SOFTWARE.
23
"""
24

25
from __future__ import annotations
8 ✔
26
import __future__
8 ✔
27
import ast
8 ✔
28
import dis
8 ✔
29
import inspect
8 ✔
30
import io
8 ✔
31
import linecache
8 ✔
32
import re
8 ✔
33
import sys
8 ✔
34
import types
8 ✔
35
from collections import defaultdict
8 ✔
36
from copy import deepcopy
8 ✔
37
from functools import lru_cache
8 ✔
38
from itertools import islice
8 ✔
39
from itertools import zip_longest
8 ✔
40
from operator import attrgetter
8 ✔
41
from pathlib import Path
8 ✔
42
from threading import RLock
8 ✔
43
from tokenize import detect_encoding
8 ✔
44
from typing import (
8 ✔
45
    TYPE_CHECKING,
46
    Any,
47
    Callable,
48
    Dict,
49
    Iterable,
50
    Iterator,
51
    List,
52
    Optional,
53
    Sequence,
54
    Set,
55
    Sized,
56
    Tuple,
57
    Type,
58
    TypeVar,
59
    Union,
60
    cast,
61
)
62
from ._utils import (
8 ✔
63
    mangled_name,
64
    assert_,
65
    EnhancedAST,
66
    EnhancedInstruction,
67
    Instruction,
68
    get_instructions,
69
    CodeKey,
70
)
71

72

8 !
73
if TYPE_CHECKING:
×
74
    from asttokens import ASTTokens, ASTText
×
75
    from asttokens.asttokens import ASTTextBase
76

77

8 ✔
78
function_node_types: Tuple[Type, ...] = (ast.FunctionDef, ast.AsyncFunctionDef)
79

8 ✔
80
cache = lru_cache(maxsize=None)
81

8 ✔
82
TESTING = 0
83

84

8 ✔
85
class NotOneValueFound(Exception):
8 ✔
86
    def __init__(self, msg: str, values: Sequence = ()) -> None:
8 ✔
87
        self.values = values
8 ✔
88
        super(NotOneValueFound, self).__init__(msg)
89

90

8 ✔
91
T = TypeVar("T")
92

93

8 ✔
94
def only(it: Iterable[T]) -> T:
8 ✔
95
    if isinstance(it, Sized):
3 ✔
96
        if len(it) != 1:
3 ✔
97
            raise NotOneValueFound("Expected one value, found %s" % len(it))
98
        # noinspection PyTypeChecker
3 ✔
99
        return list(it)[0]
100

8 ✔
101
    lst = tuple(islice(it, 2))
8 ✔
102
    if len(lst) == 0:
8 ✔
103
        raise NotOneValueFound("Expected one value, found 0")
8 ✔
104
    if len(lst) > 1:
8 ✔
105
        raise NotOneValueFound("Expected one value, found several", lst)
8 ✔
106
    return lst[0]
107

108

8 ✔
109
class Source(object):
110
    """
111
    The source code of a single file and associated metadata.
112

113
    The main method of interest is the classmethod `executing(frame)`.
114

115
    If you want an instance of this class, don't construct it.
116
    Ideally use the classmethod `for_frame(frame)`.
117
    If you don't have a frame, use `for_filename(filename [, module_globals])`.
118
    These methods cache instances by filename, so at most one instance exists per filename.
119

120
    Attributes:
121
        - filename
122
        - text
123
        - lines
124
        - tree: AST parsed from text, or None if text is not valid Python
125
            All nodes in the tree have an extra `parent` attribute
126

127
    Other methods of interest:
128
        - statements_at_line
129
        - asttokens
130
        - code_qualname
131
    """
132

8 ✔
133
    def __init__(self, filename: str, lines: Sequence[str]) -> None:
134
        """
135
        Don't call this constructor, see the class docstring.
136
        """
137

8 ✔
138
        self.filename = filename
8 ✔
139
        self.text = "".join(lines)
8 ✔
140
        self.lines = [line.rstrip("\r\n") for line in lines]
141

8 ✔
142
        self._nodes_by_line = defaultdict(list)
8 ✔
143
        self.tree = None
8 ✔
144
        self._qualnames = {}
8 ✔
145
        self._asttokens: Optional[ASTTokens] = None
8 ✔
146
        self._asttext: Optional[ASTText] = None
147

8 ✔
148
        try:
8 ✔
149
            self.tree = ast.parse(self.text, filename=filename)
8 ✔
150
        except (SyntaxError, ValueError):
8 ✔
151
            pass
152
        else:
8 ✔
153
            for node in ast.walk(self.tree):
8 ✔
154
                for child in ast.iter_child_nodes(node):
8 ✔
155
                    cast(EnhancedAST, child).parent = cast(EnhancedAST, node)
8 ✔
156
                for lineno in node_linenos(node):
8 ✔
157
                    self._nodes_by_line[lineno].append(node)
158

8 ✔
159
            visitor = QualnameVisitor()
8 ✔
160
            visitor.visit(self.tree)
8 ✔
161
            self._qualnames = visitor.qualnames
162

8 ✔
163
    @classmethod
8 ✔
164
    def for_frame(cls, frame: types.FrameType, use_cache: bool = True) -> Source:
165
        """
166
        Returns the `Source` object corresponding to the file the frame is executing in.
167
        """
8 ✔
168
        return cls.for_filename(
169
            frame.f_code.co_filename, frame.f_globals or {}, use_cache
170
        )
171

8 ✔
172
    @classmethod
8 ✔
173
    def for_filename(
174
        cls,
175
        filename: Union[str, Path],
176
        module_globals: Optional[Dict[str, Any]] = None,
177
        use_cache: bool = True,  # noqa no longer used
178
    ) -> Source:
8 ✔
179
        if isinstance(filename, Path):
8 ✔
180
            filename = str(filename)
181

8 ✔
182
        def get_lines() -> List[str]:
8 ✔
183
            return linecache.getlines(filename, module_globals)
184

185
        # Save the current linecache entry, then ensure the cache is up to date.
8 ✔
186
        entry = linecache.cache.get(filename)  # type: ignore[attr-defined]
8 ✔
187
        linecache.checkcache(filename)
8 ✔
188
        lines = get_lines()
8 ✔
189
        if entry is not None and not lines:
190
            # There was an entry, checkcache removed it, and nothing replaced it.
191
            # This means the file wasn't simply changed (because the `lines` wouldn't be empty)
192
            # but rather the file was found not to exist, probably because `filename` was fake.
193
            # Restore the original entry so that we still have something.
8 ✔
194
            linecache.cache[filename] = entry  # type: ignore[attr-defined]
8 ✔
195
            lines = get_lines()
196

8 ✔
197
        return cls._for_filename_and_lines(filename, tuple(lines))
198

8 ✔
199
    @classmethod
8 ✔
200
    def _for_filename_and_lines(cls, filename: str, lines: Sequence[str]) -> Source:
8 ✔
201
        source_cache: Dict[Tuple[str, Sequence[str]], Source] = cls._class_local(
202
            "__source_cache_with_lines", {}
203
        )
8 ✔
204
        try:
8 ✔
205
            return source_cache[(filename, lines)]
8 ✔
206
        except KeyError:
8 ✔
207
            pass
208

8 ✔
209
        result = source_cache[(filename, lines)] = cls(filename, lines)
8 ✔
210
        return result
211

8 ✔
212
    @classmethod
8 ✔
213
    def lazycache(cls, frame: types.FrameType) -> None:
8 ✔
214
        linecache.lazycache(frame.f_code.co_filename, frame.f_globals)
215

8 ✔
216
    @classmethod
8 ✔
217
    def executing(
218
        cls, frame_or_tb: Union[types.TracebackType, types.FrameType]
219
    ) -> Executing:
220
        """
221
        Returns an `Executing` object representing the operation
222
        currently executing in the given frame or traceback object.
223
        """
8 ✔
224
        if isinstance(frame_or_tb, types.TracebackType):
225
            # https://docs.python.org/3/reference/datamodel.html#traceback-objects
226
            # "tb_lineno gives the line number where the exception occurred;
227
            #  tb_lasti indicates the precise instruction.
228
            #  The line number and last instruction in the traceback may differ
229
            #  from the line number of its frame object
230
            #  if the exception occurred in a try statement with no matching except clause
231
            #  or with a finally clause."
8 ✔
232
            tb = frame_or_tb
8 ✔
233
            frame = tb.tb_frame
8 ✔
234
            lasti = tb.tb_lasti
8 ✔
235
        else:
236
            frame = frame_or_tb
8 ✔
237
            lasti = frame.f_lasti
8 ✔
238

8 ✔
239
        code = frame.f_code
240
        key = (CodeKey(code), lasti)
8 ✔
241
        executing_cache: Dict[Tuple[CodeKey, int], Any] = cls._class_local(
8 ✔
242
            "__executing_cache", {}
8 ✔
243
        )
244

245
        args = executing_cache.get(key)
246
        if not args:
8 ✔
247
            node = stmts = decorator = None
8 ✔
248
            source = cls.for_frame(frame)
8 ✔
249
            tree = source.tree
8 ✔
250
            if tree:
8 ✔
251
                use_positions = False
8 ✔
252
                try:
8 ✔
253
                    ipython = is_ipython_cell_code(code)
8 ✔
254
                    if sys.version_info >= (3, 11) and not ipython:
8 !
255
                        # Position-based lookup does not need candidate statements.
8 ✔
256
                        use_positions = True
8 ✔
257
                        node_finder = NodeFinder(frame, None, tree, lasti, source)
258
                        node = node_finder.result
259
                        decorator = node_finder.decorator
260
                    else:
8 ✔
261
                        lineno = (
8 ✔
262
                            frame_or_tb.tb_lineno
8 ✔
263
                            if isinstance(frame_or_tb, types.TracebackType)
264
                            else frame.f_lineno
8 ✔
265
                        )
8 ✔
266
                        stmts = source.statements_at_line(lineno)
8 ✔
267
                        if stmts:
8 ✔
268
                            if ipython:
8 ✔
269
                                decorator, node = find_node_ipython(
8 ✔
270
                                    frame, lasti, stmts, source
8 ✔
271
                                )
272
                            else:
8 ✔
273
                                node_finder = NodeFinder(
274
                                    frame, stmts, tree, lasti, source
8 ✔
275
                                )
276
                                node = node_finder.result
8 ✔
277
                                decorator = node_finder.decorator
8 ✔
278

279
                    if node:
280
                        new_stmts = {statement_containing_node(node)}
281
                        assert_(stmts is None or new_stmts <= stmts)
282
                        stmts = new_stmts
283
                except Exception:
8 ✔
284
                    if TESTING:
8 ✔
285
                        raise
8 ✔
286

287
                if use_positions and stmts is None:
8 ✔
288
                    # Unknown nodes still expose the line's candidate statements.
8 ✔
289
                    # Resolve the potentially expensive line number only here;
290
                    # successful position lookups already have all they need.
291
                    try:
292
                        lineno = (
293
                            frame_or_tb.tb_lineno
294
                            if isinstance(frame_or_tb, types.TracebackType)
295
                            else frame.f_lineno
296
                        )
297
                        stmts = source.statements_at_line(lineno)
298
                    except Exception:
299
                        if TESTING:
300
                            raise
301

8 ✔
302
            executing_cache[key] = args = source, node, stmts, decorator
303

8 ✔
304
        return Executing(frame, *args)
305

306
    @classmethod
307
    def _class_local(cls, name: str, default: T) -> T:
308
        """
309
        Returns an attribute directly associated with this class
8 ✔
310
        (as opposed to subclasses), setting default if necessary
311
        """
8 ✔
312
        # classes have a mappingproxy preventing us from using setdefault
8 ✔
313
        try:
314
            return cls.__dict__[name]
8 ✔
315
        except KeyError:
316
            setattr(cls, name, default)
8 ✔
317
            return default
318

319
    @cache
320
    def statements_at_line(self, lineno: int) -> Set[EnhancedAST]:
321
        """
322
        Returns the statement nodes overlapping the given line.
8 ✔
323

324
        Returns at most one statement unless semicolons are present.
8 ✔
325

8 ✔
326
        If the `text` attribute is not valid python, meaning
8 ✔
327
        `tree` is None, returns an empty set.
328

329
        Otherwise, `Source.for_frame(frame).statements_at_line(frame.f_lineno)`
330
        should return at least one statement.
331
        """
8 ✔
332

333
        return {statement_containing_node(node) for node in self._nodes_by_line[lineno]}
8 ✔
334

8 ✔
335
    def asttext(self) -> ASTText:
336
        """
8 ✔
337
        Returns an ASTText object for getting the source of specific AST nodes.
8 ✔
338

339
        See http://asttokens.readthedocs.io/en/latest/api-index.html
340
        """
341
        from asttokens import ASTText  # must be installed separately
8 ✔
342

8 ✔
343
        if self._asttext is None:
8 !
344
            self._asttext = ASTText(self.text, tree=self.tree, filename=self.filename)
8 ✔
345

8 ✔
346
        return self._asttext
347

×
348
    def asttokens(self) -> ASTTokens:
349
        """
8 ✔
350
        Returns an ASTTokens object for getting the source of specific AST nodes.
8 ✔
351

8 ✔
352
        See http://asttokens.readthedocs.io/en/latest/api-index.html
353
        """
8 ✔
354
        import asttokens  # must be installed separately
355

356
        if self._asttokens is None:
357
            if hasattr(asttokens, "ASTText"):
358
                self._asttokens = self.asttext().asttokens
359
            else:  # pragma: no cover
360
                self._asttokens = asttokens.ASTTokens(
361
                    self.text, tree=self.tree, filename=self.filename
362
                )
363
        return self._asttokens
364

365
    def _asttext_base(self) -> ASTTextBase:
366
        import asttokens  # must be installed separately
367

368
        if hasattr(asttokens, "ASTText"):
369
            return self.asttext()
370
        else:  # pragma: no cover
371
            return self.asttokens()
372

373
    @staticmethod
374
    def decode_source(source: Union[str, bytes]) -> str:
375
        if isinstance(source, bytes):
8 ✔
376
            encoding = Source.detect_encoding(source)
8 ✔
377
            return source.decode(encoding)
378
        else:
379
            return source
8 ✔
380

381
    @staticmethod
382
    def detect_encoding(source: bytes) -> str:
383
        return detect_encoding(io.BytesIO(source).readline)[0]
384

385
    def code_qualname(self, code: types.CodeType) -> str:
386
        """
387
        Imitates the __qualname__ attribute of functions for code objects.
388
        Given:
389

390
            - A function `func`
391
            - A frame `frame` for an execution of `func`, meaning:
392
                `frame.f_code is func.__code__`
8 ✔
393

394
        `Source.for_frame(frame).code_qualname(frame.f_code)`
395
        will be equal to `func.__qualname__`*. Works for Python 2 as well,
396
        where of course no `__qualname__` attribute exists.
397

398
        Falls back to `code.co_name` if there is no appropriate qualname.
399

400
        Based on https://github.com/wbolster/qualname
8 ✔
401

8 ✔
402
        (* unless `func` is a lambda
8 ✔
403
        nested inside another lambda on the same line, in which case
8 ✔
404
        the outer lambda's qualname will be returned for the codes
8 ✔
405
        of both lambdas)
406
        """
8 ✔
407
        assert_(code.co_filename == self.filename)
8 ✔
408
        return self._qualnames.get((code.co_name, code.co_firstlineno), code.co_name)
409

8 ✔
410

8 ✔
411
class Executing(object):
412
    """
8 ✔
413
    Information about the operation a frame is currently executing.
8 ✔
414

415
    Generally you will just want `node`, which is the AST node being executed,
416
    or None if it's unknown.
8 ✔
417

8 ✔
418
    If a decorator is currently being called, then:
8 ✔
419
        - `node` is a function or class definition
8 ✔
420
        - `decorator` is the expression in `node.decorator_list` being called
8 ✔
421
        - `statements == {node}`
422
    """
8 ✔
423

8 ✔
424
    def __init__(
8 ✔
425
        self,
8 ✔
426
        frame: types.FrameType,
8 ✔
427
        source: Source,
428
        node: EnhancedAST,
8 ✔
429
        stmts: Set[ast.stmt],
8 ✔
430
        decorator: Optional[EnhancedAST],
431
    ) -> None:
8 ✔
432
        self.frame = frame
8 ✔
433
        self.source = source
434
        self.node = node
435
        self.statements = stmts
8 ✔
436
        self.decorator = decorator
8 ✔
437

8 ✔
438
    def code_qualname(self) -> str:
8 ✔
439
        return self.source.code_qualname(self.frame.f_code)
8 ✔
440

441
    def text(self) -> str:
8 ✔
442
        return self.source._asttext_base().get_text(self.node)
8 ✔
443

8 ✔
444
    def text_range(self) -> Tuple[int, int]:
8 ✔
445
        return self.source._asttext_base().get_text_range(self.node)
8 ✔
446

447

448
class QualnameVisitor(ast.NodeVisitor):
449
    def __init__(self) -> None:
450
        super(QualnameVisitor, self).__init__()
8 ✔
451
        self.stack: List[str] = []
8 ✔
452
        self.qualnames: Dict[Tuple[str, int], str] = {}
8 ✔
453

8 ✔
454
    def add_qualname(self, node: ast.AST, name: Optional[str] = None) -> None:
8 ✔
455
        name = name or node.name  # type: ignore[attr-defined]
8 ✔
456
        self.stack.append(name)
8 ✔
457
        if getattr(node, "decorator_list", ()):
8 !
458
            lineno = node.decorator_list[0].lineno  # type: ignore[attr-defined]
8 ✔
459
        else:
460
            lineno = node.lineno  # type: ignore[attr-defined]
8 ✔
461
        self.qualnames.setdefault((name, lineno), ".".join(self.stack))
462

8 ✔
463
    def visit_FunctionDef(self, node: ast.AST, name: Optional[str] = None) -> None:
8 ✔
464
        assert isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)), (
8 ✔
465
            node
466
        )
8 ✔
467
        self.add_qualname(node, name)
468
        self.stack.append("<locals>")
8 ✔
469
        children: Sequence[ast.AST] = []
8 ✔
470
        if isinstance(node, ast.Lambda):
8 !
471
            children = [node.body]
×
472
        else:
8 ✔
473
            children = node.body
8 ✔
474
        for child in children:
8 ✔
475
            self.visit(child)
8 ✔
476
        self.stack.pop()
8 ✔
477
        self.stack.pop()
8 ✔
478

8 ✔
479
        # Find lambdas in the function definition outside the body,
8 !
480
        # e.g. decorators or default arguments
×
481
        # Based on iter_child_nodes
8 ✔
482
        for field, child in ast.iter_fields(node):
483
            if field == "body":
8 ✔
484
                continue
8 ✔
485
            if isinstance(child, ast.AST):
8 ✔
486
                self.visit(child)
8 ✔
487
            elif isinstance(child, list):
8 ✔
488
                for grandchild in child:
8 ✔
489
                    if isinstance(grandchild, ast.AST):
490
                        self.visit(grandchild)
8 ✔
491

8 ✔
492
    visit_AsyncFunctionDef = visit_FunctionDef
8 ✔
493

8 ✔
494
    def visit_Lambda(self, node: ast.AST) -> None:
8 ✔
495
        assert isinstance(node, ast.Lambda)
8 ✔
496
        self.visit_FunctionDef(node, "<lambda>")
497

498
    def visit_GeneratorExp(self, node: ast.GeneratorExp) -> None:
8 ✔
499
        # The outermost iterable is evaluated in the enclosing scope.
500
        self.visit(node.generators[0].iter)
501
        self.stack.append("<genexpr>")
502
        if sys.implementation.name == "pypy":
503
            self.stack.append("<locals>")
8 ✔
504
        self.visit(node.elt)
3 ✔
505
        for index, generator in enumerate(node.generators):
506
            self.visit(generator.target)
507
            if index:
508
                self.visit(generator.iter)
509
            for condition in generator.ifs:
510
                self.visit(condition)
511
        if sys.implementation.name == "pypy":
512
            self.stack.pop()
513
        self.stack.pop()
8 ✔
514

515
    def visit_ClassDef(self, node: ast.AST) -> None:
516
        assert isinstance(node, ast.ClassDef)
8 ✔
517
        self.add_qualname(node)
8 ✔
518
        outside_class: List[ast.AST] = list(node.decorator_list)
519
        outside_class.extend(node.bases)
520
        outside_class.extend(node.keywords)
521
        # Leave the class body and type parameters in their existing scope.
522
        for child in ast.iter_child_nodes(node):
523
            if child not in outside_class:
524
                self.visit(child)
525
        self.stack.pop()
8 ✔
526
        for child in outside_class:
8 ✔
527
            self.visit(child)
528

8 ✔
529

530
future_flags = sum(
531
    getattr(__future__, fname).compiler_flag for fname in __future__.all_feature_names
532
)
533

534

535
def compile_similar_to(source: ast.Module, matching_code: types.CodeType) -> Any:
536
    return compile(
3 ✔
537
        source,
3 ✔
538
        matching_code.co_filename,
3 ✔
539
        "exec",
3 ✔
540
        flags=future_flags & matching_code.co_flags,
3 ✔
541
        dont_inherit=True,
542
    )
3 ✔
543

3 ✔
544

545
sentinel = "io8urthglkjdghvljusketgIYRFYUVGHFRTBGVHKGF78678957647698"
3 ✔
546

547

3 ✔
548
def is_rewritten_by_pytest(code: types.CodeType) -> bool:
549
    return any(
3 ✔
550
        bc.opname != "LOAD_CONST"
3 ✔
551
        and isinstance(bc.argval, str)
3 ✔
552
        and bc.argval.startswith("@py")
3 ✔
553
        for bc in get_instructions(CodeKey(code))
554
    )
3 ✔
555

3 ✔
556

3 ✔
557
class SentinelNodeFinder(object):
3 ✔
558
    result: Optional[EnhancedAST] = None
3 ✔
559

3 ✔
560
    def __init__(
3 ✔
561
        self,
3 ✔
562
        frame: types.FrameType,
3 ✔
563
        stmts: Set[EnhancedAST],
564
        tree: ast.Module,
565
        lasti: int,
566
        source: Source,
567
    ) -> None:
568
        assert_(stmts)
569
        self.frame = frame
570
        self.tree = tree
571
        self.code = code = frame.f_code
572
        self.is_pytest = is_rewritten_by_pytest(code)
573

574
        if self.is_pytest:
575
            self.ignore_linenos = frozenset(assert_linenos(tree))
576
        else:
577
            self.ignore_linenos = frozenset()
3 ✔
578

3 ✔
579
        self.decorator = None
3 ✔
580

3 ✔
581
        self.instruction = instruction = self.get_actual_current_instruction(lasti)
582
        op_name = instruction.opname
583
        extra_filter: Callable[[Any], bool] = lambda e: True
584
        ctx: Type = type(None)
585

586
        typ: Type = type(None)
3 ✔
587
        if op_name.startswith("CALL_"):
3 ✔
588
            typ = ast.Call
3 ✔
589
        elif op_name.startswith(("BINARY_SUBSCR", "SLICE+")):
3 ✔
590
            typ = ast.Subscript
3 ✔
591
            ctx = ast.Load
3 ✔
592
        elif op_name.startswith("BINARY_"):
593
            typ = ast.BinOp
594
            op_type = dict(
595
                BINARY_POWER=ast.Pow,
596
                BINARY_MULTIPLY=ast.Mult,
597
                BINARY_MATRIX_MULTIPLY=getattr(ast, "MatMult", ()),
598
                BINARY_FLOOR_DIVIDE=ast.FloorDiv,
3 ✔
599
                BINARY_TRUE_DIVIDE=ast.Div,
3 ✔
600
                BINARY_MODULO=ast.Mod,
3 ✔
601
                BINARY_ADD=ast.Add,
3 ✔
602
                BINARY_SUBTRACT=ast.Sub,
3 ✔
603
                BINARY_LSHIFT=ast.LShift,
3 ✔
604
                BINARY_RSHIFT=ast.RShift,
3 ✔
605
                BINARY_AND=ast.BitAnd,
3 ✔
606
                BINARY_XOR=ast.BitXor,
3 ✔
607
                BINARY_OR=ast.BitOr,
3 ✔
608
            )[op_name]
3 ✔
609
            extra_filter = lambda e: isinstance(e.op, op_type)
3 ✔
610
        elif op_name.startswith("UNARY_"):
3 ✔
611
            typ = ast.UnaryOp
612
            op_type = dict(
3 ✔
613
                UNARY_POSITIVE=ast.UAdd,
614
                UNARY_NEGATIVE=ast.USub,
3 ✔
615
                UNARY_NOT=ast.Not,
3 ✔
616
                UNARY_INVERT=ast.Invert,
617
            )[op_name]
618
            extra_filter = lambda e: isinstance(e.op, op_type)
619
        elif op_name in ("LOAD_ATTR", "LOAD_METHOD", "LOOKUP_METHOD"):
620
            typ = ast.Attribute
621
            ctx = ast.Load
622
            extra_filter = lambda e: mangled_name(e) == instruction.argval
623
        elif op_name in (
624
            "LOAD_NAME",
625
            "LOAD_GLOBAL",
3 ✔
626
            "LOAD_FAST",
627
            "LOAD_DEREF",
628
            "LOAD_CLASSDEREF",
629
        ):
3 ✔
630
            typ = ast.Name
3 ✔
631
            ctx = ast.Load
632
            extra_filter = lambda e: mangled_name(e) == instruction.argval
3 ✔
633
        elif op_name in ("COMPARE_OP", "IS_OP", "CONTAINS_OP"):
3 ✔
634
            typ = ast.Compare
3 ✔
635
            extra_filter = lambda e: len(e.ops) == 1
636
        elif op_name.startswith(("STORE_SLICE", "STORE_SUBSCR")):
3 ✔
637
            ctx = ast.Store
638
            typ = ast.Subscript
8 ✔
639
        elif op_name.startswith("STORE_ATTR"):
3 ✔
640
            ctx = ast.Store
3 ✔
641
            typ = ast.Attribute
3 ✔
642
            extra_filter = lambda e: mangled_name(e) == instruction.argval
3 ✔
643
        else:
3 ✔
644
            raise RuntimeError(op_name)
645

646
        with lock:
647
            exprs = {
648
                cast(EnhancedAST, node)
3 ✔
649
                for stmt in stmts
650
                for node in ast.walk(stmt)
651
                if isinstance(node, typ)
652
                if isinstance(getattr(node, "ctx", None), ctx)
653
                if extra_filter(node)
3 ✔
654
                if statement_containing_node(node) == stmt
655
            }
656

657
            if ctx == ast.Store:
658
                # No special bytecode tricks here.
3 ✔
659
                # We can handle multiple assigned attributes with different names,
660
                # but only one assigned subscript.
661
                self.result = only(exprs)
662
                return
663

3 ✔
664
            matching = list(self.matching_nodes(exprs))
3 ✔
665
            if not matching and typ == ast.Call:
3 ✔
666
                self.find_decorator(stmts)
3 ✔
667
            else:
3 ✔
668
                self.result = only(matching)
669

8 ✔
670
    def find_decorator(self, stmts: Union[List[EnhancedAST], Set[EnhancedAST]]) -> None:
3 ✔
671
        stmt = only(stmts)
672
        assert_(isinstance(stmt, (ast.ClassDef, function_node_types)))
673
        decorators = stmt.decorator_list  # type: ignore[attr-defined]
674
        assert_(decorators)
675
        line_instructions = [
676
            inst
677
            for inst in self.clean_instructions(self.code)
8 ✔
678
            if inst.lineno == self.frame.f_lineno
3 ✔
679
        ]
680
        last_decorator_instruction_index = [
681
            i
682
            for i, inst in enumerate(line_instructions)
683
            if inst.opname == "CALL_FUNCTION"
684
        ][-1]
3 !
685
        assert_(
686
            line_instructions[last_decorator_instruction_index + 1].opname.startswith(
687
                "STORE_"
3 ✔
688
            )
689
        )
3 ✔
690
        decorator_instructions = line_instructions[
691
            last_decorator_instruction_index
8 ✔
692
            - len(decorators)
3 ✔
693
            + 1 : last_decorator_instruction_index + 1
3 ✔
694
        ]
695
        assert_({inst.opname for inst in decorator_instructions} == {"CALL_FUNCTION"})
696
        decorator_index = decorator_instructions.index(self.instruction)
697
        decorator = decorators[::-1][decorator_index]
698
        self.decorator = decorator
3 ✔
699
        self.result = stmt
3 ✔
700

3 ✔
701
    def clean_instructions(self, code: types.CodeType) -> List[EnhancedInstruction]:
702
        return [
3 ✔
703
            inst
704
            for inst in get_instructions(CodeKey(code))
705
            if inst.opname not in ("EXTENDED_ARG", "NOP")
706
            if inst.lineno not in self.ignore_linenos
707
        ]
3 ✔
708

3 ✔
709
    def get_original_clean_instructions(self) -> List[EnhancedInstruction]:
3 ✔
710
        result = self.clean_instructions(self.code)
3 ✔
711

712
        # pypy sometimes (when is not clear)
3 ✔
713
        # inserts JUMP_IF_NOT_DEBUG instructions in bytecode
714
        # If they're not present in our compiled instructions,
3 ✔
715
        # ignore them in the original bytecode
1 ✔
716
        if any(inst.opname == "JUMP_IF_NOT_DEBUG" for inst in result) and not any(
1 ✔
717
            inst.opname == "JUMP_IF_NOT_DEBUG" for inst in self.compile_instructions()
×
718
        ):
719
            result = [inst for inst in result if inst.opname != "JUMP_IF_NOT_DEBUG"]
×
720

×
721
        return result
×
722

723
    def matching_nodes(self, exprs: Set[EnhancedAST]) -> Iterator[EnhancedAST]:
3 ✔
724
        original_instructions = self.get_original_clean_instructions()
725
        original_index = only(
726
            i
727
            for i, inst in enumerate(original_instructions)
728
            if inst == self.instruction
729
        )
730
        for expr_index, expr in enumerate(exprs):
731
            setter = get_setter(expr)
732
            assert setter is not None
3 ✔
733
            # noinspection PyArgumentList
734
            replacement = ast.BinOp(
735
                left=cast(ast.expr, expr),
3 ✔
736
                op=ast.Pow(),
737
                right=ast.Constant(sentinel),
3 ✔
738
            )
3 ✔
739
            ast.fix_missing_locations(replacement)
740
            setter(replacement)
741
            try:
3 ✔
742
                instructions = self.compile_instructions()
3 ✔
743
            finally:
3 ✔
744
                setter(expr)
745

3 ✔
746
            if sys.version_info >= (3, 10):
3 ✔
747
                try:
748
                    handle_jumps(instructions, original_instructions)
3 ✔
749
                except Exception:
3 ✔
750
                    # Give other candidates a chance
751
                    if TESTING or expr_index < len(exprs) - 1:
752
                        continue
753
                    raise
3 ✔
754

755
            indices = [
756
                i
757
                for i, instruction in enumerate(instructions)
758
                if instruction.argval == sentinel
759
            ]
760

761
            # There can be several indices when the bytecode is duplicated,
762
            # as happens in a finally block in 3.9+
763
            # First we remove the opcodes caused by our modifications
2 ✔
764
            for index_num, sentinel_index in enumerate(indices):
765
                # Adjustment for removing sentinel instructions below
766
                # in past iterations
767
                sentinel_index -= index_num * 2
3 ✔
768

2 ✔
769
                assert_(instructions.pop(sentinel_index).opname == "LOAD_CONST")
770
                assert_(instructions.pop(sentinel_index).opname == "BINARY_POWER")
771

2 ✔
772
            # Then we see if any of the instruction indices match
773
            for index_num, sentinel_index in enumerate(indices):
3 ✔
774
                sentinel_index -= index_num * 2
775
                new_index = sentinel_index - 1
8 ✔
776

3 ✔
777
                if new_index != original_index:
3 ✔
778
                    continue
3 ✔
779

780
                original_inst = original_instructions[original_index]
8 ✔
781
                new_inst = instructions[new_index]
3 ✔
782

783
                # In Python 3.9+, changing 'not x in y' to 'not sentinel_transformation(x in y)'
784
                # changes a CONTAINS_OP(invert=1) to CONTAINS_OP(invert=0),<sentinel stuff>,UNARY_NOT
785
                if (
786
                    original_inst.opname == new_inst.opname in ("CONTAINS_OP", "IS_OP")
787
                    and original_inst.arg != new_inst.arg  # type: ignore[attr-defined]
3 ✔
788
                    and (
3 ✔
789
                        original_instructions[original_index + 1].opname
790
                        != instructions[new_index + 1].opname
791
                        == "UNARY_NOT"
792
                    )
793
                ):
3 ✔
794
                    # Remove the difference for the upcoming assert
3 ✔
795
                    instructions.pop(new_index + 1)
796

3 ✔
797
                # Check that the modified instructions don't have anything unexpected
3 ✔
798
                # 3.10 is a bit too weird to assert this in all cases but things still work
3 ✔
799
                if sys.version_info < (3, 10):
800
                    for inst1, inst2 in zip_longest(
3 ✔
801
                        original_instructions, instructions
3 ✔
802
                    ):
3 ✔
803
                        assert_(inst1 and inst2 and opnames_match(inst1, inst2))
3 ✔
804

805
                yield expr
3 ✔
806

3 ✔
807
    def compile_instructions(self) -> List[EnhancedInstruction]:
3 ✔
808
        module_code = compile_similar_to(self.tree, self.code)
809
        code = only(self.find_codes(module_code))
3 ✔
810
        return self.clean_instructions(code)
3 ✔
811

812
    def find_codes(self, root_code: types.CodeType) -> list:
8 ✔
813
        checks: List[Callable] = [
814
            attrgetter("co_firstlineno"),
815
            attrgetter("co_freevars"),
816
            attrgetter("co_cellvars"),
817
            lambda c: is_ipython_cell_code_name(c.co_name) or c.co_name,
818
        ]
819
        if not self.is_pytest:
820
            checks += [
3 ✔
821
                attrgetter("co_names"),
3 ✔
822
                attrgetter("co_varnames"),
823
            ]
824

3 ✔
825
        def matches(c: types.CodeType) -> bool:
3 ✔
826
            return all(f(c) == f(self.code) for f in checks)
3 ✔
827

2 ✔
828
        code_options = []
829
        if matches(root_code):
830
            code_options.append(root_code)
8 ✔
831

832
        def finder(code: types.CodeType) -> None:
833
            for const in code.co_consts:
834
                if not inspect.iscode(const):
835
                    continue
836

837
                if matches(const):
1 ✔
838
                    code_options.append(const)
1 !
839
                finder(const)
1 ✔
840

1 ✔
841
        finder(root_code)
1 ✔
842
        return code_options
1 ✔
843

1 ✔
844
    def get_actual_current_instruction(self, lasti: int) -> EnhancedInstruction:
1 ✔
845
        """
1 ✔
846
        Get the instruction corresponding to the current
1 ✔
847
        frame offset, skipping EXTENDED_ARG instructions
1 ✔
848
        """
849
        # Don't use get_original_clean_instructions
850
        # because we need the actual instructions including
8 ✔
851
        # EXTENDED_ARG
852
        instructions = get_instructions(CodeKey(self.code))
853
        index = only(i for i, inst in enumerate(instructions) if inst.offset == lasti)
854

855
        while True:
856
            instruction = instructions[index]
857
            if instruction.opname != "EXTENDED_ARG":
858
                return instruction
859
            index += 1
860

1 ✔
861

1 ✔
862
def non_sentinel_instructions(
1 ✔
863
    instructions: List[EnhancedInstruction], start: int
864
) -> Iterator[Tuple[int, EnhancedInstruction]]:
1 ✔
865
    """
1 ✔
866
    Yields (index, instruction) pairs excluding the basic
1 ✔
867
    instructions introduced by the sentinel transformation
1 ✔
868
    """
1 ✔
869
    skip_power = False
1 ✔
870
    for i, inst in islice(enumerate(instructions), start, None):
871
        if inst.argval == sentinel:
872
            assert_(inst.opname == "LOAD_CONST")
873
            skip_power = True
1 ✔
874
            continue
1 ✔
875
        elif skip_power:
876
            assert_(inst.opname == "BINARY_POWER")
877
            skip_power = False
878
            continue
1 ✔
879
        yield i, inst
880

881

8 ✔
882
def walk_both_instructions(
883
    original_instructions: List[EnhancedInstruction],
884
    original_start: int,
885
    instructions: List[EnhancedInstruction],
886
    start: int,
887
) -> Iterator[Tuple[int, EnhancedInstruction, int, EnhancedInstruction]]:
888
    """
889
    Yields matching indices and instructions from the new and original instructions,
890
    leaving out changes made by the sentinel transformation.
891
    """
892
    original_iter = islice(enumerate(original_instructions), original_start, None)
893
    new_iter = non_sentinel_instructions(instructions, start)
894
    inverted_comparison = False
895
    while True:
1 ✔
896
        try:
897
            original_i, original_inst = next(original_iter)
898
            new_i, new_inst = next(new_iter)
1 ✔
899
        except StopIteration:
1 ✔
900
            return
901
        if (
1 !
902
            inverted_comparison
903
            and original_inst.opname != new_inst.opname == "UNARY_NOT"
904
        ):
1 ✔
905
            new_i, new_inst = next(new_iter)
906
        inverted_comparison = (
907
            original_inst.opname == new_inst.opname in ("CONTAINS_OP", "IS_OP")
908
            and original_inst.arg != new_inst.arg  # type: ignore[attr-defined]
909
        )
910
        yield original_i, original_inst, new_i, new_inst
911

912

913
def handle_jumps(
1 ✔
914
    instructions: List[EnhancedInstruction],
915
    original_instructions: List[EnhancedInstruction],
916
) -> None:
1 ✔
917
    """
1 ✔
918
    Transforms instructions in place until it looks more like original_instructions.
919
    This is only needed in 3.10+ where optimisations lead to more drastic changes
920
    after the sentinel transformation.
×
921
    Replaces JUMP instructions that aren't also present in original_instructions
×
922
    with the sections that they jump to until a raise or return.
×
923
    In some other cases duplication found in `original_instructions`
×
924
    is replicated in `instructions`.
×
925
    """
926
    while True:
927
        for original_i, original_inst, new_i, new_inst in walk_both_instructions(
×
928
            original_instructions, 0, instructions, 0
929
        ):
×
930
            if opnames_match(original_inst, new_inst):
931
                continue
932

933
            if "JUMP" in new_inst.opname and "JUMP" not in original_inst.opname:
934
                # Find where the new instruction is jumping to, ignoring
935
                # instructions which have been copied in previous iterations
1 ✔
936
                start = only(
937
                    i
938
                    for i, inst in enumerate(instructions)
1 ✔
939
                    if inst.offset == new_inst.argval
940
                    and not getattr(inst, "_copied", False)
941
                )
8 ✔
942
                # Replace the jump instruction with the jumped to section of instructions
943
                # That section may also be deleted if it's not similarly duplicated
944
                # in original_instructions
945
                new_instructions = handle_jump(
946
                    original_instructions, original_i, instructions, start
947
                )
948
                assert new_instructions is not None
949
                instructions[new_i : new_i + 1] = new_instructions
×
950
            else:
×
951
                # Extract a section of original_instructions from original_i to return/raise
952
                orig_section = []
953
                for section_inst in original_instructions[original_i:]:
954
                    orig_section.append(section_inst)
955
                    if section_inst.opname in ("RETURN_VALUE", "RAISE_VARARGS"):
956
                        break
×
957
                else:
×
958
                    # No return/raise - this is just a mismatch we can't handle
×
959
                    raise AssertionError
×
960

961
                instructions[new_i:new_i] = only(
962
                    find_new_matching(orig_section, instructions)
8 ✔
963
                )
964

965
            # instructions has been modified, the for loop can't sensibly continue
966
            # Restart it from the beginning, checking for other issues
967
            break
968

969
        else:  # No mismatched jumps found, we're done
970
            return
971

972

973
def find_new_matching(
974
    orig_section: List[EnhancedInstruction], instructions: List[EnhancedInstruction]
975
) -> Iterator[List[EnhancedInstruction]]:
1 !
976
    """
977
    Yields sections of `instructions` which match `orig_section`.
978
    The yielded sections include sentinel instructions, but these
1 ✔
979
    are ignored when checking for matches.
1 ✔
980
    """
1 ✔
981
    for start in range(len(instructions) - len(orig_section)):
1 ✔
982
        indices, dup_section = zip(
1 ✔
983
            *islice(
1 ✔
984
                non_sentinel_instructions(instructions, start),
1 ✔
985
                len(orig_section),
986
            )
987
        )
1 ✔
988
        if len(dup_section) < len(orig_section):
1 ✔
989
            return
990
        if sections_match(orig_section, dup_section):
×
991
            yield instructions[start : indices[-1] + 1]
992

993

8 ✔
994
def handle_jump(
995
    original_instructions: List[EnhancedInstruction],
996
    original_start: int,
997
    instructions: List[EnhancedInstruction],
998
    start: int,
999
) -> Optional[List[EnhancedInstruction]]:
1000
    """
1001
    Returns the section of instructions starting at `start` and ending
1002
    with a RETURN_VALUE or RAISE_VARARGS instruction.
1 !
1003
    There should be a matching section in original_instructions starting at original_start.
1 ✔
1004
    If that section doesn't appear elsewhere in original_instructions,
1 ✔
1005
    then also delete the returned section of instructions.
1 ✔
1006
    """
1 ✔
1007
    for original_j, original_inst, new_j, new_inst in walk_both_instructions(
1 ✔
1008
        original_instructions, original_start, instructions, start
1 ✔
1009
    ):
1 ✔
1010
        assert_(opnames_match(original_inst, new_inst))
1011
        if original_inst.opname in ("RETURN_VALUE", "RAISE_VARARGS"):
×
1012
            inlined = deepcopy(instructions[start : new_j + 1])
1013
            for inl in inlined:
1014
                inl._copied = True
8 ✔
1015
            orig_section = original_instructions[original_start : original_j + 1]
1016
            if not check_duplicates(
1017
                original_start, orig_section, original_instructions
1018
            ):
1019
                instructions[start : new_j + 1] = []
1020
            return inlined
1 ✔
1021

1022
    return None
1023

1024

1025
def check_duplicates(
1026
    original_i: int,
1027
    orig_section: List[EnhancedInstruction],
1028
    original_instructions: List[EnhancedInstruction],
1029
) -> bool:
1030
    """
1031
    Returns True if a section of original_instructions starting somewhere other
8 ✔
1032
    than original_i and matching orig_section is found, i.e. orig_section is duplicated.
3 ✔
1033
    """
1034
    for dup_start in range(len(original_instructions)):
1035
        if dup_start == original_i:
1036
            continue
1037
        dup_section = original_instructions[dup_start : dup_start + len(orig_section)]
1038
        if len(dup_section) < len(orig_section):
1039
            return False
1040
        if sections_match(orig_section, dup_section):
1041
            return True
1042

1043
    return False
1044

1045

8 ✔
1046
def sections_match(
3 ✔
1047
    orig_section: List[EnhancedInstruction], dup_section: List[EnhancedInstruction]
3 !
1048
) -> bool:
3 ✔
1049
    """
1050
    Returns True if the given lists of instructions have matching linenos and opnames.
3 ✔
1051
    """
3 ✔
1052
    return all(
1053
        (
3 ✔
1054
            orig_inst.lineno == dup_inst.lineno
3 ✔
1055
            # POP_BLOCKs have been found to have differing linenos in innocent cases
3 ✔
1056
            or "POP_BLOCK" == orig_inst.opname == dup_inst.opname
3 ✔
1057
        )
1058
        and opnames_match(orig_inst, dup_inst)
3 ✔
1059
        for orig_inst, dup_inst in zip(orig_section, dup_section)
3 ✔
1060
    )
1061

3 ✔
1062

×
1063
def opnames_match(inst1: Instruction, inst2: Instruction) -> bool:
1064
    return (
1065
        inst1.opname == inst2.opname
8 ✔
1066
        or "JUMP" in inst1.opname
1067
        and "JUMP" in inst2.opname
1068
        or (inst1.opname == "PRINT_EXPR" and inst2.opname == "POP_TOP")
8 ✔
1069
        or (
8 ✔
1070
            inst1.opname in ("LOAD_METHOD", "LOOKUP_METHOD")
8 ✔
1071
            and inst2.opname == "LOAD_ATTR"
8 ✔
1072
        )
8 ✔
1073
        or (inst1.opname == "CALL_METHOD" and inst2.opname == "CALL_FUNCTION")
1074
    )
1075

8 ✔
1076

3 ✔
1077
def get_setter(node: EnhancedAST) -> Optional[Callable[[ast.AST], None]]:
3 ✔
1078
    parent = node.parent
1079
    for name, field in ast.iter_fields(parent):
1080
        if field is node:
3 ✔
1081

3 ✔
1082
            def setter(new_node: ast.AST) -> None:
1083
                return setattr(parent, name, new_node)
1084

8 ✔
1085
            return setter
1086
        elif isinstance(field, list):
1087
            for i, item in enumerate(field):
1088
                if item is node:
8 !
1089

×
1090
                    def setter(new_node: ast.AST) -> None:
1091
                        field[i] = new_node
1092

1093
                    return setter
8 ✔
1094
    return None
8 ✔
1095

8 ✔
1096

8 ✔
1097
lock = RLock()
1098

1099

8 ✔
1100
@cache
8 ✔
1101
def statement_containing_node(node: ast.AST) -> EnhancedAST:
1102
    while not isinstance(node, ast.stmt):
1103
        node = cast(EnhancedAST, node).parent
8 ✔
1104
    return cast(EnhancedAST, node)
8 ✔
1105

1106

1107
def assert_linenos(tree: ast.AST) -> Iterator[int]:
8 ✔
1108
    for node in ast.walk(tree):
8 ✔
1109
        if hasattr(node, "parent") and isinstance(
1110
            statement_containing_node(node), ast.Assert
1111
        ):
1112
            for lineno in node_linenos(node):
1113
                yield lineno
8 ✔
1114

1115

1116
def _extract_ipython_statement(stmt: EnhancedAST) -> ast.Module:
8 ✔
1117
    # IPython separates each statement in a cell to be executed separately
8 ✔
1118
    # So NodeFinder should only compile one statement at a time or it
8 ✔
1119
    # will find a code mismatch.
8 ✔
1120
    while not isinstance(stmt.parent, ast.Module):
8 ✔
1121
        stmt = stmt.parent
8 ✔
1122
    # use `ast.parse` instead of `ast.Module` for better portability
1123
    # python3.8 changes the signature of `ast.Module`
1124
    # Inspired by https://github.com/pallets/werkzeug/pull/1552/files
8 ✔
1125
    tree = ast.parse("")
1126
    tree.body = [cast(ast.stmt, stmt)]
8 ✔
1127
    ast.copy_location(tree, stmt)
8 ✔
1128
    return tree
×
1129

×
1130

8 ✔
1131
def is_ipython_cell_code_name(code_name: str) -> bool:
1132
    return bool(re.match(r"(<module>|<cell line: \d+>)$", code_name))
1133

8 ✔
1134

8 ✔
1135
def is_ipython_cell_filename(filename: str) -> bool:
8 ✔
1136
    return bool(re.search(r"<ipython-input-|[/\\]ipykernel_\d+[/\\]", filename))
8 ✔
1137

8 ✔
1138

8 ✔
1139
def is_ipython_cell_code(code_obj: types.CodeType) -> bool:
1140
    return is_ipython_cell_filename(code_obj.co_filename) and is_ipython_cell_code_name(
8 ✔
1141
        code_obj.co_name
8 ✔
1142
    )
8 ✔
1143

1144

1145
def find_node_ipython(
8 ✔
1146
    frame: types.FrameType, lasti: int, stmts: Set[EnhancedAST], source: Source
5 ✔
1147
) -> Tuple[Optional[Any], Optional[Any]]:
1148
    node = decorator = None
3 ✔
1149
    for stmt in stmts:
1150
        tree = _extract_ipython_statement(stmt)
1151
        try:
1152
            node_finder = NodeFinder(frame, stmts, tree, lasti, source)
1153
            if (node or decorator) and (node_finder.result or node_finder.decorator):
1154
                # Found potential nodes in separate statements,
1155
                # cannot resolve ambiguity, give up here
1156
                return None, None
1157

1158
            node = node_finder.result
1159
            decorator = node_finder.decorator
1160
        except Exception:
1161
            pass
1162
    return decorator, node
1163

1164

1165
def node_linenos(node: ast.AST) -> Iterator[int]:
1166
    if hasattr(node, "lineno"):
1167
        linenos: Sequence[int] = []
1168
        if hasattr(node, "end_lineno") and isinstance(node, ast.expr):
1169
            assert node.end_lineno is not None  # type: ignore[attr-defined]
1170
            linenos = range(node.lineno, node.end_lineno + 1)  # type: ignore[attr-defined]
1171
        else:
1172
            linenos = [node.lineno]  # type: ignore[attr-defined]
1173
        for lineno in linenos:
1174
            yield lineno
1175

1176

1177
if sys.version_info >= (3, 11):
1178
    from ._position_node_finder import PositionNodeFinder as NodeFinder
1179
else:
1180
    NodeFinder = SentinelNodeFinder
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc