Debian Codegraph @

mypy/semanal_newtype.py

raw
1 """Semantic analysis of NewType definitions.
2
3 This is conceptually part of mypy.semanal (semantic analyzer pass 2).
4 """
5
6 from __future__ import annotations
7
8 from mypy import errorcodes as codes
9 from mypy.errorcodes import ErrorCode
10 from mypy.exprtotype import TypeTranslationError, expr_to_unanalyzed_type
11 from mypy.messages import MessageBuilder, format_type
12 from mypy.nodes import (
13 ARG_POS,
14 MDEF,
15 Argument,
16 AssignmentStmt,
17 Block,
18 CallExpr,
19 Context,
20 FuncDef,
21 NameExpr,
22 NewTypeExpr,
23 PlaceholderNode,
24 RefExpr,
25 StrExpr,
26 SymbolTableNode,
27 TypeInfo,
28 Var,
29 )
30 from mypy.options import Options
31 from mypy.semanal_shared import SemanticAnalyzerInterface, has_placeholder
32 from mypy.typeanal import check_for_explicit_any, has_any_from_unimported_type
33 from mypy.types import (
34 AnyType,
35 CallableType,
36 Instance,
37 NoneType,
38 PlaceholderType,
39 TupleType,
40 Type,
41 TypeOfAny,
42 get_proper_type,
43 )
44
45
46 class NewTypeAnalyzer:
47 def __init__(
48 self, options: Options, api: SemanticAnalyzerInterface, msg: MessageBuilder
49 ) -> None:
50 self.options = options
51 self.api = api
52 self.msg = msg
53
54 def process_newtype_declaration(self, s: AssignmentStmt) -> bool:
55 """Check if s declares a NewType; if yes, store it in symbol table.
56
57 Return True if it's a NewType declaration. The current target may be
58 deferred as a side effect if the base type is not ready, even if
59 the return value is True.
60
61 The logic in this function mostly copies the logic for visit_class_def()
62 with a single (non-Generic) base.
63 """
64 var_name, call = self.analyze_newtype_declaration(s)
65 if var_name is None or call is None:
66 return False
67 name = var_name
68 # OK, now we know this is a NewType. But the base type may be not ready yet,
69 # add placeholder as we do for ClassDef.
70 fullname = self.api.qualified_name(name)
71
72 if not call.analyzed or isinstance(call.analyzed, NewTypeExpr) and not call.analyzed.info:
73 # Start from labeling this as a future class, as we do for normal ClassDefs.
74 placeholder = PlaceholderNode(fullname, s, s.line, becomes_typeinfo=True)
75 self.api.add_symbol(var_name, placeholder, s, can_defer=False)
76
77 old_type, should_defer = self.check_newtype_args(var_name, call, s)
78 old_type = get_proper_type(old_type)
79 if not isinstance(call.analyzed, NewTypeExpr):
80 call.analyzed = NewTypeExpr(var_name, old_type, line=call.line, column=call.column)
81 else:
82 call.analyzed.old_type = old_type
83 if old_type is None:
84 if should_defer:
85 # Base type is not ready.
86 self.api.defer()
87 return True
88
89 # Create the corresponding class definition if the aliased type is subtypeable
90 assert isinstance(call.analyzed, NewTypeExpr)
91 if isinstance(old_type, TupleType):
92 newtype_class_info = self.build_newtype_typeinfo(
93 name, old_type, old_type.partial_fallback, s.line, call.analyzed.info
94 )
95 newtype_class_info.update_tuple_type(old_type)
96 elif isinstance(old_type, Instance):
97 if old_type.type.is_protocol:
98 self.fail("NewType cannot be used with protocol classes", s)
99 newtype_class_info = self.build_newtype_typeinfo(
100 name, old_type, old_type, s.line, call.analyzed.info
101 )
102 else:
103 if old_type is not None:
104 message = "Argument 2 to NewType(...) must be subclassable (got {})"
105 self.fail(
106 message.format(format_type(old_type, self.options)),
107 s,
108 code=codes.VALID_NEWTYPE,
109 )
110 # Otherwise the error was already reported.
111 old_type = AnyType(TypeOfAny.from_error)
112 object_type = self.api.named_type("builtins.object")
113 newtype_class_info = self.build_newtype_typeinfo(
114 name, old_type, object_type, s.line, call.analyzed.info
115 )
116 newtype_class_info.fallback_to_any = True
117
118 check_for_explicit_any(
119 old_type, self.options, self.api.is_typeshed_stub_file, self.msg, context=s
120 )
121
122 if self.options.disallow_any_unimported and has_any_from_unimported_type(old_type):
123 self.msg.unimported_type_becomes_any("Argument 2 to NewType(...)", old_type, s)
124
125 # If so, add it to the symbol table.
126 assert isinstance(call.analyzed, NewTypeExpr)
127 # As we do for normal classes, create the TypeInfo only once, then just
128 # update base classes on next iterations (to get rid of placeholders there).
129 if not call.analyzed.info:
130 call.analyzed.info = newtype_class_info
131 else:
132 call.analyzed.info.bases = newtype_class_info.bases
133 self.api.add_symbol(var_name, call.analyzed.info, s)
134 if self.api.is_nested_within_func_scope():
135 self.api.add_global_symbol(var_name, s, call.analyzed.info)
136 newtype_class_info.line = s.line
137 return True
138
139 def analyze_newtype_declaration(self, s: AssignmentStmt) -> tuple[str | None, CallExpr | None]:
140 """Return the NewType call expression if `s` is a newtype declaration or None otherwise."""
141 name, call = None, None
142 if (
143 len(s.lvalues) == 1
144 and isinstance(s.lvalues[0], NameExpr)
145 and isinstance(s.rvalue, CallExpr)
146 and isinstance(s.rvalue.callee, RefExpr)
147 and (s.rvalue.callee.fullname in ("typing.NewType", "typing_extensions.NewType"))
148 ):
149 name = s.lvalues[0].name
150
151 if s.type:
152 self.fail("Cannot declare the type of a NewType declaration", s)
153
154 names = self.api.current_symbol_table()
155 existing = names.get(name)
156 # Give a better error message than generic "Name already defined".
157 if (
158 existing
159 and not isinstance(existing.node, PlaceholderNode)
160 and not s.rvalue.analyzed
161 ):
162 self.fail(f'Cannot redefine "{name}" as a NewType', s)
163
164 # This dummy NewTypeExpr marks the call as sufficiently analyzed; it will be
165 # overwritten later with a fully complete NewTypeExpr if there are no other
166 # errors with the NewType() call.
167 call = s.rvalue
168
169 return name, call
170
171 def check_newtype_args(
172 self, name: str, call: CallExpr, context: Context
173 ) -> tuple[Type | None, bool]:
174 """Analyze base type in NewType call.
175
176 Return a tuple (type, should defer).
177 """
178 has_failed = False
179 args, arg_kinds = call.args, call.arg_kinds
180 if len(args) != 2 or arg_kinds[0] != ARG_POS or arg_kinds[1] != ARG_POS:
181 self.fail("NewType(...) expects exactly two positional arguments", context)
182 return None, False
183
184 # Check first argument
185 if not isinstance(args[0], StrExpr):
186 self.fail("Argument 1 to NewType(...) must be a string literal", context)
187 has_failed = True
188 elif args[0].value != name:
189 msg = 'String argument 1 "{}" to NewType(...) does not match variable name "{}"'
190 self.fail(msg.format(args[0].value, name), context)
191 has_failed = True
192
193 # Check second argument
194 msg = "Argument 2 to NewType(...) must be a valid type"
195 try:
196 unanalyzed_type = expr_to_unanalyzed_type(args[1], self.options, self.api.is_stub_file)
197 except TypeTranslationError:
198 self.fail(msg, context)
199 return None, False
200
201 # We want to use our custom error message (see above), so we suppress
202 # the default error message for invalid types here.
203 old_type = get_proper_type(
204 self.api.anal_type(
205 unanalyzed_type,
206 report_invalid_types=False,
207 allow_placeholder=not self.api.is_func_scope(),
208 )
209 )
210 should_defer = False
211 if isinstance(old_type, PlaceholderType):
212 old_type = None
213 if old_type is None:
214 should_defer = True
215
216 # The caller of this function assumes that if we return a Type, it's always
217 # a valid one. So, we translate AnyTypes created from errors into None.
218 if isinstance(old_type, AnyType) and old_type.is_from_error:
219 self.fail(msg, context)
220 return None, False
221
222 return None if has_failed else old_type, should_defer
223
224 def build_newtype_typeinfo(
225 self,
226 name: str,
227 old_type: Type,
228 base_type: Instance,
229 line: int,
230 existing_info: TypeInfo | None,
231 ) -> TypeInfo:
232 info = existing_info or self.api.basic_new_typeinfo(name, base_type, line)
233 info.bases = [base_type] # Update in case there were nested placeholders.
234 info.is_newtype = True
235
236 # Add __init__ method
237 args = [
238 Argument(Var("self"), NoneType(), None, ARG_POS),
239 self.make_argument("item", old_type),
240 ]
241 signature = CallableType(
242 arg_types=[Instance(info, []), old_type],
243 arg_kinds=[arg.kind for arg in args],
244 arg_names=["self", "item"],
245 ret_type=NoneType(),
246 fallback=self.api.named_type("builtins.function"),
247 name=name,
248 )
249 init_func = FuncDef("__init__", args, Block([]), typ=signature)
250 init_func.info = info
251 init_func._fullname = info.fullname + ".__init__"
252 if not existing_info:
253 updated = True
254 else:
255 previous_sym = info.names["__init__"].node
256 assert isinstance(previous_sym, FuncDef)
257 updated = old_type != previous_sym.arguments[1].variable.type
258 sym = SymbolTableNode(MDEF, init_func)
259 sym.plugin_generated = True
260 info.names["__init__"] = sym
261
262 if has_placeholder(old_type):
263 self.api.process_placeholder(None, "NewType base", info, force_progress=updated)
264 return info
265
266 # Helpers
267
268 def make_argument(self, name: str, type: Type) -> Argument:
269 return Argument(Var(name), type, None, ARG_POS)
270
271 def fail(self, msg: str, ctx: Context, *, code: ErrorCode | None = None) -> None:
272 self.api.fail(msg, ctx, code=code)