17
17
)
18
18
19
19
from mypy .nodes import (
20
- TVAR , TYPE_ALIAS , UNBOUND_IMPORTED ,
21
- TypeInfo , Context , SymbolTableNode , Var , Expression ,
22
- IndexExpr , RefExpr , nongen_builtins , check_arg_names , check_arg_kinds ,
23
- ARG_POS , ARG_NAMED , ARG_OPT , ARG_NAMED_OPT , ARG_STAR , ARG_STAR2 , TypeVarExpr
20
+ TVAR , TYPE_ALIAS , UNBOUND_IMPORTED , TypeInfo , Context , SymbolTableNode , Var , Expression ,
21
+ IndexExpr , RefExpr , nongen_builtins , check_arg_names , check_arg_kinds , ARG_POS , ARG_NAMED ,
22
+ ARG_OPT , ARG_NAMED_OPT , ARG_STAR , ARG_STAR2 , TypeVarExpr
24
23
)
25
24
from mypy .tvar_scope import TypeVarScope
26
25
from mypy .sametypes import is_same_type
27
26
from mypy .exprtotype import expr_to_unanalyzed_type , TypeTranslationError
28
27
from mypy .subtypes import is_subtype
29
28
from mypy .plugin import Plugin , AnalyzerPluginInterface , AnalyzeTypeContext
30
- from mypy import nodes
31
- from mypy import experiments
29
+ from mypy import nodes , messages
32
30
33
31
34
32
T = TypeVar ('T' )
@@ -58,6 +56,8 @@ def analyze_type_alias(node: Expression,
58
56
tvar_scope : TypeVarScope ,
59
57
fail_func : Callable [[str , Context ], None ],
60
58
plugin : Plugin ,
59
+ options : Options ,
60
+ is_typeshed_stub : bool ,
61
61
allow_unnormalized : bool = False ) -> Optional [Type ]:
62
62
"""Return type if node is valid as a type alias rvalue.
63
63
@@ -100,8 +100,8 @@ def analyze_type_alias(node: Expression,
100
100
except TypeTranslationError :
101
101
fail_func ('Invalid type alias' , node )
102
102
return None
103
- analyzer = TypeAnalyser (lookup_func , lookup_fqn_func , tvar_scope , fail_func , plugin ,
104
- aliasing = True , allow_unnormalized = allow_unnormalized )
103
+ analyzer = TypeAnalyser (lookup_func , lookup_fqn_func , tvar_scope , fail_func , plugin , options ,
104
+ is_typeshed_stub , aliasing = True , allow_unnormalized = allow_unnormalized )
105
105
return type .accept (analyzer )
106
106
107
107
@@ -124,7 +124,9 @@ def __init__(self,
124
124
lookup_fqn_func : Callable [[str ], SymbolTableNode ],
125
125
tvar_scope : TypeVarScope ,
126
126
fail_func : Callable [[str , Context ], None ],
127
- plugin : Plugin , * ,
127
+ plugin : Plugin ,
128
+ options : Options ,
129
+ is_typeshed_stub : bool , * ,
128
130
aliasing : bool = False ,
129
131
allow_tuple_literal : bool = False ,
130
132
allow_unnormalized : bool = False ) -> None :
@@ -138,6 +140,8 @@ def __init__(self,
138
140
self .nesting_level = 0
139
141
self .allow_unnormalized = allow_unnormalized
140
142
self .plugin = plugin
143
+ self .options = options
144
+ self .is_typeshed_stub = is_typeshed_stub
141
145
142
146
def visit_unbound_type (self , t : UnboundType ) -> Type :
143
147
if t .optional :
@@ -172,7 +176,11 @@ def visit_unbound_type(self, t: UnboundType) -> Type:
172
176
elif fullname == 'typing.Tuple' :
173
177
if len (t .args ) == 0 and not t .empty_tuple_index :
174
178
# Bare 'Tuple' is same as 'tuple'
175
- return self .named_type ('builtins.tuple' )
179
+ if 'generics' in self .options .disallow_any and not self .is_typeshed_stub :
180
+ self .fail (messages .BARE_GENERIC , t )
181
+ typ = self .named_type ('builtins.tuple' , line = t .line , column = t .column )
182
+ typ .from_generic_builtin = True
183
+ return typ
176
184
if len (t .args ) == 2 and isinstance (t .args [1 ], EllipsisType ):
177
185
# Tuple[T, ...] (uniform, variable-length tuple)
178
186
instance = self .named_type ('builtins.tuple' , [self .anal_type (t .args [0 ])])
@@ -192,7 +200,8 @@ def visit_unbound_type(self, t: UnboundType) -> Type:
192
200
return self .analyze_callable_type (t )
193
201
elif fullname == 'typing.Type' :
194
202
if len (t .args ) == 0 :
195
- return TypeType (AnyType (), line = t .line )
203
+ any_type = AnyType (from_omitted_generics = True , line = t .line , column = t .column )
204
+ return TypeType (any_type , line = t .line , column = t .column )
196
205
if len (t .args ) != 1 :
197
206
self .fail ('Type[...] must have exactly one type argument' , t )
198
207
item = self .anal_type (t .args [0 ])
@@ -221,7 +230,8 @@ def visit_unbound_type(self, t: UnboundType) -> Type:
221
230
act_len = len (an_args )
222
231
if exp_len > 0 and act_len == 0 :
223
232
# Interpret bare Alias same as normal generic, i.e., Alias[Any, Any, ...]
224
- return self .replace_alias_tvars (override , all_vars , [AnyType ()] * exp_len ,
233
+ any_type = AnyType (from_omitted_generics = True , line = t .line , column = t .column )
234
+ return self .replace_alias_tvars (override , all_vars , [any_type ] * exp_len ,
225
235
t .line , t .column )
226
236
if exp_len == 0 and act_len == 0 :
227
237
return override
@@ -257,6 +267,7 @@ def visit_unbound_type(self, t: UnboundType) -> Type:
257
267
# valid count at this point. Thus we may construct an
258
268
# Instance with an invalid number of type arguments.
259
269
instance = Instance (info , self .anal_array (t .args ), t .line , t .column )
270
+ instance .from_generic_builtin = sym .normalized
260
271
tup = info .tuple_type
261
272
if tup is not None :
262
273
# The class has a Tuple[...] base class so it will be
@@ -397,10 +408,11 @@ def analyze_callable_type(self, t: UnboundType) -> Type:
397
408
fallback = self .named_type ('builtins.function' )
398
409
if len (t .args ) == 0 :
399
410
# Callable (bare). Treat as Callable[..., Any].
400
- ret = CallableType ([AnyType (), AnyType ()],
411
+ any_type = AnyType (from_omitted_generics = True , line = t .line , column = t .column )
412
+ ret = CallableType ([any_type , any_type ],
401
413
[nodes .ARG_STAR , nodes .ARG_STAR2 ],
402
414
[None , None ],
403
- ret_type = AnyType () ,
415
+ ret_type = any_type ,
404
416
fallback = fallback ,
405
417
is_ellipsis_args = True )
406
418
elif len (t .args ) == 2 :
@@ -555,10 +567,14 @@ def anal_var_defs(self, var_defs: List[TypeVarDef]) -> List[TypeVarDef]:
555
567
vd .line ))
556
568
return a
557
569
558
- def named_type (self , fully_qualified_name : str , args : List [Type ] = None ) -> Instance :
570
+ def named_type (self , fully_qualified_name : str ,
571
+ args : List [Type ] = None ,
572
+ line : int = - 1 ,
573
+ column : int = - 1 ) -> Instance :
559
574
node = self .lookup_fqn_func (fully_qualified_name )
560
575
assert isinstance (node .node , TypeInfo )
561
- return Instance (node .node , args or [])
576
+ return Instance (node .node , args or [AnyType ()] * len (node .node .defn .type_vars ),
577
+ line = line , column = column )
562
578
563
579
def tuple_type (self , items : List [Type ]) -> TupleType :
564
580
return TupleType (items , fallback = self .named_type ('builtins.tuple' , [AnyType ()]))
@@ -584,16 +600,29 @@ class TypeAnalyserPass3(TypeVisitor[None]):
584
600
to types.
585
601
"""
586
602
587
- def __init__ (self , fail_func : Callable [[str , Context ], None ]) -> None :
603
+ def __init__ (self ,
604
+ fail_func : Callable [[str , Context ], None ],
605
+ options : Options ,
606
+ is_typeshed_stub : bool ) -> None :
588
607
self .fail = fail_func
608
+ self .options = options
609
+ self .is_typeshed_stub = is_typeshed_stub
589
610
590
611
def visit_instance (self , t : Instance ) -> None :
591
612
info = t .type
592
613
# Check type argument count.
593
614
if len (t .args ) != len (info .type_vars ):
594
615
if len (t .args ) == 0 :
616
+ from_builtins = t .type .fullname () in nongen_builtins and not t .from_generic_builtin
617
+ if ('generics' in self .options .disallow_any and
618
+ not self .is_typeshed_stub and
619
+ from_builtins ):
620
+ alternative = nongen_builtins [t .type .fullname ()]
621
+ self .fail (messages .IMPLICIT_GENERIC_ANY_BUILTIN .format (alternative ), t )
595
622
# Insert implicit 'Any' type arguments.
596
- t .args = [AnyType ()] * len (info .type_vars )
623
+ any_type = AnyType (from_omitted_generics = not from_builtins , line = t .line ,
624
+ column = t .line )
625
+ t .args = [any_type ] * len (info .type_vars )
597
626
return
598
627
# Invalid number of type parameters.
599
628
n = len (info .type_vars )
@@ -809,6 +838,26 @@ def visit_typeddict_type(self, t: TypedDictType) -> bool:
809
838
return False
810
839
811
840
841
+ def collect_any_types (t : Type ) -> List [AnyType ]:
842
+ """Return all inner `AnyType`s of type t"""
843
+ return t .accept (CollectAnyTypesQuery ())
844
+
845
+
846
+ class CollectAnyTypesQuery (TypeQuery [List [AnyType ]]):
847
+ def __init__ (self ) -> None :
848
+ super ().__init__ (self .combine_lists_strategy )
849
+
850
+ def visit_any (self , t : AnyType ) -> List [AnyType ]:
851
+ return [t ]
852
+
853
+ @classmethod
854
+ def combine_lists_strategy (cls , it : Iterable [List [AnyType ]]) -> List [AnyType ]:
855
+ result = [] # type: List[AnyType]
856
+ for l in it :
857
+ result .extend (l )
858
+ return result
859
+
860
+
812
861
def make_optional_type (t : Type ) -> Type :
813
862
"""Return the type corresponding to Optional[t].
814
863
0 commit comments