Debian Codegraph @

test-data/unit/plugins/dyn_class.py

raw
1 from __future__ import annotations
2
3 from typing import Callable
4
5 from mypy.nodes import GDEF, Block, ClassDef, SymbolTable, SymbolTableNode, TypeInfo, Var
6 from mypy.plugin import ClassDefContext, DynamicClassDefContext, Plugin
7 from mypy.types import Instance, get_proper_type
8
9 DECL_BASES: set[str] = set()
10
11
12 class DynPlugin(Plugin):
13 def get_dynamic_class_hook(
14 self, fullname: str
15 ) -> Callable[[DynamicClassDefContext], None] | None:
16 if fullname == "mod.declarative_base":
17 return add_info_hook
18 return None
19
20 def get_base_class_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None:
21 if fullname in DECL_BASES:
22 return replace_col_hook
23 return None
24
25
26 def add_info_hook(ctx: DynamicClassDefContext) -> None:
27 class_def = ClassDef(ctx.name, Block([]))
28 class_def.fullname = ctx.api.qualified_name(ctx.name)
29
30 info = TypeInfo(SymbolTable(), class_def, ctx.api.cur_mod_id)
31 class_def.info = info
32 obj = ctx.api.named_type("builtins.object")
33 info.mro = [info, obj.type]
34 info.bases = [obj]
35 ctx.api.add_symbol_table_node(ctx.name, SymbolTableNode(GDEF, info))
36 DECL_BASES.add(class_def.fullname)
37
38
39 def replace_col_hook(ctx: ClassDefContext) -> None:
40 info = ctx.cls.info
41 for sym in info.names.values():
42 node = sym.node
43 if isinstance(node, Var) and isinstance(
44 (node_type := get_proper_type(node.type)), Instance
45 ):
46 if node_type.type.fullname == "mod.Column":
47 new_sym = ctx.api.lookup_fully_qualified_or_none("mod.Instr")
48 if new_sym:
49 new_info = new_sym.node
50 assert isinstance(new_info, TypeInfo)
51 node.type = Instance(
52 new_info, node_type.args, node_type.line, node_type.column
53 )
54
55
56 def plugin(version: str) -> type[DynPlugin]:
57 return DynPlugin