Skip to content

Commit

Permalink
[undefined vars] do not double report errors in class defs (#14350)
Browse files Browse the repository at this point in the history
These errors are already reported by the (new) semantic analyzer. 

I've discovered this while updating unit tests for new semanal in
#14166.

Tests are included.
  • Loading branch information
ilinum authored Dec 28, 2022
1 parent 109c8ce commit 20e9733
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 16 deletions.
49 changes: 33 additions & 16 deletions mypy/partially_defined.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from __future__ import annotations

from enum import Enum

from mypy import checker, errorcodes
from mypy.messages import MessageBuilder
from mypy.nodes import (
Expand Down Expand Up @@ -164,13 +166,21 @@ def done(self) -> BranchState:
)


class ScopeType(Enum):
Global = 1
Class = 2
Func = 3
Generator = 3


class Scope:
def __init__(self, stmts: list[BranchStatement]) -> None:
def __init__(self, stmts: list[BranchStatement], scope_type: ScopeType) -> None:
self.branch_stmts: list[BranchStatement] = stmts
self.scope_type = scope_type
self.undefined_refs: dict[str, set[NameExpr]] = {}

def copy(self) -> Scope:
result = Scope([s.copy() for s in self.branch_stmts])
result = Scope([s.copy() for s in self.branch_stmts], self.scope_type)
result.undefined_refs = self.undefined_refs.copy()
return result

Expand All @@ -188,7 +198,7 @@ class DefinedVariableTracker:

def __init__(self) -> None:
# There's always at least one scope. Within each scope, there's at least one "global" BranchingStatement.
self.scopes: list[Scope] = [Scope([BranchStatement(BranchState())])]
self.scopes: list[Scope] = [Scope([BranchStatement(BranchState())], ScopeType.Global)]
# disable_branch_skip is used to disable skipping a branch due to a return/raise/etc. This is useful
# in things like try/except/finally statements.
self.disable_branch_skip = False
Expand All @@ -203,13 +213,18 @@ def _scope(self) -> Scope:
assert len(self.scopes) > 0
return self.scopes[-1]

def enter_scope(self) -> None:
def enter_scope(self, scope_type: ScopeType) -> None:
assert len(self._scope().branch_stmts) > 0
self.scopes.append(Scope([BranchStatement(self._scope().branch_stmts[-1].branches[-1])]))
self.scopes.append(
Scope([BranchStatement(self._scope().branch_stmts[-1].branches[-1])], scope_type)
)

def exit_scope(self) -> None:
self.scopes.pop()

def in_scope(self, scope_type: ScopeType) -> bool:
return self._scope().scope_type == scope_type

def start_branch_statement(self) -> None:
assert len(self._scope().branch_stmts) > 0
self._scope().branch_stmts.append(
Expand Down Expand Up @@ -320,12 +335,14 @@ def variable_may_be_undefined(self, name: str, context: Context) -> None:

def process_definition(self, name: str) -> None:
# Was this name previously used? If yes, it's a used-before-definition error.
refs = self.tracker.pop_undefined_ref(name)
for ref in refs:
if self.loops:
self.variable_may_be_undefined(name, ref)
else:
self.var_used_before_def(name, ref)
if not self.tracker.in_scope(ScopeType.Class):
# Errors in class scopes are caught by the semantic analyzer.
refs = self.tracker.pop_undefined_ref(name)
for ref in refs:
if self.loops:
self.variable_may_be_undefined(name, ref)
else:
self.var_used_before_def(name, ref)
self.tracker.record_definition(name)

def visit_global_decl(self, o: GlobalDecl) -> None:
Expand Down Expand Up @@ -392,7 +409,7 @@ def visit_match_stmt(self, o: MatchStmt) -> None:

def visit_func_def(self, o: FuncDef) -> None:
self.process_definition(o.name)
self.tracker.enter_scope()
self.tracker.enter_scope(ScopeType.Func)
super().visit_func_def(o)
self.tracker.exit_scope()

Expand All @@ -405,14 +422,14 @@ def visit_func(self, o: FuncItem) -> None:
super().visit_func(o)

def visit_generator_expr(self, o: GeneratorExpr) -> None:
self.tracker.enter_scope()
self.tracker.enter_scope(ScopeType.Generator)
for idx in o.indices:
self.process_lvalue(idx)
super().visit_generator_expr(o)
self.tracker.exit_scope()

def visit_dictionary_comprehension(self, o: DictionaryComprehension) -> None:
self.tracker.enter_scope()
self.tracker.enter_scope(ScopeType.Generator)
for idx in o.indices:
self.process_lvalue(idx)
super().visit_dictionary_comprehension(o)
Expand Down Expand Up @@ -446,7 +463,7 @@ def visit_return_stmt(self, o: ReturnStmt) -> None:
self.tracker.skip_branch()

def visit_lambda_expr(self, o: LambdaExpr) -> None:
self.tracker.enter_scope()
self.tracker.enter_scope(ScopeType.Func)
super().visit_lambda_expr(o)
self.tracker.exit_scope()

Expand Down Expand Up @@ -613,7 +630,7 @@ def visit_with_stmt(self, o: WithStmt) -> None:

def visit_class_def(self, o: ClassDef) -> None:
self.process_definition(o.name)
self.tracker.enter_scope()
self.tracker.enter_scope(ScopeType.Class)
super().visit_class_def(o)
self.tracker.exit_scope()

Expand Down
27 changes: 27 additions & 0 deletions test-data/unit/check-possibly-undefined.test
Original file line number Diff line number Diff line change
Expand Up @@ -931,3 +931,30 @@ def f():
x = 0
z = y # E: Name "y" is used before definition
y: int = x # E: Name "x" may be undefined

[case testClassBody]
# flags: --enable-error-code possibly-undefined --enable-error-code used-before-def

class A:
# The following should not only trigger an error from semantic analyzer, but not the used-before-def check.
y = x + 1 # E: Name "x" is not defined
x = 0
# Same as above but in a loop, which should trigger a possibly-undefined error.
for _ in [1, 2, 3]:
b = a + 1 # E: Name "a" is not defined
a = 0


class B:
if int():
x = 0
else:
# This type of check is not caught by the semantic analyzer. If we ever update it to catch such issues,
# we should make sure that errors are not double-reported.
y = x # E: Name "x" is used before definition
for _ in [1, 2, 3]:
if int():
a = 0
else:
# Same as above but in a loop.
b = a # E: Name "a" may be undefined

0 comments on commit 20e9733

Please sign in to comment.