Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix daemon crash on malformed NamedTuple #14119

Merged
merged 3 commits into from
Nov 18, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions mypy/semanal_namedtuple.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
NameExpr,
PassStmt,
RefExpr,
Statement,
StrExpr,
SymbolTable,
SymbolTableNode,
Expand Down Expand Up @@ -111,7 +112,7 @@ def analyze_namedtuple_classdef(
if result is None:
# This is a valid named tuple, but some types are incomplete.
return True, None
items, types, default_items = result
items, types, default_items, statements = result
if is_func_scope and "@" not in defn.name:
defn.name += "@" + str(defn.line)
existing_info = None
Expand All @@ -123,31 +124,35 @@ def analyze_namedtuple_classdef(
defn.analyzed = NamedTupleExpr(info, is_typed=True)
defn.analyzed.line = defn.line
defn.analyzed.column = defn.column
defn.defs.body = statements
# All done: this is a valid named tuple with all types known.
return True, info
# This can't be a valid named tuple.
return False, None

def check_namedtuple_classdef(
self, defn: ClassDef, is_stub_file: bool
) -> tuple[list[str], list[Type], dict[str, Expression]] | None:
) -> tuple[list[str], list[Type], dict[str, Expression], list[Statement]] | None:
"""Parse and validate fields in named tuple class definition.

Return a three tuple:
hauntsaninja marked this conversation as resolved.
Show resolved Hide resolved
* field names
* field types
* field default values
* valid statements
or None, if any of the types are not ready.
"""
if self.options.python_version < (3, 6) and not is_stub_file:
self.fail("NamedTuple class syntax is only supported in Python 3.6", defn)
return [], [], {}
return [], [], {}, []
if len(defn.base_type_exprs) > 1:
self.fail("NamedTuple should be a single base", defn)
items: list[str] = []
types: list[Type] = []
default_items: dict[str, Expression] = {}
statements: list[Statement] = []
for stmt in defn.defs.body:
statements.append(stmt)
if not isinstance(stmt, AssignmentStmt):
# Still allow pass or ... (for empty namedtuples).
if isinstance(stmt, PassStmt) or (
Expand All @@ -160,9 +165,11 @@ def check_namedtuple_classdef(
# And docstrings.
if isinstance(stmt, ExpressionStmt) and isinstance(stmt.expr, StrExpr):
continue
statements.pop()
self.fail(NAMEDTUP_CLASS_ERROR, stmt)
elif len(stmt.lvalues) > 1 or not isinstance(stmt.lvalues[0], NameExpr):
# An assignment, but an invalid one.
statements.pop()
self.fail(NAMEDTUP_CLASS_ERROR, stmt)
else:
# Append name and type in this case...
Expand Down Expand Up @@ -199,7 +206,7 @@ def check_namedtuple_classdef(
)
else:
default_items[name] = stmt.rvalue
return items, types, default_items
return items, types, default_items, statements

def check_namedtuple(
self, node: Expression, var_name: str | None, is_func_scope: bool
Expand Down
2 changes: 0 additions & 2 deletions test-data/unit/check-class-namedtuple.test
Original file line number Diff line number Diff line change
Expand Up @@ -393,8 +393,6 @@ class X(typing.NamedTuple):
[out]
main:6: error: Invalid statement in NamedTuple definition; expected "field_name: field_type [= default]"
main:7: error: Invalid statement in NamedTuple definition; expected "field_name: field_type [= default]"
main:7: error: Type cannot be declared in assignment to non-self attribute
main:7: error: "int" has no attribute "x"
main:9: error: Non-default NamedTuple fields cannot follow default fields

[builtins fixtures/list.pyi]
Expand Down
24 changes: 24 additions & 0 deletions test-data/unit/fine-grained.test
Original file line number Diff line number Diff line change
Expand Up @@ -10205,3 +10205,27 @@ C
[builtins fixtures/dict.pyi]
[out]
==

[case testNamedTupleNestedCrash]
import m
[file m.py]
from typing import NamedTuple

class NT(NamedTuple):
class C: ...
x: int
y: int

[file m.py.2]
from typing import NamedTuple

class NT(NamedTuple):
class C: ...
x: int
y: int
# change
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe also test a change in another module to test AST stripping and reprocessing of an invalid named tuple?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, it actually doesn't work. This btw also affects the recent TypedDict PR too, I am going to fix both.

[builtins fixtures/tuple.pyi]
[out]
m.py:4: error: Invalid statement in NamedTuple definition; expected "field_name: field_type [= default]"
==
m.py:4: error: Invalid statement in NamedTuple definition; expected "field_name: field_type [= default]"