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/rules.py ADDED
@@ -0,0 +1,538 @@
1
+ """识别规则:哪些函数是入口、哪些调用是派发、哪些调用是噪音。纯静态匹配,不导入被分析代码。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ import builtins
7
+ import re
8
+ from dataclasses import dataclass, field
9
+ from typing import TYPE_CHECKING, Literal
10
+
11
+ from .config import ProjectConfig
12
+ from .external import ExternalObjects
13
+ from .index import FunctionInfo, ModuleInfo, ProjectIndex, _attr_chain
14
+ from .index import _scope_bindings as _all_bindings
15
+ from .model import FnKind, Resolution
16
+ from .resolve import dotted_name_of
17
+
18
+ if TYPE_CHECKING:
19
+ from .resolve import Resolver
20
+
21
+
22
+ @dataclass
23
+ class EntryInfo:
24
+ kind: FnKind
25
+ title: str | None = None
26
+ group: str | None = None
27
+ route: str | None = None
28
+ retries: bool = False
29
+ marked: bool = False
30
+ rule: str | None = None # 识别出该入口的规则集名
31
+ name: str | None = None # pystepkit workflow 的 name=
32
+ version: str | None = None # pystepkit workflow 的 version=
33
+
34
+
35
+ @dataclass
36
+ class DispatchRule:
37
+ methods: list[str] # 方法名,如 ["kiq"]
38
+ task_from: Literal["receiver", "arg0"] # 任务在接收者表达式里,还是参数里
39
+ dynamic_ok: bool = True # 找不到任务名时是否仍算派发(目标未知)
40
+
41
+
42
+ @dataclass
43
+ class RuleSet:
44
+ name: str
45
+ entry_decorators: list[tuple[str, FnKind]] # (匹配装饰器源码的正则, 类型)
46
+ dispatch: list[DispatchRule] = field(default_factory=list)
47
+ retry_keywords: list[str] = field(default_factory=list)
48
+
49
+
50
+ _ROUTE_METHODS = ("get", "post", "put", "delete", "patch", "head", "options", "websocket", "api_route")
51
+ _HTTP = r"(" + "|".join(_ROUTE_METHODS) + r")\b"
52
+ # 模块级实例是这些类时,它上面的 _ROUTE_METHODS 装饰器都是路由(不论变量叫什么)
53
+ _FASTAPI_CLASSES = frozenset({"fastapi.FastAPI", "fastapi.APIRouter", "fastapi.applications.FastAPI",
54
+ "fastapi.routing.APIRouter"})
55
+ BUILTIN: dict[str, RuleSet] = {
56
+ "fastapi": RuleSet("fastapi", [(r"^\w*router\." + _HTTP, "route"), (r"^app\." + _HTTP, "route")], []),
57
+ # Flask(以及写法相同的 Quart、Sanic、Bottle):@app.route(...) / @bp.route(...);@app.get(...) 这类由 fastapi 那条认
58
+ "flask": RuleSet("flask", [(r"\.route\b", "route")], []),
59
+ "taskiq": RuleSet("taskiq", [(r"\.task\b", "task")],
60
+ [DispatchRule(["kiq"], "receiver")], ["retry_on_error"]),
61
+ # Celery:@shared_task、@app.task;派发是 任务.delay(...) / 任务.apply_async(...)。只在项目导入了 celery 时启用
62
+ # (_uses_celery),这时 @x.task 归它、不归 taskiq
63
+ "celery": RuleSet("celery", [(r"^(celery\.)?shared_task\b", "task"), (r"\.task\b", "task")],
64
+ [DispatchRule(["delay", "apply_async"], "receiver", dynamic_ok=False)]),
65
+ "dbos": RuleSet("dbos", [(r"^DBOS\.workflow\b", "workflow"), (r"^DBOS\.step\b", "step")], [
66
+ DispatchRule(["start_workflow", "start_workflow_async"], "arg0"),
67
+ DispatchRule(["enqueue", "enqueue_async", "enqueue_workflow", "enqueue_workflow_async"], "arg0",
68
+ dynamic_ok=False)]),
69
+ "pystepkit": RuleSet("pystepkit", []), # 不按源码文字匹配:装饰器要经 import 来自 pystepkit(见 _pystepkit_mark)
70
+ }
71
+ _PYSTEPKIT_MARKS: dict[str, FnKind] = {"workflow": "workflow", "step": "step", "node": "step", "condition": "condition"}
72
+
73
+ _COUNTER_METHODS = {"inc", "dec", "observe", "set"}
74
+
75
+
76
+ def known_rule_names(config: ProjectConfig) -> set[str]:
77
+ """内置识别规则和配置里 extra_rules 的规则名(不论项目里有没有用到)。"""
78
+ return set(BUILTIN) | {d.get("name", "extra") for d in config.extra_rules}
79
+
80
+
81
+ def rule_entry_kinds(config: ProjectConfig) -> dict[str, set[FnKind]]:
82
+ """每条识别规则(内置的和配置里 extra_rules 的)能识别出的入口类型。pystepkit 的标记不按正则认,这里是空集。"""
83
+ sets = [*BUILTIN.values(), *(_ruleset_from_dict(d) for d in config.extra_rules)]
84
+ return {rs.name: {k for _, k in rs.entry_decorators} for rs in sets}
85
+
86
+
87
+ def _ruleset_from_dict(d: dict) -> RuleSet:
88
+ return RuleSet(
89
+ name=d.get("name", "extra"),
90
+ entry_decorators=[(p, k) for p, k in d.get("entry_decorators", [])],
91
+ dispatch=[DispatchRule(list(x.get("methods", [])), x.get("task_from", "arg0"),
92
+ x.get("dynamic_ok", True)) for x in d.get("dispatch", [])],
93
+ retry_keywords=list(d.get("retry_keywords", [])))
94
+
95
+
96
+ def _str_kw(dec: ast.expr, name: str) -> str | None:
97
+ if isinstance(dec, ast.Call):
98
+ for kw in dec.keywords:
99
+ if kw.arg == name and isinstance(kw.value, ast.Constant) and isinstance(kw.value.value, str):
100
+ return kw.value.value
101
+ return None
102
+
103
+
104
+ def _module_strings(mod: ModuleInfo) -> dict[str, str]:
105
+ """模块级的字符串常量:名字 -> 值。只算写在模块顶层(不在 if / try 里)的 NAME = "……"(可带注解),而且这个名字
106
+ 在模块里只绑定了这一次、没有函数用 global 改写它。"""
107
+ bindings = _all_bindings(mod.tree.body)
108
+ rebound = {name for n in ast.walk(mod.tree) if isinstance(n, ast.Global) for name in n.names}
109
+ out: dict[str, str] = {}
110
+ for st in mod.tree.body:
111
+ if isinstance(st, ast.Assign) and len(st.targets) == 1:
112
+ target, value = st.targets[0], st.value
113
+ elif isinstance(st, ast.AnnAssign):
114
+ target, value = st.target, st.value
115
+ else:
116
+ continue
117
+ if isinstance(target, ast.Name) and isinstance(value, ast.Constant) and isinstance(value.value, str) \
118
+ and len(bindings.get(target.id, ())) == 1 and target.id not in rebound:
119
+ out[target.id] = value.value
120
+ return out
121
+
122
+
123
+ # 标记的参数读不出来时,当作没写之后的结果(mark_notes 里说)
124
+ _UNREAD_EFFECT = {"group": "这条功能线按文件名(或入口的种类)分组", "title": "标题改用文档注释或函数名"}
125
+ MAX_CONST_HOPS = 4 # 常量经导入转了几手还跟
126
+
127
+
128
+ def _str_arg(dec: ast.Call, pos: int, name: str) -> str | None:
129
+ """第 pos 个位置参数或关键字参数 name 的字符串常量。"""
130
+ v = dec.args[pos] if len(dec.args) > pos else next((k.value for k in dec.keywords if k.arg == name), None)
131
+ return v.value if isinstance(v, ast.Constant) and isinstance(v.value, str) else None
132
+
133
+
134
+ def _constructor_call(mod: ModuleInfo, name: str) -> ast.Call | None:
135
+ """模块级 name = 某某(...) 的那个调用(多次赋值取最后一次,同 ModuleInfo.instances)。"""
136
+ found = None
137
+ for st in mod.tree.body:
138
+ target = st.targets[0] if isinstance(st, ast.Assign) and len(st.targets) == 1 else \
139
+ st.target if isinstance(st, ast.AnnAssign) else None
140
+ if isinstance(target, ast.Name) and target.id == name and isinstance(st.value, ast.Call):
141
+ found = st.value
142
+ return found
143
+
144
+
145
+ _OTHER = object() # 名字在这一层绑定成了别的东西(参数、循环变量、解包赋值、嵌套的 def / class、import……)
146
+
147
+
148
+ def _target_names(t: ast.expr) -> list[str]:
149
+ """赋值目标里绑定的名字(解包、星号展开都算;属性、下标不算)。"""
150
+ if isinstance(t, ast.Name):
151
+ return [t.id]
152
+ if isinstance(t, ast.Tuple | ast.List):
153
+ return [n for e in t.elts for n in _target_names(e)]
154
+ if isinstance(t, ast.Starred):
155
+ return _target_names(t.value)
156
+ return []
157
+
158
+
159
+ def _scope_bindings(scope: ast.AST) -> dict[str, object]:
160
+ """函数 scope 这一层绑定的名字 -> 按源码顺序最后一次绑定的值:`x = 值`、`x: T = 值`、`x = y = 值`、`(x := 值)`
161
+ 是那个值的表达式;参数、解包赋值、循环变量、with … as、except … as、增量赋值、import、嵌套的 def / class 是 _OTHER。
162
+ 不进嵌套的函数、类、lambda 的里面(那是别的作用域)。"""
163
+ out: dict[str, object] = {}
164
+ args = getattr(scope, "args", None)
165
+ if isinstance(args, ast.arguments):
166
+ for a in [*args.posonlyargs, *args.args, *args.kwonlyargs, args.vararg, args.kwarg]:
167
+ if a is not None:
168
+ out[a.arg] = _OTHER
169
+ stack = list(ast.iter_child_nodes(scope))
170
+ while stack:
171
+ st = stack.pop(0)
172
+ if isinstance(st, ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef):
173
+ out[st.name] = _OTHER
174
+ continue
175
+ if isinstance(st, ast.Lambda | ast.arguments):
176
+ continue
177
+ if isinstance(st, ast.Assign):
178
+ for t in st.targets:
179
+ for n in _target_names(t):
180
+ out[n] = st.value if isinstance(t, ast.Name) else _OTHER
181
+ elif isinstance(st, ast.AnnAssign):
182
+ if isinstance(st.target, ast.Name) and st.value is not None:
183
+ out[st.target.id] = st.value
184
+ elif isinstance(st, ast.NamedExpr):
185
+ out[st.target.id] = st.value
186
+ elif isinstance(st, ast.AugAssign | ast.For | ast.AsyncFor | ast.comprehension):
187
+ for n in _target_names(st.target):
188
+ out[n] = _OTHER
189
+ elif isinstance(st, ast.withitem):
190
+ if st.optional_vars is not None:
191
+ for n in _target_names(st.optional_vars):
192
+ out[n] = _OTHER
193
+ elif isinstance(st, ast.ExceptHandler):
194
+ if st.name:
195
+ out[st.name] = _OTHER
196
+ elif isinstance(st, ast.Import | ast.ImportFrom):
197
+ for al in st.names:
198
+ out[(al.asname or al.name).split(".")[0]] = _OTHER
199
+ stack[0:0] = list(ast.iter_child_nodes(st))
200
+ return out
201
+
202
+
203
+ def _route_receiver(dec: ast.expr) -> str | None:
204
+ """@x.get(...) 等路由装饰器里的 x;不是这个样子时 None。"""
205
+ if isinstance(dec, ast.Call) and isinstance(dec.func, ast.Attribute) and dec.func.attr in _ROUTE_METHODS \
206
+ and isinstance(dec.func.value, ast.Name):
207
+ return dec.func.value.id
208
+ return None
209
+
210
+
211
+ def _route_title(dec: ast.Call, mod: ModuleInfo, ctor: ast.Call | None = None) -> str:
212
+ """路由标题 "方法 前缀路径":websocket 为 WS;api_route 取字面量的 methods=(省略时同 FastAPI 为 GET,不是
213
+ 字面量时为 ROUTE);前缀取 APIRouter(prefix=...) 的字面量(ctor:外层函数里的构造调用;没有时找同一模块的模块级
214
+ 实例)。"""
215
+ attr = dec.func.attr
216
+ if attr == "websocket":
217
+ method = "WS"
218
+ elif attr in ("api_route", "route"): # route 是 Flask 的写法:methods= 省略时也是 GET
219
+ given = next((k.value for k in dec.keywords if k.arg == "methods"), None)
220
+ if given is None:
221
+ method = "GET"
222
+ elif isinstance(given, ast.List | ast.Tuple) and all(
223
+ isinstance(e, ast.Constant) and isinstance(e.value, str) for e in given.elts):
224
+ method = ",".join(e.value.upper() for e in given.elts)
225
+ else:
226
+ method = "ROUTE"
227
+ else:
228
+ method = attr.upper()
229
+ prefix = ""
230
+ if isinstance(dec.func.value, ast.Name):
231
+ ctor = ctor or _constructor_call(mod, dec.func.value.id)
232
+ if ctor is not None and name_of(ctor.func) == "APIRouter":
233
+ prefix = _str_kw(ctor, "prefix") or ""
234
+ elif ctor is not None and name_of(ctor.func) == "Blueprint":
235
+ prefix = _str_kw(ctor, "url_prefix") or ""
236
+ return f"{method} {prefix}{_str_arg(dec, 0, 'path') or ''}".strip()
237
+
238
+
239
+ def pystepkit_name(e: ast.expr, mod: ModuleInfo) -> str | None:
240
+ """名字或属性链经本模块的 import 展开后在 pystepkit 或 pystepkit.* 里时,返回它的最后一段(workflow、outcome……);
241
+ 否则 None。from pystepkit import workflow [as wf]、import pystepkit [as fk] 后的 fk.workflow 都算。"""
242
+ dotted = dotted_name_of(e, mod)
243
+ return dotted.rpartition(".")[2] if dotted and dotted.startswith("pystepkit.") else None
244
+
245
+
246
+ def _pystepkit_mark(dec: ast.expr, mod: ModuleInfo) -> FnKind | None:
247
+ """装饰器是 pystepkit 的 workflow / step / node / condition(可以带参数)时,返回对应的类型。"""
248
+ return _PYSTEPKIT_MARKS.get(pystepkit_name(dec.func if isinstance(dec, ast.Call) else dec, mod) or "")
249
+
250
+
251
+ def _fastapi_instance_route(dec: ast.expr, mod: ModuleInfo) -> bool:
252
+ """@x.get(...) 等,x 是本模块里 FastAPI() / APIRouter() 的模块级实例。"""
253
+ name = _route_receiver(dec)
254
+ return name is not None and mod.instances.get(name) in _FASTAPI_CLASSES
255
+
256
+
257
+ def _leftmost_name(node: ast.expr) -> str | None:
258
+ while True:
259
+ if isinstance(node, ast.Name):
260
+ return node.id
261
+ if isinstance(node, ast.Attribute):
262
+ node = node.value
263
+ elif isinstance(node, ast.Call):
264
+ node = node.func
265
+ elif isinstance(node, ast.Subscript):
266
+ node = node.value
267
+ else:
268
+ return None
269
+
270
+
271
+ @dataclass
272
+ class Dispatch:
273
+ """一个派发调用:被派发的任务。"""
274
+
275
+ name: str | None # 任务表达式里的名字;找不到任务时 None(目标未知)
276
+ target: str | None # 被派发函数的 key
277
+ how: Resolution
278
+
279
+
280
+ def name_of(e: ast.expr) -> str | None:
281
+ """名字的 id、属性的属性名;其他表达式为 None。"""
282
+ return e.id if isinstance(e, ast.Name) else e.attr if isinstance(e, ast.Attribute) else None
283
+
284
+
285
+ class ActiveRules:
286
+ def __init__(self, index: ProjectIndex, config: ProjectConfig):
287
+ self.index = index
288
+ self.config = config
289
+ self.external = ExternalObjects(index, config.noise_receivers) # 建图时判断"落在项目外对象上的调用"用
290
+ self._compiled: dict[str, list[tuple[re.Pattern, FnKind]]] = {}
291
+ self._sets: dict[str, RuleSet] = {}
292
+ texts = [ast.unparse(d) for f in index.functions.values() for d in f.decorators]
293
+ texts += [ast.unparse(d) for m in index.modules.values()
294
+ for c in m.classes.values() for d in c.decorators]
295
+ imported = {d.split(".")[0] for m in index.modules.values() for d in m.imports.values()}
296
+ skip = "taskiq" if "celery" in imported and "taskiq" not in imported else "celery"
297
+ for rs in BUILTIN.values():
298
+ if rs.name != skip and any(re.search(p, t) for p, _ in rs.entry_decorators for t in texts):
299
+ self._add(rs)
300
+ self._bindings: dict[int, dict[str, object]] = {} # id(函数的 AST 节点) -> 这一层绑定的名字(每个函数只扫一次)
301
+ self._strings: dict[str, dict[str, str]] = {} # 模块相对路径 -> 模块级字符串常量(用到时才扫)
302
+ self._unread: dict[tuple[str, int, str], str] = {} # (文件, 行, 参数名) -> 标记里读不出来的参数的原文
303
+ if "fastapi" not in self._sets and any(
304
+ self._fastapi_route(d, index.modules[f.file], self._scopes(f))
305
+ for f in index.functions.values() for d in f.decorators):
306
+ self._add(BUILTIN["fastapi"])
307
+ decorated = [(d, index.modules[f.file]) for f in index.functions.values() for d in f.decorators]
308
+ decorated += [(d, m) for m in index.modules.values() for c in m.classes.values() for d in c.decorators]
309
+ if any(_pystepkit_mark(d, m) for d, m in decorated):
310
+ self._add(BUILTIN["pystepkit"])
311
+ for d in config.extra_rules:
312
+ self._add(_ruleset_from_dict(d))
313
+ self.names: list[str] = list(self._sets)
314
+ self.task_names: set[str] = set() # 任务 / 工作流的名字(pystepkit 类形式工作流用类名):派发识别按它找任务表达式
315
+ self.tasks: dict[str, str] = {} # 只有一个任务叫这个名字时:名字 -> key(派发解析不了时按它猜)
316
+ self._class_tasks: dict[int, str] = {} # id(pystepkit 类形式工作流的 ClassInfo) -> 入口方法的 key
317
+ self._task_keys: set[str] = set()
318
+ self._build_tasks()
319
+
320
+ def _add(self, rs: RuleSet) -> None:
321
+ self._sets[rs.name] = rs
322
+ self._compiled[rs.name] = [(re.compile(p), k) for p, k in rs.entry_decorators]
323
+
324
+ def _scopes(self, fn: FunctionInfo) -> list[ast.AST]:
325
+ """fn 外层的函数(从最近的一层往外)。"""
326
+ out: list[ast.AST] = []
327
+ parent = fn.parent
328
+ while parent is not None and parent in self.index.functions:
329
+ out.append(self.index.functions[parent].node)
330
+ parent = self.index.functions[parent].parent
331
+ return out
332
+
333
+ def _local_ctor(self, dec: ast.expr, mod: ModuleInfo, scopes: list[ast.AST]) -> ast.Call | None | bool:
334
+ """@x.get(...) 等,x 在外层函数(scopes:从最近的一层往外)里绑定过时,看最近绑定它的那一层:最后一次绑定是
335
+ x = FastAPI(...) / APIRouter(...) → 返回那个构造调用;绑定成了别的(参数、别的值)→ False(这个 x 不是模块级
336
+ 的那个实例,也不再往外找)。哪一层都没绑定过、或者装饰器不是这个样子 → None。"""
337
+ name = _route_receiver(dec)
338
+ if name is None:
339
+ return None
340
+ for scope in scopes:
341
+ found = self._bindings.get(id(scope))
342
+ if found is None:
343
+ found = self._bindings[id(scope)] = _scope_bindings(scope)
344
+ if name not in found:
345
+ continue
346
+ value = found[name]
347
+ chain = _attr_chain(value.func) if isinstance(value, ast.Call) else None
348
+ if chain and chain[0] in mod.imports and ".".join([mod.imports[chain[0]], *chain[1:]]) in _FASTAPI_CLASSES:
349
+ return value
350
+ return False
351
+ return None
352
+
353
+ def _fastapi_route(self, dec: ast.expr, mod: ModuleInfo, scopes: list[ast.AST]) -> bool:
354
+ """装饰器是 FastAPI() / APIRouter() 实例上的路由:外层函数里的局部实例;外层没有绑定这个名字时看模块级的。"""
355
+ local = self._local_ctor(dec, mod, scopes)
356
+ return _fastapi_instance_route(dec, mod) if local is None else local is not False
357
+
358
+ def _match_one(self, dec: ast.expr, mod: ModuleInfo, scopes: list[ast.AST]):
359
+ """一个装饰器对上的 (规则集, 类型, 装饰器);对不上时 None。"""
360
+ mark = _pystepkit_mark(dec, mod) if "pystepkit" in self._sets else None
361
+ if mark is not None:
362
+ return self._sets["pystepkit"], mark, dec
363
+ text = ast.unparse(dec)
364
+ for name, pats in self._compiled.items():
365
+ for pat, kind in pats:
366
+ if pat.search(text):
367
+ return self._sets[name], kind, dec
368
+ if "fastapi" in self._sets and self._fastapi_route(dec, mod, scopes):
369
+ return self._sets["fastapi"], "route", dec
370
+ return None
371
+
372
+ def _matches(self, decorators: list[ast.expr], mod: ModuleInfo, scopes: list[ast.AST] | None = None) -> list:
373
+ """每个对得上的装饰器的 (规则集, 类型, 装饰器),排在前面的说了算:pystepkit 标记最先,其次是别的类型,接口
374
+ (route)最后——同一个函数既是工作流又挂在路由上时算工作流,两个装饰器谁写在上面都一样。同一档里按源码顺序。"""
375
+ found = [m for m in (self._match_one(d, mod, scopes or []) for d in decorators) if m is not None]
376
+ return sorted(found, key=lambda m: 0 if m[0].name == "pystepkit" else 2 if m[1] == "route" else 1)
377
+
378
+ def _match(self, decorators: list[ast.expr], mod: ModuleInfo, scopes: list[ast.AST] | None = None):
379
+ """返回 (规则集, 类型, 装饰器);无匹配时 None。pystepkit 标记按 import 来源认;其他规则按装饰器源码的正则匹配;
380
+ 另外 FastAPI() / APIRouter() 的实例(模块级的,或者 scopes——外层函数——里的局部变量,比如 create_app 里的
381
+ api = FastAPI())上的路由装饰器不论变量名都算路由。几个装饰器都对得上时见 _matches。"""
382
+ found = self._matches(decorators, mod, scopes)
383
+ return found[0] if found else None
384
+
385
+ def _const_str(self, e: ast.expr, mod: ModuleInfo, hops: int = 0) -> str | None:
386
+ """表达式的字符串值:字面量;模块级的字符串常量(_module_strings)——本模块的名字、from 导入的名字、
387
+ 导入的模块.名字,项目内转手导入的接着跟。读不出来时 None。"""
388
+ if isinstance(e, ast.Constant):
389
+ return e.value if isinstance(e.value, str) else None
390
+ chain = _attr_chain(e)
391
+ if not chain or hops > MAX_CONST_HOPS:
392
+ return None
393
+ if len(chain) == 1 and chain[0] in self._module_strs(mod):
394
+ return self._module_strs(mod)[chain[0]]
395
+ if chain[0] not in mod.imports:
396
+ return None
397
+ module, _, name = ".".join([mod.imports[chain[0]], *chain[1:]]).rpartition(".")
398
+ rel = self.index.by_dotted.get(module)
399
+ return None if rel is None else self._const_str(ast.Name(id=name, ctx=ast.Load()), self.index.modules[rel], hops + 1)
400
+
401
+ def _module_strs(self, mod: ModuleInfo) -> dict[str, str]:
402
+ if mod.rel not in self._strings:
403
+ self._strings[mod.rel] = _module_strings(mod)
404
+ return self._strings[mod.rel]
405
+
406
+ def _mark_str(self, dec: ast.expr, name: str, mod: ModuleInfo) -> str | None:
407
+ """pystepkit 标记的关键字参数 name 的字符串值(见 _const_str)。写了却读不出来的(算出来的值、绑定了几次的
408
+ 名字、项目外的常量)当作没写,并记下是哪一处:mark_notes 里说出来,不能悄悄丢掉。"""
409
+ kw = next((k for k in dec.keywords if k.arg == name), None) if isinstance(dec, ast.Call) else None
410
+ if kw is None:
411
+ return None
412
+ value = self._const_str(kw.value, mod)
413
+ if value is None and not (isinstance(kw.value, ast.Constant) and kw.value.value is None):
414
+ self._unread[(mod.rel, kw.value.lineno, name)] = ast.unparse(kw.value)
415
+ return value
416
+
417
+ def mark_notes(self) -> list[str]:
418
+ """标记里读不出来的参数,每处一句(按文件、行排)。classify 过的函数才有:分析时每个函数都会 classify 一次。"""
419
+ return [f"{file}:{line} 标记里的 {name}={text} 读不出来,当作没写({_UNREAD_EFFECT.get(name, '按没有这个参数处理')}):"
420
+ "要写成字符串字面量,或者模块级只赋值一次的字符串常量"
421
+ for (file, line, name), text in sorted(self._unread.items())]
422
+
423
+ def _class_info(self, fn: FunctionInfo):
424
+ mod = self.index.modules.get(fn.file)
425
+ return mod.classes.get(fn.cls) if mod and fn.cls else None
426
+
427
+ def _pystepkit_class_entry(self, fn: FunctionInfo) -> ast.expr | None:
428
+ """fn 是 pystepkit 类形式工作流的入口方法时,返回类上的 workflow 装饰器;否则 None。"""
429
+ cls = self._class_info(fn)
430
+ if cls is None:
431
+ return None
432
+ m = self._match(cls.decorators, self.index.modules[fn.file])
433
+ if m and m[0].name == "pystepkit" and m[1] == "workflow":
434
+ entry = self._mark_str(m[2], "entry", self.index.modules[fn.file]) or "run"
435
+ if fn.node.name == entry and fn.qualname == f"{cls.name}.{entry}":
436
+ return m[2]
437
+ return None
438
+
439
+ def classify(self, fn: FunctionInfo) -> EntryInfo:
440
+ dec = self._pystepkit_class_entry(fn)
441
+ mod = self.index.modules[fn.file]
442
+ read = lambda name: self._mark_str(dec, name, mod)
443
+ if dec is not None:
444
+ return EntryInfo("workflow", read("title"), read("group"), marked=True, rule="pystepkit",
445
+ name=read("name"), version=read("version"))
446
+ scopes = self._scopes(fn)
447
+ found = self._matches(fn.decorators, mod, scopes)
448
+ if not found:
449
+ return EntryInfo("function")
450
+ rs, kind, dec = found[0]
451
+ info = EntryInfo(kind, rule=rs.name)
452
+ if rs.name == "pystepkit":
453
+ info.marked = True
454
+ info.title, info.group = read("title"), read("group")
455
+ if kind == "workflow":
456
+ info.name, info.version = read("name"), read("version")
457
+ # 路由装饰器:自己就是接口,或者工作流、任务同时挂在路由上——"方法 路径" 照样记下
458
+ rdec = next((d for _, k, d in found if k == "route"), None)
459
+ if isinstance(rdec, ast.Call) and isinstance(rdec.func, ast.Attribute):
460
+ info.route = _route_title(rdec, mod, self._local_ctor(rdec, mod, scopes) or None)
461
+ if isinstance(dec, ast.Call):
462
+ info.retries = any(kw.arg in rs.retry_keywords and isinstance(kw.value, ast.Constant)
463
+ and kw.value.value is True for kw in dec.keywords)
464
+ return info
465
+
466
+ def _build_tasks(self) -> None:
467
+ """任务名登记:任务和工作流按函数名;pystepkit 类形式工作流按类名(入口方法的名字不登记)。"""
468
+ by_name: dict[str, set[str]] = {}
469
+ for fn in self.index.functions.values():
470
+ if self.classify(fn).kind not in ("task", "workflow"):
471
+ continue
472
+ if self._pystepkit_class_entry(fn) is not None:
473
+ cls = self._class_info(fn)
474
+ self._class_tasks[id(cls)] = fn.key
475
+ name = cls.name
476
+ else:
477
+ name = fn.node.name
478
+ by_name.setdefault(name, set()).add(fn.key)
479
+ self.task_names = set(by_name)
480
+ self.tasks = {name: next(iter(keys)) for name, keys in by_name.items() if len(keys) == 1}
481
+ self._task_keys = {k for keys in by_name.values() for k in keys}
482
+
483
+ def dispatch(self, call: ast.Call, fn: FunctionInfo, resolver: Resolver) -> Dispatch | None:
484
+ """函数 fn 里的调用是不是派发;是时给出被派发的任务。不是派发时 None。
485
+ 任务在接收者链里(kiq)或参数里(DBOS)。先按解析器找:其中第一个解析到任务函数的名字 / 属性(按导入、模块级
486
+ 符号,exact;pystepkit 类形式工作流的类对应到入口方法);没有时取第一个名字是某个任务名的,再解析它(_named_task);
487
+ 都没有时,规则允许的话算目标未知的派发。"""
488
+ if not isinstance(call.func, ast.Attribute):
489
+ return None
490
+ mod = self.index.modules[fn.file]
491
+ for rs in self._sets.values():
492
+ for rule in rs.dispatch:
493
+ if call.func.attr not in rule.methods:
494
+ continue
495
+ roots = [call.func.value] if rule.task_from == "receiver" else [*call.args, *(k.value for k in call.keywords)]
496
+ candidates = [n for root in roots for n in ast.walk(root) if isinstance(n, ast.Name | ast.Attribute)]
497
+ for n in candidates:
498
+ key = self._task_of(resolver.symbol(n, mod, fn))
499
+ if key:
500
+ return Dispatch(name_of(n), key, "exact")
501
+ named = next((n for n in candidates if name_of(n) in self.task_names), None)
502
+ if named is not None:
503
+ return Dispatch(name_of(named), *self._named_task(named, fn, resolver))
504
+ if rule.dynamic_ok:
505
+ return Dispatch(None, None, "unresolved")
506
+ return None
507
+
508
+ def _named_task(self, e: ast.expr, fn: FunctionInfo, resolver: Resolver) -> tuple[str | None, Resolution]:
509
+ """名字是某个任务名、但没有解析到任务的表达式(在函数 fn 里)→ (被派发函数的 key, 解析方式):解析到项目内的
510
+ 函数时就是它(exact);解析到项目外为 external;解析不了时,恰好一个任务叫这个名字才按名字对应(guessed),
511
+ 同名的有几个就无法判断(unresolved)。"""
512
+ sym = resolver.symbol(e, self.index.modules[fn.file], fn)
513
+ kind = sym[0] if sym else None
514
+ if kind == "func":
515
+ return sym[1], "exact"
516
+ if kind == "external":
517
+ return None, "external"
518
+ key = self.tasks.get(name_of(e))
519
+ return (key, "guessed") if key else (None, "unresolved")
520
+
521
+ def _task_of(self, sym) -> str | None:
522
+ """符号是任务函数(或 pystepkit 类形式工作流的类)时,任务函数的 key。"""
523
+ if sym and sym[0] == "func" and sym[1] in self._task_keys:
524
+ return sym[1]
525
+ if sym and sym[0] == "class":
526
+ return self._class_tasks.get(id(sym[1]))
527
+ return None
528
+
529
+ def is_noise(self, call: ast.Call) -> bool:
530
+ func = call.func
531
+ if isinstance(func, ast.Name):
532
+ return hasattr(builtins, func.id) and not func.id.startswith("_")
533
+ if isinstance(func, ast.Attribute):
534
+ if func.attr in _COUNTER_METHODS and isinstance(func.value, ast.Call) \
535
+ and isinstance(func.value.func, ast.Attribute) and func.value.func.attr == "labels":
536
+ return True
537
+ return _leftmost_name(func.value) in self.config.noise_receivers
538
+ return False