Debian Codegraph @

test-data/unit/plugins/common_api_incremental.py

raw
1 from __future__ import annotations
2
3 from typing import Callable
4
5 from mypy.nodes import GDEF, MDEF, Block, ClassDef, SymbolTable, SymbolTableNode, TypeInfo, Var
6 from mypy.plugin import ClassDefContext, DynamicClassDefContext, Plugin
7
8
9 class DynPlugin(Plugin):
10 def get_dynamic_class_hook(
11 self, fullname: str
12 ) -> Callable[[DynamicClassDefContext], None] | None:
13 if fullname == "lib.declarative_base":
14 return add_info_hook
15 return None
16
17 def get_base_class_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None:
18 sym = self.lookup_fully_qualified(fullname)
19 if sym and isinstance(sym.node, TypeInfo):
20 if sym.node.metadata.get("magic"):
21 return add_magic_hook
22 return None
23
24
25 def add_info_hook(ctx: DynamicClassDefContext) -> None:
26 class_def = ClassDef(ctx.name, Block([]))
27 class_def.fullname = ctx.api.qualified_name(ctx.name)
28
29 info = TypeInfo(SymbolTable(), class_def, ctx.api.cur_mod_id)
30 class_def.info = info
31 obj = ctx.api.named_type("builtins.object", [])
32 info.mro = [info, obj.type]
33 info.bases = [obj]
34 ctx.api.add_symbol_table_node(ctx.name, SymbolTableNode(GDEF, info))
35 info.metadata["magic"] = {"value": True}
36
37
38 def add_magic_hook(ctx: ClassDefContext) -> None:
39 info = ctx.cls.info
40 str_type = ctx.api.named_type_or_none("builtins.str", [])
41 assert str_type is not None
42 var = Var("__magic__", str_type)
43 var.info = info
44 info.names["__magic__"] = SymbolTableNode(MDEF, var)
45
46
47 def plugin(version: str) -> type[DynPlugin]:
48 return DynPlugin