forked from python/mypy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsemanal_typeargs.py
126 lines (112 loc) · 5.68 KB
/
semanal_typeargs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
"""Verify properties of type arguments, like 'int' in C[int] being valid.
This must happen after semantic analysis since there can be placeholder
types until the end of semantic analysis, and these break various type
operations, including subtype checks.
"""
from typing import List, Optional, Set
from mypy.nodes import TypeInfo, Context, MypyFile, FuncItem, ClassDef, Block, FakeInfo
from mypy.types import (
Type, Instance, TypeVarType, AnyType, get_proper_types, TypeAliasType, ParamSpecType,
UnpackType, TupleType, get_proper_type
)
from mypy.mixedtraverser import MixedTraverserVisitor
from mypy.subtypes import is_subtype
from mypy.sametypes import is_same_type
from mypy.errors import Errors
from mypy.scope import Scope
from mypy.options import Options
from mypy.errorcodes import ErrorCode
from mypy import message_registry, errorcodes as codes
from mypy.messages import format_type
class TypeArgumentAnalyzer(MixedTraverserVisitor):
def __init__(self, errors: Errors, options: Options, is_typeshed_file: bool) -> None:
self.errors = errors
self.options = options
self.is_typeshed_file = is_typeshed_file
self.scope = Scope()
# Should we also analyze function definitions, or only module top-levels?
self.recurse_into_functions = True
# Keep track of the type aliases already visited. This is needed to avoid
# infinite recursion on types like A = Union[int, List[A]].
self.seen_aliases: Set[TypeAliasType] = set()
def visit_mypy_file(self, o: MypyFile) -> None:
self.errors.set_file(o.path, o.fullname, scope=self.scope)
with self.scope.module_scope(o.fullname):
super().visit_mypy_file(o)
def visit_func(self, defn: FuncItem) -> None:
if not self.recurse_into_functions:
return
with self.scope.function_scope(defn):
super().visit_func(defn)
def visit_class_def(self, defn: ClassDef) -> None:
with self.scope.class_scope(defn.info):
super().visit_class_def(defn)
def visit_block(self, o: Block) -> None:
if not o.is_unreachable:
super().visit_block(o)
def visit_type_alias_type(self, t: TypeAliasType) -> None:
super().visit_type_alias_type(t)
if t in self.seen_aliases:
# Avoid infinite recursion on recursive type aliases.
# Note: it is fine to skip the aliases we have already seen in non-recursive types,
# since errors there have already already reported.
return
self.seen_aliases.add(t)
get_proper_type(t).accept(self)
def visit_instance(self, t: Instance) -> None:
# Type argument counts were checked in the main semantic analyzer pass. We assume
# that the counts are correct here.
info = t.type
if isinstance(info, FakeInfo):
return # https://github.com/python/mypy/issues/11079
for (i, arg), tvar in zip(enumerate(t.args), info.defn.type_vars):
if isinstance(tvar, TypeVarType):
if isinstance(arg, ParamSpecType):
# TODO: Better message
self.fail(f'Invalid location for ParamSpec "{arg.name}"', t)
continue
if tvar.values:
if isinstance(arg, TypeVarType):
arg_values = arg.values
if not arg_values:
self.fail(
message_registry.INVALID_TYPEVAR_AS_TYPEARG.format(
arg.name, info.name),
t, code=codes.TYPE_VAR)
continue
else:
arg_values = [arg]
self.check_type_var_values(info, arg_values, tvar.name, tvar.values, i + 1, t)
if not is_subtype(arg, tvar.upper_bound):
self.fail(
message_registry.INVALID_TYPEVAR_ARG_BOUND.format(
format_type(arg), info.name, format_type(tvar.upper_bound)),
t, code=codes.TYPE_VAR)
super().visit_instance(t)
def visit_unpack_type(self, typ: UnpackType) -> None:
proper_type = get_proper_type(typ.type)
if isinstance(proper_type, TupleType):
return
if isinstance(proper_type, Instance) and proper_type.type.fullname == "builtins.tuple":
return
self.fail(message_registry.INVALID_UNPACK.format(proper_type), typ)
def check_type_var_values(self, type: TypeInfo, actuals: List[Type], arg_name: str,
valids: List[Type], arg_number: int, context: Context) -> None:
for actual in get_proper_types(actuals):
if (not isinstance(actual, AnyType) and
not any(is_same_type(actual, value)
for value in valids)):
if len(actuals) > 1 or not isinstance(actual, Instance):
self.fail(
message_registry.INVALID_TYPEVAR_ARG_VALUE.format(type.name),
context, code=codes.TYPE_VAR)
else:
class_name = '"{}"'.format(type.name)
actual_type_name = '"{}"'.format(actual.type.name)
self.fail(
message_registry.INCOMPATIBLE_TYPEVAR_VALUE.format(
arg_name, class_name, actual_type_name),
context,
code=codes.TYPE_VAR)
def fail(self, msg: str, context: Context, *, code: Optional[ErrorCode] = None) -> None:
self.errors.report(context.get_line(), context.get_column(), msg, code=code)