fixup.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. """Fix up various things after deserialization."""
  2. from __future__ import annotations
  3. from typing import Any, Final
  4. from mypy.lookup import lookup_fully_qualified
  5. from mypy.nodes import (
  6. Block,
  7. ClassDef,
  8. Decorator,
  9. FuncDef,
  10. MypyFile,
  11. OverloadedFuncDef,
  12. ParamSpecExpr,
  13. SymbolTable,
  14. TypeAlias,
  15. TypeInfo,
  16. TypeVarExpr,
  17. TypeVarTupleExpr,
  18. Var,
  19. )
  20. from mypy.types import (
  21. NOT_READY,
  22. AnyType,
  23. CallableType,
  24. Instance,
  25. LiteralType,
  26. Overloaded,
  27. Parameters,
  28. ParamSpecType,
  29. TupleType,
  30. TypeAliasType,
  31. TypedDictType,
  32. TypeOfAny,
  33. TypeType,
  34. TypeVarTupleType,
  35. TypeVarType,
  36. TypeVisitor,
  37. UnboundType,
  38. UnionType,
  39. UnpackType,
  40. )
  41. from mypy.visitor import NodeVisitor
  42. # N.B: we do a allow_missing fixup when fixing up a fine-grained
  43. # incremental cache load (since there may be cross-refs into deleted
  44. # modules)
  45. def fixup_module(tree: MypyFile, modules: dict[str, MypyFile], allow_missing: bool) -> None:
  46. node_fixer = NodeFixer(modules, allow_missing)
  47. node_fixer.visit_symbol_table(tree.names, tree.fullname)
  48. # TODO: Fix up .info when deserializing, i.e. much earlier.
  49. class NodeFixer(NodeVisitor[None]):
  50. current_info: TypeInfo | None = None
  51. def __init__(self, modules: dict[str, MypyFile], allow_missing: bool) -> None:
  52. self.modules = modules
  53. self.allow_missing = allow_missing
  54. self.type_fixer = TypeFixer(self.modules, allow_missing)
  55. # NOTE: This method isn't (yet) part of the NodeVisitor API.
  56. def visit_type_info(self, info: TypeInfo) -> None:
  57. save_info = self.current_info
  58. try:
  59. self.current_info = info
  60. if info.defn:
  61. info.defn.accept(self)
  62. if info.names:
  63. self.visit_symbol_table(info.names, info.fullname)
  64. if info.bases:
  65. for base in info.bases:
  66. base.accept(self.type_fixer)
  67. if info._promote:
  68. for p in info._promote:
  69. p.accept(self.type_fixer)
  70. if info.tuple_type:
  71. info.tuple_type.accept(self.type_fixer)
  72. info.update_tuple_type(info.tuple_type)
  73. if info.special_alias:
  74. info.special_alias.alias_tvars = list(info.defn.type_vars)
  75. if info.typeddict_type:
  76. info.typeddict_type.accept(self.type_fixer)
  77. info.update_typeddict_type(info.typeddict_type)
  78. if info.special_alias:
  79. info.special_alias.alias_tvars = list(info.defn.type_vars)
  80. if info.declared_metaclass:
  81. info.declared_metaclass.accept(self.type_fixer)
  82. if info.metaclass_type:
  83. info.metaclass_type.accept(self.type_fixer)
  84. if info.alt_promote:
  85. info.alt_promote.accept(self.type_fixer)
  86. instance = Instance(info, [])
  87. # Hack: We may also need to add a backwards promotion (from int to native int),
  88. # since it might not be serialized.
  89. if instance not in info.alt_promote.type._promote:
  90. info.alt_promote.type._promote.append(instance)
  91. if info._mro_refs:
  92. info.mro = [
  93. lookup_fully_qualified_typeinfo(
  94. self.modules, name, allow_missing=self.allow_missing
  95. )
  96. for name in info._mro_refs
  97. ]
  98. info._mro_refs = None
  99. finally:
  100. self.current_info = save_info
  101. # NOTE: This method *definitely* isn't part of the NodeVisitor API.
  102. def visit_symbol_table(self, symtab: SymbolTable, table_fullname: str) -> None:
  103. # Copy the items because we may mutate symtab.
  104. for key, value in list(symtab.items()):
  105. cross_ref = value.cross_ref
  106. if cross_ref is not None: # Fix up cross-reference.
  107. value.cross_ref = None
  108. if cross_ref in self.modules:
  109. value.node = self.modules[cross_ref]
  110. else:
  111. stnode = lookup_fully_qualified(
  112. cross_ref, self.modules, raise_on_missing=not self.allow_missing
  113. )
  114. if stnode is not None:
  115. assert stnode.node is not None, (table_fullname + "." + key, cross_ref)
  116. value.node = stnode.node
  117. elif not self.allow_missing:
  118. assert False, f"Could not find cross-ref {cross_ref}"
  119. else:
  120. # We have a missing crossref in allow missing mode, need to put something
  121. value.node = missing_info(self.modules)
  122. else:
  123. if isinstance(value.node, TypeInfo):
  124. # TypeInfo has no accept(). TODO: Add it?
  125. self.visit_type_info(value.node)
  126. elif value.node is not None:
  127. value.node.accept(self)
  128. else:
  129. assert False, f"Unexpected empty node {key!r}: {value}"
  130. def visit_func_def(self, func: FuncDef) -> None:
  131. if self.current_info is not None:
  132. func.info = self.current_info
  133. if func.type is not None:
  134. func.type.accept(self.type_fixer)
  135. def visit_overloaded_func_def(self, o: OverloadedFuncDef) -> None:
  136. if self.current_info is not None:
  137. o.info = self.current_info
  138. if o.type:
  139. o.type.accept(self.type_fixer)
  140. for item in o.items:
  141. item.accept(self)
  142. if o.impl:
  143. o.impl.accept(self)
  144. def visit_decorator(self, d: Decorator) -> None:
  145. if self.current_info is not None:
  146. d.var.info = self.current_info
  147. if d.func:
  148. d.func.accept(self)
  149. if d.var:
  150. d.var.accept(self)
  151. for node in d.decorators:
  152. node.accept(self)
  153. def visit_class_def(self, c: ClassDef) -> None:
  154. for v in c.type_vars:
  155. if isinstance(v, TypeVarType):
  156. for value in v.values:
  157. value.accept(self.type_fixer)
  158. v.upper_bound.accept(self.type_fixer)
  159. v.default.accept(self.type_fixer)
  160. def visit_type_var_expr(self, tv: TypeVarExpr) -> None:
  161. for value in tv.values:
  162. value.accept(self.type_fixer)
  163. tv.upper_bound.accept(self.type_fixer)
  164. tv.default.accept(self.type_fixer)
  165. def visit_paramspec_expr(self, p: ParamSpecExpr) -> None:
  166. p.upper_bound.accept(self.type_fixer)
  167. p.default.accept(self.type_fixer)
  168. def visit_type_var_tuple_expr(self, tv: TypeVarTupleExpr) -> None:
  169. tv.upper_bound.accept(self.type_fixer)
  170. tv.default.accept(self.type_fixer)
  171. def visit_var(self, v: Var) -> None:
  172. if self.current_info is not None:
  173. v.info = self.current_info
  174. if v.type is not None:
  175. v.type.accept(self.type_fixer)
  176. def visit_type_alias(self, a: TypeAlias) -> None:
  177. a.target.accept(self.type_fixer)
  178. for v in a.alias_tvars:
  179. v.accept(self.type_fixer)
  180. class TypeFixer(TypeVisitor[None]):
  181. def __init__(self, modules: dict[str, MypyFile], allow_missing: bool) -> None:
  182. self.modules = modules
  183. self.allow_missing = allow_missing
  184. def visit_instance(self, inst: Instance) -> None:
  185. # TODO: Combine Instances that are exactly the same?
  186. type_ref = inst.type_ref
  187. if type_ref is None:
  188. return # We've already been here.
  189. inst.type_ref = None
  190. inst.type = lookup_fully_qualified_typeinfo(
  191. self.modules, type_ref, allow_missing=self.allow_missing
  192. )
  193. # TODO: Is this needed or redundant?
  194. # Also fix up the bases, just in case.
  195. for base in inst.type.bases:
  196. if base.type is NOT_READY:
  197. base.accept(self)
  198. for a in inst.args:
  199. a.accept(self)
  200. if inst.last_known_value is not None:
  201. inst.last_known_value.accept(self)
  202. def visit_type_alias_type(self, t: TypeAliasType) -> None:
  203. type_ref = t.type_ref
  204. if type_ref is None:
  205. return # We've already been here.
  206. t.type_ref = None
  207. t.alias = lookup_fully_qualified_alias(
  208. self.modules, type_ref, allow_missing=self.allow_missing
  209. )
  210. for a in t.args:
  211. a.accept(self)
  212. def visit_any(self, o: Any) -> None:
  213. pass # Nothing to descend into.
  214. def visit_callable_type(self, ct: CallableType) -> None:
  215. if ct.fallback:
  216. ct.fallback.accept(self)
  217. for argt in ct.arg_types:
  218. # argt may be None, e.g. for __self in NamedTuple constructors.
  219. if argt is not None:
  220. argt.accept(self)
  221. if ct.ret_type is not None:
  222. ct.ret_type.accept(self)
  223. for v in ct.variables:
  224. v.accept(self)
  225. for arg in ct.bound_args:
  226. if arg:
  227. arg.accept(self)
  228. if ct.type_guard is not None:
  229. ct.type_guard.accept(self)
  230. def visit_overloaded(self, t: Overloaded) -> None:
  231. for ct in t.items:
  232. ct.accept(self)
  233. def visit_erased_type(self, o: Any) -> None:
  234. # This type should exist only temporarily during type inference
  235. raise RuntimeError("Shouldn't get here", o)
  236. def visit_deleted_type(self, o: Any) -> None:
  237. pass # Nothing to descend into.
  238. def visit_none_type(self, o: Any) -> None:
  239. pass # Nothing to descend into.
  240. def visit_uninhabited_type(self, o: Any) -> None:
  241. pass # Nothing to descend into.
  242. def visit_partial_type(self, o: Any) -> None:
  243. raise RuntimeError("Shouldn't get here", o)
  244. def visit_tuple_type(self, tt: TupleType) -> None:
  245. if tt.items:
  246. for it in tt.items:
  247. it.accept(self)
  248. if tt.partial_fallback is not None:
  249. tt.partial_fallback.accept(self)
  250. def visit_typeddict_type(self, tdt: TypedDictType) -> None:
  251. if tdt.items:
  252. for it in tdt.items.values():
  253. it.accept(self)
  254. if tdt.fallback is not None:
  255. if tdt.fallback.type_ref is not None:
  256. if (
  257. lookup_fully_qualified(
  258. tdt.fallback.type_ref,
  259. self.modules,
  260. raise_on_missing=not self.allow_missing,
  261. )
  262. is None
  263. ):
  264. # We reject fake TypeInfos for TypedDict fallbacks because
  265. # the latter are used in type checking and must be valid.
  266. tdt.fallback.type_ref = "typing._TypedDict"
  267. tdt.fallback.accept(self)
  268. def visit_literal_type(self, lt: LiteralType) -> None:
  269. lt.fallback.accept(self)
  270. def visit_type_var(self, tvt: TypeVarType) -> None:
  271. if tvt.values:
  272. for vt in tvt.values:
  273. vt.accept(self)
  274. tvt.upper_bound.accept(self)
  275. tvt.default.accept(self)
  276. def visit_param_spec(self, p: ParamSpecType) -> None:
  277. p.upper_bound.accept(self)
  278. p.default.accept(self)
  279. def visit_type_var_tuple(self, t: TypeVarTupleType) -> None:
  280. t.upper_bound.accept(self)
  281. t.default.accept(self)
  282. def visit_unpack_type(self, u: UnpackType) -> None:
  283. u.type.accept(self)
  284. def visit_parameters(self, p: Parameters) -> None:
  285. for argt in p.arg_types:
  286. if argt is not None:
  287. argt.accept(self)
  288. for var in p.variables:
  289. var.accept(self)
  290. def visit_unbound_type(self, o: UnboundType) -> None:
  291. for a in o.args:
  292. a.accept(self)
  293. def visit_union_type(self, ut: UnionType) -> None:
  294. if ut.items:
  295. for it in ut.items:
  296. it.accept(self)
  297. def visit_void(self, o: Any) -> None:
  298. pass # Nothing to descend into.
  299. def visit_type_type(self, t: TypeType) -> None:
  300. t.item.accept(self)
  301. def lookup_fully_qualified_typeinfo(
  302. modules: dict[str, MypyFile], name: str, *, allow_missing: bool
  303. ) -> TypeInfo:
  304. stnode = lookup_fully_qualified(name, modules, raise_on_missing=not allow_missing)
  305. node = stnode.node if stnode else None
  306. if isinstance(node, TypeInfo):
  307. return node
  308. else:
  309. # Looks like a missing TypeInfo during an initial daemon load, put something there
  310. assert (
  311. allow_missing
  312. ), "Should never get here in normal mode, got {}:{} instead of TypeInfo".format(
  313. type(node).__name__, node.fullname if node else ""
  314. )
  315. return missing_info(modules)
  316. def lookup_fully_qualified_alias(
  317. modules: dict[str, MypyFile], name: str, *, allow_missing: bool
  318. ) -> TypeAlias:
  319. stnode = lookup_fully_qualified(name, modules, raise_on_missing=not allow_missing)
  320. node = stnode.node if stnode else None
  321. if isinstance(node, TypeAlias):
  322. return node
  323. elif isinstance(node, TypeInfo):
  324. if node.special_alias:
  325. # Already fixed up.
  326. return node.special_alias
  327. if node.tuple_type:
  328. alias = TypeAlias.from_tuple_type(node)
  329. elif node.typeddict_type:
  330. alias = TypeAlias.from_typeddict_type(node)
  331. else:
  332. assert allow_missing
  333. return missing_alias()
  334. node.special_alias = alias
  335. return alias
  336. else:
  337. # Looks like a missing TypeAlias during an initial daemon load, put something there
  338. assert (
  339. allow_missing
  340. ), "Should never get here in normal mode, got {}:{} instead of TypeAlias".format(
  341. type(node).__name__, node.fullname if node else ""
  342. )
  343. return missing_alias()
  344. _SUGGESTION: Final = "<missing {}: *should* have gone away during fine-grained update>"
  345. def missing_info(modules: dict[str, MypyFile]) -> TypeInfo:
  346. suggestion = _SUGGESTION.format("info")
  347. dummy_def = ClassDef(suggestion, Block([]))
  348. dummy_def.fullname = suggestion
  349. info = TypeInfo(SymbolTable(), dummy_def, "<missing>")
  350. obj_type = lookup_fully_qualified_typeinfo(modules, "builtins.object", allow_missing=False)
  351. info.bases = [Instance(obj_type, [])]
  352. info.mro = [info, obj_type]
  353. return info
  354. def missing_alias() -> TypeAlias:
  355. suggestion = _SUGGESTION.format("alias")
  356. return TypeAlias(AnyType(TypeOfAny.special_form), suggestion, line=-1, column=-1)