pystepmap-core 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pystepmap/resolve.py ADDED
@@ -0,0 +1,605 @@
1
+ """调用解析:判断一个调用指向哪个项目内函数——精确、带标记的猜测、项目外,或无法判断。
2
+
3
+ 宁可答 unresolved 也不连错线:任何一层拿不准都往下一层走,最后仍不确定就放弃。
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import ast
9
+ import builtins
10
+ from collections.abc import Iterator
11
+ from dataclasses import dataclass
12
+
13
+ from .index import ClassInfo, FunctionInfo, ModuleInfo, ProjectIndex, import_bindings
14
+ from .model import Resolution
15
+
16
+ # 方法名太常见时,即使项目里只有一个定义也不猜
17
+ COMMON_NAMES = frozenset({"get", "set", "delete", "run", "execute", "commit", "close", "add", "send",
18
+ "start", "stop", "list", "create", "update", "save", "load"})
19
+
20
+ # 常见内置 / 标准库类型(str、bytes、list、dict、set、tuple、int、float、io.IOBase、io.TextIOWrapper、io.BytesIO、
21
+ # pathlib.Path、re.Pattern、re.Match、datetime 的 datetime / date / timedelta、asyncio 的 Future / Task / Queue / Lock /
22
+ # Event、logging.Logger、threading.Thread、subprocess.Popen、生成器、协程、异步生成器)上可调用、不以 _ 开头的方法名:
23
+ # 接收者类型未知时,x.open()、x.read() 多半调用的是它们的方法,这些方法名不按名字推测。写死成清单(Python 3.12 与
24
+ # 3.13 算出的并集),分析结果不随运行的 Python 版本变;重新生成见 core/tests/builtin_method_names.py。
25
+ BUILTIN_METHOD_NAMES = frozenset({
26
+ "absolute", "aclose", "acquire", "add", "addFilter", "addHandler", "add_done_callback", "append",
27
+ "as_integer_ratio", "as_posix", "as_uri", "asend", "astimezone", "athrow", "bit_count", "bit_length",
28
+ "callHandlers", "cancel", "cancelled", "cancelling", "capitalize", "casefold", "center", "chmod", "clear",
29
+ "close", "combine", "communicate", "conjugate", "copy", "count", "critical", "ctime", "cwd", "date", "debug",
30
+ "decode", "detach", "difference", "difference_update", "discard", "done", "dst", "empty", "encode", "end",
31
+ "endswith", "error", "exception", "exists", "expand", "expandtabs", "expanduser", "extend", "fatal", "fileno",
32
+ "filter", "find", "findCaller", "findall", "finditer", "flush", "format", "format_map", "from_bytes",
33
+ "from_uri", "fromhex", "fromisocalendar", "fromisoformat", "fromkeys", "fromordinal", "fromtimestamp", "full",
34
+ "full_match", "fullmatch", "get", "getChild", "getChildren", "getEffectiveLevel", "getName", "get_context",
35
+ "get_coro", "get_loop", "get_name", "get_nowait", "get_stack", "getbuffer", "getvalue", "glob", "group",
36
+ "groupdict", "groups", "handle", "hardlink_to", "hasHandlers", "hex", "home", "index", "info", "insert",
37
+ "intersection", "intersection_update", "isDaemon", "isEnabledFor", "is_absolute", "is_alive", "is_block_device",
38
+ "is_char_device", "is_dir", "is_fifo", "is_file", "is_integer", "is_junction", "is_mount", "is_relative_to",
39
+ "is_reserved", "is_set", "is_socket", "is_symlink", "isalnum", "isalpha", "isascii", "isatty", "isdecimal",
40
+ "isdigit", "isdisjoint", "isidentifier", "islower", "isnumeric", "isocalendar", "isoformat", "isoweekday",
41
+ "isprintable", "isspace", "issubset", "issuperset", "istitle", "isupper", "items", "iterdir", "join",
42
+ "joinpath", "keys", "kill", "lchmod", "ljust", "locked", "log", "lower", "lstat", "lstrip", "makeRecord",
43
+ "maketrans", "match", "mkdir", "now", "open", "owner", "partition", "poll", "pop", "popitem", "print_stack",
44
+ "put", "put_nowait", "qsize", "read", "read1", "read_bytes", "read_text", "readable", "readinto", "readinto1",
45
+ "readline", "readlines", "readlink", "reconfigure", "relative_to", "release", "remove", "removeFilter",
46
+ "removeHandler", "remove_done_callback", "removeprefix", "removesuffix", "rename", "replace", "resolve",
47
+ "result", "reverse", "rfind", "rglob", "rindex", "rjust", "rmdir", "rpartition", "rsplit", "rstrip", "run",
48
+ "samefile", "scanner", "search", "seek", "seekable", "send", "send_signal", "set", "setDaemon", "setLevel",
49
+ "setName", "set_exception", "set_name", "set_result", "setdefault", "shutdown", "sort", "span", "split",
50
+ "splitlines", "start", "startswith", "stat", "strftime", "strip", "strptime", "sub", "subn", "swapcase",
51
+ "symlink_to", "symmetric_difference", "symmetric_difference_update", "task_done", "tell", "terminate", "throw",
52
+ "time", "timestamp", "timetuple", "timetz", "title", "to_bytes", "today", "toordinal", "total_seconds", "touch",
53
+ "translate", "truncate", "tzname", "uncancel", "union", "unlink", "update", "upper", "utcfromtimestamp",
54
+ "utcnow", "utcoffset", "utctimetuple", "values", "wait", "walk", "warn", "warning", "weekday", "with_name",
55
+ "with_segments", "with_stem", "with_suffix", "writable", "write", "write_bytes", "write_text", "writelines",
56
+ "zfill"
57
+ })
58
+
59
+ _BUILTIN_NAMES = frozenset(dir(builtins))
60
+ _LITERALS = (ast.Constant, ast.JoinedStr, ast.List, ast.Dict, ast.Set, ast.Tuple,
61
+ ast.ListComp, ast.DictComp, ast.SetComp)
62
+ _PROTOCOLS = frozenset({"typing.Protocol", "typing_extensions.Protocol"})
63
+ _THREAD_WRAPPERS = frozenset({"asyncio.to_thread"}) # 把函数交给别的线程执行:第一个参数是被执行的函数
64
+
65
+ # 符号:("func", key) / ("class", ClassInfo) / ("inst", ClassInfo) / ("module", 点分名) / ("external",)
66
+ # / ("cls", ClassInfo):classmethod 的首参,是这个类或它的某个子类本身(取属性同类和实例,调用见 _cls_call)
67
+ Sym = tuple | None
68
+
69
+
70
+ @dataclass
71
+ class Resolved:
72
+ target: str | None # 函数 key
73
+ how: Resolution
74
+ display: str # "svc.match_with_auth"、"load_raw"
75
+ constructor: bool = False # 调用的是项目内的类本身,target 是它(或最近的项目基类)的 __init__
76
+
77
+
78
+ def _is_stub(node: ast.FunctionDef | ast.AsyncFunctionDef) -> bool:
79
+ """方法体只是占位:...、pass、只有文档注释、raise NotImplementedError(可以带文档注释)。"""
80
+ body = node.body[1:] if ast.get_docstring(node) is not None else node.body
81
+ for st in body:
82
+ if isinstance(st, ast.Pass) or (isinstance(st, ast.Expr) and isinstance(st.value, ast.Constant)
83
+ and st.value.value is Ellipsis):
84
+ continue
85
+ if isinstance(st, ast.Raise):
86
+ exc = st.exc.func if isinstance(st.exc, ast.Call) else st.exc
87
+ if isinstance(exc, ast.Name) and exc.id == "NotImplementedError":
88
+ continue
89
+ return False
90
+ return True
91
+
92
+
93
+ def _short(e: ast.expr) -> str:
94
+ """接收者的显示名:只留最后一个部分。"""
95
+ if isinstance(e, ast.Name):
96
+ return e.id
97
+ if isinstance(e, ast.Attribute):
98
+ return e.attr
99
+ if isinstance(e, ast.Call):
100
+ return _short(e.func)
101
+ if isinstance(e, ast.Subscript | ast.Await):
102
+ return _short(e.value)
103
+ return "…"
104
+
105
+
106
+ def _display(func: ast.expr) -> str:
107
+ if isinstance(func, ast.Name):
108
+ return func.id
109
+ if isinstance(func, ast.Attribute):
110
+ return f"{_short(func.value)}.{func.attr}"
111
+ # 被调用的是另一个调用的结果(f()())、下标取出来的东西(handlers[k]()):写出来,不和里面那个调用同名——
112
+ # 否则自检里"目标不明:f"看上去像是 f 本身没解析到,其实不明的是它返回的东西
113
+ if isinstance(func, ast.Call):
114
+ return f"{_display(func.func)}()"
115
+ if isinstance(func, ast.Subscript):
116
+ return f"{_short(func.value)}[…]"
117
+ return _short(func)
118
+
119
+
120
+ def dotted_name_of(e: ast.expr, mod: ModuleInfo) -> str | None:
121
+ """名字或属性链在本模块里的点分全名(根名按 import 展开);其他表达式为 None。"""
122
+ parts: list[str] = []
123
+ while isinstance(e, ast.Attribute):
124
+ parts.append(e.attr)
125
+ e = e.value
126
+ if not isinstance(e, ast.Name):
127
+ return None
128
+ return ".".join([mod.imports.get(e.id, e.id), *reversed(parts)])
129
+
130
+
131
+ def unwrap_thread_call(call: ast.Call, mod: ModuleInfo) -> ast.Call:
132
+ """把函数交给别的线程执行,等于在那个线程里调用它:asyncio.to_thread(f, *a, **kw) → f(*a, **kw),
133
+ <事件循环>.run_in_executor(执行器, f, *a) → f(*a)。f 要直接写出名字或属性,或者是没有参数、体是一次调用的
134
+ lambda(to_thread(lambda: g(…)) → g(…),后面不能再有给它的参数);别的 lambda、partial(...) 等不展开(lambda 体里
135
+ 的调用照样算外层函数的调用,进 call_targets,只是不成步骤的调用)。返回代表被执行的那次调用的节点(位置同原调用,
136
+ 每次新建);其他调用原样返回。构建函数图和约束检查共用。"""
137
+ args = call.args
138
+ if args and dotted_name_of(call.func, mod) in _THREAD_WRAPPERS:
139
+ func, rest, keywords = args[0], args[1:], call.keywords
140
+ elif isinstance(call.func, ast.Attribute) and call.func.attr == "run_in_executor" and len(args) >= 2 \
141
+ and not isinstance(args[0], ast.Starred):
142
+ func, rest, keywords = args[1], args[2:], []
143
+ else:
144
+ return call
145
+ if isinstance(func, ast.Lambda) and _no_params(func.args) and isinstance(func.body, ast.Call) \
146
+ and not rest and not keywords:
147
+ func, rest, keywords = func.body.func, func.body.args, func.body.keywords
148
+ elif not isinstance(func, ast.Name | ast.Attribute):
149
+ return call
150
+ return ast.copy_location(ast.Call(func=func, args=rest, keywords=keywords), call)
151
+
152
+
153
+ def _no_params(a: ast.arguments) -> bool:
154
+ return not (a.posonlyargs or a.args or a.vararg or a.kwonlyargs or a.kwarg)
155
+
156
+
157
+ def _value_exprs(e: ast.expr | None) -> Iterator[ast.expr]:
158
+ """作为值出现的名字 / 属性:e 本身,或列表、元组、集合字面量里的元素(可以嵌套)。"""
159
+ if isinstance(e, ast.Starred):
160
+ e = e.value
161
+ if isinstance(e, ast.Name | ast.Attribute):
162
+ yield e
163
+ elif isinstance(e, ast.List | ast.Tuple | ast.Set):
164
+ for x in e.elts:
165
+ yield from _value_exprs(x)
166
+
167
+
168
+ class Resolver:
169
+ def __init__(self, index: ProjectIndex):
170
+ self.index = index
171
+ self._tops = {d.split(".")[0] for d in [*index.by_dotted, *index.ambiguous]} # 项目内模块的顶层名
172
+ self._locals_cache: dict[str, dict[str, Sym]] = {}
173
+ self._inner: dict[tuple[str, str], str] | None = None
174
+ self._by_name: dict[str, set[str]] | None = None
175
+ self._protocol_methods: set[str] = set() # 协议类上的空方法 key,随 _names() 一起建
176
+ self._module_functions: set[str] = set() # 模块级函数的 key,随 _names() 一起建
177
+ self._aliases: dict[tuple[str, str], Sym] = {} # (模块相对路径, 别名) -> 指向的函数
178
+ self._subclasses: dict[int, list[ClassInfo]] | None = None # id(类) -> 直接的项目内子类
179
+
180
+ # ---------- 对外入口 ----------
181
+
182
+ def resolve(self, call: ast.Call, ctx: FunctionInfo) -> Resolved:
183
+ func = call.func
184
+ display = _display(func)
185
+ mod = self.index.modules[ctx.file]
186
+ if isinstance(func, ast.Name):
187
+ return self._resolve_name(func.id, ctx, mod, display)
188
+ if not isinstance(func, ast.Attribute):
189
+ return Resolved(None, "unresolved", display)
190
+ base = self._sym(func.value, mod, self._locals(ctx))
191
+ kind = base[0] if base else None
192
+ if kind in ("inst", "class", "cls"):
193
+ key = self._find_method(base[1], func.attr, set())
194
+ return Resolved(key, "exact", display) if key else Resolved(None, "unresolved", display)
195
+ if kind == "module":
196
+ return self._from_symbol(self._lookup(f"{base[1]}.{func.attr}"), display)
197
+ if kind == "external" or isinstance(func.value, _LITERALS):
198
+ return Resolved(None, "external", display)
199
+ if isinstance(func.value, ast.Call) and isinstance(func.value.func, ast.Name) and func.value.func.id == "super":
200
+ return Resolved(None, "unresolved", display) # 执行的是某个基类的方法:按名字推测多半推到调用方自己
201
+ return self._guess(func.attr, display, ctx)
202
+
203
+ def symbol(self, e: ast.expr, mod: ModuleInfo, ctx: FunctionInfo | None) -> Sym:
204
+ """表达式(名字或属性链)本身指向的符号,不是调用它:内部函数、局部名、模块级符号、导入;类或有类型的实例上的
205
+ 方法为 ("func", 方法 key)。ctx 为 None 时按 mod 的模块级代码看。"""
206
+ local = self._locals(ctx) if ctx is not None else {}
207
+ if isinstance(e, ast.Name):
208
+ key = self._inner_function(e.id, ctx)
209
+ return ("func", key) if key else self._sym(e, mod, local)
210
+ if isinstance(e, ast.Attribute):
211
+ base = self._sym(e.value, mod, local)
212
+ if base and base[0] in ("inst", "class", "cls"):
213
+ key = self._find_method(base[1], e.attr, set())
214
+ return ("func", key) if key else None
215
+ return self._sym(e, mod, local)
216
+
217
+ def value_references(self) -> set[str]:
218
+ """项目里被当作值交出去的函数(调用的参数、字典的值、赋值的右边,含其中的列表 / 元组 / 集合字面量的元素):
219
+ 别处会调用它们(回调、注册表、依赖注入)。函数只在自己里面引用自己不算。"""
220
+ by_node = {id(f.node): f for f in self.index.functions.values()}
221
+ found: set[str] = set()
222
+ for mod in self.index.modules.values():
223
+ stack: list[tuple[ast.AST, FunctionInfo | None]] = [(mod.tree, None)]
224
+ while stack:
225
+ n, ctx = stack.pop()
226
+ if isinstance(n, ast.FunctionDef | ast.AsyncFunctionDef):
227
+ ctx = by_node.get(id(n), ctx)
228
+ if isinstance(n, ast.Call):
229
+ values = [*n.args, *(k.value for k in n.keywords)]
230
+ elif isinstance(n, ast.Dict):
231
+ values = [v for v in n.values if v is not None]
232
+ elif isinstance(n, ast.Assign | ast.AnnAssign | ast.AugAssign | ast.NamedExpr):
233
+ values = [n.value]
234
+ else:
235
+ values = []
236
+ for v in values:
237
+ for e in _value_exprs(v):
238
+ sym = self.symbol(e, mod, ctx)
239
+ if sym and sym[0] == "func" and (ctx is None or sym[1] != ctx.key):
240
+ found.add(sym[1])
241
+ stack.extend((c, ctx) for c in ast.iter_child_nodes(n))
242
+ return found
243
+
244
+ def mentions(self, names: set[str]) -> set[str]:
245
+ """项目里有地方提到过的函数(只查名字在 names 里的):调用、当作值交出去、当装饰器用、写在模块顶层的调用、
246
+ `(a if x else b)()` 这种算出来再调的都算——只要名字出现在一个表达式里并且解析到它。函数只在自己里面提到自己
247
+ 不算;import 语句不算(只是把名字带进来)。"""
248
+ by_node = {id(f.node): f for f in self.index.functions.values()}
249
+ found: set[str] = set()
250
+ for mod in self.index.modules.values():
251
+ stack: list[tuple[ast.AST, FunctionInfo | None]] = [(mod.tree, None)]
252
+ while stack:
253
+ n, ctx = stack.pop()
254
+ if isinstance(n, ast.FunctionDef | ast.AsyncFunctionDef):
255
+ ctx = by_node.get(id(n), ctx)
256
+ if (isinstance(n, ast.Name) and n.id in names or isinstance(n, ast.Attribute) and n.attr in names) \
257
+ and isinstance(n.ctx, ast.Load):
258
+ sym = self.symbol(n, mod, ctx)
259
+ if sym and sym[0] == "func" and (ctx is None or sym[1] != ctx.key):
260
+ found.add(sym[1])
261
+ stack.extend((c, ctx) for c in ast.iter_child_nodes(n))
262
+ return found
263
+
264
+ # ---------- 各层 ----------
265
+
266
+ def _inner_function(self, name: str, ctx: FunctionInfo | None) -> str | None:
267
+ """ctx 自己和各级外层函数里叫 name 的内部函数。"""
268
+ inner = self._inner_map()
269
+ cur = ctx
270
+ while cur is not None:
271
+ key = inner.get((cur.key, name))
272
+ if key:
273
+ return key
274
+ cur = self.index.functions.get(cur.parent) if cur.parent else None
275
+ return None
276
+
277
+ def _resolve_name(self, name: str, ctx: FunctionInfo, mod: ModuleInfo, display: str) -> Resolved:
278
+ key = self._inner_function(name, ctx) # 1. 外层函数里的内部函数(自己和各级外层)
279
+ if key:
280
+ return Resolved(key, "exact", display)
281
+ return self._from_symbol(self._sym(ast.Name(id=name), mod, self._locals(ctx)), display)
282
+
283
+ def _from_symbol(self, sym: Sym, display: str) -> Resolved:
284
+ """调用一个符号:函数 → 它自己;类 → 构造函数 __init__(类上或最近的项目基类上定义的;都没有时算项目外);
285
+ 有类型的实例 → 它的 __call__(同样查到项目基类;没有时无法判断);classmethod 的 cls → 见 _cls_call。"""
286
+ kind = sym[0] if sym else None
287
+ if kind == "func":
288
+ return Resolved(sym[1], "exact", display)
289
+ if kind == "class":
290
+ init = self._find_method(sym[1], "__init__", set())
291
+ return Resolved(init, "exact", display, constructor=True) if init else Resolved(None, "external", display)
292
+ if kind == "cls":
293
+ return self._cls_call(sym[1], display)
294
+ if kind == "inst":
295
+ call = self._find_method(sym[1], "__call__", set())
296
+ return Resolved(call, "exact", display) if call else Resolved(None, "unresolved", display)
297
+ if kind == "external":
298
+ return Resolved(None, "external", display)
299
+ return Resolved(None, "unresolved", display)
300
+
301
+ def _cls_call(self, cls: ClassInfo, display: str) -> Resolved:
302
+ """classmethod 里调用 cls(...):运行时 cls 可能是这个类或它的任何项目内子类(直接、间接,含定义在函数里的)。
303
+ 每个都按方法查找(同 _find_method,沿项目内基类)得到 __init__:都是同一个函数时为 exact;都得不到项目内的
304
+ __init__ 时同调用项目内的类(项目外);得到的不一样、或有哪个类体里的 __init__ 不是顶层 def(__init__ = 函数、
305
+ if 下的 def)时目标不确定,记为无法判断——不推测。"""
306
+ family = [cls, *self._descendants(cls)]
307
+ if any("__init__" in c.other_bindings for c in family):
308
+ return Resolved(None, "unresolved", display)
309
+ inits = {self._find_method(c, "__init__", set()) for c in family}
310
+ if inits == {None}:
311
+ return Resolved(None, "external", display)
312
+ if len(inits) == 1:
313
+ return Resolved(inits.pop(), "exact", display, constructor=True)
314
+ return Resolved(None, "unresolved", display)
315
+
316
+ def _guess(self, name: str, display: str, ctx: FunctionInfo) -> Resolved:
317
+ """接收者类型未知的 x.name(...):按方法名推测。方法名太常见、或是常见内置 / 标准库类型的方法名时不推测;
318
+ 只看调用方所在源码根(包含它的最内层源码根)下的定义:恰好一处、而且是类上的方法才推测到它——模块级函数、
319
+ 协议上的空方法、调用所在的函数及其外层函数自己不是推测目标,但都算作同名定义。"""
320
+ if name in COMMON_NAMES or name in BUILTIN_METHOD_NAMES:
321
+ return Resolved(None, "unresolved", display)
322
+ root = self.index.modules[ctx.file].source_root
323
+ here = [k for k in self._names().get(name, ()) if self._source_root_of(k) == root]
324
+ if len(here) == 1 and here[0] not in self._module_functions and here[0] not in self._protocol_methods \
325
+ and here[0] not in self._enclosing(ctx):
326
+ return Resolved(here[0], "guessed", display)
327
+ return Resolved(None, "unresolved", display)
328
+
329
+ def _enclosing(self, ctx: FunctionInfo) -> set[str]:
330
+ """ctx 自己和各级外层函数的 key。"""
331
+ keys: set[str] = set()
332
+ cur: FunctionInfo | None = ctx
333
+ while cur is not None:
334
+ keys.add(cur.key)
335
+ cur = self.index.functions.get(cur.parent) if cur.parent else None
336
+ return keys
337
+
338
+ # ---------- 索引辅助 ----------
339
+
340
+ def _inner_map(self) -> dict[tuple[str, str], str]:
341
+ if self._inner is None:
342
+ self._inner = {}
343
+ for fi in self.index.functions.values():
344
+ if fi.parent:
345
+ parent = self.index.functions[fi.parent]
346
+ name = fi.node.name
347
+ if fi.qualname == f"{parent.qualname}.<locals>.{name}":
348
+ self._inner[(fi.parent, name)] = fi.key
349
+ return self._inner
350
+
351
+ def _names(self) -> dict[str, set[str]]:
352
+ """方法名(含类体里的别名;嵌套在类里、定义在函数里的类的方法也算)/ 模块级函数名 -> 项目里的定义(含协议类上
353
+ 的空方法:协议声明了这个方法,说明可能有多个实现)。"""
354
+ if self._by_name is None:
355
+ self._by_name = {}
356
+ for m in self.index.modules.values():
357
+ for n, k in m.functions.items():
358
+ self._by_name.setdefault(n, set()).add(k)
359
+ self._module_functions.add(k)
360
+ for c in self.index.classes:
361
+ for n, k in [*c.methods.items(), *c.aliases.items()]:
362
+ self._by_name.setdefault(n, set()).add(k)
363
+ if self._is_protocol(c):
364
+ self._protocol_methods.update(k for k in c.methods.values() if self._stub(k))
365
+ return self._by_name
366
+
367
+ def _source_root_of(self, key: str) -> str:
368
+ return self.index.modules[self.index.functions[key].file].source_root
369
+
370
+ def _descendants(self, cls: ClassInfo) -> list[ClassInfo]:
371
+ """cls 的项目内子类(直接和间接,含嵌套定义的类)。"""
372
+ if self._subclasses is None:
373
+ self._subclasses = {}
374
+ for c in self.index.classes:
375
+ for base in c.bases:
376
+ b = self._base_class(base, self.index.modules[c.file])
377
+ if b is not None:
378
+ self._subclasses.setdefault(id(b), []).append(c)
379
+ seen = {id(cls)}
380
+ out: list[ClassInfo] = []
381
+ stack = list(self._subclasses.get(id(cls), []))
382
+ while stack:
383
+ c = stack.pop()
384
+ if id(c) in seen:
385
+ continue
386
+ seen.add(id(c))
387
+ out.append(c)
388
+ stack.extend(self._subclasses.get(id(c), []))
389
+ return out
390
+
391
+ def _base_class(self, base: str, mod: ModuleInfo) -> ClassInfo | None:
392
+ """基类表达式(源码文本)在模块 mod 里指向的项目内类。带下标的(BaseRepo[int])看下标前的部分:运行时
393
+ 继承的就是它。"""
394
+ try:
395
+ expr = ast.parse(base, mode="eval").body
396
+ except SyntaxError:
397
+ return None
398
+ if isinstance(expr, ast.Subscript):
399
+ expr = expr.value
400
+ sym = self._sym(expr, mod, {})
401
+ return sym[1] if sym and sym[0] == "class" else None
402
+
403
+ def _is_protocol(self, cls: ClassInfo) -> bool:
404
+ """直接基类里有 typing.Protocol:它的空方法只是接口声明,运行时执行的是某个实现类的方法。"""
405
+ mod = self.index.modules[cls.file]
406
+ for base in cls.bases:
407
+ head, _, rest = base.split("[", 1)[0].partition(".")
408
+ if ".".join(filter(None, [mod.imports.get(head, head), rest])) in _PROTOCOLS:
409
+ return True
410
+ return False
411
+
412
+ def _stub(self, key: str) -> bool:
413
+ return _is_stub(self.index.functions[key].node)
414
+
415
+ def _find_method(self, cls: ClassInfo, name: str, seen: set[int]) -> str | None:
416
+ """类上(或沿项目内基类找到)的方法;落在协议类的空方法上时算找不到(协议上写了方法体的是默认实现,照常解析)。"""
417
+ if id(cls) in seen:
418
+ return None
419
+ seen.add(id(cls))
420
+ key = cls.methods.get(name) or cls.aliases.get(name) # 类体里的 m2 = m1:m2 就是 m1
421
+ if key:
422
+ return None if self._is_protocol(cls) and self._stub(key) else key
423
+ mod = self.index.modules[cls.file]
424
+ for base in cls.bases:
425
+ b = self._base_class(base, mod)
426
+ if b is not None:
427
+ key = self._find_method(b, name, seen)
428
+ if key:
429
+ return key
430
+ return None
431
+
432
+ # ---------- 符号求值 ----------
433
+
434
+ def _lookup(self, dotted: str, depth: int = 0) -> Sym:
435
+ """点分全名 -> 符号;项目外为 external,项目内查不到为 None。"""
436
+ if dotted.split(".")[0] not in self._tops:
437
+ return ("external",)
438
+ if dotted in self.index.by_dotted:
439
+ return ("module", dotted)
440
+ mod_part, _, last = dotted.rpartition(".")
441
+ rel = self.index.by_dotted.get(mod_part)
442
+ if rel is None:
443
+ return None
444
+ m = self.index.modules[rel]
445
+ if last in m.functions:
446
+ return ("func", m.functions[last])
447
+ if last in m.classes:
448
+ return ("class", m.classes[last])
449
+ if last in m.instances:
450
+ sym = self._lookup(m.instances[last], depth + 1) if depth < 5 else None
451
+ return ("inst", sym[1]) if sym and sym[0] == "class" else None
452
+ if last in m.aliases:
453
+ sym = self._alias(m, last)
454
+ if sym:
455
+ return sym
456
+ if last in m.imports and depth < 5: # 包的 __init__ 里转手导出
457
+ return self._lookup(m.imports[last], depth + 1)
458
+ return None
459
+
460
+ def _alias(self, mod: ModuleInfo, name: str) -> Sym:
461
+ """模块级别名 name = 函数 / 模块.函数 / 类.方法 指向的项目内函数 ("func", key);右边不是项目内函数时 None
462
+ (不建立别名,查找照旧往下走)。别名互相指向成环时为 None。"""
463
+ k = (mod.rel, name)
464
+ if k not in self._aliases:
465
+ self._aliases[k] = None # 先占位:成环时查到这里为止
466
+ sym = self.symbol(mod.aliases[name], mod, None)
467
+ self._aliases[k] = sym if sym and sym[0] == "func" else None
468
+ return self._aliases[k]
469
+
470
+ def _sym(self, e: ast.expr, mod: ModuleInfo, local: dict[str, Sym]) -> Sym:
471
+ if isinstance(e, ast.Name):
472
+ return self._name_sym(e.id, mod, local)
473
+ if isinstance(e, ast.Attribute):
474
+ base = self._sym(e.value, mod, local)
475
+ if base and base[0] == "module":
476
+ return self._lookup(f"{base[1]}.{e.attr}")
477
+ if base and base[0] == "external":
478
+ return base
479
+ return None
480
+ if isinstance(e, ast.Call):
481
+ f = self._sym(e.func, mod, local)
482
+ return ("inst", f[1]) if f and f[0] == "class" else None
483
+ return None
484
+
485
+ def _name_sym(self, name: str, mod: ModuleInfo, local: dict[str, Sym]) -> Sym:
486
+ if name in local:
487
+ return local[name]
488
+ if name in mod.functions:
489
+ return ("func", mod.functions[name])
490
+ if name in mod.classes:
491
+ return ("class", mod.classes[name])
492
+ if name in mod.instances:
493
+ sym = self._lookup(mod.instances[name])
494
+ return ("inst", sym[1]) if sym and sym[0] == "class" else None
495
+ if name in mod.aliases:
496
+ sym = self._alias(mod, name)
497
+ if sym:
498
+ return sym
499
+ if name in mod.imports:
500
+ return self._lookup(mod.imports[name])
501
+ if name in _BUILTIN_NAMES:
502
+ return ("external",)
503
+ return None
504
+
505
+ # ---------- 局部变量类型 ----------
506
+
507
+ def _locals(self, ctx: FunctionInfo) -> dict[str, Sym]:
508
+ """函数自己和各级外层函数里的局部名;有类型的给 ("inst", 类),函数体里 import 绑定的给它导入的符号,
509
+ 其余为 None(挡住同名的模块级符号)。"""
510
+ cached = self._locals_cache.get(ctx.key)
511
+ if cached is not None:
512
+ return cached
513
+ chain: list[FunctionInfo] = []
514
+ cur: FunctionInfo | None = ctx
515
+ while cur is not None:
516
+ chain.append(cur)
517
+ cur = self.index.functions.get(cur.parent) if cur.parent else None
518
+ out: dict[str, Sym] = {}
519
+ for fn in reversed(chain): # 外层先,内层覆盖
520
+ out.update(self._scan(fn))
521
+ self._locals_cache[ctx.key] = out
522
+ return out
523
+
524
+ def _scan(self, fn: FunctionInfo) -> dict[str, Sym]:
525
+ mod = self.index.modules[fn.file]
526
+ node = fn.node
527
+ out: dict[str, Sym] = {}
528
+ bound: set[str] = set()
529
+
530
+ def bind(name: str, sym: Sym) -> None:
531
+ """名字的所有绑定必须一致才有类型;任何分歧或无类型的重绑定都让它永久无类型。"""
532
+ if name not in bound:
533
+ bound.add(name)
534
+ out[name] = sym
535
+ elif sym is None or out[name] is None or out[name] != sym:
536
+ out[name] = None
537
+
538
+ a = node.args
539
+ positional = [*a.posonlyargs, *a.args]
540
+ for arg in [*positional, *a.kwonlyargs, a.vararg, a.kwarg]:
541
+ if arg is not None:
542
+ bind(arg.arg, self._inst_of_annotation(arg.annotation, mod) if arg.annotation else None)
543
+ decorators = {d.id for d in fn.decorators if isinstance(d, ast.Name)}
544
+ if fn.cls and positional and "staticmethod" not in decorators and fn.cls in mod.classes:
545
+ cls = mod.classes[fn.cls]
546
+ if "classmethod" in decorators and cls.methods.get(fn.node.name) == fn.key:
547
+ out[positional[0].arg] = ("cls", cls) # classmethod 的首参是类本身(运行时可能是子类)
548
+ else:
549
+ out[positional[0].arg] = ("inst", cls) # 首参视为本类实例
550
+ handled: set[int] = set()
551
+
552
+ def visit(n: ast.AST) -> None:
553
+ if isinstance(n, ast.FunctionDef | ast.AsyncFunctionDef | ast.Lambda | ast.ClassDef):
554
+ return
555
+ if isinstance(n, ast.AnnAssign) and isinstance(n.target, ast.Name):
556
+ handled.add(id(n.target))
557
+ sym = self._inst_of_annotation(n.annotation, mod) # 有注解就只信注解
558
+ bind(n.target.id, sym)
559
+ elif isinstance(n, ast.Assign):
560
+ sym = self._inst_of_value(n.value, mod, out)
561
+ for t in n.targets:
562
+ if isinstance(t, ast.Name):
563
+ handled.add(id(t))
564
+ bind(t.id, sym)
565
+ elif isinstance(n, ast.Import | ast.ImportFrom): # 函数体里的 import 绑定局部名,盖过同名的模块级符号
566
+ for name, target in import_bindings(n, mod):
567
+ bind(name, self._lookup(target))
568
+ elif isinstance(n, ast.Name) and isinstance(n.ctx, ast.Store) and id(n) not in handled:
569
+ bind(n.id, None)
570
+ for c in ast.iter_child_nodes(n):
571
+ visit(c)
572
+
573
+ for st in node.body:
574
+ visit(st)
575
+ return out
576
+
577
+ def _inst_of_value(self, value: ast.expr, mod: ModuleInfo, local: dict[str, Sym]) -> Sym:
578
+ """x = ClassName(...) 才有类型。"""
579
+ if isinstance(value, ast.Call):
580
+ f = self._sym(value.func, mod, local)
581
+ if f and f[0] == "class":
582
+ return ("inst", f[1])
583
+ return None
584
+
585
+ def _inst_of_annotation(self, ann: ast.expr, mod: ModuleInfo) -> Sym:
586
+ if isinstance(ann, ast.Constant) and isinstance(ann.value, str):
587
+ try:
588
+ ann = ast.parse(ann.value, mode="eval").body
589
+ except SyntaxError:
590
+ return None
591
+ if isinstance(ann, ast.Subscript): # Optional[Svc];Annotated[Svc, Depends(...)] 同 svc: Svc = Depends(...),看第一项
592
+ wrapper = _short(ann.value) if isinstance(ann.value, ast.Name | ast.Attribute) else None
593
+ if wrapper == "Optional":
594
+ return self._inst_of_annotation(ann.slice, mod)
595
+ if wrapper == "Annotated" and isinstance(ann.slice, ast.Tuple) and ann.slice.elts:
596
+ return self._inst_of_annotation(ann.slice.elts[0], mod)
597
+ return None
598
+ if isinstance(ann, ast.BinOp) and isinstance(ann.op, ast.BitOr): # Svc | None
599
+ sides = [s for s in (ann.left, ann.right) if not (isinstance(s, ast.Constant) and s.value is None)]
600
+ return self._inst_of_annotation(sides[0], mod) if len(sides) == 1 else None
601
+ if isinstance(ann, ast.Name | ast.Attribute):
602
+ sym = self._sym(ann, mod, {})
603
+ if sym and sym[0] == "class":
604
+ return ("inst", sym[1])
605
+ return None