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/outline.py
ADDED
|
@@ -0,0 +1,863 @@
|
|
|
1
|
+
"""给 AI 读的流程文本:一个函数、一条功能线写成缩进的大纲(function_outline / line_outline),或画成 Mermaid 流程图
|
|
2
|
+
(line_mermaid)。纯函数,只读图。
|
|
3
|
+
|
|
4
|
+
大纲的写法:
|
|
5
|
+
- 函数头一行"<种类> <限定名> <文件>:<def 行> [<函数 sid>]"(种类:接口 / 任务 / 工作流 / 函数),开始节点就是这一行。
|
|
6
|
+
- 其余每个节点恰好一行"[节点 sid] L行号 文字"(隐含节点没有 L):步骤写标题(副标题不同时括号里写调用名),判断、循环、
|
|
7
|
+
捕获写"判断 / 循环 / 捕获 <源码原文>"(另有标题时括号里写标题),结局写"结局·正常 / 跳过 / 失败 / 异常:标题"。
|
|
8
|
+
隐含的"未捕获异常退出"不写(每个函数都有,它没有入边,任何节点都可能从它离开;[end:uncaught] 这个 sid 照样能
|
|
9
|
+
用);只有"未捕获异常退出(任务会重试)"写在函数段的最后。再是"走不到的节点:"一块(有的话)。
|
|
10
|
+
- 缩进表示分支:判断、循环的每条出路、异常的落脚点(raise 连线,画在连线的起点下面)另起一行,以"是 →""否 →"
|
|
11
|
+
"`模式` →""都不匹配 →""每次 →""循环结束 →""出错 →"开头并缩进一级,接着的节点和这一行同样缩进;分支之后的主干回到
|
|
12
|
+
分出它的节点的缩进。主干在汇合点接上:分出去的几条路都走到的第一个节点(后支配点);一条路提前结束(return、raise、
|
|
13
|
+
continue、break)时不算它,汇合点就是另一条路的去处;几条路都提前结束时没有汇合点,每条都缩进着画完。循环之后的主干
|
|
14
|
+
只从"循环结束"和 break 的去处算,不会落在循环体里。elif 写成"否则 →",和第一个 if 的分支同一缩进。match 的每个
|
|
15
|
+
非兜底分支都有自己的一行。
|
|
16
|
+
- **读者推断的"接下来"必须是真实的后继**:一块(一条分支、循环体、"出错 →"的处理)写完时,读者会以为接着的是这一块
|
|
17
|
+
之后同一缩进的那一行("每次 →"块是回到循环节点);真实的去处不是它时写一行"↪":已经画过的"↪ 回到 [sid] 文字",
|
|
18
|
+
还没画到的"↪ 到 …",break、进入 finally 体分别写"↪ 跳出循环,到 …""↪ 进入 finally,到 …";break / continue
|
|
19
|
+
穿过 finally 时写明出 finally 体之后做什么:"↪ 进入 finally 再跳出循环,到 …""↪ 进入 finally 再回到循环,到 …"
|
|
20
|
+
(分不清时"再跳出循环或回到循环")。节点除了往下走还有 break / continue / 进 finally 的出路时(如 finally 体的出口),
|
|
21
|
+
那几条写成它下面缩进一级的"↪"行。判断的两条分支走到同一个节点、走法不同时(一条直接、一条穿过 finally),两条都算分支。
|
|
22
|
+
- match 的分支按分支体所在行排;没有节点的分支(pass、直接 break / continue)图里没有它在源码里的位置,排在后面,前面
|
|
23
|
+
先写一行"(以下分支没有节点,原顺序未知)",读者不要从这几行的先后推断哪个先匹配;兜底的(_、裸名字)和"都不匹配"
|
|
24
|
+
最后。
|
|
25
|
+
- depth(限制在 0~5):depth > 0 时步骤调用的项目内函数在这一步下面缩进一级展开(以"调用 函数名 文件:行 [函数 sid]"
|
|
26
|
+
起头),被调函数里再减一;同一份大纲里一个函数只展开一次,之后写"(上面已展开)"。depth = 0(以及判断、循环上的调用)
|
|
27
|
+
只在行尾标"⇒ 可展开 [函数 sid]",被调函数里会派发任务时再注"(内部派发 …)"。派发写"⇒ 见下面 / 上面的任务 …"(功能
|
|
28
|
+
线里)、"⇒ 公共任务 …(不并入本线)"、"⇒ 派发的任务 [sid]"。
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
from __future__ import annotations
|
|
32
|
+
|
|
33
|
+
import re
|
|
34
|
+
from dataclasses import dataclass, field
|
|
35
|
+
|
|
36
|
+
from .build import UNCAUGHT_TITLE
|
|
37
|
+
from .model import Edge, FlowLine, FunctionGraph, LineTask, Node, ProjectGraph
|
|
38
|
+
from .query import line_functions
|
|
39
|
+
|
|
40
|
+
INDENT = " "
|
|
41
|
+
MAX_DEPTH = 5
|
|
42
|
+
_FN_KIND = {"route": "接口", "task": "任务", "workflow": "工作流"}
|
|
43
|
+
_END = {"ok": "正常", "skipped": "跳过", "failed": "失败", "exception": "异常"}
|
|
44
|
+
_HEAD_WORD = {"cond": "判断", "loop": "循环", "catch": "捕获"}
|
|
45
|
+
_PLAIN = frozenset({"next", "yes", "no", "case", "loop_each", "loop_exit"}) # 走到汇合点时不用说的连线
|
|
46
|
+
_SIDE = frozenset({"break", "finally", "loop_back"}) # 非判断、循环节点的另外的出路:写成"↪"行
|
|
47
|
+
_KIND_WORD = {"next": "接着", "yes": "是", "no": "否", "case": "分支", "loop_each": "每次", "loop_exit": "循环结束",
|
|
48
|
+
"loop_back": "回到循环", "break": "跳出循环", "finally": "进入 finally", "raise": "出错"}
|
|
49
|
+
_JUMP_LEAD = {"break": "跳出循环,", "finally": "进入 finally,"}
|
|
50
|
+
_ELIF = "否则 → "
|
|
51
|
+
_AGAIN = "\0again" # 合流分析里"又回到了出发的节点"(循环体回到循环节点):当作一个提前结束的去处
|
|
52
|
+
_IRREFUTABLE = re.compile(r"[A-Za-z_]\w*") # 不带守卫的 _ 或裸名字:兜底的 case(None、True、False 除外)
|
|
53
|
+
_VALUE_NAMES = frozenset({"None", "True", "False"})
|
|
54
|
+
_QUIET = {"yes": "是", "no": "否"}
|
|
55
|
+
_UNORDERED = "(以下分支没有节点,原顺序未知)"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def node_ref(fg: FunctionGraph, node: Node) -> str:
|
|
59
|
+
"""节点在大纲里的引用:"[<节点 sid>]"(没有 sid 的旧图用节点 id)。"""
|
|
60
|
+
return f"[{node.sid or node.id}]"
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def node_text(node: Node) -> str:
|
|
64
|
+
"""节点行里 sid、行号之后的文字(完整形式,不截断)。"""
|
|
65
|
+
title = node.title_full or node.title
|
|
66
|
+
sub = node.subtitle_full or node.subtitle
|
|
67
|
+
if node.type == "start":
|
|
68
|
+
return f"开始:{title}"
|
|
69
|
+
if node.type == "end":
|
|
70
|
+
return f"结局·{_END[node.end_kind]}:{title}" if node.end_kind in _END else f"结局:{title}"
|
|
71
|
+
if node.type in _HEAD_WORD:
|
|
72
|
+
word = _HEAD_WORD[node.type]
|
|
73
|
+
if not sub:
|
|
74
|
+
return title if title.startswith(word) else f"{word} {title}"
|
|
75
|
+
own = title not in (sub, f"{word} {sub}")
|
|
76
|
+
return f"{word} {sub}" + (f"({title})" if own else "")
|
|
77
|
+
if node.calls and all(ref.is_dispatch for ref in node.calls): # 派发:标题已是"派发:任务标题",行尾再写任务名
|
|
78
|
+
return title
|
|
79
|
+
return title + (f"({sub})" if sub and sub != title else "")
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _head(fg: FunctionGraph) -> str:
|
|
83
|
+
name = fg.qualname + (f"({fg.route})" if fg.route else "") # 接口,以及挂在路由上的工作流、任务
|
|
84
|
+
return f"{_FN_KIND.get(fg.kind, '函数')} {name} {fg.file}:{fg.line} [{fg.sid or fg.key}]"
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _plain(e: Edge) -> bool:
|
|
88
|
+
"""顺着结构走的连线;break、进入 finally、continue(带分支的 loop_back)、raise 不算。"""
|
|
89
|
+
return e.kind in _PLAIN or (e.kind == "loop_back" and not (e.branch or e.label))
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _early(e: Edge) -> bool:
|
|
93
|
+
"""判断的一条分支直接 continue / 穿过 finally 跳走(带分支的 loop_back、finally):合流分析里算提前结束。"""
|
|
94
|
+
return e.kind in ("loop_back", "finally") and bool(e.branch or e.label)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _dominators(root: str, succ: dict[str, list[str]]) -> dict[str, str]:
|
|
98
|
+
"""root 出发的图里每个节点的直接支配点(Cooper–Harvey–Kennedy 迭代);走不到的节点不在结果里。"""
|
|
99
|
+
order: list[str] = []
|
|
100
|
+
seen = {root}
|
|
101
|
+
stack = [(root, iter(succ.get(root, ())))]
|
|
102
|
+
while stack:
|
|
103
|
+
node, it = stack[-1]
|
|
104
|
+
for nxt in it:
|
|
105
|
+
if nxt not in seen:
|
|
106
|
+
seen.add(nxt)
|
|
107
|
+
stack.append((nxt, iter(succ.get(nxt, ()))))
|
|
108
|
+
break
|
|
109
|
+
else:
|
|
110
|
+
stack.pop()
|
|
111
|
+
order.append(node)
|
|
112
|
+
rpo = order[::-1]
|
|
113
|
+
index = {n: i for i, n in enumerate(rpo)}
|
|
114
|
+
preds: dict[str, list[str]] = {n: [] for n in rpo}
|
|
115
|
+
for n in rpo:
|
|
116
|
+
for m in succ.get(n, ()):
|
|
117
|
+
preds[m].append(n)
|
|
118
|
+
idom = {root: root}
|
|
119
|
+
|
|
120
|
+
def meet(a: str, b: str) -> str:
|
|
121
|
+
while a != b:
|
|
122
|
+
while index[a] > index[b]:
|
|
123
|
+
a = idom[a]
|
|
124
|
+
while index[b] > index[a]:
|
|
125
|
+
b = idom[b]
|
|
126
|
+
return a
|
|
127
|
+
|
|
128
|
+
changed = True
|
|
129
|
+
while changed:
|
|
130
|
+
changed = False
|
|
131
|
+
for n in rpo[1:]:
|
|
132
|
+
new = None
|
|
133
|
+
for p in preds[n]:
|
|
134
|
+
if p in idom:
|
|
135
|
+
new = p if new is None else meet(p, new)
|
|
136
|
+
if new is not None and idom.get(n) != new:
|
|
137
|
+
idom[n] = new
|
|
138
|
+
changed = True
|
|
139
|
+
return idom
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
class _Fn:
|
|
143
|
+
"""一个函数图的索引:节点、出边、入边、生成顺序、从开始节点走得到的节点、主干的自然出口、循环体。"""
|
|
144
|
+
|
|
145
|
+
def __init__(self, fg: FunctionGraph) -> None:
|
|
146
|
+
self.fg = fg
|
|
147
|
+
self.nodes = {n.id: n for n in fg.nodes}
|
|
148
|
+
self.order = {n.id: i for i, n in enumerate(fg.nodes)}
|
|
149
|
+
self.outs: dict[str, list[Edge]] = {n.id: [] for n in fg.nodes}
|
|
150
|
+
self.ins: dict[str, list[Edge]] = {n.id: [] for n in fg.nodes}
|
|
151
|
+
for e in fg.edges:
|
|
152
|
+
if e.src in self.nodes and e.dst in self.nodes:
|
|
153
|
+
self.outs[e.src].append(e)
|
|
154
|
+
self.ins[e.dst].append(e)
|
|
155
|
+
self.start = next((n.id for n in fg.nodes if n.type == "start"), None)
|
|
156
|
+
self.reach: set[str] = set()
|
|
157
|
+
stack = [self.start] if self.start else []
|
|
158
|
+
while stack:
|
|
159
|
+
cur = stack.pop()
|
|
160
|
+
if cur not in self.reach:
|
|
161
|
+
self.reach.add(cur)
|
|
162
|
+
stack += [e.dst for e in self.outs[cur]]
|
|
163
|
+
self.uncaught = [n.id for n in fg.nodes if n.type == "end" and n.end_kind == "exception" and not n.line]
|
|
164
|
+
ends = [n.id for n in fg.nodes if n.type == "end" and n.id in self.reach and n.id not in self.uncaught]
|
|
165
|
+
implicit = [nid for nid in ends if not self.nodes[nid].line]
|
|
166
|
+
# 主干的自然出口:执行到函数末尾;没有时(每条路都 return / raise)是最后一个结局
|
|
167
|
+
self.natural = implicit[0] if implicit else max(ends, key=self.order.__getitem__, default=None)
|
|
168
|
+
if not implicit: # 每条路都以结局结束、最后进同一个 finally 体(它的出口不往后接):主干落在这个 finally 体上
|
|
169
|
+
closing = [e.dst for e in fg.edges if e.kind == "finally" and e.src in ends and not self._ends_after(e.dst)]
|
|
170
|
+
if closing:
|
|
171
|
+
self.natural = max(closing, key=self.order.__getitem__)
|
|
172
|
+
self._bodies: dict[str, set[str]] = {}
|
|
173
|
+
self._idom: dict[str, str] | None = None
|
|
174
|
+
|
|
175
|
+
def _ends_after(self, nid: str) -> bool:
|
|
176
|
+
"""从 nid 往后还走得到结局。"""
|
|
177
|
+
seen, stack = set(), [nid]
|
|
178
|
+
while stack:
|
|
179
|
+
cur = stack.pop()
|
|
180
|
+
if cur in seen:
|
|
181
|
+
continue
|
|
182
|
+
seen.add(cur)
|
|
183
|
+
if self.nodes[cur].type == "end":
|
|
184
|
+
return True
|
|
185
|
+
stack += [e.dst for e in self.outs[cur]]
|
|
186
|
+
return False
|
|
187
|
+
|
|
188
|
+
def normal(self, nid: str) -> list[Edge]:
|
|
189
|
+
"""nid 不是 raise 的出边(自环不算)。"""
|
|
190
|
+
return [e for e in self.outs[nid] if e.kind != "raise" and e.dst != nid]
|
|
191
|
+
|
|
192
|
+
def only_from(self, nid: str, src: str) -> bool:
|
|
193
|
+
"""nid 只从 src 进来(不算 raise 连线)。"""
|
|
194
|
+
ins = [e for e in self.ins[nid] if e.kind != "raise"]
|
|
195
|
+
return bool(ins) and all(e.src == src for e in ins)
|
|
196
|
+
|
|
197
|
+
def dominated(self, node: str, head: str) -> bool:
|
|
198
|
+
"""从开始节点到 node 的每条路都经过 head。"""
|
|
199
|
+
if self._idom is None:
|
|
200
|
+
succ = {n: [e.dst for e in es] for n, es in self.outs.items()}
|
|
201
|
+
self._idom = _dominators(self.start, succ) if self.start else {}
|
|
202
|
+
cur = node
|
|
203
|
+
while cur in self._idom:
|
|
204
|
+
if cur == head:
|
|
205
|
+
return True
|
|
206
|
+
nxt = self._idom[cur]
|
|
207
|
+
if nxt == cur:
|
|
208
|
+
return False
|
|
209
|
+
cur = nxt
|
|
210
|
+
return False
|
|
211
|
+
|
|
212
|
+
def body(self, loop: str) -> set[str]:
|
|
213
|
+
"""循环 loop 的循环体(自然循环):回到它的连线中起点受它支配的(回边),从这些起点倒着走、不经过它能到的节点。
|
|
214
|
+
内层循环的 break 落在外层循环体末尾时画成到外层循环节点的 loop_back,外层循环节点不受内层支配,不算内层的循环体。"""
|
|
215
|
+
if loop not in self._bodies:
|
|
216
|
+
stack = [e.src for e in self.ins[loop] if e.src != loop and self.dominated(e.src, loop)]
|
|
217
|
+
body: set[str] = set()
|
|
218
|
+
while stack:
|
|
219
|
+
u = stack.pop()
|
|
220
|
+
if u != loop and u not in body:
|
|
221
|
+
body.add(u)
|
|
222
|
+
stack += [e.src for e in self.ins[u]]
|
|
223
|
+
self._bodies[loop] = body
|
|
224
|
+
return self._bodies[loop]
|
|
225
|
+
|
|
226
|
+
def loop_exits(self, loop: str) -> list[str]:
|
|
227
|
+
"""循环之后的路从哪里开始:loop_exit 的去处(else 体或循环之后),和循环体里 break 跳到的循环体外的节点。"""
|
|
228
|
+
body = self.body(loop)
|
|
229
|
+
out = [e.dst for e in self.normal(loop) if e.kind in ("loop_exit", "break")]
|
|
230
|
+
out += [x.dst for b in sorted(body, key=self.order.__getitem__) for x in self.outs[b]
|
|
231
|
+
if x.kind == "break" and x.dst not in body]
|
|
232
|
+
return list(dict.fromkeys(out))
|
|
233
|
+
|
|
234
|
+
def is_match(self, node: Node) -> bool:
|
|
235
|
+
"""match 的判断节点(docs/graph-schema.md"读连线"第 1 点)。"""
|
|
236
|
+
if node.type != "cond" or not node.subtitle.startswith("match "):
|
|
237
|
+
return False
|
|
238
|
+
return not any(e.kind in ("yes", "no") or e.label in ("是", "否") for e in self.outs[node.id] if e.kind != "raise")
|
|
239
|
+
|
|
240
|
+
def is_else(self, node: Node, e: Edge) -> bool:
|
|
241
|
+
"""match 没有兜底分支时越过整个 match 的那一条(都不匹配)。"""
|
|
242
|
+
return e.branch == "else" or (not e.branch and e.label == "都不匹配")
|
|
243
|
+
|
|
244
|
+
def branch_word(self, node: Node, e: Edge, quoted: bool) -> str:
|
|
245
|
+
"""判断节点一条分支的说法:是 / 否 / `模式` / 都不匹配(没有 branch 的旧图按 kind、label 回退)。"""
|
|
246
|
+
if self.is_match(node):
|
|
247
|
+
if self.is_else(node, e):
|
|
248
|
+
return "都不匹配"
|
|
249
|
+
text = e.label_full or e.label or e.branch
|
|
250
|
+
return f"`{text}`" if quoted else text
|
|
251
|
+
which = e.branch or {"yes": "yes", "no": "no"}.get(e.kind) or {"是": "yes", "否": "no"}.get(e.label, "")
|
|
252
|
+
return {"yes": "是", "no": "否"}.get(which, _KIND_WORD.get(e.kind, e.kind))
|
|
253
|
+
|
|
254
|
+
def label(self, node: Node, e: Edge) -> str:
|
|
255
|
+
if e.kind == "raise":
|
|
256
|
+
return "出错"
|
|
257
|
+
if node.type == "cond":
|
|
258
|
+
return self.branch_word(node, e, quoted=True)
|
|
259
|
+
if node.type == "loop":
|
|
260
|
+
return "循环结束" if e.kind == "loop_exit" else "每次"
|
|
261
|
+
return _KIND_WORD.get(e.kind, e.kind)
|
|
262
|
+
|
|
263
|
+
def case_bodies(self, node: Node) -> set[str]:
|
|
264
|
+
"""match 节点各个非兜底分支自己的分支体的第一个节点(只从这个 match 进来的节点)。"""
|
|
265
|
+
return {e.dst for e in self.normal(node.id) if not self.is_else(node, e) and self.only_from(e.dst, node.id)}
|
|
266
|
+
|
|
267
|
+
def is_fallback(self, node: Node, e: Edge) -> bool:
|
|
268
|
+
"""match 的兜底分支:不带守卫的 _ 或裸名字(None、True、False 是值,不算),以及"都不匹配"。"""
|
|
269
|
+
label = e.label_full or e.label
|
|
270
|
+
return self.is_else(node, e) or (bool(_IRREFUTABLE.fullmatch(label)) and label not in _VALUE_NAMES)
|
|
271
|
+
|
|
272
|
+
def case_line(self, node: Node, e: Edge, own: set[str]) -> int | None:
|
|
273
|
+
"""match 一个分支的分支体第一个节点所在行;分支没有自己的节点时为 None。"""
|
|
274
|
+
return self.nodes[e.dst].line or None if e.dst in own else None
|
|
275
|
+
|
|
276
|
+
def branch_order(self, node: Node, edges: list[Edge]) -> list[Edge]:
|
|
277
|
+
"""分支的先后:循环先"每次"后"循环结束";if 先"是"后"否";match 有分支体的按分支体所在行,没有的(pass、直接
|
|
278
|
+
break、continue)按连线顺序排在它们后面,兜底的(_、裸名字)和"都不匹配"最后。"""
|
|
279
|
+
if node.type == "loop":
|
|
280
|
+
return sorted(edges, key=lambda e: e.kind == "loop_exit")
|
|
281
|
+
if node.type != "cond":
|
|
282
|
+
return edges
|
|
283
|
+
if not self.is_match(node):
|
|
284
|
+
rank = {"是": 0, "否": 1}
|
|
285
|
+
return sorted(edges, key=lambda e: rank.get(self.branch_word(node, e, quoted=False), 0))
|
|
286
|
+
own = self.case_bodies(node)
|
|
287
|
+
|
|
288
|
+
def key(item: tuple[int, Edge]) -> tuple[bool, float, int]:
|
|
289
|
+
i, e = item
|
|
290
|
+
line = self.case_line(node, e, own)
|
|
291
|
+
return self.is_fallback(node, e), float("inf") if line is None else line, i
|
|
292
|
+
|
|
293
|
+
return [e for _, e in sorted(enumerate(edges), key=key)]
|
|
294
|
+
|
|
295
|
+
def unordered_from(self, node: Node, ordered: list[Edge]) -> Edge | None:
|
|
296
|
+
"""match 里第一个没有节点的非兜底分支:从它起的几个分支在源码里的先后不知道(至少有两个非兜底分支时才要说)。"""
|
|
297
|
+
if not self.is_match(node):
|
|
298
|
+
return None
|
|
299
|
+
own = self.case_bodies(node)
|
|
300
|
+
refutable = [e for e in ordered if not self.is_fallback(node, e)]
|
|
301
|
+
if len(refutable) < 2:
|
|
302
|
+
return None
|
|
303
|
+
return next((e for e in refutable if self.case_line(node, e, own) is None), None)
|
|
304
|
+
|
|
305
|
+
def finally_leg(self, fin: str, many: bool = False, seen: frozenset[str] = frozenset()) -> str:
|
|
306
|
+
"""break / continue 穿过 finally 进入 finally 体 fin 之后做什么:"跳出循环""回到循环""跳出循环或回到循环",
|
|
307
|
+
看不出来时为空。从 fin 顺着唯一的 next 走到 finally 体的出口(有 break / loop_back / finally 出边的节点):
|
|
308
|
+
出口有 next(finally 之后还有语句)时,它的 break / loop_back 出边就是穿过它的跳转的后半段;没有 next 时
|
|
309
|
+
loop_back 是正常走完,穿过它的 continue 和它合成了一条。只有一个跳转穿过(many 为假)时,有 break 的后半段
|
|
310
|
+
就是 break,否则是 continue。出口再进外层 finally 时接着看外层的。"""
|
|
311
|
+
jumps = [e for e in self.ins[fin] if e.kind == "finally" and self.nodes[e.src].type != "end"]
|
|
312
|
+
many = many or len(jumps) > 1
|
|
313
|
+
cur = fin
|
|
314
|
+
while True:
|
|
315
|
+
if cur in seen:
|
|
316
|
+
return ""
|
|
317
|
+
seen = seen | {cur}
|
|
318
|
+
outs = self.normal(cur)
|
|
319
|
+
legs = [e for e in outs if e.kind in ("break", "loop_back", "finally") and not (e.branch or e.label)]
|
|
320
|
+
if legs:
|
|
321
|
+
break
|
|
322
|
+
if len(outs) != 1 or outs[0].kind != "next":
|
|
323
|
+
return ""
|
|
324
|
+
cur = outs[0].dst
|
|
325
|
+
if any(e.kind == "finally" for e in legs): # 还要再进外层的 finally
|
|
326
|
+
if any(e.kind != "finally" for e in legs):
|
|
327
|
+
return ""
|
|
328
|
+
outer = {e.dst for e in legs}
|
|
329
|
+
return self.finally_leg(outer.pop(), many, seen) if len(outer) == 1 else ""
|
|
330
|
+
brk = any(e.kind == "break" for e in legs)
|
|
331
|
+
back = any(e.kind == "loop_back" for e in legs)
|
|
332
|
+
if not many:
|
|
333
|
+
return "跳出循环" if brk else "回到循环" if back else ""
|
|
334
|
+
return "或".join(word for word, has in (("跳出循环", brk), ("回到循环", back)) if has)
|
|
335
|
+
|
|
336
|
+
def merge(self, b: str, edges: list[Edge], stops: frozenset[str], natural: str | None,
|
|
337
|
+
keep: set[str] = frozenset()) -> str | None:
|
|
338
|
+
"""b 的这几条出边分开的路在哪里汇合(后支配点),None 表示没有汇合点(各条路都提前结束)。
|
|
339
|
+
|
|
340
|
+
在"从这几条出边出发、不越过 stops"的区域里找:stops 和结局是终点(结局之后进 finally 体的连线不算),回到 b
|
|
341
|
+
算提前结束。先看能不能走到这一段的自然出口 natural(先不算 continue,走不到再算上),能走到就只看走得到它的
|
|
342
|
+
那些路——提前结束的路不算;走不到时取生成得最晚的终点(通常是最后一个结局)。汇合点就是那个终点时:它不在
|
|
343
|
+
stops 里(这一段接着画它)就返回它,否则返回 None。keep 里的节点不当汇合点(往后支配树上走)。"""
|
|
344
|
+
succ: dict[str, list[tuple[str, bool]]] = {}
|
|
345
|
+
|
|
346
|
+
def link(e: Edge) -> tuple[str, bool]:
|
|
347
|
+
return (_AGAIN if e.dst == b else e.dst), _early(e)
|
|
348
|
+
|
|
349
|
+
succ[b] = [link(e) for e in edges if e.dst != b]
|
|
350
|
+
todo = [d for d, _ in succ[b]]
|
|
351
|
+
while todo:
|
|
352
|
+
u = todo.pop()
|
|
353
|
+
if u in succ:
|
|
354
|
+
continue
|
|
355
|
+
if u == _AGAIN or u in stops or self.nodes[u].type == "end": # 结局是终点:进 finally 体不算接着走
|
|
356
|
+
succ[u] = []
|
|
357
|
+
continue
|
|
358
|
+
succ[u] = [link(e) for e in self.outs[u] if e.dst != u]
|
|
359
|
+
todo += [d for d, _ in succ[u]]
|
|
360
|
+
|
|
361
|
+
def alive(target: str, with_early: bool) -> set[str]:
|
|
362
|
+
rev: dict[str, list[str]] = {}
|
|
363
|
+
for u, outs in succ.items():
|
|
364
|
+
if u == target:
|
|
365
|
+
continue
|
|
366
|
+
for d, early in outs:
|
|
367
|
+
if with_early or not early:
|
|
368
|
+
rev.setdefault(d, []).append(u)
|
|
369
|
+
seen, stack = {target}, [target]
|
|
370
|
+
while stack:
|
|
371
|
+
for p in rev.get(stack.pop(), []):
|
|
372
|
+
if p not in seen:
|
|
373
|
+
seen.add(p)
|
|
374
|
+
stack.append(p)
|
|
375
|
+
return seen
|
|
376
|
+
|
|
377
|
+
target, with_early, live = None, True, set()
|
|
378
|
+
if natural is not None and natural in succ:
|
|
379
|
+
for with_early in (False, True):
|
|
380
|
+
live = alive(natural, with_early)
|
|
381
|
+
if b in live:
|
|
382
|
+
target = natural
|
|
383
|
+
break
|
|
384
|
+
if target is None:
|
|
385
|
+
sinks = [u for u, outs in succ.items() if u not in (b, _AGAIN) and (not outs or u in stops)]
|
|
386
|
+
if not sinks:
|
|
387
|
+
return None
|
|
388
|
+
target, with_early = max(sinks, key=self.order.__getitem__), True
|
|
389
|
+
live = alive(target, True)
|
|
390
|
+
rsucc: dict[str, list[str]] = {u: [] for u in live}
|
|
391
|
+
for u in live:
|
|
392
|
+
if u != target:
|
|
393
|
+
for d, early in succ[u]:
|
|
394
|
+
if d in live and (with_early or not early):
|
|
395
|
+
rsucc[d].append(u)
|
|
396
|
+
idom = _dominators(target, rsucc)
|
|
397
|
+
m = idom.get(b)
|
|
398
|
+
while m is not None and m in keep and m != target:
|
|
399
|
+
m = idom.get(m)
|
|
400
|
+
if m is None or m == b:
|
|
401
|
+
return None
|
|
402
|
+
if m == target: # 汇合在终点上:是这一段接着画的节点(自然出口、最后一个结局)时就是它,是 stops 时没有
|
|
403
|
+
return None if target in stops else target
|
|
404
|
+
return m
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
@dataclass
|
|
408
|
+
class _Part:
|
|
409
|
+
"""一份大纲里待写的一个函数(功能线的一段,或步骤下展开的被调函数):写到它时才走它的图,所以展开不递归。"""
|
|
410
|
+
|
|
411
|
+
key: str
|
|
412
|
+
level: int # 函数头的缩进
|
|
413
|
+
depth: int
|
|
414
|
+
head: str # 函数头(不含缩进)
|
|
415
|
+
segment: int | None = None # 功能线的第几段
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
@dataclass
|
|
419
|
+
class _Ctx:
|
|
420
|
+
"""一份大纲共用的状态。"""
|
|
421
|
+
|
|
422
|
+
graph: ProjectGraph
|
|
423
|
+
expanded: set[str] = field(default_factory=set) # 已经写出过的函数(展开过、或是功能线的一段)
|
|
424
|
+
segments: dict[str, int] | None = None # 功能线:任务 key -> 段的序号(派发树先序,goto 不算);单个函数时为 None
|
|
425
|
+
common: frozenset[str] = frozenset()
|
|
426
|
+
segment: int = 0 # 正在写第几段
|
|
427
|
+
|
|
428
|
+
def dispatch_note(self, target: str) -> str:
|
|
429
|
+
fg = self.graph.functions.get(target)
|
|
430
|
+
name = fg.qualname if fg else target
|
|
431
|
+
if self.segments is not None:
|
|
432
|
+
if target in self.segments:
|
|
433
|
+
return f"见{'下' if self.segments[target] > self.segment else '上'}面的任务 {name}"
|
|
434
|
+
if target in self.common:
|
|
435
|
+
return f"公共任务 {name}(不并入本线)"
|
|
436
|
+
return f"派发的任务 [{fg.sid if fg and fg.sid else target}]"
|
|
437
|
+
|
|
438
|
+
def name(self, key: str) -> str:
|
|
439
|
+
fg = self.graph.functions.get(key)
|
|
440
|
+
return fg.qualname if fg else key
|
|
441
|
+
|
|
442
|
+
def write(self, parts: list[str | _Part]) -> list[str]:
|
|
443
|
+
"""按出现的先后写出各行:遇到待写的函数时走它的图,它里面再展开的接着按先后写(用栈,不递归)。"""
|
|
444
|
+
out: list[str] = []
|
|
445
|
+
stack = [iter(parts)]
|
|
446
|
+
while stack:
|
|
447
|
+
item = next(stack[-1], None)
|
|
448
|
+
if item is None:
|
|
449
|
+
stack.pop()
|
|
450
|
+
elif isinstance(item, str):
|
|
451
|
+
out.append(item)
|
|
452
|
+
elif item.key in self.expanded:
|
|
453
|
+
out.append(INDENT * item.level + item.head + "(上面已展开)")
|
|
454
|
+
else:
|
|
455
|
+
self.expanded.add(item.key)
|
|
456
|
+
if item.segment is not None:
|
|
457
|
+
self.segment = item.segment
|
|
458
|
+
out.append(INDENT * item.level + item.head)
|
|
459
|
+
stack.append(iter(_Walk(self, self.graph.functions[item.key], item.depth, item.level + 1).run()))
|
|
460
|
+
return out
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
class _Walk:
|
|
464
|
+
"""把一个函数图写成大纲的节点行(不含函数头),从缩进 base 级开始;展开的被调函数留成 _Part,由 _Ctx.write 接着写。
|
|
465
|
+
|
|
466
|
+
chain 画一串:stops 是外层接着画的节点(走到就停),natural 是这一段的自然出口(合流分析用),after 是这一串写完后
|
|
467
|
+
读者以为接着的节点(None:说不准,走到哪都要明写)。"""
|
|
468
|
+
|
|
469
|
+
def __init__(self, ctx: _Ctx, fg: FunctionGraph, depth: int, base: int) -> None:
|
|
470
|
+
self.ctx, self.fg, self.depth, self.base = ctx, fg, depth, base
|
|
471
|
+
self.fn = _Fn(fg)
|
|
472
|
+
self.out: list[str | _Part] = []
|
|
473
|
+
self.rendered: set[str] = set()
|
|
474
|
+
|
|
475
|
+
def run(self) -> list[str | _Part]:
|
|
476
|
+
fn = self.fn
|
|
477
|
+
if fn.start is not None:
|
|
478
|
+
self.chain(fn.start, frozenset(), fn.natural, None, self.base, quiet=True)
|
|
479
|
+
missed = [n.id for n in self.fg.nodes if n.id in fn.reach and n.id not in self.rendered]
|
|
480
|
+
if missed: # 走得到却没排进分支里的(不该有):照样各写一次,不丢节点
|
|
481
|
+
self.emit(self.base, "(以下节点没能按分支排进去)")
|
|
482
|
+
for nid in missed:
|
|
483
|
+
if nid not in self.rendered:
|
|
484
|
+
self.chain(nid, frozenset(), fn.natural, None, self.base)
|
|
485
|
+
for nid in fn.uncaught: # 每个函数都有的那一行不写(没有信息);任务会重试的那种才写
|
|
486
|
+
if nid not in self.rendered:
|
|
487
|
+
self.rendered.add(nid)
|
|
488
|
+
if fn.nodes[nid].title != UNCAUGHT_TITLE:
|
|
489
|
+
self.node_line(nid, self.base, "")
|
|
490
|
+
rest = [n.id for n in self.fg.nodes if n.id not in self.rendered]
|
|
491
|
+
if rest:
|
|
492
|
+
self.emit(self.base, "走不到的节点:")
|
|
493
|
+
for nid in rest:
|
|
494
|
+
self.rendered.add(nid)
|
|
495
|
+
self.node_line(nid, self.base + 1, "")
|
|
496
|
+
return self.out
|
|
497
|
+
|
|
498
|
+
def emit(self, level: int, text: str) -> None:
|
|
499
|
+
self.out.append(INDENT * level + text)
|
|
500
|
+
|
|
501
|
+
# ---------- 走图 ----------
|
|
502
|
+
|
|
503
|
+
def chain(self, cur: str | None, stops: frozenset[str], natural: str | None, after: str | None, level: int,
|
|
504
|
+
prefix: str = "", quiet: bool = False, elif_row: bool = False) -> None:
|
|
505
|
+
"""从 cur(还没画过)起一路画下去,直到走到 stops、画过的节点或尽头;本层的汇合点画完一段再接着画(它们在这一串
|
|
506
|
+
里也算 stops)。prefix 加在第一行前面(分支的"是 → ");quiet:第一个节点不写行(开始节点,由函数头代表);
|
|
507
|
+
elif_row:第一个节点是"否则 →"链上的一行。"""
|
|
508
|
+
pending: list[str] = []
|
|
509
|
+
while True:
|
|
510
|
+
if cur is None:
|
|
511
|
+
while pending and pending[0] in self.rendered:
|
|
512
|
+
pending.pop(0)
|
|
513
|
+
if not pending:
|
|
514
|
+
return
|
|
515
|
+
cur = pending.pop(0)
|
|
516
|
+
if cur in self.rendered:
|
|
517
|
+
return
|
|
518
|
+
self.rendered.add(cur)
|
|
519
|
+
if not quiet:
|
|
520
|
+
self.node_line(cur, level, prefix)
|
|
521
|
+
quiet, prefix = False, ""
|
|
522
|
+
here = stops | frozenset(pending)
|
|
523
|
+
implied = next((p for p in pending if p not in self.rendered), after)
|
|
524
|
+
cur = self.leave(cur, here, natural, implied, level, pending, elif_row)
|
|
525
|
+
elif_row = False
|
|
526
|
+
|
|
527
|
+
def leave(self, cur: str, stops: frozenset[str], natural: str | None, after: str | None, level: int,
|
|
528
|
+
pending: list[str], elif_row: bool) -> str | None:
|
|
529
|
+
"""画 cur 的出路,返回同一层接着画的节点(None:这一串到头了)。after:cur 这一组之后读者以为接着的。"""
|
|
530
|
+
fn = self.fn
|
|
531
|
+
node = fn.nodes[cur]
|
|
532
|
+
outs = [e for e in fn.outs[cur] if e.dst != cur] # 自环(循环体为空)不画
|
|
533
|
+
normal = [e for e in outs if e.kind != "raise"]
|
|
534
|
+
raises = list({e.dst: e for e in reversed([e for e in outs if e.kind == "raise"])}.values())[::-1]
|
|
535
|
+
catch_all = None # 连异常的落脚点一起算的汇合点
|
|
536
|
+
if raises: # 循环只从循环之后的路和异常的落脚点算,不让汇合点落进循环体
|
|
537
|
+
base = [Edge(cur, t, "next") for t in fn.loop_exits(cur)] if node.type == "loop" else normal
|
|
538
|
+
catch_all = fn.merge(cur, base + raises, stops, natural)
|
|
539
|
+
if catch_all is not None and fn.nodes[catch_all].type == "catch" and any(e.dst == catch_all for e in raises):
|
|
540
|
+
catch_all = None # try 体正常走都提前结束了:捕获之后的路缩进在"出错 →"下面画完,不挪到主干上
|
|
541
|
+
side_stops = stops | {catch_all} if catch_all else stops
|
|
542
|
+
side_natural = catch_all or natural
|
|
543
|
+
side_after = catch_all or after
|
|
544
|
+
dsts = list(dict.fromkeys(e.dst for e in normal))
|
|
545
|
+
# 判断的两条出边即使到同一个节点,走法不同(一条直接、一条穿过 finally)也要各写一行
|
|
546
|
+
branching = node.type == "loop" or len(dsts) >= 2 or (node.type == "cond" and len(normal) >= 2)
|
|
547
|
+
if node.type == "loop":
|
|
548
|
+
m = self.loop_branches(cur, normal, side_stops, side_natural, side_after, level)
|
|
549
|
+
elif node.type != "cond" and len(normal) >= 2 and len({e.dst for e in normal if e.kind not in _SIDE}) <= 1:
|
|
550
|
+
# finally 体的出口之类:break / continue / 进 finally 写成下面的"↪"行(和正常的路去同一个节点也写),正常的路
|
|
551
|
+
# 接着往下
|
|
552
|
+
for e in normal:
|
|
553
|
+
if e.kind in _SIDE:
|
|
554
|
+
self.jump(e, level + 1, "")
|
|
555
|
+
normal = [e for e in normal if e.kind not in _SIDE]
|
|
556
|
+
dsts = list(dict.fromkeys(e.dst for e in normal))
|
|
557
|
+
branching, m = False, None
|
|
558
|
+
elif branching:
|
|
559
|
+
keep = fn.case_bodies(node) if fn.is_match(node) else set()
|
|
560
|
+
m = fn.merge(cur, normal, side_stops, side_natural, keep)
|
|
561
|
+
self.cond_branches(cur, normal, m, side_stops, side_natural, side_after, level, elif_row)
|
|
562
|
+
if branching:
|
|
563
|
+
self.raise_branches(raises, dsts, catch_all, side_stops, side_natural, m or side_after, level)
|
|
564
|
+
if catch_all:
|
|
565
|
+
pending.insert(0, catch_all)
|
|
566
|
+
return m
|
|
567
|
+
e = next((x for x in normal if _plain(x)), normal[0]) if normal else None
|
|
568
|
+
self.raise_branches(raises, dsts, catch_all, side_stops, side_natural,
|
|
569
|
+
self.next_after(e, catch_all, stops, side_stops, after), level)
|
|
570
|
+
if e is None:
|
|
571
|
+
return catch_all if catch_all and catch_all not in self.rendered else None
|
|
572
|
+
if catch_all is not None and e.dst != catch_all: # try 体其余的语句:同一缩进,到汇合点为止
|
|
573
|
+
self.follow(e, side_stops, side_natural, catch_all, level, "")
|
|
574
|
+
return None if catch_all in self.rendered else catch_all
|
|
575
|
+
return self.step(e, stops, after, level)
|
|
576
|
+
|
|
577
|
+
def next_after(self, e: Edge | None, catch_all: str | None, stops: frozenset[str], side_stops: frozenset[str],
|
|
578
|
+
after: str | None) -> str | None:
|
|
579
|
+
"""只有一条(或没有)正常出路的节点:它这一组("出错 →"那几块)之后读者以为接着的是什么。下一行是跳转行时
|
|
580
|
+
说不准(None)。"""
|
|
581
|
+
if e is None:
|
|
582
|
+
return catch_all or after
|
|
583
|
+
if catch_all is not None and e.dst != catch_all:
|
|
584
|
+
return e.dst if _plain(e) and e.dst not in side_stops and e.dst not in self.rendered else None
|
|
585
|
+
if e.dst in stops or e.dst in self.rendered:
|
|
586
|
+
return after if e.dst == after and _plain(e) else None
|
|
587
|
+
return e.dst if _plain(e) else None
|
|
588
|
+
|
|
589
|
+
def loop_branches(self, cur: str, normal: list[Edge], stops: frozenset[str], natural: str | None,
|
|
590
|
+
after: str | None, level: int) -> str | None:
|
|
591
|
+
"""循环节点的出路,返回循环之后的主干从哪接上:只从"循环结束"和 break 的去处(循环体外)算,不会落在循环体里。
|
|
592
|
+
"每次 →"块写完读者以为回到循环节点。"""
|
|
593
|
+
fn = self.fn
|
|
594
|
+
node = fn.nodes[cur]
|
|
595
|
+
out = fn.loop_exits(cur)
|
|
596
|
+
m = fn.merge(cur, [Edge(cur, t, "next") for t in out], stops, natural) if out else None
|
|
597
|
+
branch_stops = stops | {cur} | ({m} if m else set())
|
|
598
|
+
for e in fn.branch_order(node, normal):
|
|
599
|
+
if e.kind in ("loop_exit", "break"):
|
|
600
|
+
self.follow(e, branch_stops, m or natural, m or after, level + 1, fn.label(node, e) + " → ")
|
|
601
|
+
else:
|
|
602
|
+
self.follow(e, branch_stops, cur, cur, level + 1, "每次 → ")
|
|
603
|
+
return m
|
|
604
|
+
|
|
605
|
+
def cond_branches(self, cur: str, normal: list[Edge], m: str | None, stops: frozenset[str], natural: str | None,
|
|
606
|
+
after: str | None, level: int, elif_row: bool) -> None:
|
|
607
|
+
"""判断(或别的有几条正常出路的节点)的各条分支,cur 那一行在 level。if 的"否"是 elif(只从这里进来的 if)时
|
|
608
|
+
写成"否则 →":cur 本身是"否则 →"链上的一行、又没有汇合点时,和 cur 同级接着写(一个循环,不递归),否则在分支
|
|
609
|
+
那一级起一条新的链。match 的非兜底分支直接到汇合点时也写一行。"""
|
|
610
|
+
fn = self.fn
|
|
611
|
+
c, edges, row_level = cur, normal, level
|
|
612
|
+
while True:
|
|
613
|
+
node = fn.nodes[c]
|
|
614
|
+
b_stops = stops | {m} if m else stops
|
|
615
|
+
if m is not None: # continue / break 穿过 finally 的分支:它进的 finally 体主干后面还会画到,只写跳转
|
|
616
|
+
early = {e.dst for e in edges if _early(e) and e.dst != m}
|
|
617
|
+
b_stops |= early & self.reach_from(m, b_stops)
|
|
618
|
+
b_natural, b_after = m or natural, m or after
|
|
619
|
+
match = fn.is_match(node)
|
|
620
|
+
nxt = None
|
|
621
|
+
ordered = fn.branch_order(node, edges)
|
|
622
|
+
unordered = fn.unordered_from(node, ordered)
|
|
623
|
+
for e in ordered:
|
|
624
|
+
if e is unordered:
|
|
625
|
+
self.emit(row_level + 1, _UNORDERED)
|
|
626
|
+
if self.elif_of(node, e, b_stops):
|
|
627
|
+
if elif_row and m is None:
|
|
628
|
+
nxt = e
|
|
629
|
+
else:
|
|
630
|
+
self.follow(e, b_stops, b_natural, b_after, row_level + 1, _ELIF, elif_row=True)
|
|
631
|
+
continue
|
|
632
|
+
force = match and not fn.is_else(node, e)
|
|
633
|
+
self.follow(e, b_stops, b_natural, b_after, row_level + 1, fn.label(node, e) + " → ", force)
|
|
634
|
+
if c != cur and m is not None: # 同级写的 elif 有自己的汇合点:接在它那一块里
|
|
635
|
+
self.chain(m, stops, natural, after, row_level)
|
|
636
|
+
if nxt is None:
|
|
637
|
+
return
|
|
638
|
+
c = nxt.dst
|
|
639
|
+
self.rendered.add(c)
|
|
640
|
+
self.node_line(c, row_level, _ELIF)
|
|
641
|
+
edges = fn.normal(c)
|
|
642
|
+
m = fn.merge(c, edges, stops, natural)
|
|
643
|
+
elif_row = True
|
|
644
|
+
|
|
645
|
+
def reach_from(self, start: str, stops: frozenset[str]) -> set[str]:
|
|
646
|
+
"""从 start 出发、不经过 stops 能走到的节点(含 start)。"""
|
|
647
|
+
seen, todo = {start}, [start]
|
|
648
|
+
while todo:
|
|
649
|
+
for e in self.fn.outs[todo.pop()]:
|
|
650
|
+
if e.dst not in seen and e.dst not in stops:
|
|
651
|
+
seen.add(e.dst)
|
|
652
|
+
todo.append(e.dst)
|
|
653
|
+
return seen
|
|
654
|
+
|
|
655
|
+
def elif_of(self, node: Node, e: Edge, stops: frozenset[str]) -> bool:
|
|
656
|
+
"""if 节点 node 的"否"出路 e 是不是 elif:走到另一个只从这里进来、不是 try 体入口的 if(还没画过)。"""
|
|
657
|
+
fn = self.fn
|
|
658
|
+
if node.type != "cond" or fn.is_match(node) or e.kind != "no":
|
|
659
|
+
return False
|
|
660
|
+
d = fn.nodes[e.dst]
|
|
661
|
+
if d.type != "cond" or fn.is_match(d) or d.id in stops or d.id in self.rendered:
|
|
662
|
+
return False
|
|
663
|
+
if any(x.kind == "raise" for x in fn.outs[d.id]) or not fn.only_from(d.id, node.id):
|
|
664
|
+
return False
|
|
665
|
+
return len(fn.normal(d.id)) >= 2 # 两条出边到同一个节点也算(走法不同)
|
|
666
|
+
|
|
667
|
+
def raise_branches(self, raises: list[Edge], dsts: list[str], catch_all: str | None,
|
|
668
|
+
stops: frozenset[str], natural: str | None, after: str | None, level: int) -> None:
|
|
669
|
+
""""出错 →"分支(after:它们之后读者以为接着的)。异常落到汇合点、落到正常的路也去的地方(只写日志的 except 吞掉
|
|
670
|
+
异常后照常往下、没被捕获的异常穿过 finally 体)时不写:主干上会画到那里。"""
|
|
671
|
+
for e in raises:
|
|
672
|
+
quiet = e.dst == catch_all or e.dst in dsts or (e.dst == natural and e.dst in stops)
|
|
673
|
+
if not quiet:
|
|
674
|
+
self.follow(e, stops, natural, after, level + 1, "出错 → ")
|
|
675
|
+
|
|
676
|
+
def step(self, e: Edge, stops: frozenset[str], after: str | None, level: int) -> str | None:
|
|
677
|
+
"""同一串里顺着 e 往下走:返回下一个要画的节点;走到 stops、画过的节点时,正是读者以为接着的就不写,否则写一行
|
|
678
|
+
跳转,返回 None。"""
|
|
679
|
+
d = e.dst
|
|
680
|
+
if d in stops or d in self.rendered:
|
|
681
|
+
if not (d == after and _plain(e)):
|
|
682
|
+
self.jump(e, level, "")
|
|
683
|
+
return None
|
|
684
|
+
if not _plain(e):
|
|
685
|
+
self.jump(e, level, "")
|
|
686
|
+
return d
|
|
687
|
+
|
|
688
|
+
def follow(self, e: Edge, stops: frozenset[str], natural: str | None, after: str | None, level: int,
|
|
689
|
+
prefix: str, force: bool = False, elif_row: bool = False) -> None:
|
|
690
|
+
"""一条分支:直接到读者以为接着的节点时不写(force 时照写);到 stops 里、画过的节点时写一行跳转;否则从它的
|
|
691
|
+
终点画一串。"""
|
|
692
|
+
d = e.dst
|
|
693
|
+
if d in stops or d in self.rendered:
|
|
694
|
+
if not (d == after and _plain(e) and not force):
|
|
695
|
+
self.jump(e, level, prefix)
|
|
696
|
+
return
|
|
697
|
+
if not _plain(e) and e.kind != "raise": # "出错 →"已经说了是异常
|
|
698
|
+
self.jump(e, level, prefix)
|
|
699
|
+
prefix = ""
|
|
700
|
+
self.chain(d, stops, natural, after, level, prefix, elif_row=elif_row)
|
|
701
|
+
|
|
702
|
+
def jump(self, e: Edge, level: int, prefix: str) -> None:
|
|
703
|
+
fn = self.fn
|
|
704
|
+
node = fn.nodes[e.dst]
|
|
705
|
+
verb = "回到" if e.dst in self.rendered else "到"
|
|
706
|
+
lead = _JUMP_LEAD.get(e.kind, "")
|
|
707
|
+
if e.kind == "finally" and fn.nodes[e.src].type != "end": # break / continue 穿过 finally:说出来之后做什么
|
|
708
|
+
leg = fn.finally_leg(e.dst)
|
|
709
|
+
lead = f"进入 finally 再{leg}," if leg else lead
|
|
710
|
+
self.emit(level, f"{prefix}↪ {lead}{verb} {node_ref(self.fg, node)} {node_text(node)}")
|
|
711
|
+
|
|
712
|
+
# ---------- 节点行 ----------
|
|
713
|
+
|
|
714
|
+
def node_line(self, nid: str, level: int, prefix: str) -> None:
|
|
715
|
+
node = self.fn.nodes[nid]
|
|
716
|
+
callees: dict[str, bool] = {} # 解析到的项目内函数 -> 是否推测
|
|
717
|
+
for ref in node.calls:
|
|
718
|
+
if not ref.is_dispatch and ref.target in self.ctx.graph.functions and ref.resolution in ("exact", "guessed"):
|
|
719
|
+
callees.setdefault(ref.target, ref.resolution == "guessed")
|
|
720
|
+
expand = self.depth > 0 and node.type == "step" and bool(callees)
|
|
721
|
+
loc = f"L{node.line} " if node.line else ""
|
|
722
|
+
self.emit(level, f"{prefix}{node_ref(self.fg, node)} {loc}{node_text(node)}{self.suffix(node, callees, expand)}")
|
|
723
|
+
for branch, text in node.quiet.items(): # 没有节点、但改了变量的分支:不写的话读大纲的人不知道有这条规则
|
|
724
|
+
self.emit(level + 1, f"{_QUIET[branch]} →(这条分支没有节点,只赋值:{text})接着往下")
|
|
725
|
+
if expand:
|
|
726
|
+
for key, guessed in callees.items():
|
|
727
|
+
fg = self.ctx.graph.functions[key]
|
|
728
|
+
head = f"调用 {fg.qualname}{'(推测)' if guessed else ''} {fg.file}:{fg.line} [{fg.sid or key}]"
|
|
729
|
+
self.out.append(_Part(key, level + 1, self.depth - 1, head))
|
|
730
|
+
|
|
731
|
+
def suffix(self, node: Node, callees: dict[str, bool], expand: bool) -> str:
|
|
732
|
+
out = ""
|
|
733
|
+
if callees and not expand:
|
|
734
|
+
graph = self.ctx.graph
|
|
735
|
+
refs = " ".join(f"[{graph.functions[k].sid or k}]" + ("(推测)" if g else "") for k, g in callees.items())
|
|
736
|
+
out += f" ⇒ 可展开 {refs}"
|
|
737
|
+
inner = dict.fromkeys(t for ref in node.calls if not ref.is_dispatch and ref.target in callees
|
|
738
|
+
for t in ref.dispatches)
|
|
739
|
+
if inner:
|
|
740
|
+
out += f"(内部派发 {'、'.join(self.ctx.name(t) for t in inner)})"
|
|
741
|
+
for target in dict.fromkeys(ref.target for ref in node.calls if ref.is_dispatch and ref.target):
|
|
742
|
+
out += f" ⇒ {self.ctx.dispatch_note(target)}"
|
|
743
|
+
return out
|
|
744
|
+
|
|
745
|
+
|
|
746
|
+
def _depth(depth: int) -> int:
|
|
747
|
+
return max(0, min(depth, MAX_DEPTH))
|
|
748
|
+
|
|
749
|
+
|
|
750
|
+
def function_outline(graph: ProjectGraph, function: str, *, depth: int = 0) -> list[str]:
|
|
751
|
+
"""函数 function(key)的大纲:函数头一行,接着节点行(缩进一级)。写法见模块说明;depth 限制在 0~MAX_DEPTH。"""
|
|
752
|
+
fg = graph.functions[function]
|
|
753
|
+
return _Ctx(graph).write([_Part(function, 0, _depth(depth), _head(fg))])
|
|
754
|
+
|
|
755
|
+
|
|
756
|
+
def _preorder(task: LineTask) -> list[LineTask]:
|
|
757
|
+
out, stack = [], [task]
|
|
758
|
+
while stack:
|
|
759
|
+
t = stack.pop()
|
|
760
|
+
out.append(t)
|
|
761
|
+
stack.extend(reversed(t.children))
|
|
762
|
+
return out
|
|
763
|
+
|
|
764
|
+
|
|
765
|
+
def _segments(graph: ProjectGraph, line: FlowLine) -> list[str]:
|
|
766
|
+
"""功能线的各段:派发树先序上的任务(goto 的、不在图里的不算),不重复。"""
|
|
767
|
+
keys = [t.function for t in _preorder(line.root) if not t.goto and t.function in graph.functions]
|
|
768
|
+
return list(dict.fromkeys(keys))
|
|
769
|
+
|
|
770
|
+
|
|
771
|
+
def _common_names(graph: ProjectGraph, line: FlowLine) -> list[str]:
|
|
772
|
+
"""这条线涉及的函数派发到的公共任务的限定名,按出现顺序。"""
|
|
773
|
+
common = set(graph.common_tasks) - {line.root.function}
|
|
774
|
+
found = dict.fromkeys(ref.target for key in line_functions(graph, line) for n in graph.functions[key].nodes
|
|
775
|
+
for ref in n.calls if ref.is_dispatch and ref.target in common)
|
|
776
|
+
return [graph.functions[k].qualname if k in graph.functions else k for k in found]
|
|
777
|
+
|
|
778
|
+
|
|
779
|
+
def line_outline(graph: ProjectGraph, line: FlowLine, *, depth: int = 0) -> str:
|
|
780
|
+
"""功能线的大纲:标题行,派发树上每个任务一段(先序;goto 的只写"回到任务 …"),最后一行列出派发到的公共任务。
|
|
781
|
+
depth 限制在 0~MAX_DEPTH。"""
|
|
782
|
+
segments = _segments(graph, line)
|
|
783
|
+
ctx = _Ctx(graph, segments={k: i for i, k in enumerate(segments)}, common=frozenset(graph.common_tasks))
|
|
784
|
+
parts: list[str | _Part] = [f"# {line.title_full or line.title} [{line.sid or line.id}] 分组:{line.group}"]
|
|
785
|
+
for task in _preorder(line.root):
|
|
786
|
+
fg = graph.functions.get(task.function)
|
|
787
|
+
if fg is None:
|
|
788
|
+
continue
|
|
789
|
+
if task.goto:
|
|
790
|
+
parts.append(f"回到任务 {fg.qualname} [{fg.sid or fg.key}]")
|
|
791
|
+
else:
|
|
792
|
+
parts.append(_Part(task.function, 0, _depth(depth), _head(fg), ctx.segments[task.function]))
|
|
793
|
+
names = _common_names(graph, line)
|
|
794
|
+
if names:
|
|
795
|
+
parts.append(f"公共任务(不并入本线,各自成线):{'、'.join(names)}")
|
|
796
|
+
return "\n".join(ctx.write(parts))
|
|
797
|
+
|
|
798
|
+
|
|
799
|
+
# ---------- Mermaid ----------
|
|
800
|
+
|
|
801
|
+
_MM_ESCAPE = {"#": "#35;", '"': "#quot;", "<": "#lt;", ">": "#gt;", "|": "#124;", "`": "#96;", "&": "#amp;"}
|
|
802
|
+
_MM_KIND = {"loop_each": "每次", "loop_exit": "循环结束", "loop_back": "下一轮", "break": "跳出循环",
|
|
803
|
+
"finally": "进入 finally", "raise": "出错", "yes": "是", "no": "否"}
|
|
804
|
+
_MM_SHAPE = {"cond": ("{", "}"), "end": ("(", ")")}
|
|
805
|
+
|
|
806
|
+
|
|
807
|
+
def _mm(text: str) -> str:
|
|
808
|
+
"""放进 Mermaid 引号里的文字:换行变空格,引号、|、尖括号、#、&、反引号转成 Mermaid 的实体写法。"""
|
|
809
|
+
return "".join(_MM_ESCAPE.get(ch, ch) for ch in text.replace("\r", " ").replace("\n", " "))
|
|
810
|
+
|
|
811
|
+
|
|
812
|
+
def _mm_edge_word(fn: _Fn, e: Edge) -> str:
|
|
813
|
+
node = fn.nodes[e.src]
|
|
814
|
+
if e.kind != "raise" and node.type == "cond" and (e.branch or e.label or e.kind in ("yes", "no", "case")):
|
|
815
|
+
word = fn.branch_word(node, e, quoted=False)
|
|
816
|
+
return word if e.kind in ("yes", "no", "case") else f"{word} · {_MM_KIND.get(e.kind, e.kind)}"
|
|
817
|
+
return _MM_KIND.get(e.kind, "")
|
|
818
|
+
|
|
819
|
+
|
|
820
|
+
def _dispatch_sources(fg: FunctionGraph, child: str) -> list[str]:
|
|
821
|
+
"""fg 里派发 child 的节点:直接派发的;没有时是调用了会派发它的函数的;都没有时是开始节点。"""
|
|
822
|
+
direct = [n.id for n in fg.nodes if any(r.is_dispatch and r.target == child for r in n.calls)]
|
|
823
|
+
inner = [n.id for n in fg.nodes if any(not r.is_dispatch and child in r.dispatches for r in n.calls)]
|
|
824
|
+
return direct or inner or [n.id for n in fg.nodes if n.type == "start"][:1]
|
|
825
|
+
|
|
826
|
+
|
|
827
|
+
def line_mermaid(graph: ProjectGraph, line: FlowLine) -> str:
|
|
828
|
+
"""功能线的 Mermaid 流程图(flowchart TD):派发树上每个任务一个 subgraph(f1、f2……按先序),节点 id 是"f序号_节点
|
|
829
|
+
id",判断是菱形,结局是圆角,其余是方框;连线带标签(raise 用虚线);派发画成从派发处到被派发任务开始节点的虚线。
|
|
830
|
+
不展开被调函数。公共任务写在最后的注释行里。"""
|
|
831
|
+
segments = _segments(graph, line)
|
|
832
|
+
index = {k: i for i, k in enumerate(segments, 1)}
|
|
833
|
+
out = ["flowchart TD"]
|
|
834
|
+
for i, key in enumerate(segments, 1):
|
|
835
|
+
fg = graph.functions[key]
|
|
836
|
+
fn = _Fn(fg)
|
|
837
|
+
head = _head(fg).rsplit(" [", 1)[0]
|
|
838
|
+
out.append(f' subgraph f{i}["{_mm(head)}"]')
|
|
839
|
+
for n in fg.nodes:
|
|
840
|
+
left, right = _MM_SHAPE.get(n.type, ("[", "]"))
|
|
841
|
+
text = (f"L{n.line} " if n.line and n.type != "start" else "") + node_text(n)
|
|
842
|
+
out.append(f' f{i}_{n.id}{left}"{_mm(text)}"{right}')
|
|
843
|
+
for e in fg.edges:
|
|
844
|
+
if e.src in fn.nodes and e.dst in fn.nodes:
|
|
845
|
+
word = _mm_edge_word(fn, e)
|
|
846
|
+
arrow = "-.->" if e.kind == "raise" else "-->"
|
|
847
|
+
out.append(f" f{i}_{e.src} {arrow}" + (f'|"{_mm(word)}"|' if word else "") + f" f{i}_{e.dst}")
|
|
848
|
+
out.append(" end")
|
|
849
|
+
for parent in _preorder(line.root):
|
|
850
|
+
if parent.goto or parent.function not in index:
|
|
851
|
+
continue
|
|
852
|
+
for child in parent.children:
|
|
853
|
+
if child.function not in index:
|
|
854
|
+
continue
|
|
855
|
+
start = next((n.id for n in graph.functions[child.function].nodes if n.type == "start"), None)
|
|
856
|
+
if start is None:
|
|
857
|
+
continue
|
|
858
|
+
for src in _dispatch_sources(graph.functions[parent.function], child.function):
|
|
859
|
+
out.append(f' f{index[parent.function]}_{src} -.->|"派发"| f{index[child.function]}_{start}')
|
|
860
|
+
names = _common_names(graph, line)
|
|
861
|
+
if names:
|
|
862
|
+
out.append(f" %% 公共任务(不并入本线,各自成线):{'、'.join(names)}")
|
|
863
|
+
return "\n".join(out)
|