Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
56 commits
Select commit Hold shift + click to select a range
8e49664
Support redefinition of local variables with a different type
JukkaL Sep 20, 2018
3b409fc
Add docstring
JukkaL Sep 20, 2018
71cb8ea
Allow redefinitions of form "x = f(x)"
JukkaL Sep 20, 2018
35f56ae
Fix special cases
JukkaL Sep 20, 2018
2524777
Add test cases
JukkaL Sep 20, 2018
ab70d0d
Fix redefinition with 'break' and 'continue'
JukkaL Sep 20, 2018
525d5f4
Fix issues
JukkaL Sep 20, 2018
2c614a2
Fix some edge cases
JukkaL Sep 20, 2018
bf2f869
Support top-level redefinition through renaming (WIP)
JukkaL Sep 28, 2018
9e2c6b8
Remove obsolete code
JukkaL Sep 28, 2018
2b885da
Cleanup
JukkaL Sep 28, 2018
712669c
Merge transform code into a single class
JukkaL Sep 28, 2018
e0b7df0
Code cleanup
JukkaL Sep 28, 2018
f153809
Fix issues
JukkaL Sep 28, 2018
856d401
Fix issues
JukkaL Sep 28, 2018
865f1dd
Work around type check error
JukkaL Sep 28, 2018
2deff14
Merge branch 'master' into redefine-var
JukkaL Oct 4, 2018
27a1e57
Fix merge issue
JukkaL Oct 4, 2018
f04e37a
Fix lint
JukkaL Oct 4, 2018
1f9f62e
Fix more tests
JukkaL Oct 4, 2018
9ba82a9
Rename semanal_redef -> renaming
JukkaL Oct 4, 2018
fbf052e
Only perform redefinition if variable has been read
JukkaL Oct 9, 2018
1116b47
A few fixes
JukkaL Oct 9, 2018
70a3085
Add hacky workaround for 'self'
JukkaL Oct 9, 2018
cfad560
Merge branch 'master' into redefine-var
JukkaL Oct 9, 2018
b57960b
Remove unused things
JukkaL Oct 10, 2018
580a774
Revert some unnecessary changes
JukkaL Oct 10, 2018
051e695
Merge commit '3bea26f89a66834f42caaa90cf8db44f99d39dcc' into redefine…
JukkaL Dec 9, 2018
77495fb
Merge branch 'master' into redefine-var
JukkaL Dec 9, 2018
dc03143
Fix test case
JukkaL Dec 9, 2018
4ceed87
Merge branch 'master' into redefine-var
JukkaL Dec 19, 2018
ac00e6d
Merge branch 'master' into redefine-var
JukkaL Dec 20, 2018
20fd0f9
Use `if int():` consistently
JukkaL Dec 20, 2018
3843cea
Fix some test cases
JukkaL Dec 20, 2018
5cfaf9c
Add flag for allowing redefinitions
JukkaL Dec 20, 2018
83ba85f
Use the flag
JukkaL Dec 20, 2018
43a0362
Fix tests
JukkaL Dec 20, 2018
59b3413
Fix test cases
JukkaL Dec 20, 2018
7e3eff9
Add test case for turning flag off explicitly
JukkaL Dec 20, 2018
afa1096
Rename flag to --[dis]allow-redefinition (no plural)
JukkaL Dec 20, 2018
916288c
Fix semantic analyzer tests
JukkaL Dec 21, 2018
459187e
Update test case
JukkaL Dec 21, 2018
e165e46
Merge branch 'master' into redefine-var
JukkaL Jan 15, 2019
0a119b3
Merge branch 'master' into redefine-var
JukkaL Jan 15, 2019
fadb322
Merge branch 'master' into redefine-var
JukkaL Jan 17, 2019
76ad071
Fix brokenness from merge
JukkaL Jan 17, 2019
979a17c
Respond to review
JukkaL Jan 18, 2019
ae0043f
Clarify code
JukkaL Jan 18, 2019
512c1ed
Test additional special case
JukkaL Jan 18, 2019
1f7e36d
Add test case
JukkaL Jan 18, 2019
72043ae
Fix with statements
JukkaL Jan 18, 2019
8c30c90
Remove unnecessary check
JukkaL Jan 18, 2019
e390f38
Add comment
JukkaL Jan 18, 2019
bc0ee19
Ensure renaming cannot happen across scopes in class
JukkaL Jan 18, 2019
54b86d8
Remove unnecessary call
JukkaL Jan 18, 2019
496d2dd
The final assignments takes precedence in class when renaming
JukkaL Jan 18, 2019
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
Prev Previous commit
Next Next commit
Fix special cases
  • Loading branch information
JukkaL committed Sep 28, 2018
commit 35f56ae983e744325b60026b9865818aba8eb6e5
12 changes: 12 additions & 0 deletions mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -373,9 +373,17 @@ def file_context(self, file_node: MypyFile, fnam: str, options: Options,
def visit_func_def(self, defn: FuncDef) -> None:
if not self.recurse_into_functions:
return

# Conservatively do not allow variable defined before a function to
# be redefined later, since function could refer to either definition.
self.var_def_analyzer.reject_redefinition_of_vars_in_scope()
self.var_def_analyzer.enter_scope()

with self.scope.function_scope(defn):
self._visit_func_def(defn)

self.var_def_analyzer.leave_scope()

def _visit_func_def(self, defn: FuncDef) -> None:
phase_info = self.postpone_nested_functions_stack[-1]
if phase_info != FUNCTION_SECOND_PHASE:
Expand Down Expand Up @@ -2666,7 +2674,9 @@ def visit_try_stmt(self, s: TryStmt) -> None:

def analyze_try_stmt(self, s: TryStmt, visitor: NodeVisitor[None],
add_global: bool = False) -> None:
self.var_def_analyzer.enter_with_or_try()
s.body.accept(visitor)
self.var_def_analyzer.leave_with_or_try()
for type, var, handler in zip(s.types, s.vars, s.handlers):
if type:
type.accept(visitor)
Expand Down Expand Up @@ -2723,7 +2733,9 @@ def visit_with_stmt(self, s: WithStmt) -> None:
elif isinstance(s.target_type, TupleType):
s.target_type = s.target_type.copy_modified(items=new_types)

self.var_def_analyzer.enter_with_or_try()
self.visit_block(s.body)
self.var_def_analyzer.leave_with_or_try()

def visit_del_stmt(self, s: DelStmt) -> None:
s.expr.accept(self)
Expand Down
31 changes: 21 additions & 10 deletions mypy/semanal_shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,12 +166,13 @@ class VarDefAnalyzer:

def __init__(self) -> None:
self.block_id = 0
self.disallow_redef_depth = 0
self.blocks = [] # type: List[int]
self.var_blocks = {} # type: Dict[str, int]
self.var_blocks = [{}] # type: List[Dict[str, int]]

def clear(self) -> None:
self.blocks = []
self.var_blocks = {}
self.var_blocks = [{}]

def enter_block(self) -> None:
self.block_id += 1
Expand All @@ -180,37 +181,47 @@ def enter_block(self) -> None:
def leave_block(self) -> None:
self.blocks.pop()

def enter_with_or_try(self) -> None:
self.disallow_redef_depth += 1

def leave_with_or_try(self) -> None:
self.disallow_redef_depth -= 1

def current_block(self) -> int:
return self.blocks[-1]

def enter_scope(self) -> None:
pass # TODO
self.var_blocks.append({})

def leave_scope(self) -> None:
pass # TODO
self.var_blocks.pop()

def reject_redefinition_of_vars_in_scope(self) -> None:
"""Make it impossible to redefine defined variables in the current scope.

This is used if we encounter a function definition or break/continue that
can make it ambiguous which definition is live.
"""
for key in self.var_blocks:
self.var_blocks[key] = -1
var_blocks = self.var_blocks[-1]
for key in var_blocks:
var_blocks[key] = -1

def process_assignment(self, name: str, can_be_redefined: bool) -> bool:
"""Record assignment to given name and return True if it defines a new name."""
if self.disallow_redef_depth > 0:
can_be_redefined = False
block = self.current_block()
if name not in self.var_blocks:
var_blocks = self.var_blocks[-1]
if name not in var_blocks:
# New definition
if can_be_redefined:
self.var_blocks[name] = block
var_blocks[name] = block
else:
# This doesn't support arbitrary redefinition.
# TODO: Make this less restricted.
self.var_blocks[name] = -1
var_blocks[name] = -1
return True
elif self.var_blocks[name] == block:
elif var_blocks[name] == block:
# Redefinition
return True
else:
Expand Down
112 changes: 104 additions & 8 deletions test-data/unit/check-redefine.test
Original file line number Diff line number Diff line change
@@ -1,23 +1,26 @@
-- Redefinition of variable with a different type
-- ----------------------------------------------
-- Test cases for the redefinition of variable with a different type.


-- Redefine local variable
-- -----------------------


[case testRedefineLocalWithDifferentType]
def f() -> None:
x = 0
reveal_type(x) # E: Revealed type is 'builtins.int'
reveal_type(x) # E: Revealed type is 'builtins.int'
x = ''
reveal_type(x) # E: Revealed type is 'builtins.str'
reveal_type(x) # E: Revealed type is 'builtins.str'

[case testCannotConditionallyRedefineLocalWithDifferentType]
def f() -> None:
y = 0
reveal_type(y) # E: Revealed type is 'builtins.int'
reveal_type(y) # E: Revealed type is 'builtins.int'
if int():
y = '' \
# E: Incompatible types in assignment (expression has type "str", variable has type "int")
reveal_type(y) # E: Revealed type is 'builtins.int'
reveal_type(y) # E: Revealed type is 'builtins.int'
reveal_type(y) # E: Revealed type is 'builtins.int'

[case testRedefineFunctionArg]
def f(x: int) -> None:
Expand All @@ -33,9 +36,9 @@ def f() -> None:
x: int
x = '' \
# E: Incompatible types in assignment (expression has type "str", variable has type "int")
reveal_type(x) # E: Revealed type is 'builtins.int'
reveal_type(x) # E: Revealed type is 'builtins.int'
def g() -> None:
x: int # This syntax prevents redefinition through assignment
x: int # This syntax prevents redefinition through assignment
x = 1
x = '' \
# E: Incompatible types in assignment (expression has type "str", variable has type "int")
Expand All @@ -53,3 +56,96 @@ def f(x: int) -> None:
reveal_type(y) # E: Revealed type is 'Union[builtins.int*, builtins.str]'

def g(x: T) -> Union[T, str]: pass

[case testRedefineLocalForLoopIndexVariable]
from typing import Iterable
def f(a: Iterable[int], b: Iterable[str]) -> None:
for x in a:
x = '' \
# E: Incompatible types in assignment (expression has type "str", variable has type "int")
reveal_type(x) # E: Revealed type is 'builtins.int*'
for x in b:
x = 1 \
# E: Incompatible types in assignment (expression has type "int", variable has type "str")
reveal_type(x) # E: Revealed type is 'builtins.str*'

def g(a: Iterable[int]) -> None:
for x in a: pass
x = ''

def h(a: Iterable[int]) -> None:
x = ''
for x in a: pass

[case testCannotRedefineLocalWithinTry]
def f() -> None:
try:
x = 0
g() # Might raise an exception
x = '' \
# E: Incompatible types in assignment (expression has type "str", variable has type "int")
except:
pass
reveal_type(x) # E: Revealed type is 'builtins.int'
y = 0
y = ''

def g(): pass

[case testCannotRedefineLocalWithinWith]
def f() -> None:
with g():
x = 0
g() # Might raise an exception
x = '' \
# E: Incompatible types in assignment (expression has type "str", variable has type "int")
reveal_type(x) # E: Revealed type is 'builtins.int'
y = 0
y = ''

def g(): pass

[case testCannotRedefineAcrossNestedFunction]
def f() -> None:
x = 0
def g() -> None:
x
g()
x = '' \
# E: Incompatible types in assignment (expression has type "str", variable has type "int")
g()
y = 0
y = ''

[case testCannotRedefineAcrossNestedDecoratedFunction]
def dec(f): return f

def f() -> None:
x = 0
@dec
def g() -> None:
x
g()
x = '' \
# E: Incompatible types in assignment (expression has type "str", variable has type "int")
g()
y = 0
y = ''

[case testCannotRedefineAcrossNestedOverloadedFunction]
from typing import overload

def f() -> None:
x = 0
@overload
def g() -> None: pass
@overload
def g(x: int) -> None: pass
def g(x=0):
pass
g()
x = '' \
# E: Incompatible types in assignment (expression has type "str", variable has type "int")
g()
y = 0
y = ''