Debian Codegraph @

mypy/fixup.py

raw
1 """Fix up various things after deserialization."""
2
3 from __future__ import annotations
4
5 from typing import Any, Final
6
7 from mypy.lookup import lookup_fully_qualified
8 from mypy.nodes import (
9 Block,
10 ClassDef,
11 Decorator,
12 FuncDef,
13 MypyFile,
14 OverloadedFuncDef,
15 ParamSpecExpr,
16 SymbolTable,
17 SymbolTableNode,
18 TypeAlias,
19 TypeInfo,
20 TypeVarExpr,
21 TypeVarTupleExpr,
22 Var,
23 )
24 from mypy.types import (
25 NOT_READY,
26 AnyType,
27 CallableType,
28 Instance,
29 LiteralType,
30 Overloaded,
31 Parameters,
32 ParamSpecType,
33 ProperType,
34 TupleType,
35 TypeAliasType,
36 TypedDictType,
37 TypeOfAny,
38 TypeType,
39 TypeVarTupleType,
40 TypeVarType,
41 TypeVisitor,
42 UnboundType,
43 UnionType,
44 UnpackType,
45 )
46 from mypy.visitor import NodeVisitor
47
48
49 class NodeFixer(NodeVisitor[None]):
50 current_info: TypeInfo | None = None
51
52 def __init__(self, modules: dict[str, MypyFile], allow_missing: bool) -> None:
53 self.modules = modules
54 # N.B: we do an allow_missing fixup when fixing up a fine-grained
55 # incremental cache load (since there may be cross-refs into deleted
56 # modules)
57 self.allow_missing = allow_missing
58 self.type_fixer = TypeFixer(self.modules, allow_missing)
59
60 # NOTE: This method isn't (yet) part of the NodeVisitor API.
61 def visit_type_info(self, info: TypeInfo) -> None:
62 save_info = self.current_info
63 try:
64 self.current_info = info
65 if info.defn:
66 info.defn.accept(self)
67 if info.names:
68 self.visit_symbol_table(info.names)
69 if info.bases:
70 for base in info.bases:
71 base.accept(self.type_fixer)
72 if info._promote:
73 for p in info._promote:
74 p.accept(self.type_fixer)
75 if info.tuple_type:
76 info.tuple_type.accept(self.type_fixer)
77 info.update_tuple_type(info.tuple_type)
78 if info.special_alias:
79 info.special_alias.alias_tvars = list(info.defn.type_vars)
80 for i, t in enumerate(info.defn.type_vars):
81 if isinstance(t, TypeVarTupleType):
82 info.special_alias.tvar_tuple_index = i
83 if info.typeddict_type:
84 info.typeddict_type.accept(self.type_fixer)
85 info.update_typeddict_type(info.typeddict_type)
86 if info.special_alias:
87 info.special_alias.alias_tvars = list(info.defn.type_vars)
88 for i, t in enumerate(info.defn.type_vars):
89 if isinstance(t, TypeVarTupleType):
90 info.special_alias.tvar_tuple_index = i
91 if info.declared_metaclass:
92 info.declared_metaclass.accept(self.type_fixer)
93 if info.metaclass_type:
94 info.metaclass_type.accept(self.type_fixer)
95 if info.self_type:
96 info.self_type.accept(self.type_fixer)
97 if info.alt_promote:
98 info.alt_promote.accept(self.type_fixer)
99 instance = Instance(info, [])
100 # Hack: We may also need to add a backwards promotion (from int to native int),
101 # since it might not be serialized.
102 if instance not in info.alt_promote.type._promote:
103 info.alt_promote.type._promote.append(instance)
104 if info._mro_refs:
105 info.mro = [
106 lookup_fully_qualified_typeinfo(
107 self.modules, name, allow_missing=self.allow_missing
108 )
109 for name in info._mro_refs
110 ]
111 info._mro_refs = None
112 finally:
113 self.current_info = save_info
114
115 # NOTE: This method *definitely* isn't part of the NodeVisitor API.
116 def visit_symbol_table(self, symtab: SymbolTable) -> None:
117 for key in symtab:
118 value = symtab[key]
119 cross_ref = value.cross_ref
120 # Fix up module cross-reference eagerly because it is very cheap.
121 if cross_ref is not None:
122 if cross_ref in self.modules:
123 value.cross_ref = None
124 value.unfixed = False
125 value._node = self.modules[cross_ref]
126 # TODO: this should not be needed, looks like a daemon bug.
127 elif self.allow_missing:
128 self.resolve_cross_ref(value)
129 # Look at private attribute to avoid triggering fixup eagerly.
130 elif isinstance(value._node, TypeInfo):
131 self.visit_type_info(value._node)
132 else:
133 value.stored_info = self.current_info
134
135 def resolve_cross_ref(self, value: SymbolTableNode) -> None:
136 """Replace cross-reference with an actual referred node."""
137 assert value.cross_ref is not None
138 cross_ref = value.cross_ref
139 value.cross_ref = None
140 value.unfixed = False
141 stnode = lookup_fully_qualified(
142 cross_ref, self.modules, raise_on_missing=not self.allow_missing
143 )
144 if stnode is not None:
145 if stnode is value:
146 # The node seems to refer to itself, which can mean that
147 # the target is a deleted submodule of the current module,
148 # and thus lookup falls back to the symbol table of the parent
149 # package. Here's how this may happen:
150 #
151 # pkg/__init__.py:
152 # from pkg import sub
153 #
154 # Now if pkg.sub is deleted, the pkg.sub symbol table entry
155 # appears to refer to itself. Replace the entry with a
156 # placeholder to avoid a crash. We can't delete the entry,
157 # as it would stop dependency propagation.
158 short_name = cross_ref.rsplit(".", maxsplit=1)[-1]
159 value._node = Var(short_name + "@deleted")
160 else:
161 assert stnode.node is not None, cross_ref
162 value._node = stnode.node
163 elif not self.allow_missing:
164 assert False, f"Could not find cross-ref {cross_ref}"
165 else:
166 # We have a missing crossref in allow missing mode, need to put something
167 value._node = missing_info(self.modules)
168
169 def visit_func_def(self, func: FuncDef) -> None:
170 if func.type is not None:
171 func.type.accept(self.type_fixer)
172 if isinstance(func.type, CallableType):
173 func.type.definition = func
174
175 def visit_overloaded_func_def(self, o: OverloadedFuncDef) -> None:
176 if o.type:
177 o.type.accept(self.type_fixer)
178 for item in o.items:
179 item.accept(self)
180 if o.impl:
181 o.impl.accept(self)
182 if isinstance(o.type, Overloaded):
183 # For error messages we link the original definition for each item.
184 for typ, item in zip(o.type.items, o.items):
185 typ.definition = item
186
187 def visit_decorator(self, d: Decorator) -> None:
188 if d.func:
189 d.func.accept(self)
190 if d.var:
191 d.var.accept(self)
192 typ = d.var.type
193 if isinstance(typ, ProperType) and isinstance(typ, CallableType):
194 typ.definition = d.func
195
196 def visit_class_def(self, c: ClassDef) -> None:
197 for v in c.type_vars:
198 v.accept(self.type_fixer)
199
200 def visit_type_var_expr(self, tv: TypeVarExpr) -> None:
201 for value in tv.values:
202 value.accept(self.type_fixer)
203 tv.upper_bound.accept(self.type_fixer)
204 tv.default.accept(self.type_fixer)
205
206 def visit_paramspec_expr(self, p: ParamSpecExpr) -> None:
207 p.upper_bound.accept(self.type_fixer)
208 p.default.accept(self.type_fixer)
209
210 def visit_type_var_tuple_expr(self, tv: TypeVarTupleExpr) -> None:
211 tv.upper_bound.accept(self.type_fixer)
212 tv.tuple_fallback.accept(self.type_fixer)
213 tv.default.accept(self.type_fixer)
214
215 def visit_var(self, v: Var) -> None:
216 if v.type is not None:
217 v.type.accept(self.type_fixer)
218 if v.setter_type is not None:
219 v.setter_type.accept(self.type_fixer)
220
221 def visit_type_alias(self, a: TypeAlias) -> None:
222 a.target.accept(self.type_fixer)
223 for v in a.alias_tvars:
224 v.accept(self.type_fixer)
225
226
227 class TypeFixer(TypeVisitor[None]):
228 def __init__(self, modules: dict[str, MypyFile], allow_missing: bool) -> None:
229 self.modules = modules
230 self.allow_missing = allow_missing
231
232 def visit_instance(self, inst: Instance) -> None:
233 type_ref = inst.type_ref
234 if type_ref is None:
235 return # We've already been here.
236 inst.type_ref = None
237 inst.type = lookup_fully_qualified_typeinfo(
238 self.modules, type_ref, allow_missing=self.allow_missing
239 )
240 # TODO: Is this needed or redundant?
241 # Also fix up the bases, just in case.
242 for base in inst.type.bases:
243 if base.type is NOT_READY:
244 base.accept(self)
245 for a in inst.args:
246 a.accept(self)
247 if inst.last_known_value is not None:
248 inst.last_known_value.accept(self)
249 if inst.extra_attrs:
250 for v in inst.extra_attrs.attrs.values():
251 v.accept(self)
252
253 def visit_type_alias_type(self, t: TypeAliasType) -> None:
254 type_ref = t.type_ref
255 if type_ref is None:
256 return # We've already been here.
257 t.type_ref = None
258 t.alias = lookup_fully_qualified_alias(
259 self.modules, type_ref, allow_missing=self.allow_missing
260 )
261 for a in t.args:
262 a.accept(self)
263
264 def visit_any(self, o: Any) -> None:
265 pass # Nothing to descend into.
266
267 def visit_callable_type(self, ct: CallableType) -> None:
268 if ct.fallback:
269 ct.fallback.accept(self)
270 for argt in ct.arg_types:
271 # argt may be None, e.g. for __self in NamedTuple constructors.
272 if argt is not None:
273 argt.accept(self)
274 if ct.ret_type is not None:
275 ct.ret_type.accept(self)
276 for v in ct.variables:
277 v.accept(self)
278 if ct.type_guard is not None:
279 ct.type_guard.accept(self)
280 if ct.type_is is not None:
281 ct.type_is.accept(self)
282 if ct.instance_type is not None:
283 ct.instance_type.accept(self)
284
285 def visit_overloaded(self, t: Overloaded) -> None:
286 for ct in t.items:
287 ct.accept(self)
288
289 def visit_erased_type(self, o: Any) -> None:
290 # This type should exist only temporarily during type inference
291 raise RuntimeError("Shouldn't get here", o)
292
293 def visit_deleted_type(self, o: Any) -> None:
294 pass # Nothing to descend into.
295
296 def visit_none_type(self, o: Any) -> None:
297 pass # Nothing to descend into.
298
299 def visit_uninhabited_type(self, o: Any) -> None:
300 pass # Nothing to descend into.
301
302 def visit_partial_type(self, o: Any) -> None:
303 raise RuntimeError("Shouldn't get here", o)
304
305 def visit_tuple_type(self, tt: TupleType) -> None:
306 if tt.items:
307 for it in tt.items:
308 it.accept(self)
309 if tt.partial_fallback is not None:
310 tt.partial_fallback.accept(self)
311
312 def visit_typeddict_type(self, tdt: TypedDictType) -> None:
313 if tdt.items:
314 for it in tdt.items.values():
315 it.accept(self)
316 if tdt.fallback is not None:
317 if tdt.fallback.type_ref is not None:
318 if (
319 lookup_fully_qualified(
320 tdt.fallback.type_ref,
321 self.modules,
322 raise_on_missing=not self.allow_missing,
323 )
324 is None
325 ):
326 # We reject fake TypeInfos for TypedDict fallbacks because
327 # the latter are used in type checking and must be valid.
328 tdt.fallback.type_ref = "typing._TypedDict"
329 tdt.fallback.accept(self)
330
331 def visit_literal_type(self, lt: LiteralType) -> None:
332 lt.fallback.accept(self)
333
334 def visit_type_var(self, tvt: TypeVarType) -> None:
335 if tvt.values:
336 for vt in tvt.values:
337 vt.accept(self)
338 tvt.upper_bound.accept(self)
339 tvt.default.accept(self)
340
341 def visit_param_spec(self, p: ParamSpecType) -> None:
342 p.upper_bound.accept(self)
343 p.default.accept(self)
344 p.prefix.accept(self)
345
346 def visit_type_var_tuple(self, t: TypeVarTupleType) -> None:
347 t.tuple_fallback.accept(self)
348 t.upper_bound.accept(self)
349 t.default.accept(self)
350
351 def visit_unpack_type(self, u: UnpackType) -> None:
352 u.type.accept(self)
353
354 def visit_parameters(self, p: Parameters) -> None:
355 for argt in p.arg_types:
356 if argt is not None:
357 argt.accept(self)
358 for var in p.variables:
359 var.accept(self)
360
361 def visit_unbound_type(self, o: UnboundType) -> None:
362 for a in o.args:
363 a.accept(self)
364
365 def visit_union_type(self, ut: UnionType) -> None:
366 if ut.items:
367 for it in ut.items:
368 it.accept(self)
369
370 def visit_type_type(self, t: TypeType) -> None:
371 t.item.accept(self)
372
373
374 def lookup_fully_qualified_typeinfo(
375 modules: dict[str, MypyFile], name: str, *, allow_missing: bool
376 ) -> TypeInfo:
377 stnode = lookup_fully_qualified(name, modules, raise_on_missing=not allow_missing)
378 node = stnode.node if stnode else None
379 if isinstance(node, TypeInfo):
380 return node
381 else:
382 # Looks like a missing TypeInfo during an initial daemon load, put something there
383 assert (
384 allow_missing
385 ), "Should never get here in normal mode, got {}:{} instead of TypeInfo".format(
386 type(node).__name__, node.fullname if node else ""
387 )
388 return missing_info(modules)
389
390
391 def lookup_fully_qualified_alias(
392 modules: dict[str, MypyFile], name: str, *, allow_missing: bool
393 ) -> TypeAlias:
394 stnode = lookup_fully_qualified(name, modules, raise_on_missing=not allow_missing)
395 node = stnode.node if stnode else None
396 if isinstance(node, TypeAlias):
397 return node
398 elif isinstance(node, TypeInfo):
399 if node.special_alias:
400 # Already fixed up.
401 return node.special_alias
402 if node.tuple_type:
403 alias = TypeAlias.from_tuple_type(node)
404 elif node.typeddict_type:
405 alias = TypeAlias.from_typeddict_type(node)
406 else:
407 assert allow_missing
408 return missing_alias()
409 node.special_alias = alias
410 return alias
411 else:
412 # Looks like a missing TypeAlias during an initial daemon load, put something there
413 assert (
414 allow_missing
415 ), "Should never get here in normal mode, got {}:{} instead of TypeAlias".format(
416 type(node).__name__, node.fullname if node else ""
417 )
418 return missing_alias()
419
420
421 _SUGGESTION: Final = "<missing {}: *should* have gone away during fine-grained update>"
422
423
424 def missing_info(modules: dict[str, MypyFile]) -> TypeInfo:
425 suggestion = _SUGGESTION.format("info")
426 dummy_def = ClassDef(suggestion, Block([]))
427 dummy_def.fullname = suggestion
428
429 info = TypeInfo(SymbolTable(), dummy_def, "<missing>")
430 obj_type = lookup_fully_qualified_typeinfo(modules, "builtins.object", allow_missing=False)
431 info.bases = [Instance(obj_type, [])]
432 info.mro = [info, obj_type]
433 return info
434
435
436 def missing_alias() -> TypeAlias:
437 suggestion = _SUGGESTION.format("alias")
438 return TypeAlias(AnyType(TypeOfAny.special_form), suggestion, "<missing>", line=-1, column=-1)