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 crashes and fails in forward references #3952

Merged
merged 43 commits into from
Sep 27, 2017
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
43 commits
Select commit Hold shift + click to select a range
45e5931
Add basic tests, more details will be added when they will not crash
ilevkivskyi Aug 31, 2017
cb4caa5
Correct tests
ilevkivskyi Sep 1, 2017
1cdc980
Implement ForwardRef type, wrap UnboundType, pass SecondPass to third…
ilevkivskyi Sep 11, 2017
260ef02
Add ForwardRefRemover
ilevkivskyi Sep 11, 2017
a58a217
Add elimination patches
ilevkivskyi Sep 11, 2017
950a022
Fix replacement logic; fix newtype error formatting
ilevkivskyi Sep 11, 2017
411b24d
Fix third pass (need to go deeper)
ilevkivskyi Sep 11, 2017
b9b8528
Implement syntethic replacer
ilevkivskyi Sep 11, 2017
48d6de4
Need to go deeper (as usual)
ilevkivskyi Sep 11, 2017
ec45441
Fix postponed fallback join
ilevkivskyi Sep 11, 2017
ac32ed4
Simplify some code and add annotations
ilevkivskyi Sep 11, 2017
3fb3019
Simplify traversal logic; add loads of tests
ilevkivskyi Sep 12, 2017
f9b1320
Take care about one more special case; add few tests and dcostrings
ilevkivskyi Sep 12, 2017
cf014b8
Unify visitors
ilevkivskyi Sep 12, 2017
665236b
Add some more comments and docstrings
ilevkivskyi Sep 12, 2017
9a318aa
Add recursive type warnings
ilevkivskyi Sep 12, 2017
757fbd9
Fix lint
ilevkivskyi Sep 12, 2017
4502ce2
Also clean-up bases; add more tests and allow some previously skipped
ilevkivskyi Sep 13, 2017
3b39d40
One more TypedDict test
ilevkivskyi Sep 13, 2017
c8b28fe
Add another simple self-referrential NamedTuple test
ilevkivskyi Sep 13, 2017
9f92b0f
Fix type_override; add tests for recursive aliases; fix Callable TODO…
Sep 13, 2017
9779103
Merge branch 'master' into fix-synthetic-crashes
ilevkivskyi Sep 14, 2017
b914bdb
Merge remote-tracking branch 'upstream/master' into fix-synthetic-cra…
ilevkivskyi Sep 19, 2017
3568fdb
Skip the whole ForwardRef dance in unchecked functions
ilevkivskyi Sep 19, 2017
54d9331
Simplify test
ilevkivskyi Sep 19, 2017
b9ddacc
Fix self-check
ilevkivskyi Sep 19, 2017
5bfe9ca
Fix cross-file forward references (+test)
ilevkivskyi Sep 19, 2017
a2912e9
More tests
ilevkivskyi Sep 19, 2017
10c65b8
Merge branch 'master' into fix-synthetic-crashes
ilevkivskyi Sep 20, 2017
21dfbfe
Fix situation when recursive namedtuple appears directly in base clas…
ilevkivskyi Sep 20, 2017
f2ddbcd
Merge branch 'fix-synthetic-crashes' of https://github.com/ilevkivsky…
ilevkivskyi Sep 20, 2017
03597ee
Clean-up PR: Remove unnecesary imports, outdated comment, unnecessary…
ilevkivskyi Sep 20, 2017
649ef32
Add tests for generic classes, enums, with statements and for statements
ilevkivskyi Sep 20, 2017
83f8907
Add processing for for and with statements (+more tests)
ilevkivskyi Sep 20, 2017
13c7176
Add support for generic types with forward references
ilevkivskyi Sep 20, 2017
79b10d6
Prohibit forward refs to type vars and subscripted forward refs to al…
ilevkivskyi Sep 21, 2017
321a809
Refactor code to avoid passing semantic analyzer to type analyzer, on…
ilevkivskyi Sep 21, 2017
076c909
Address the rest of the review comments
ilevkivskyi Sep 22, 2017
c1a63ec
Improve two tests
ilevkivskyi Sep 22, 2017
97e6f47
Add one more test as suggested in #3990
ilevkivskyi Sep 23, 2017
8f52654
Address latest review comments
ilevkivskyi Sep 26, 2017
6edd078
Improve tests; Fix one more crash on NewType MRO
ilevkivskyi Sep 27, 2017
514b8bd
Fix formatting in tests
ilevkivskyi Sep 27, 2017
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
40 changes: 39 additions & 1 deletion mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -4120,8 +4120,14 @@ def visit_class_def(self, tdef: ClassDef) -> None:
# NamedTuple base classes are validated in check_namedtuple_classdef; we don't have to
# check them again here.
if not tdef.info.is_named_tuple:
types = list(tdef.info.bases) # type: List[Type]
for tvar in tdef.type_vars:
if tvar.upper_bound:
types.append(tvar.upper_bound)
if tvar.values:
types.extend(tvar.values)
self.analyze_types(types, tdef.info)
for type in tdef.info.bases:
self.analyze(type, tdef.info)
if tdef.info.is_protocol:
if not isinstance(type, Instance) or not type.type.is_protocol:
if type.type.fullname() != 'builtins.object':
Expand Down Expand Up @@ -4212,6 +4218,13 @@ def visit_assignment_stmt(self, s: AssignmentStmt) -> None:
analyzed = s.rvalue.analyzed
if isinstance(analyzed, NewTypeExpr):
self.analyze(analyzed.old_type, analyzed)
if isinstance(analyzed, TypeVarExpr):
types = []
if analyzed.upper_bound:
types.append(analyzed.upper_bound)
if analyzed.values:
types.extend(analyzed.values)
self.analyze_types(types, analyzed)
if isinstance(analyzed, TypedDictExpr):
self.analyze(analyzed.info.typeddict_type, analyzed, warn=True)
if isinstance(analyzed, NamedTupleExpr):
Expand Down Expand Up @@ -4267,6 +4280,11 @@ def perform_transform(self, node: Union[Node, SymbolTableNode],
node.type = transform(node.type)
Copy link
Collaborator

Choose a reason for hiding this comment

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

What about type_annotation of Argument? Should we process it?

Copy link
Member Author

Choose a reason for hiding this comment

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

I was not able to trigger any errors with this, I will double check.

if isinstance(node, NewTypeExpr):
node.old_type = transform(node.old_type)
if isinstance(node, TypeVarExpr):
if node.upper_bound:
node.upper_bound = transform(node.upper_bound)
if node.values:
node.values = [transform(v) for v in node.values]
if isinstance(node, TypedDictExpr):
node.info.typeddict_type = cast(TypedDictType,
transform(node.info.typeddict_type))
Expand All @@ -4278,6 +4296,11 @@ def perform_transform(self, node: Union[Node, SymbolTableNode],
if isinstance(node, SymbolTableNode):
node.type_override = transform(node.type_override)
if isinstance(node, TypeInfo):
for tvar in node.defn.type_vars:
if tvar.upper_bound:
tvar.upper_bound = transform(tvar.upper_bound)
if tvar.values:
tvar.values = [transform(v) for v in tvar.values]
new_bases = []
for base in node.bases:
new_base = transform(base)
Expand Down Expand Up @@ -4317,6 +4340,21 @@ def patch() -> None:
node, warn)))
self.patches.append(patch)

def analyze_types(self, types: List[Type], node: Node) -> None:
# Similar to above but for nodes with multiple types.
indicator = {} # type: Dict[str, bool]
for type in types:
analyzer = TypeAnalyserPass3(self.fail, self.options, self.is_typeshed_file,
self.sem, indicator)
type.accept(analyzer)
self.check_for_omitted_generics(type)
if indicator.get('forward') or indicator.get('synthetic'):
def patch() -> None:
self.perform_transform(node,
lambda tp: tp.accept(TypeReplacer(self.fail,
node, warn=False)))
self.patches.append(patch)

def check_for_omitted_generics(self, typ: Type) -> None:
if 'generics' not in self.options.disallow_any or self.is_typeshed_file:
return
Expand Down
21 changes: 19 additions & 2 deletions mypy/typeanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -660,6 +660,7 @@ def visit_instance(self, t: Instance) -> None:
t.invalid = True
elif info.defn.type_vars:
# Check type argument values.
# TODO: Calling is_subtype and is_same_types in semantic analysis is a bad idea
for (i, arg), tvar in zip(enumerate(t.args), info.defn.type_vars):
if tvar.values:
if isinstance(arg, TypeVarType):
Expand All @@ -672,12 +673,28 @@ def visit_instance(self, t: Instance) -> None:
else:
arg_values = [arg]
self.check_type_var_values(info, arg_values, tvar.name, tvar.values, i + 1, t)
# TODO: These hacks will be not necessary when this will be moved to later stage.
if isinstance(arg, ForwardRef):
arg = arg.link
if not is_subtype(arg, tvar.upper_bound):
bound = tvar.upper_bound
if isinstance(bound, ForwardRef):
bound = bound.link
if isinstance(bound, Instance) and bound.type.replaced:
Copy link
Collaborator

Choose a reason for hiding this comment

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

I wonder if this code is almost duplicated somewhere else. If so, it would be better to have only one implementation in a utility function/method.

Copy link
Member Author

Choose a reason for hiding this comment

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

I will minimize duplication (but I can't use exactly the code from visitor in semanal.py it is too soon here).

replaced = bound.type.replaced
if replaced.tuple_type:
bound = replaced.tuple_type
if replaced.typeddict_type:
bound = replaced.typeddict_type
if isinstance(arg, Instance) and arg.type.replaced:
replaced = arg.type.replaced
if replaced.tuple_type:
arg = replaced.tuple_type
if replaced.typeddict_type:
arg = replaced.typeddict_type
if not is_subtype(arg, bound):
self.fail('Type argument "{}" of "{}" must be '
'a subtype of "{}"'.format(
arg, info.name(), tvar.upper_bound), t)
arg, info.name(), bound), t)
for arg in t.args:
arg.accept(self)
if info.is_newtype:
Expand Down
2 changes: 1 addition & 1 deletion test-data/unit/check-namedtuple.test
Original file line number Diff line number Diff line change
Expand Up @@ -440,7 +440,7 @@ T = TypeVar('T', bound='M')
class G(Generic[T]):
x: T

yb: G[int]
yb: G[int] # E: Type argument "builtins.int" of "G" must be a subtype of "Tuple[builtins.int, fallback=__main__.M]"
yg: G[M]
z: int = G[M]().x.x
Copy link
Collaborator

Choose a reason for hiding this comment

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

Using reveal_type would be more reliable as it would catch unwanted Any types.

z = G[M]().x[0]
Copy link
Collaborator

Choose a reason for hiding this comment

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

reveal_type would be better here as well.

Expand Down
4 changes: 2 additions & 2 deletions test-data/unit/check-typeddict.test
Original file line number Diff line number Diff line change
Expand Up @@ -1333,9 +1333,9 @@ T = TypeVar('T', bound='M')
class G(Generic[T]):
x: T

yb: G[int]
yb: G[int] # E: Type argument "builtins.int" of "G" must be a subtype of "TypedDict({'x': builtins.int}, fallback=typing.Mapping[builtins.str, builtins.object])"
yg: G[M]
z: int = G().x['x']
z: int = G[M]().x['x']

class M(TypedDict):
x: int
Expand Down