astmerge.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. """Merge a new version of a module AST and symbol table to older versions of those.
  2. When the source code of a module has a change in fine-grained incremental mode,
  3. we build a new AST from the updated source. However, other parts of the program
  4. may have direct references to parts of the old AST (namely, those nodes exposed
  5. in the module symbol table). The merge operation changes the identities of new
  6. AST nodes that have a correspondence in the old AST to the old ones so that
  7. existing cross-references in other modules will continue to point to the correct
  8. nodes. Also internal cross-references within the new AST are replaced. AST nodes
  9. that aren't externally visible will get new, distinct object identities. This
  10. applies to most expression and statement nodes, for example.
  11. We perform this merge operation so that we don't have to update all
  12. external references (which would be slow and fragile) or always perform
  13. translation when looking up references (which would be hard to retrofit).
  14. The AST merge operation is performed after semantic analysis. Semantic
  15. analysis has to deal with potentially multiple aliases to certain AST
  16. nodes (in particular, MypyFile nodes). Type checking assumes that we
  17. don't have multiple variants of a single AST node visible to the type
  18. checker.
  19. Discussion of some notable special cases:
  20. * If a node is replaced with a different kind of node (say, a function is
  21. replaced with a class), we don't perform the merge. Fine-grained dependencies
  22. will be used to rebind all references to the node.
  23. * If a function is replaced with another function with an identical signature,
  24. call sites continue to point to the same object (by identity) and don't need
  25. to be reprocessed. Similarly, if a class is replaced with a class that is
  26. sufficiently similar (MRO preserved, etc.), class references don't need any
  27. processing. A typical incremental update to a file only changes a few
  28. externally visible things in a module, and this means that often only few
  29. external references need any processing, even if the modified module is large.
  30. * A no-op update of a module should not require any processing outside the
  31. module, since all relevant object identities are preserved.
  32. * The AST diff operation (mypy.server.astdiff) and the top-level fine-grained
  33. incremental logic (mypy.server.update) handle the cases where the new AST has
  34. differences from the old one that may need to be propagated to elsewhere in the
  35. program.
  36. See the main entry point merge_asts for more details.
  37. """
  38. from __future__ import annotations
  39. from typing import TypeVar, cast
  40. from mypy.nodes import (
  41. MDEF,
  42. AssertTypeExpr,
  43. AssignmentStmt,
  44. Block,
  45. CallExpr,
  46. CastExpr,
  47. ClassDef,
  48. EnumCallExpr,
  49. FuncBase,
  50. FuncDef,
  51. LambdaExpr,
  52. MemberExpr,
  53. MypyFile,
  54. NamedTupleExpr,
  55. NameExpr,
  56. NewTypeExpr,
  57. OverloadedFuncDef,
  58. RefExpr,
  59. Statement,
  60. SuperExpr,
  61. SymbolNode,
  62. SymbolTable,
  63. TypeAlias,
  64. TypeAliasExpr,
  65. TypedDictExpr,
  66. TypeInfo,
  67. Var,
  68. )
  69. from mypy.traverser import TraverserVisitor
  70. from mypy.types import (
  71. AnyType,
  72. CallableArgument,
  73. CallableType,
  74. DeletedType,
  75. EllipsisType,
  76. ErasedType,
  77. Instance,
  78. LiteralType,
  79. NoneType,
  80. Overloaded,
  81. Parameters,
  82. ParamSpecType,
  83. PartialType,
  84. PlaceholderType,
  85. RawExpressionType,
  86. SyntheticTypeVisitor,
  87. TupleType,
  88. Type,
  89. TypeAliasType,
  90. TypedDictType,
  91. TypeList,
  92. TypeType,
  93. TypeVarTupleType,
  94. TypeVarType,
  95. UnboundType,
  96. UninhabitedType,
  97. UnionType,
  98. UnpackType,
  99. )
  100. from mypy.typestate import type_state
  101. from mypy.util import get_prefix, replace_object_state
  102. def merge_asts(
  103. old: MypyFile, old_symbols: SymbolTable, new: MypyFile, new_symbols: SymbolTable
  104. ) -> None:
  105. """Merge a new version of a module AST to a previous version.
  106. The main idea is to preserve the identities of externally visible
  107. nodes in the old AST (that have a corresponding node in the new AST).
  108. All old node state (outside identity) will come from the new AST.
  109. When this returns, 'old' will refer to the merged AST, but 'new_symbols'
  110. will be the new symbol table. 'new' and 'old_symbols' will no longer be
  111. valid.
  112. """
  113. assert new.fullname == old.fullname
  114. # Find the mapping from new to old node identities for all nodes
  115. # whose identities should be preserved.
  116. replacement_map = replacement_map_from_symbol_table(
  117. old_symbols, new_symbols, prefix=old.fullname
  118. )
  119. # Also replace references to the new MypyFile node.
  120. replacement_map[new] = old
  121. # Perform replacements to everywhere within the new AST (not including symbol
  122. # tables).
  123. node = replace_nodes_in_ast(new, replacement_map)
  124. assert node is old
  125. # Also replace AST node references in the *new* symbol table (we'll
  126. # continue to use the new symbol table since it has all the new definitions
  127. # that have no correspondence in the old AST).
  128. replace_nodes_in_symbol_table(new_symbols, replacement_map)
  129. def replacement_map_from_symbol_table(
  130. old: SymbolTable, new: SymbolTable, prefix: str
  131. ) -> dict[SymbolNode, SymbolNode]:
  132. """Create a new-to-old object identity map by comparing two symbol table revisions.
  133. Both symbol tables must refer to revisions of the same module id. The symbol tables
  134. are compared recursively (recursing into nested class symbol tables), but only within
  135. the given module prefix. Don't recurse into other modules accessible through the symbol
  136. table.
  137. """
  138. replacements: dict[SymbolNode, SymbolNode] = {}
  139. for name, node in old.items():
  140. if name in new and (
  141. node.kind == MDEF or node.node and get_prefix(node.node.fullname) == prefix
  142. ):
  143. new_node = new[name]
  144. if (
  145. type(new_node.node) == type(node.node) # noqa: E721
  146. and new_node.node
  147. and node.node
  148. and new_node.node.fullname == node.node.fullname
  149. and new_node.kind == node.kind
  150. ):
  151. replacements[new_node.node] = node.node
  152. if isinstance(node.node, TypeInfo) and isinstance(new_node.node, TypeInfo):
  153. type_repl = replacement_map_from_symbol_table(
  154. node.node.names, new_node.node.names, prefix
  155. )
  156. replacements.update(type_repl)
  157. if node.node.special_alias and new_node.node.special_alias:
  158. replacements[new_node.node.special_alias] = node.node.special_alias
  159. return replacements
  160. def replace_nodes_in_ast(
  161. node: SymbolNode, replacements: dict[SymbolNode, SymbolNode]
  162. ) -> SymbolNode:
  163. """Replace all references to replacement map keys within an AST node, recursively.
  164. Also replace the *identity* of any nodes that have replacements. Return the
  165. *replaced* version of the argument node (which may have a different identity, if
  166. it's included in the replacement map).
  167. """
  168. visitor = NodeReplaceVisitor(replacements)
  169. node.accept(visitor)
  170. return replacements.get(node, node)
  171. SN = TypeVar("SN", bound=SymbolNode)
  172. class NodeReplaceVisitor(TraverserVisitor):
  173. """Transform some nodes to new identities in an AST.
  174. Only nodes that live in the symbol table may be
  175. replaced, which simplifies the implementation some. Also
  176. replace all references to the old identities.
  177. """
  178. def __init__(self, replacements: dict[SymbolNode, SymbolNode]) -> None:
  179. self.replacements = replacements
  180. def visit_mypy_file(self, node: MypyFile) -> None:
  181. node = self.fixup(node)
  182. node.defs = self.replace_statements(node.defs)
  183. super().visit_mypy_file(node)
  184. def visit_block(self, node: Block) -> None:
  185. node.body = self.replace_statements(node.body)
  186. super().visit_block(node)
  187. def visit_func_def(self, node: FuncDef) -> None:
  188. node = self.fixup(node)
  189. self.process_base_func(node)
  190. super().visit_func_def(node)
  191. def visit_overloaded_func_def(self, node: OverloadedFuncDef) -> None:
  192. self.process_base_func(node)
  193. super().visit_overloaded_func_def(node)
  194. def visit_class_def(self, node: ClassDef) -> None:
  195. # TODO additional things?
  196. node.info = self.fixup_and_reset_typeinfo(node.info)
  197. node.defs.body = self.replace_statements(node.defs.body)
  198. info = node.info
  199. for tv in node.type_vars:
  200. if isinstance(tv, TypeVarType):
  201. self.process_type_var_def(tv)
  202. if info:
  203. if info.is_named_tuple:
  204. self.process_synthetic_type_info(info)
  205. else:
  206. self.process_type_info(info)
  207. super().visit_class_def(node)
  208. def process_base_func(self, node: FuncBase) -> None:
  209. self.fixup_type(node.type)
  210. node.info = self.fixup(node.info)
  211. if node.unanalyzed_type:
  212. # Unanalyzed types can have AST node references
  213. self.fixup_type(node.unanalyzed_type)
  214. def process_type_var_def(self, tv: TypeVarType) -> None:
  215. for value in tv.values:
  216. self.fixup_type(value)
  217. self.fixup_type(tv.upper_bound)
  218. self.fixup_type(tv.default)
  219. def process_param_spec_def(self, tv: ParamSpecType) -> None:
  220. self.fixup_type(tv.upper_bound)
  221. self.fixup_type(tv.default)
  222. def process_type_var_tuple_def(self, tv: TypeVarTupleType) -> None:
  223. self.fixup_type(tv.upper_bound)
  224. self.fixup_type(tv.default)
  225. def visit_assignment_stmt(self, node: AssignmentStmt) -> None:
  226. self.fixup_type(node.type)
  227. super().visit_assignment_stmt(node)
  228. # Expressions
  229. def visit_name_expr(self, node: NameExpr) -> None:
  230. self.visit_ref_expr(node)
  231. def visit_member_expr(self, node: MemberExpr) -> None:
  232. if node.def_var:
  233. node.def_var = self.fixup(node.def_var)
  234. self.visit_ref_expr(node)
  235. super().visit_member_expr(node)
  236. def visit_ref_expr(self, node: RefExpr) -> None:
  237. if node.node is not None:
  238. node.node = self.fixup(node.node)
  239. if isinstance(node.node, Var):
  240. # The Var node may be an orphan and won't otherwise be processed.
  241. node.node.accept(self)
  242. def visit_namedtuple_expr(self, node: NamedTupleExpr) -> None:
  243. super().visit_namedtuple_expr(node)
  244. node.info = self.fixup_and_reset_typeinfo(node.info)
  245. self.process_synthetic_type_info(node.info)
  246. def visit_cast_expr(self, node: CastExpr) -> None:
  247. super().visit_cast_expr(node)
  248. self.fixup_type(node.type)
  249. def visit_assert_type_expr(self, node: AssertTypeExpr) -> None:
  250. super().visit_assert_type_expr(node)
  251. self.fixup_type(node.type)
  252. def visit_super_expr(self, node: SuperExpr) -> None:
  253. super().visit_super_expr(node)
  254. if node.info is not None:
  255. node.info = self.fixup(node.info)
  256. def visit_call_expr(self, node: CallExpr) -> None:
  257. super().visit_call_expr(node)
  258. if isinstance(node.analyzed, SymbolNode):
  259. node.analyzed = self.fixup(node.analyzed)
  260. def visit_newtype_expr(self, node: NewTypeExpr) -> None:
  261. if node.info:
  262. node.info = self.fixup_and_reset_typeinfo(node.info)
  263. self.process_synthetic_type_info(node.info)
  264. self.fixup_type(node.old_type)
  265. super().visit_newtype_expr(node)
  266. def visit_lambda_expr(self, node: LambdaExpr) -> None:
  267. node.info = self.fixup(node.info)
  268. super().visit_lambda_expr(node)
  269. def visit_typeddict_expr(self, node: TypedDictExpr) -> None:
  270. super().visit_typeddict_expr(node)
  271. node.info = self.fixup_and_reset_typeinfo(node.info)
  272. self.process_synthetic_type_info(node.info)
  273. def visit_enum_call_expr(self, node: EnumCallExpr) -> None:
  274. node.info = self.fixup_and_reset_typeinfo(node.info)
  275. self.process_synthetic_type_info(node.info)
  276. super().visit_enum_call_expr(node)
  277. def visit_type_alias_expr(self, node: TypeAliasExpr) -> None:
  278. self.fixup_type(node.type)
  279. super().visit_type_alias_expr(node)
  280. # Others
  281. def visit_var(self, node: Var) -> None:
  282. node.info = self.fixup(node.info)
  283. self.fixup_type(node.type)
  284. super().visit_var(node)
  285. def visit_type_alias(self, node: TypeAlias) -> None:
  286. self.fixup_type(node.target)
  287. for v in node.alias_tvars:
  288. self.fixup_type(v)
  289. super().visit_type_alias(node)
  290. # Helpers
  291. def fixup(self, node: SN) -> SN:
  292. if node in self.replacements:
  293. new = self.replacements[node]
  294. skip_slots: tuple[str, ...] = ()
  295. if isinstance(node, TypeInfo) and isinstance(new, TypeInfo):
  296. # Special case: special_alias is not exposed in symbol tables, but may appear
  297. # in external types (e.g. named tuples), so we need to update it manually.
  298. skip_slots = ("special_alias",)
  299. replace_object_state(new.special_alias, node.special_alias)
  300. replace_object_state(new, node, skip_slots=skip_slots)
  301. return cast(SN, new)
  302. return node
  303. def fixup_and_reset_typeinfo(self, node: TypeInfo) -> TypeInfo:
  304. """Fix-up type info and reset subtype caches.
  305. This needs to be called at least once per each merged TypeInfo, as otherwise we
  306. may leak stale caches.
  307. """
  308. if node in self.replacements:
  309. # The subclass relationships may change, so reset all caches relevant to the
  310. # old MRO.
  311. new = self.replacements[node]
  312. assert isinstance(new, TypeInfo)
  313. type_state.reset_all_subtype_caches_for(new)
  314. return self.fixup(node)
  315. def fixup_type(self, typ: Type | None) -> None:
  316. if typ is not None:
  317. typ.accept(TypeReplaceVisitor(self.replacements))
  318. def process_type_info(self, info: TypeInfo | None) -> None:
  319. if info is None:
  320. return
  321. self.fixup_type(info.declared_metaclass)
  322. self.fixup_type(info.metaclass_type)
  323. for target in info._promote:
  324. self.fixup_type(target)
  325. self.fixup_type(info.tuple_type)
  326. self.fixup_type(info.typeddict_type)
  327. if info.special_alias:
  328. self.fixup_type(info.special_alias.target)
  329. info.defn.info = self.fixup(info)
  330. replace_nodes_in_symbol_table(info.names, self.replacements)
  331. for i, item in enumerate(info.mro):
  332. info.mro[i] = self.fixup(info.mro[i])
  333. for i, base in enumerate(info.bases):
  334. self.fixup_type(info.bases[i])
  335. def process_synthetic_type_info(self, info: TypeInfo) -> None:
  336. # Synthetic types (types not created using a class statement) don't
  337. # have bodies in the AST so we need to iterate over their symbol
  338. # tables separately, unlike normal classes.
  339. self.process_type_info(info)
  340. for name, node in info.names.items():
  341. if node.node:
  342. node.node.accept(self)
  343. def replace_statements(self, nodes: list[Statement]) -> list[Statement]:
  344. result = []
  345. for node in nodes:
  346. if isinstance(node, SymbolNode):
  347. node = self.fixup(node)
  348. result.append(node)
  349. return result
  350. class TypeReplaceVisitor(SyntheticTypeVisitor[None]):
  351. """Similar to NodeReplaceVisitor, but for type objects.
  352. Note: this visitor may sometimes visit unanalyzed types
  353. such as 'UnboundType' and 'RawExpressionType' For example, see
  354. NodeReplaceVisitor.process_base_func.
  355. """
  356. def __init__(self, replacements: dict[SymbolNode, SymbolNode]) -> None:
  357. self.replacements = replacements
  358. def visit_instance(self, typ: Instance) -> None:
  359. typ.type = self.fixup(typ.type)
  360. for arg in typ.args:
  361. arg.accept(self)
  362. if typ.last_known_value:
  363. typ.last_known_value.accept(self)
  364. def visit_type_alias_type(self, typ: TypeAliasType) -> None:
  365. assert typ.alias is not None
  366. typ.alias = self.fixup(typ.alias)
  367. for arg in typ.args:
  368. arg.accept(self)
  369. def visit_any(self, typ: AnyType) -> None:
  370. pass
  371. def visit_none_type(self, typ: NoneType) -> None:
  372. pass
  373. def visit_callable_type(self, typ: CallableType) -> None:
  374. for arg in typ.arg_types:
  375. arg.accept(self)
  376. typ.ret_type.accept(self)
  377. if typ.definition:
  378. # No need to fixup since this is just a cross-reference.
  379. typ.definition = self.replacements.get(typ.definition, typ.definition)
  380. # Fallback can be None for callable types that haven't been semantically analyzed.
  381. if typ.fallback is not None:
  382. typ.fallback.accept(self)
  383. for tv in typ.variables:
  384. if isinstance(tv, TypeVarType):
  385. tv.upper_bound.accept(self)
  386. for value in tv.values:
  387. value.accept(self)
  388. def visit_overloaded(self, t: Overloaded) -> None:
  389. for item in t.items:
  390. item.accept(self)
  391. # Fallback can be None for overloaded types that haven't been semantically analyzed.
  392. if t.fallback is not None:
  393. t.fallback.accept(self)
  394. def visit_erased_type(self, t: ErasedType) -> None:
  395. # This type should exist only temporarily during type inference
  396. raise RuntimeError
  397. def visit_deleted_type(self, typ: DeletedType) -> None:
  398. pass
  399. def visit_partial_type(self, typ: PartialType) -> None:
  400. raise RuntimeError
  401. def visit_tuple_type(self, typ: TupleType) -> None:
  402. for item in typ.items:
  403. item.accept(self)
  404. # Fallback can be None for implicit tuple types that haven't been semantically analyzed.
  405. if typ.partial_fallback is not None:
  406. typ.partial_fallback.accept(self)
  407. def visit_type_type(self, typ: TypeType) -> None:
  408. typ.item.accept(self)
  409. def visit_type_var(self, typ: TypeVarType) -> None:
  410. typ.upper_bound.accept(self)
  411. typ.default.accept(self)
  412. for value in typ.values:
  413. value.accept(self)
  414. def visit_param_spec(self, typ: ParamSpecType) -> None:
  415. typ.upper_bound.accept(self)
  416. typ.default.accept(self)
  417. def visit_type_var_tuple(self, typ: TypeVarTupleType) -> None:
  418. typ.upper_bound.accept(self)
  419. typ.default.accept(self)
  420. def visit_unpack_type(self, typ: UnpackType) -> None:
  421. typ.type.accept(self)
  422. def visit_parameters(self, typ: Parameters) -> None:
  423. for arg in typ.arg_types:
  424. arg.accept(self)
  425. def visit_typeddict_type(self, typ: TypedDictType) -> None:
  426. for value_type in typ.items.values():
  427. value_type.accept(self)
  428. typ.fallback.accept(self)
  429. def visit_raw_expression_type(self, t: RawExpressionType) -> None:
  430. pass
  431. def visit_literal_type(self, typ: LiteralType) -> None:
  432. typ.fallback.accept(self)
  433. def visit_unbound_type(self, typ: UnboundType) -> None:
  434. for arg in typ.args:
  435. arg.accept(self)
  436. def visit_type_list(self, typ: TypeList) -> None:
  437. for item in typ.items:
  438. item.accept(self)
  439. def visit_callable_argument(self, typ: CallableArgument) -> None:
  440. typ.typ.accept(self)
  441. def visit_ellipsis_type(self, typ: EllipsisType) -> None:
  442. pass
  443. def visit_uninhabited_type(self, typ: UninhabitedType) -> None:
  444. pass
  445. def visit_union_type(self, typ: UnionType) -> None:
  446. for item in typ.items:
  447. item.accept(self)
  448. def visit_placeholder_type(self, t: PlaceholderType) -> None:
  449. for item in t.args:
  450. item.accept(self)
  451. # Helpers
  452. def fixup(self, node: SN) -> SN:
  453. if node in self.replacements:
  454. new = self.replacements[node]
  455. return cast(SN, new)
  456. return node
  457. def replace_nodes_in_symbol_table(
  458. symbols: SymbolTable, replacements: dict[SymbolNode, SymbolNode]
  459. ) -> None:
  460. for name, node in symbols.items():
  461. if node.node:
  462. if node.node in replacements:
  463. new = replacements[node.node]
  464. old = node.node
  465. # Needed for TypeInfo, see comment in fixup() above.
  466. replace_object_state(new, old, skip_slots=("special_alias",))
  467. node.node = new
  468. if isinstance(node.node, (Var, TypeAlias)):
  469. # Handle them here just in case these aren't exposed through the AST.
  470. node.node.accept(NodeReplaceVisitor(replacements))