Skip to content

Commit 135a306

Browse files
committed
Track imports in stripped function bodies
When ignore_errors is set, mypy strips function bodies to speed up type checking. However, Import/ImportFrom nodes inside those bodies were never registered in tree.imports, so the imported modules were never tracked as dependencies and never type-checked. The native parser deserializes tree.imports directly from raw data in load_from_raw(), which replaces the MypyFile object entirely. Any imports collected before deserialization are therefore lost. The fix restores stripped-body imports after load_from_raw() in both the threaded (BuildManager.parse_all) and non-threaded (State.parse_file) build paths, using Python's ast module to scan the source for imports inside function bodies. A matching fix was already applied to the Python (fastparse) parser path via _collect_imports_from_stmts(). Adds regression tests for both parser configurations, verifying that a module imported inside a stripped function body is still type-checked. Fixes #22280
1 parent b286c11 commit 135a306

4 files changed

Lines changed: 154 additions & 2 deletions

File tree

‎mypy/build.py‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,7 @@
164164
from mypy.modules_state import modules_state
165165
from mypy.nodes import Expression
166166
from mypy.options import Options
167-
from mypy.parse import load_from_raw, parse
167+
from mypy.parse import _restore_stripped_body_imports, load_from_raw, parse
168168
from mypy.plugin import ChainedPlugin, Plugin, ReportConfigContext
169169
from mypy.plugins.default import DefaultPlugin
170170
from mypy.renaming import LimitedVariableRenameVisitor, VariableRenameVisitor
@@ -1071,6 +1071,13 @@ def parse_all(self, states: list[State], post_parse: bool = True) -> None:
10711071
state.options,
10721072
imports_only=bool(self.workers),
10731073
)
1074+
# When function bodies are stripped (ignore_errors mode), imports inside
1075+
# those bodies are not serialized into tree.imports by the native parser.
1076+
# Re-extract them from source so dependency tracking still works.
1077+
ignore_errors = state.ignore_all or state.options.ignore_errors
1078+
strip_function_bodies = ignore_errors and not state.options.preserve_asts
1079+
if strip_function_bodies:
1080+
_restore_stripped_body_imports(state.xpath, state.source, state.tree.imports)
10741081
if self.errors.is_blockers():
10751082
self.log("Bailing due to parse errors")
10761083
self.errors.raise_error()
@@ -3313,6 +3320,13 @@ def parse_file(self, *, temporary: bool = False, raw_data: FileRawData | None =
33133320
self.options,
33143321
imports_only=bool(self.manager.workers),
33153322
)
3323+
# When function bodies are stripped (ignore_errors mode), imports inside
3324+
# those bodies are not serialized into tree.imports by the native parser.
3325+
# Re-extract them from source so dependency tracking still works.
3326+
ignore_errors = self.ignore_all or self.options.ignore_errors
3327+
strip_function_bodies = ignore_errors and not self.options.preserve_asts
3328+
if strip_function_bodies:
3329+
_restore_stripped_body_imports(self.xpath, source, self.tree.imports)
33163330
if manager.errors.is_blockers():
33173331
manager.log("Bailing due to parse errors")
33183332
manager.errors.raise_error()

‎mypy/fastparse.py‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -492,6 +492,7 @@ def translate_stmt_list(
492492
and stack[0] == "F"
493493
and not is_coroutine
494494
):
495+
self._collect_imports_from_stmts(stmts)
495496
return []
496497

497498
res: list[Statement] = []
@@ -528,6 +529,41 @@ def translate_stmt_list(
528529
return []
529530
return res
530531

532+
def _collect_imports_from_stmts(self, stmts: list[ast3.stmt]) -> None:
533+
"""Collect import statements from raw AST when stripping function bodies.
534+
535+
When ``strip_function_bodies`` is True, the fast path returns an empty
536+
body without visiting individual statements. This means ``Import`` /
537+
``ImportFrom`` nodes inside function bodies never get added to
538+
``self.imports``, and the imported modules are never tracked as
539+
dependencies. This method scans the raw AST statements for imports and
540+
registers them so dependency tracking still works for ignored modules.
541+
"""
542+
for stmt in stmts:
543+
if isinstance(stmt, ast3.Import):
544+
names: list[tuple[str, str | None]] = []
545+
for alias in stmt.names:
546+
name = self.translate_module_id(alias.name)
547+
asname = alias.asname
548+
if asname is None and name != alias.name:
549+
asname = alias.name
550+
names.append((name, asname))
551+
self.imports.append(Import(names))
552+
elif isinstance(stmt, ast3.ImportFrom):
553+
if len(stmt.names) == 1 and stmt.names[0].name == "*":
554+
mod = stmt.module if stmt.module is not None else ""
555+
self.imports.append(ImportAll(mod, stmt.level))
556+
else:
557+
self.imports.append(
558+
ImportFrom(
559+
self.translate_module_id(stmt.module)
560+
if stmt.module is not None
561+
else "",
562+
stmt.level,
563+
[(a.name, a.asname) for a in stmt.names],
564+
)
565+
)
566+
531567
def translate_type_comment(
532568
self, n: ast3.stmt | ast3.arg, type_comment: str | None
533569
) -> ProperType | None:

‎mypy/parse.py‎

Lines changed: 71 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,23 @@
11
from __future__ import annotations
22

3+
import ast
34
import re
45

56
from librt.internal import ReadBuffer
67

78
from mypy import errorcodes as codes
89
from mypy.cache import read_int
910
from mypy.errors import Errors
10-
from mypy.nodes import FileRawData, MypyFile, ParseError, StrExpr
11+
from mypy.nodes import (
12+
FileRawData,
13+
Import,
14+
ImportAll,
15+
ImportBase,
16+
ImportFrom,
17+
MypyFile,
18+
ParseError,
19+
StrExpr,
20+
)
1121
from mypy.options import Options
1222
from mypy.types import ProperType
1323

@@ -106,6 +116,66 @@ def load_from_raw(
106116
return tree
107117

108118

119+
def _restore_stripped_body_imports(
120+
fnam: str, source: str | bytes | None, imports: list[ImportBase]
121+
) -> None:
122+
"""Collect imports from inside function bodies when the native parser strips them.
123+
124+
When ``ignore_errors`` is set, the native parser skips function bodies to
125+
speed up type checking. This means ``Import`` / ``ImportFrom`` nodes inside
126+
function bodies never get serialized into ``tree.imports``, and the imported
127+
modules are never tracked as dependencies. This function scans the source
128+
with Python's ``ast`` module and adds any imports found inside function
129+
bodies to the imports list.
130+
"""
131+
if source is None:
132+
try:
133+
with open(fnam, encoding="utf-8") as f:
134+
source = f.read()
135+
except OSError:
136+
return
137+
try:
138+
src_tree = ast.parse(source)
139+
except SyntaxError:
140+
return
141+
142+
class ImportCollector(ast.NodeVisitor):
143+
def __init__(self) -> None:
144+
self.collected: list[ImportBase] = []
145+
self.in_function = 0
146+
147+
def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
148+
self.in_function += 1
149+
self.generic_visit(node)
150+
self.in_function -= 1
151+
152+
def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
153+
self.in_function += 1
154+
self.generic_visit(node)
155+
self.in_function -= 1
156+
157+
def visit_Import(self, node: ast.Import) -> None:
158+
if self.in_function > 0:
159+
names = [(alias.name, alias.asname) for alias in node.names]
160+
self.collected.append(Import(names))
161+
self.generic_visit(node)
162+
163+
def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
164+
if self.in_function > 0:
165+
if len(node.names) == 1 and node.names[0].name == "*":
166+
mod = node.module if node.module is not None else ""
167+
self.collected.append(ImportAll(mod, node.level))
168+
else:
169+
names = [(a.name, a.asname) for a in node.names]
170+
mod = node.module if node.module is not None else ""
171+
self.collected.append(ImportFrom(mod, node.level, names))
172+
self.generic_visit(node)
173+
174+
collector = ImportCollector()
175+
collector.visit(src_tree)
176+
imports.extend(collector.collected)
177+
178+
109179
def report_parse_error(error: ParseError, errors: Errors) -> None:
110180
message = error["message"]
111181
# Standardize error message by capitalizing the first word

‎test-data/unit/check-ignore.test‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -418,3 +418,35 @@ y # mypy: ignore[assignment] # type: ignore
418418
[out]
419419
main:1: error: Unrecognized error code "whatever"
420420
main:1: note: Error code "misc" not covered by "type: ignore[whatever]" comment
421+
422+
[case testIgnoreErrorsFollowsImportInsideStrippedFunctionBody]
423+
# flags: --config-file tmp/mypy.ini
424+
import a
425+
[file mypy.ini]
426+
\[mypy]
427+
\[mypy-a]
428+
ignore_errors = True
429+
[file a.py]
430+
class A:
431+
def f(self) -> None:
432+
import b
433+
[file b.py]
434+
x: int = "moo"
435+
[out]
436+
tmp/b.py:1: error: Incompatible types in assignment (expression has type "str", variable has type "int")
437+
438+
[case testIgnoreErrorsFollowsImportInsideStrippedFunctionBodyNativeParser]
439+
# flags: --no-native-parser --config-file tmp/mypy.ini
440+
import a
441+
[file mypy.ini]
442+
\[mypy]
443+
\[mypy-a]
444+
ignore_errors = True
445+
[file a.py]
446+
class A:
447+
def f(self) -> None:
448+
import b
449+
[file b.py]
450+
x: int = "moo"
451+
[out]
452+
tmp/b.py:1: error: Incompatible types in assignment (expression has type "str", variable has type "int")

0 commit comments

Comments
 (0)