From c11f99c1a24b472271c3c7fc8c93212f0bf3e5ab Mon Sep 17 00:00:00 2001 From: Michael Krasnyk Date: Sat, 7 May 2022 21:06:21 +0200 Subject: [PATCH] Fix reporting location in aliased types. --- mypy/types.py | 14 ++++++++++++++ test-data/unit/check-generics.test | 24 ++++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/mypy/types.py b/mypy/types.py index b7e76c9f9f6b..df0999ed3ca6 100644 --- a/mypy/types.py +++ b/mypy/types.py @@ -2760,6 +2760,7 @@ def get_proper_types( TypeTranslator as TypeTranslator, TypeVisitor as TypeVisitor, ) +from mypy.typetraverser import TypeTraverserVisitor class TypeStrVisitor(SyntheticTypeVisitor[str]): @@ -3122,6 +3123,18 @@ def visit_type_var(self, typ: TypeVarType) -> Type: return typ +class LocationSetter(TypeTraverserVisitor): + # TODO: Should we update locations of other Type subclasses? + def __init__(self, line: int, column: int) -> None: + self.line = line + self.column = column + + def visit_instance(self, typ: Instance) -> None: + typ.line = self.line + typ.column = self.column + super().visit_instance(typ) + + def replace_alias_tvars( tp: Type, vars: List[str], subs: List[Type], newline: int, newcolumn: int ) -> Type: @@ -3130,6 +3143,7 @@ def replace_alias_tvars( """ replacer = InstantiateAliasVisitor(vars, subs) new_tp = tp.accept(replacer) + new_tp.accept(LocationSetter(newline, newcolumn)) new_tp.line = newline new_tp.column = newcolumn return new_tp diff --git a/test-data/unit/check-generics.test b/test-data/unit/check-generics.test index c52addbad182..b8d70d1dae96 100644 --- a/test-data/unit/check-generics.test +++ b/test-data/unit/check-generics.test @@ -648,6 +648,30 @@ reveal_type(f3()) # N: Revealed type is "Union[builtins.int, __main__.Node[built [builtins fixtures/list.pyi] +[case testGenericTypeAliasesWithNestedArgs] +# flags: --pretty --show-error-codes +import other +a: other.Array[float] +reveal_type(a) # N: Revealed type is "other.array[Any, other.dtype[builtins.float]]" + +[out] +main:3: error: Type argument "float" of "dtype" must be a subtype of "generic" [type-var] + a: other.Array[float] + ^ +[file other.py] +from typing import Any, Generic, TypeVar + +DT = TypeVar("DT", covariant=True, bound=dtype[Any]) +DTS = TypeVar("DTS", covariant=True, bound=generic) +S = TypeVar("S", bound=Any) +ST = TypeVar("ST", bound=generic, covariant=True) + +class common: pass +class generic(common): pass +class dtype(Generic[DTS]): pass +class array(common, Generic[S, DT]): pass +Array = array[Any, dtype[ST]] + [case testGenericTypeAliasesAny] from typing import TypeVar, Generic T = TypeVar('T')