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/__init__.py +3 -0
- pystepmap/analyze.py +68 -0
- pystepmap/build.py +1101 -0
- pystepmap/cli.py +427 -0
- pystepmap/config.py +144 -0
- pystepmap/diff.py +733 -0
- pystepmap/engineid.py +73 -0
- pystepmap/entries.py +196 -0
- pystepmap/external.py +280 -0
- pystepmap/index.py +529 -0
- pystepmap/kit.py +431 -0
- pystepmap/kit_assets/SKILL.md +455 -0
- pystepmap/kit_assets/check_edited_file.py +160 -0
- pystepmap/kit_assets/dbos.md +91 -0
- pystepmap/kit_assets/openspec-flow-rules.yaml +19 -0
- pystepmap/kit_assets/pre-commit +91 -0
- pystepmap/kit_assets/requirements.md +52 -0
- pystepmap/kit_assets/routes.md +55 -0
- pystepmap/kit_assets/transfer_workflow.py +256 -0
- pystepmap/lines.py +164 -0
- pystepmap/lint.py +348 -0
- pystepmap/model.py +261 -0
- pystepmap/outline.py +863 -0
- pystepmap/progress.py +174 -0
- pystepmap/query.py +386 -0
- pystepmap/requirements.py +765 -0
- pystepmap/resolve.py +605 -0
- pystepmap/rules.py +538 -0
- pystepmap/runpath.py +585 -0
- pystepmap/selfcheck.py +112 -0
- pystepmap/stale.py +49 -0
- pystepmap/titles.py +65 -0
- pystepmap/trace.py +756 -0
- pystepmap/verify.py +968 -0
- pystepmap_core-0.1.0.dist-info/METADATA +31 -0
- pystepmap_core-0.1.0.dist-info/RECORD +39 -0
- pystepmap_core-0.1.0.dist-info/WHEEL +4 -0
- pystepmap_core-0.1.0.dist-info/entry_points.txt +2 -0
- pystepmap_core-0.1.0.dist-info/licenses/LICENSE +21 -0
pystepmap/lines.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""功能线组装:沿任务派发关系,把每个入口及其派发的后台任务整理成主列表的行。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from fnmatch import fnmatchcase
|
|
6
|
+
|
|
7
|
+
from pystepmap.config import ProjectConfig
|
|
8
|
+
from pystepmap.entries import AUTO_GROUPS
|
|
9
|
+
from pystepmap.model import FlowLine, FunctionGraph, LineTask, numbered
|
|
10
|
+
|
|
11
|
+
ENTRY_KINDS = ("route", "task", "workflow")
|
|
12
|
+
GROUP_TASK = "后台任务"
|
|
13
|
+
GROUP_OTHER = "其他入口"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _dispatch_refs(fg: FunctionGraph):
|
|
17
|
+
for node in fg.nodes:
|
|
18
|
+
for ref in node.calls:
|
|
19
|
+
if ref.is_dispatch:
|
|
20
|
+
yield ref
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def direct_dispatches(fg: FunctionGraph, functions: dict[str, FunctionGraph]) -> list[str]:
|
|
24
|
+
"""fg 自己以及沿 call_targets(不穿过别的入口)能到达的函数所派发的任务 key,按首次出现去重。"""
|
|
25
|
+
result: list[str] = []
|
|
26
|
+
seen_fns = {fg.key}
|
|
27
|
+
|
|
28
|
+
def visit(cur: FunctionGraph) -> None:
|
|
29
|
+
for ref in _dispatch_refs(cur):
|
|
30
|
+
if ref.target is not None and ref.target not in result:
|
|
31
|
+
result.append(ref.target)
|
|
32
|
+
for key in cur.call_targets:
|
|
33
|
+
callee = functions.get(key)
|
|
34
|
+
if callee is None or key in seen_fns or callee.kind in ENTRY_KINDS:
|
|
35
|
+
continue
|
|
36
|
+
seen_fns.add(key)
|
|
37
|
+
visit(callee)
|
|
38
|
+
visit(fg)
|
|
39
|
+
return result
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def annotate_dispatches(functions: dict[str, FunctionGraph]) -> None:
|
|
43
|
+
"""填写每个普通 CallRef.dispatches:其 target 任意深度能派发到的任务 key,排序去重。"""
|
|
44
|
+
cache: dict[str, list[str]] = {}
|
|
45
|
+
for fg in functions.values():
|
|
46
|
+
for node in fg.nodes:
|
|
47
|
+
for ref in node.calls:
|
|
48
|
+
if ref.is_dispatch or ref.target is None or ref.target not in functions:
|
|
49
|
+
continue
|
|
50
|
+
if ref.target not in cache:
|
|
51
|
+
cache[ref.target] = sorted(direct_dispatches(functions[ref.target], functions))
|
|
52
|
+
ref.dispatches = list(cache[ref.target])
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _is_other_entry(fg: FunctionGraph, called: set[str], referenced: set[str], dispatched: list[str]) -> bool:
|
|
56
|
+
"""没有被识别为入口、但会派发任务的顶层函数:项目里没有人调用它,也没有被当作值交出去(回调、注册表)。"""
|
|
57
|
+
return fg.kind == "function" and fg.parent is None and bool(dispatched) and fg.key not in called \
|
|
58
|
+
and fg.key not in referenced
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _extra_group(fg: FunctionGraph, config: ProjectConfig) -> str | None:
|
|
62
|
+
"""fg 是配置里 extra_entries 点名的入口时,它的分组(没写分组时"其他入口");不是时 None。只看普通函数——已经是
|
|
63
|
+
入口的、步骤、判断,以及嵌套在别的函数里的函数不受影响。"""
|
|
64
|
+
if fg.kind != "function" or fg.parent is not None: # 嵌套在别的函数里的不算(模式里的 * 也会对上它们)
|
|
65
|
+
return None
|
|
66
|
+
name = f"{fg.file}::{fg.qualname}"
|
|
67
|
+
for e in config.extra_entries:
|
|
68
|
+
if fnmatchcase(name, e["match"]):
|
|
69
|
+
return e.get("group") or GROUP_OTHER
|
|
70
|
+
return None
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def extra_entry_keys(functions: dict[str, FunctionGraph], config: ProjectConfig) -> set[str]:
|
|
74
|
+
"""配置的 extra_entries 点了名的函数。"""
|
|
75
|
+
return {k for k, fg in functions.items() if _extra_group(fg, config) is not None} if config.extra_entries else set()
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _group(fg: FunctionGraph, extra: str | None = None) -> str:
|
|
79
|
+
if fg.group:
|
|
80
|
+
return fg.group
|
|
81
|
+
if extra:
|
|
82
|
+
return extra
|
|
83
|
+
if fg.kind == "function" and fg.rule in AUTO_GROUPS: # 不靠装饰器规则认出来的入口,见 entries.py
|
|
84
|
+
return AUTO_GROUPS[fg.rule]
|
|
85
|
+
if fg.kind == "route" or fg.route: # 接口,以及挂在路由上的工作流、任务:按文件名
|
|
86
|
+
return fg.file.rsplit("/", 1)[-1].rsplit(".", 1)[0]
|
|
87
|
+
if fg.kind in ("task", "workflow"):
|
|
88
|
+
return GROUP_TASK
|
|
89
|
+
return GROUP_OTHER
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _title(fg: FunctionGraph) -> tuple[str, str]:
|
|
93
|
+
"""(标题,完整形式):没有标题的接口(含挂在路由上的工作流、任务)用 "方法 路径"(不截断,没有完整形式),其余用
|
|
94
|
+
函数的标题和 title_full。"""
|
|
95
|
+
if fg.route and fg.title == fg.qualname.rsplit(".", 1)[-1]:
|
|
96
|
+
return fg.route, ""
|
|
97
|
+
if fg.kind == "function" and fg.rule in AUTO_GROUPS and fg.title == fg.qualname.rsplit(".", 1)[-1]:
|
|
98
|
+
return f"{fg.qualname}({fg.file})", "" # 没有文档注释的 main、run:带上文件才分得清是哪一个
|
|
99
|
+
return fg.title, fg.title_full
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def assemble_lines(functions: dict[str, FunctionGraph], config: ProjectConfig,
|
|
103
|
+
referenced: set[str] = frozenset(), auto: dict[str, str] | None = None) -> tuple[list[FlowLine], list[str]]:
|
|
104
|
+
"""返回 (功能线列表, 公共任务 key 列表)。referenced:项目里被当作值交出去的函数(见 Resolver.value_references)。
|
|
105
|
+
auto:不靠装饰器规则认出来的入口(函数 key -> 认出它的方式,见 entries.auto_entries),记到函数的 rule 上。"""
|
|
106
|
+
for key, how in (auto or {}).items():
|
|
107
|
+
if functions[key].kind == "function":
|
|
108
|
+
functions[key].rule = how
|
|
109
|
+
called = {k for fg in functions.values() for k in fg.call_targets}
|
|
110
|
+
direct: dict[str, list[str]] = {}
|
|
111
|
+
entries: list[FunctionGraph] = []
|
|
112
|
+
for fg in functions.values():
|
|
113
|
+
d = direct_dispatches(fg, functions)
|
|
114
|
+
if fg.kind in ENTRY_KINDS or _is_other_entry(fg, called, referenced, d) \
|
|
115
|
+
or _extra_group(fg, config) is not None or (fg.kind == "function" and fg.rule in AUTO_GROUPS):
|
|
116
|
+
direct[fg.key] = d
|
|
117
|
+
entries.append(fg)
|
|
118
|
+
|
|
119
|
+
dispatchers: dict[str, set[str]] = {}
|
|
120
|
+
for entry in entries:
|
|
121
|
+
for t in direct[entry.key]:
|
|
122
|
+
dispatchers.setdefault(t, set()).add(entry.key)
|
|
123
|
+
common = [k for k in functions
|
|
124
|
+
if functions[k].kind in ("task", "workflow") and k in dispatchers
|
|
125
|
+
and len(dispatchers[k]) >= config.common_task_threshold]
|
|
126
|
+
common_set = set(common)
|
|
127
|
+
|
|
128
|
+
def expand(key: str, expanded: set[str]) -> LineTask:
|
|
129
|
+
"""key 及其派发的任务(递归);本条线里已经展开过的只留跳转(含成环的)。"""
|
|
130
|
+
if key in expanded:
|
|
131
|
+
return LineTask(function=key, goto=True)
|
|
132
|
+
expanded.add(key)
|
|
133
|
+
# 被派发的通常是入口(任务、工作流),direct 里有;派发表达式解析到的普通项目函数不一定在 direct 里,现算
|
|
134
|
+
dispatched = direct[key] if key in direct else direct_dispatches(functions[key], functions)
|
|
135
|
+
children = [expand(c, expanded) for c in dispatched if c in functions and c not in common_set]
|
|
136
|
+
return LineTask(function=key, children=children)
|
|
137
|
+
|
|
138
|
+
lines: list[FlowLine] = []
|
|
139
|
+
covered: set[str] = set()
|
|
140
|
+
|
|
141
|
+
def add_line(fg: FunctionGraph) -> None:
|
|
142
|
+
root = expand(fg.key, set())
|
|
143
|
+
title, title_full = _title(fg)
|
|
144
|
+
lines.append(FlowLine(id=fg.key, title=title, group=_group(fg, _extra_group(fg, config)), kind=fg.kind, root=root, title_full=title_full))
|
|
145
|
+
stack = [root]
|
|
146
|
+
while stack:
|
|
147
|
+
t = stack.pop()
|
|
148
|
+
if not t.goto:
|
|
149
|
+
covered.add(t.function)
|
|
150
|
+
stack.extend(t.children)
|
|
151
|
+
|
|
152
|
+
for fg in entries:
|
|
153
|
+
contained = fg.kind in ("task", "workflow") and fg.key not in common_set \
|
|
154
|
+
and bool(dispatchers.get(fg.key, set()) - {fg.key})
|
|
155
|
+
if not contained:
|
|
156
|
+
add_line(fg)
|
|
157
|
+
# 纯任务环(互相派发、没有入口能到达)会让每个任务都被当成"已被包含":补一条线,保证每个任务都出现
|
|
158
|
+
for fg in sorted((f for f in entries if f.kind in ("task", "workflow")), key=lambda f: f.key):
|
|
159
|
+
if fg.key not in covered:
|
|
160
|
+
add_line(fg)
|
|
161
|
+
lines.sort(key=lambda l: (l.group, l.title))
|
|
162
|
+
for line, sid in zip(lines, numbered(f"line:{functions[l.root.function].sid}" for l in lines)):
|
|
163
|
+
line.sid = sid
|
|
164
|
+
return lines, common
|
pystepmap/lint.py
ADDED
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
"""约束检查:只检查带标记的函数。编排函数只调用步骤,步骤之间不互相调用。
|
|
2
|
+
|
|
3
|
+
每条规则是一个小函数,便于单独测试和日后放宽。宁可漏报也不误报。规则在一个真实的 DBOS 项目上校准过。
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import ast
|
|
9
|
+
import builtins
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from .config import ProjectConfig
|
|
14
|
+
from .index import (
|
|
15
|
+
NOT_SOURCE_REASONS,
|
|
16
|
+
FunctionInfo,
|
|
17
|
+
ModuleInfo,
|
|
18
|
+
ProjectIndex,
|
|
19
|
+
build_index,
|
|
20
|
+
)
|
|
21
|
+
from .resolve import Resolved, Resolver, unwrap_thread_call
|
|
22
|
+
from .rules import ActiveRules, pystepkit_name
|
|
23
|
+
|
|
24
|
+
_BUILTIN_FUNCS = frozenset(n for n in dir(builtins) if not n.startswith("_"))
|
|
25
|
+
_NESTED = (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)
|
|
26
|
+
_CALLEE_KINDS = ("step", "condition", "workflow")
|
|
27
|
+
_LITERALS = (ast.Constant, ast.Dict, ast.List, ast.Tuple, ast.Set)
|
|
28
|
+
# 框架自带的编排原语(识别规则名 -> (编排对象的点分全名, 放行的方法)):项目启用了该规则时,直接调用这些方法
|
|
29
|
+
# (以及在它们返回的句柄上继续调用)在编排函数里放行。DBOS 的这些方法在工作流里调用时由 DBOS 自己按步骤记录
|
|
30
|
+
# (dbos 2.30 的 _dbos.py:启动 / 入队子工作流、run_step、消息与事件、sleep、取别的工作流的结果与状态、写流、patch、
|
|
31
|
+
# cancel_workflow),重放安全。直接读写系统库、不记成步骤的接口(队列管理、read_stream、launch / destroy 等)、
|
|
32
|
+
# DBOS.logger 这类先取属性再调用的都不放行。
|
|
33
|
+
_DBOS_PRIMITIVES = frozenset({
|
|
34
|
+
"start_workflow", "start_workflow_async", "enqueue_workflow", "enqueue_workflow_async",
|
|
35
|
+
"enqueue_workflow_with_options", "enqueue_workflow_with_options_async", "run_step", "run_step_async",
|
|
36
|
+
"send", "send_async", "send_bulk", "send_bulk_async", "recv", "recv_async",
|
|
37
|
+
"set_event", "set_event_async", "get_event", "get_event_async", "get_all_events", "get_all_events_async",
|
|
38
|
+
"sleep", "sleep_async", "asyncio_wait", "retrieve_workflow", "retrieve_workflow_async",
|
|
39
|
+
"get_result", "get_result_async", "get_workflow_status", "get_workflow_status_async", "wait_first", "wait_first_async",
|
|
40
|
+
"write_stream", "write_stream_async", "close_stream", "close_stream_async",
|
|
41
|
+
"patch", "patch_async", "deprecate_patch", "deprecate_patch_async",
|
|
42
|
+
"cancel_workflow", "cancel_workflow_async", "cancel_workflows", "cancel_workflows_async"})
|
|
43
|
+
_ORCHESTRATION: dict[str, tuple[str, frozenset[str]]] = {"dbos": ("dbos.DBOS", _DBOS_PRIMITIVES)}
|
|
44
|
+
# 容器 / 字符串取值:方法链上全是它们时算操作数据(根可以是参数)
|
|
45
|
+
_ACCESSORS = frozenset({"get", "pop", "items", "keys", "values", "copy", "strip", "split", "splitlines",
|
|
46
|
+
"lower", "upper", "startswith", "endswith", "replace"})
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclass(frozen=True)
|
|
50
|
+
class Violation:
|
|
51
|
+
file: str
|
|
52
|
+
line: int
|
|
53
|
+
code: str
|
|
54
|
+
message: str
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@dataclass
|
|
58
|
+
class CheckResult:
|
|
59
|
+
violations: list[Violation]
|
|
60
|
+
skipped: list[tuple[str, str]] # 检查范围内解析不了、没有检查的文件:(相对路径, 原因)
|
|
61
|
+
unmatched: list[str] # only_files 里没有对应到任何项目文件的项(规范化后的相对路径)
|
|
62
|
+
# 检查范围内不是项目源文件、没有读的 .py 路径(指到项目之外或指到非 .py 的符号链接、FIFO 等):只是警告
|
|
63
|
+
ignored: list[tuple[str, str]] = field(default_factory=list)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass
|
|
67
|
+
class CallSite:
|
|
68
|
+
call: ast.Call
|
|
69
|
+
in_test: bool # 位于 if / elif / while 的条件里
|
|
70
|
+
awaited: bool
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
# ---------- 收集 ----------
|
|
74
|
+
|
|
75
|
+
def collect_body(fn: FunctionInfo) -> tuple[list[CallSite], list[ast.AST]]:
|
|
76
|
+
"""函数体里的所有调用,以及内部函数 / lambda 的定义(不进入它们内部)。装饰器与参数默认值不算函数体。"""
|
|
77
|
+
calls: list[CallSite] = []
|
|
78
|
+
nested: list[ast.AST] = []
|
|
79
|
+
|
|
80
|
+
def visit(n: ast.AST, in_test: bool, awaited: bool) -> None:
|
|
81
|
+
if isinstance(n, _NESTED):
|
|
82
|
+
nested.append(n)
|
|
83
|
+
return
|
|
84
|
+
if isinstance(n, ast.Call):
|
|
85
|
+
calls.append(CallSite(n, in_test, awaited))
|
|
86
|
+
for field_name, value in ast.iter_fields(n):
|
|
87
|
+
kids = value if isinstance(value, list) else [value]
|
|
88
|
+
for c in kids:
|
|
89
|
+
if not isinstance(c, ast.AST):
|
|
90
|
+
continue
|
|
91
|
+
test = in_test or (isinstance(n, ast.If | ast.While) and field_name == "test")
|
|
92
|
+
visit(c, test, isinstance(n, ast.Await))
|
|
93
|
+
|
|
94
|
+
for st in fn.node.body:
|
|
95
|
+
visit(st, False, False)
|
|
96
|
+
return calls, nested
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def local_names(fn: FunctionInfo) -> set[str]:
|
|
100
|
+
"""参数和函数体里绑定的局部名(不含内部函数里的)。"""
|
|
101
|
+
a = fn.node.args
|
|
102
|
+
names = {x.arg for x in [*a.posonlyargs, *a.args, *a.kwonlyargs, a.vararg, a.kwarg] if x is not None}
|
|
103
|
+
|
|
104
|
+
def visit(n: ast.AST) -> None:
|
|
105
|
+
if isinstance(n, _NESTED):
|
|
106
|
+
if not isinstance(n, ast.Lambda):
|
|
107
|
+
names.add(n.name)
|
|
108
|
+
return
|
|
109
|
+
if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Store):
|
|
110
|
+
names.add(n.id)
|
|
111
|
+
elif isinstance(n, ast.ExceptHandler) and n.name:
|
|
112
|
+
names.add(n.name)
|
|
113
|
+
for c in ast.iter_child_nodes(n):
|
|
114
|
+
visit(c)
|
|
115
|
+
|
|
116
|
+
for st in fn.node.body:
|
|
117
|
+
visit(st)
|
|
118
|
+
return names
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
# ---------- 单条调用的判断 ----------
|
|
122
|
+
|
|
123
|
+
def _callee_name(call: ast.Call) -> str | None:
|
|
124
|
+
f = call.func
|
|
125
|
+
return f.id if isinstance(f, ast.Name) else f.attr if isinstance(f, ast.Attribute) else None
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def is_outcome_call(call: ast.Call, mod: ModuleInfo) -> bool:
|
|
129
|
+
"""pystepkit 的 outcome(...)(经本模块的 import 来自 pystepkit)。"""
|
|
130
|
+
return pystepkit_name(call.func, mod) == "outcome"
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def is_construction(call: ast.Call, fn: FunctionInfo, index: ProjectIndex) -> bool:
|
|
134
|
+
name = _callee_name(call)
|
|
135
|
+
if name is None:
|
|
136
|
+
return False
|
|
137
|
+
if name[:1].isupper():
|
|
138
|
+
return True
|
|
139
|
+
return isinstance(call.func, ast.Name) and name in index.modules[fn.file].classes
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def is_builtin_call(call: ast.Call, resolved: Resolved) -> bool:
|
|
143
|
+
return isinstance(call.func, ast.Name) and call.func.id in _BUILTIN_FUNCS and resolved.target is None
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _rooted_at(e: ast.expr, names: set[str]) -> bool:
|
|
147
|
+
"""表达式以 names 里的名字为根:穿过属性和下标(不穿过调用),以及 (x or {}) 这类带字面量兜底的写法。"""
|
|
148
|
+
while isinstance(e, ast.Attribute | ast.Subscript):
|
|
149
|
+
e = e.value
|
|
150
|
+
if isinstance(e, ast.BoolOp):
|
|
151
|
+
rooted = [v for v in e.values if not isinstance(v, _LITERALS)]
|
|
152
|
+
return bool(rooted) and all(_rooted_at(v, names) for v in rooted)
|
|
153
|
+
return isinstance(e, ast.Name) and e.id in names
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _method_chain(e: ast.expr) -> tuple[list[ast.Call], ast.expr]:
|
|
157
|
+
"""接收者表达式里的方法链:(链上的调用,从外到内;链的根)。穿过属性、下标、调用和 await。"""
|
|
158
|
+
calls: list[ast.Call] = []
|
|
159
|
+
while True:
|
|
160
|
+
if isinstance(e, ast.Attribute | ast.Subscript | ast.Await):
|
|
161
|
+
e = e.value
|
|
162
|
+
elif isinstance(e, ast.Call):
|
|
163
|
+
calls.append(e)
|
|
164
|
+
e = e.func
|
|
165
|
+
else:
|
|
166
|
+
return calls, e
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def is_orchestration_call(call: ast.Call, mod: ModuleInfo, rules: ActiveRules) -> bool:
|
|
170
|
+
"""直接调用框架的编排原语(DBOS.sleep(…)),或在它返回的句柄上继续调用(DBOS.start_workflow(…).get_result())。"""
|
|
171
|
+
allowed = {_ORCHESTRATION[name] for name in rules.names if name in _ORCHESTRATION}
|
|
172
|
+
if not allowed:
|
|
173
|
+
return False
|
|
174
|
+
chain: list[ast.expr] = [call]
|
|
175
|
+
e: ast.expr = call.func
|
|
176
|
+
while True:
|
|
177
|
+
chain.append(e)
|
|
178
|
+
if isinstance(e, ast.Call):
|
|
179
|
+
e = e.func
|
|
180
|
+
elif isinstance(e, ast.Attribute | ast.Subscript | ast.Await):
|
|
181
|
+
e = e.value
|
|
182
|
+
else:
|
|
183
|
+
break
|
|
184
|
+
# chain 末尾应是 [..., 调用, 属性, 名字]:编排对象上的放行方法被直接调用
|
|
185
|
+
if not (len(chain) >= 3 and isinstance(chain[-1], ast.Name) and isinstance(chain[-2], ast.Attribute)
|
|
186
|
+
and isinstance(chain[-3], ast.Call)):
|
|
187
|
+
return False
|
|
188
|
+
target = mod.imports.get(chain[-1].id)
|
|
189
|
+
return any(target == obj and chain[-2].attr in methods for obj, methods in allowed)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def is_result_call(call: ast.Call, fn: FunctionInfo, kind_of, index: ProjectIndex, rules: ActiveRules,
|
|
193
|
+
resolver: Resolver) -> bool:
|
|
194
|
+
"""调用的是步骤、判断函数、工作流、派发或编排原语:它的返回值是"步骤结果"。"""
|
|
195
|
+
call = unwrap_thread_call(call, index.modules[fn.file])
|
|
196
|
+
if rules.dispatch(call, fn, resolver) is not None or is_orchestration_call(call, index.modules[fn.file], rules):
|
|
197
|
+
return True
|
|
198
|
+
target = resolver.resolve(call, fn).target
|
|
199
|
+
return target is not None and kind_of(target) in _CALLEE_KINDS
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def result_names(fn: FunctionInfo, is_result) -> set[str]:
|
|
203
|
+
"""每次绑定都来自步骤结果(is_result 为真的调用,可以被 await)的局部名;参数和其他方式绑定过的名字不算。"""
|
|
204
|
+
a = fn.node.args
|
|
205
|
+
bad = {x.arg for x in [*a.posonlyargs, *a.args, *a.kwonlyargs, a.vararg, a.kwarg] if x is not None}
|
|
206
|
+
good: set[str] = set()
|
|
207
|
+
handled: set[int] = set()
|
|
208
|
+
|
|
209
|
+
def from_result(v: ast.expr | None) -> bool:
|
|
210
|
+
v = v.value if isinstance(v, ast.Await) else v
|
|
211
|
+
return isinstance(v, ast.Call) and is_result(v)
|
|
212
|
+
|
|
213
|
+
def visit(n: ast.AST) -> None:
|
|
214
|
+
if isinstance(n, _NESTED):
|
|
215
|
+
return
|
|
216
|
+
if isinstance(n, ast.Assign | ast.AnnAssign | ast.NamedExpr):
|
|
217
|
+
targets = n.targets if isinstance(n, ast.Assign) else [n.target]
|
|
218
|
+
ok = from_result(n.value)
|
|
219
|
+
for t in targets:
|
|
220
|
+
if isinstance(t, ast.Name):
|
|
221
|
+
handled.add(id(t))
|
|
222
|
+
(good if ok else bad).add(t.id)
|
|
223
|
+
elif isinstance(n, ast.Name) and isinstance(n.ctx, ast.Store) and id(n) not in handled:
|
|
224
|
+
bad.add(n.id)
|
|
225
|
+
for c in ast.iter_child_nodes(n):
|
|
226
|
+
visit(c)
|
|
227
|
+
|
|
228
|
+
for st in fn.node.body:
|
|
229
|
+
visit(st)
|
|
230
|
+
return good - bad
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def is_local_method_call(call: ast.Call, resolved: Resolved, locals_: set[str], awaited: bool,
|
|
234
|
+
results: set[str] = frozenset(), is_result=lambda c: False) -> bool:
|
|
235
|
+
"""操作步骤结果的方法调用,且不是项目内函数:
|
|
236
|
+
- 不经方法链、直接在局部名或参数上调用方法(原规则;它把任何局部名都当作步骤结果,是遗留问题);
|
|
237
|
+
- 方法链从步骤结果开始:根是 results 里的局部名,或链最里面的调用本身就是步骤 / 派发 / 编排原语;
|
|
238
|
+
- 方法链上全是容器 / 字符串取值(_ACCESSORS),根是局部名或参数。"""
|
|
239
|
+
if awaited or not isinstance(call.func, ast.Attribute):
|
|
240
|
+
return False
|
|
241
|
+
if resolved.how == "exact" and resolved.target:
|
|
242
|
+
return False
|
|
243
|
+
chain, root = _method_chain(call.func.value)
|
|
244
|
+
if not chain:
|
|
245
|
+
return _rooted_at(call.func.value, locals_)
|
|
246
|
+
if is_result(chain[-1]) or _rooted_at(root, results):
|
|
247
|
+
return True
|
|
248
|
+
accessors = call.func.attr in _ACCESSORS and all(
|
|
249
|
+
isinstance(c.func, ast.Attribute) and c.func.attr in _ACCESSORS for c in chain)
|
|
250
|
+
return accessors and _rooted_at(root, locals_)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def check_workflow_call(site: CallSite, fn: FunctionInfo, kind_of, index: ProjectIndex,
|
|
254
|
+
rules: ActiveRules, resolver: Resolver, locals_: set[str],
|
|
255
|
+
results: set[str] = frozenset()) -> tuple[str, str] | None:
|
|
256
|
+
"""SM001 / SM002 的判断;返回 (代码, 信息),合规时 None。results:每次绑定都来自步骤结果的局部名。"""
|
|
257
|
+
mod = index.modules[fn.file]
|
|
258
|
+
call = unwrap_thread_call(site.call, mod)
|
|
259
|
+
if is_orchestration_call(call, mod, rules):
|
|
260
|
+
return None
|
|
261
|
+
resolved = resolver.resolve(call, fn)
|
|
262
|
+
target_kind = kind_of(resolved.target) if resolved.target else None
|
|
263
|
+
show = resolved.display
|
|
264
|
+
|
|
265
|
+
def is_result(c: ast.Call) -> bool:
|
|
266
|
+
return is_result_call(c, fn, kind_of, index, rules, resolver)
|
|
267
|
+
|
|
268
|
+
if site.in_test:
|
|
269
|
+
ok = target_kind in ("step", "condition") or is_builtin_call(call, resolved) \
|
|
270
|
+
or is_local_method_call(call, resolved, locals_, site.awaited, results, is_result)
|
|
271
|
+
return None if ok else ("SM002", f"判断条件里不能做计算:{show}(…),改为引用步骤结果或判断函数")
|
|
272
|
+
if rules.dispatch(call, fn, resolver) is not None:
|
|
273
|
+
return None
|
|
274
|
+
if target_kind in _CALLEE_KINDS or is_outcome_call(call, mod) or is_construction(call, fn, index) \
|
|
275
|
+
or is_builtin_call(call, resolved) or is_local_method_call(call, resolved, locals_, site.awaited, results,
|
|
276
|
+
is_result):
|
|
277
|
+
return None
|
|
278
|
+
return ("SM001", f"编排函数只能调用步骤:{show}(…) 不是步骤")
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def check_step_call(call: ast.Call, fn: FunctionInfo, kind_of, resolver: Resolver) -> str | None:
|
|
282
|
+
"""SM003:步骤里调用另一个步骤(只信精确解析;asyncio.to_thread(另一个步骤, …) 也算)。"""
|
|
283
|
+
resolved = resolver.resolve(unwrap_thread_call(call, resolver.index.modules[fn.file]), fn)
|
|
284
|
+
if resolved.how != "exact" or not resolved.target or resolved.target == fn.key:
|
|
285
|
+
return None
|
|
286
|
+
if kind_of(resolved.target) != "step":
|
|
287
|
+
return None
|
|
288
|
+
return f"步骤 {fn.node.name} 里不能调用另一个步骤 {resolver.index.functions[resolved.target].node.name}"
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
# ---------- 入口 ----------
|
|
292
|
+
|
|
293
|
+
def _norm_files(root: Path, files: list[str]) -> set[str]:
|
|
294
|
+
out = set()
|
|
295
|
+
for f in files:
|
|
296
|
+
p = Path(f)
|
|
297
|
+
if p.is_absolute():
|
|
298
|
+
try:
|
|
299
|
+
p = p.resolve().relative_to(root)
|
|
300
|
+
except ValueError:
|
|
301
|
+
pass
|
|
302
|
+
out.add(p.as_posix())
|
|
303
|
+
return out
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def check_project(root: Path, config: ProjectConfig | None = None, *,
|
|
307
|
+
treat_as_marked: frozenset[str] = frozenset(),
|
|
308
|
+
only_files: list[str] | None = None) -> CheckResult:
|
|
309
|
+
"""检查 root 下带标记的函数(only_files 给出时只检查这些文件里的)。解析不了的文件没法检查,在检查范围内的
|
|
310
|
+
列在结果的 skipped 里;不是项目源文件、没有读的路径(见 index.NOT_SOURCE_REASONS)列在 ignored 里。"""
|
|
311
|
+
config = config or ProjectConfig()
|
|
312
|
+
root = Path(root).resolve()
|
|
313
|
+
index = build_index(root, config)
|
|
314
|
+
rules, resolver = ActiveRules(index, config), Resolver(index)
|
|
315
|
+
wanted = _norm_files(root, only_files) if only_files is not None else None
|
|
316
|
+
kinds = {k: rules.classify(f) for k, f in index.functions.items()}
|
|
317
|
+
|
|
318
|
+
def kind_of(key: str) -> str:
|
|
319
|
+
return kinds[key].kind
|
|
320
|
+
|
|
321
|
+
out: list[Violation] = []
|
|
322
|
+
for key in sorted(index.functions):
|
|
323
|
+
fn, info = index.functions[key], kinds[key]
|
|
324
|
+
if wanted is not None and fn.file not in wanted:
|
|
325
|
+
continue
|
|
326
|
+
if not (info.marked or info.rule in treat_as_marked) or info.kind not in ("workflow", "step"):
|
|
327
|
+
continue
|
|
328
|
+
calls, nested = collect_body(fn)
|
|
329
|
+
if info.kind == "step":
|
|
330
|
+
for site in calls:
|
|
331
|
+
msg = check_step_call(site.call, fn, kind_of, resolver)
|
|
332
|
+
if msg:
|
|
333
|
+
out.append(Violation(fn.file, site.call.lineno, "SM003", msg))
|
|
334
|
+
continue
|
|
335
|
+
locals_ = local_names(fn)
|
|
336
|
+
results = result_names(fn, lambda c, fn=fn: is_result_call(c, fn, kind_of, index, rules, resolver))
|
|
337
|
+
for site in calls:
|
|
338
|
+
r = check_workflow_call(site, fn, kind_of, index, rules, resolver, locals_, results)
|
|
339
|
+
if r:
|
|
340
|
+
out.append(Violation(fn.file, site.call.lineno, r[0], r[1]))
|
|
341
|
+
for n in nested:
|
|
342
|
+
out.append(Violation(fn.file, n.lineno, "SM004", "编排函数里不能定义内部函数"))
|
|
343
|
+
in_scope = [(f, why) for f, why in index.skipped if wanted is None or f in wanted]
|
|
344
|
+
skipped = [(f, why) for f, why in in_scope if why not in NOT_SOURCE_REASONS]
|
|
345
|
+
ignored = [(f, why) for f, why in in_scope if why in NOT_SOURCE_REASONS]
|
|
346
|
+
known = set(index.modules) | {f for f, _ in index.skipped}
|
|
347
|
+
unmatched = sorted(wanted - known) if wanted is not None else []
|
|
348
|
+
return CheckResult(sorted(out, key=lambda v: (v.file, v.line, v.code)), skipped, unmatched, ignored)
|