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/build.py ADDED
@@ -0,0 +1,1101 @@
1
+ """函数图:把一个函数的语法树变成节点和连线。
2
+
3
+ 分两段:先把语句列表建成结构树,同时折叠掉没有内容的分支;再从结构树生成节点和连线。
4
+ 生成时维护"悬空的出边"——起点已经确定、还没接到下一个节点上的连线。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import ast
10
+ import hashlib
11
+ import io
12
+ import re
13
+ import tokenize
14
+ from collections.abc import Iterable, Iterator
15
+ from dataclasses import dataclass, field, replace
16
+ from http import HTTPStatus
17
+ from itertools import count
18
+ from typing import get_args
19
+
20
+ from .config import ProjectConfig
21
+ from .external import ExternalCalls
22
+ from .index import FunctionInfo, ProjectIndex
23
+ from .model import (
24
+ CallRef,
25
+ Edge,
26
+ EdgeKind,
27
+ EndKind,
28
+ FunctionGraph,
29
+ Node,
30
+ NodeType,
31
+ OutcomeKind,
32
+ UnresolvedCall,
33
+ numbered,
34
+ )
35
+ from .resolve import Resolver, dotted_name_of, unwrap_thread_call
36
+ from .rules import ActiveRules, pystepkit_name
37
+ from .titles import FULL_LIMIT, clean, clean_full, comment_above, cut, first_sentence
38
+
39
+ TITLE_LIMIT = 60 # 标题、步骤副标题的最大长度(被截断时完整的另记,见 Node.title_full)
40
+ COND_LIMIT = 80 # 判断、循环、捕获节点副标题(源码)的最大长度
41
+ NO_MATCH_LABEL = "都不匹配" # match 没有兜底分支时,越过 match 的那条 case 连线的标签
42
+ NO_MATCH_BRANCH = "else" # 同一条连线的 branch
43
+ FELL_OFF_TITLE = "执行到函数末尾"
44
+ UNCAUGHT_TITLE = "未捕获异常退出"
45
+ UNCAUGHT_RETRY_TITLE = "未捕获异常退出(任务会重试)"
46
+ _OUTCOME_KINDS = get_args(OutcomeKind) # pystepkit outcome(kind=...) 的取值
47
+ _BRANCH_LABELS = {"yes": "是", "no": "否"} # 出边改成 break / loop_back / raise 时,原来的分支写进 label
48
+
49
+ # 嵌套定义:内部函数单独成图,类体不属于本函数的流程
50
+ _SCOPES = (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)
51
+
52
+
53
+ # ---------- 结构树 ----------
54
+
55
+
56
+ _Pos = tuple[int, int] # 头部原文里的位置:行(从 1 起)、字符列,同 tokenize 的记法
57
+
58
+
59
+ def _full_form(text: str, whole: str) -> str:
60
+ """节点标题 clean(text, TITLE_LIMIT) 的完整形式:whole 是 text 没有只取第一句时的原文(一样时就是 text)。
61
+ 显示的标题和完整的一样(或者只差句末的标点)时为 ""。"""
62
+ full = cut(clean(whole), FULL_LIMIT)
63
+ return "" if full.rstrip("。;;. ") == clean(text, TITLE_LIMIT).rstrip("。;;. ") else full
64
+
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class _Head:
69
+ """节点代表的语句头部(见 Node.sid):起始位置(行、UTF-8 字节列)和源码原文。skip:头部里不参与 sid 的 as 目标,
70
+ 每项是(它前面的上下文表达式的终点,目标的终点),见 _head_tokens。"""
71
+
72
+ line: int
73
+ col: int
74
+ text: str
75
+ skip: tuple[tuple[_Pos, _Pos], ...] = ()
76
+
77
+
78
+ @dataclass
79
+ class _Step:
80
+ line: int
81
+ end_line: int
82
+ calls: list[CallRef]
83
+ head: _Head
84
+ quiet: dict[str, str] = field(default_factory=dict) # 折叠掉的 if 变成的步骤:见 Node.quiet
85
+
86
+
87
+ @dataclass
88
+ class _If:
89
+ stmt: ast.If
90
+ calls: list[CallRef] # 条件里有意义的调用
91
+ body: list[_Item]
92
+ orelse: list[_Item]
93
+ quiet: dict[str, str] = field(default_factory=dict) # 见 Node.quiet
94
+
95
+
96
+ @dataclass
97
+ class _Return:
98
+ stmt: ast.Return
99
+
100
+
101
+ @dataclass
102
+ class _Case:
103
+ label: str # 进入分支的连线标签:模式原文,带守卫时为"模式 if 守卫"(超长截断)
104
+ label_full: str # label 被截断时的完整形式,否则为 ""(见 Edge.label_full)
105
+ body: list[_Item]
106
+
107
+
108
+ @dataclass
109
+ class _Match:
110
+ stmt: ast.Match
111
+ calls: list[CallRef] # 主语和各 case 守卫里有意义的调用
112
+ cases: list[_Case]
113
+ exhaustive: bool # 有兜底分支(case _、不带守卫的捕获等必然匹配的模式),没有"都不匹配"的路径
114
+
115
+
116
+ @dataclass
117
+ class _Raise:
118
+ stmt: ast.Raise
119
+
120
+
121
+ @dataclass
122
+ class _Break:
123
+ pass
124
+
125
+
126
+ @dataclass
127
+ class _Continue:
128
+ pass
129
+
130
+
131
+ @dataclass
132
+ class _Loop:
133
+ stmt: ast.For | ast.AsyncFor | ast.While
134
+ calls: list[CallRef] # 循环头里有意义的调用
135
+ body: list[_Item]
136
+ orelse: list[_Item]
137
+
138
+
139
+ @dataclass
140
+ class _Handler:
141
+ handler: ast.ExceptHandler
142
+ body: list[_Item] # 为空(只写日志等)时不画捕获节点
143
+
144
+
145
+ @dataclass
146
+ class _Try:
147
+ body: list[_Item]
148
+ handlers: list[_Handler]
149
+ orelse: list[_Item]
150
+ final: list[_Item]
151
+
152
+
153
+ _Item = _Step | _If | _Return | _Match | _Raise | _Break | _Continue | _Loop | _Try
154
+
155
+
156
+ @dataclass(frozen=True)
157
+ class _Out:
158
+ """悬空的出边:src 节点的这条连线接到下一个生成的节点上。"""
159
+
160
+ src: str
161
+ kind: EdgeKind
162
+ label: str = ""
163
+ branch: str = "" # 判断节点的分支出边:是哪个分支(见 Edge.branch);改 kind 时随出边带着走,改成 raise 时清空
164
+ jump: int = 0 # 非 0:一组正穿过 finally 体的 break / continue 的出边(编号认出是哪一组,见 _emit_finally)
165
+ label_full: str = "" # case 出边的 label 被截断时的完整形式(见 Edge.label_full);改 kind 时随出边带着走
166
+
167
+
168
+ @dataclass
169
+ class _Jumps:
170
+ """一个有 finally 体的 try:try 体、except、else 里越过它的 break / continue 的出边,等 finally 体生成时接进去。"""
171
+
172
+ breaks: list[_Out]
173
+ continues: list[_Out]
174
+
175
+
176
+ @dataclass
177
+ class _LoopCtx:
178
+ head: str # 循环节点 id:continue 和循环体的正常出口回到这里
179
+ breaks: list[_Out] # 已经过所有 finally 的 break 出边,接到循环之后的节点
180
+ jumped: list[_Out] # 每个 break / continue 语句的出边(原样记下;连线被去重时也在这里),供 _thrown 用
181
+ finals: list[_Jumps] # 包住当前位置、在这个循环之内的有 finally 体的 try(正在生成 try 体、except 或 else),内层在后
182
+
183
+
184
+ # ---------- 语法树辅助 ----------
185
+
186
+
187
+ def _walk(root: ast.AST, into_lambda: bool = False) -> Iterator[ast.AST]:
188
+ """root 子树里的节点(先序),不进入嵌套的函数和类定义;是否进入 lambda 由 into_lambda 决定。"""
189
+ stack: list[ast.AST] = [root]
190
+ while stack:
191
+ n = stack.pop()
192
+ if isinstance(n, _SCOPES) or (isinstance(n, ast.Lambda) and not into_lambda):
193
+ continue
194
+ yield n
195
+ stack.extend(reversed(list(ast.iter_child_nodes(n))))
196
+
197
+
198
+ def _iter_calls(root: ast.AST, into_lambda: bool = False) -> Iterator[ast.Call]:
199
+ """root 子树里的调用(先序),范围同 _walk。"""
200
+ return (n for n in _walk(root, into_lambda) if isinstance(n, ast.Call))
201
+
202
+
203
+ def _nested_headers(root: ast.AST) -> Iterator[tuple[ast.expr, bool]]:
204
+ """root 子树里(不进入嵌套定义的体)每个嵌套函数 / 类定义在外层帧执行的部分:(表达式, 是否装饰器)。
205
+ 函数是装饰器和参数默认值,类是装饰器、基类和关键字参数。"""
206
+ stack: list[ast.AST] = [root]
207
+ while stack:
208
+ n = stack.pop()
209
+ if isinstance(n, ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef):
210
+ yield from ((d, True) for d in n.decorator_list)
211
+ if isinstance(n, ast.ClassDef):
212
+ rest = [*n.bases, *(k.value for k in n.keywords)]
213
+ else:
214
+ rest = [*n.args.defaults, *(d for d in n.args.kw_defaults if d is not None)]
215
+ yield from ((e, False) for e in rest)
216
+ elif not isinstance(n, ast.Lambda):
217
+ stack.extend(ast.iter_child_nodes(n))
218
+
219
+
220
+ def _short_circuited(n: ast.AST) -> Iterable[ast.expr]:
221
+ """不一定求值的子表达式:三元表达式的两个分支、and / or 第一个操作数之后的各项、match 的 case 守卫
222
+ (模式匹配上才求值;守卫里的调用记在 match 的判断节点上)。"""
223
+ if isinstance(n, ast.IfExp):
224
+ return (n.body, n.orelse)
225
+ if isinstance(n, ast.BoolOp):
226
+ return n.values[1:]
227
+ if isinstance(n, ast.match_case) and n.guard is not None:
228
+ return (n.guard,)
229
+ return ()
230
+
231
+
232
+ def _irrefutable(p: ast.pattern) -> bool:
233
+ """必然匹配的模式(同 CPython 的判断):_ 和捕获、它们再加 as、含这样一项的 |。"""
234
+ if isinstance(p, ast.MatchAs):
235
+ return p.pattern is None or _irrefutable(p.pattern)
236
+ return isinstance(p, ast.MatchOr) and any(_irrefutable(alt) for alt in p.patterns)
237
+
238
+
239
+ def _binds(n: ast.AST, name: str) -> bool:
240
+ """n 是否在本作用域里绑定 name(赋值、for / with / except / import / match 的目标、global 等)。"""
241
+ if isinstance(n, ast.Name):
242
+ return n.id == name and not isinstance(n.ctx, ast.Load)
243
+ if isinstance(n, ast.ExceptHandler | ast.MatchAs | ast.MatchStar):
244
+ return n.name == name
245
+ if isinstance(n, ast.MatchMapping):
246
+ return n.rest == name
247
+ if isinstance(n, ast.alias):
248
+ return (n.asname or n.name.split(".")[0]) == name
249
+ if isinstance(n, ast.Global | ast.Nonlocal):
250
+ return name in n.names
251
+ return False
252
+
253
+
254
+ def _by_position(calls: Iterable[ast.Call]) -> list[ast.Call]:
255
+ return sorted(calls, key=lambda c: (c.lineno, c.col_offset))
256
+
257
+
258
+ def _outcome_args(call: ast.Call) -> dict[str, ast.expr | str]:
259
+ """outcome(kind="ok", title=None, **字段) 的实参,以参数名为键;省略 kind 时为 "ok"。"""
260
+ args: dict[str, ast.expr | str] = {"kind": "ok"}
261
+ for name, value in zip(("kind", "title"), call.args):
262
+ args[name] = value
263
+ for kw in call.keywords:
264
+ if kw.arg is not None:
265
+ args[kw.arg] = kw.value
266
+ return args
267
+
268
+
269
+ def _outcome_kind(kind: ast.expr | str) -> EndKind | None:
270
+ """outcome 的 kind 实参就是结局分类,不看配置;不是这三个字符串常量之一时返回 None(交给配置判断)。"""
271
+ value = kind.value if isinstance(kind, ast.Constant) else kind
272
+ return value if value in _OUTCOME_KINDS else None
273
+
274
+
275
+ def _source(lines: list[str], node: ast.AST) -> str:
276
+ """表达式的源码原文。跨行且含 # 时(可能夹着注释)改用 ast.unparse。"""
277
+ try:
278
+ rows = [r.encode() for r in lines[node.lineno - 1: node.end_lineno]]
279
+ rows[-1] = rows[-1][: node.end_col_offset] # 列号是 UTF-8 字节偏移
280
+ rows[0] = rows[0][node.col_offset:]
281
+ text = "\n".join(r.decode() for r in rows)
282
+ except (AttributeError, IndexError, TypeError, UnicodeDecodeError): # 没有位置信息或行号越界
283
+ return ast.unparse(node)
284
+ if node.lineno != node.end_lineno and "#" in text:
285
+ return ast.unparse(node)
286
+ return text
287
+
288
+
289
+ # 头部记号流里不算的记号:注释、换行、缩进
290
+ _LAYOUT_TOKENS = frozenset({tokenize.COMMENT, tokenize.NL, tokenize.NEWLINE, tokenize.INDENT, tokenize.DEDENT,
291
+ tokenize.ENDMARKER})
292
+
293
+
294
+ _OPENERS, _CLOSERS = frozenset("([{"), frozenset(")]}")
295
+
296
+
297
+ def _head_tokens(text: str, skip: tuple[tuple[_Pos, _Pos], ...] = ()) -> str:
298
+ """语句头部的记号流(见 Node.sid):分词,去掉注释、换行和缩进记号,其余记号之间用一个空格连接。换行重排、改缩进、
299
+ 改注释都不改变结果;改引号、加减末尾逗号会改变。
300
+ skip 里的每一段(上下文表达式的终点,as 目标的终点):从段里的 as 起到目标的终点的记号不算,包住目标的括号
301
+ (as (x) 的右括号在目标之后)也不算;as 之前的记号(包住上下文表达式的右括号)照算。
302
+ 头部从语句开头起、到一个表达式的结尾止,可能少右括号(with (a(), b()) as x、if (a and b): 的头部):这时分词到
303
+ 片段末尾才报错,之前的记号已经是全部。万一没分到末尾就出错(解析过的源码里不会发生):退回到去掉已找到的注释、
304
+ 连续空白压成一个空格的源码(不再跳过 skip)。"""
305
+ rows = text.split("\n")
306
+ kept: list[str] = []
307
+ comments: list[tuple[int, int]] = []
308
+ end = (1, 0) # 最后一个记号的终点
309
+ segments = iter(sorted(skip))
310
+ seg = next(segments, None)
311
+ dropping = False # 正在跳过 as 和它的目标
312
+ unclosed = 0 # 跳过的记号里多出的左括号(包住目标的括号):目标之后跳过同样多的右括号
313
+ try:
314
+ for tok in tokenize.generate_tokens(io.StringIO(text).readline):
315
+ if tok.type == tokenize.COMMENT:
316
+ comments.append(tok.start)
317
+ continue
318
+ if tok.type in _LAYOUT_TOKENS:
319
+ continue
320
+ end = tok.end
321
+ while seg is not None and tok.start >= seg[1]: # 走过了这一段
322
+ seg, dropping = next(segments, None), False
323
+ is_op = tok.type == tokenize.OP
324
+ if seg is not None and tok.start >= seg[0] and (dropping or tok.string == "as"):
325
+ dropping = True
326
+ if is_op and tok.string in _OPENERS:
327
+ unclosed += 1
328
+ elif is_op and tok.string in _CLOSERS:
329
+ unclosed -= 1
330
+ continue
331
+ if unclosed > 0 and is_op and tok.string in _CLOSERS:
332
+ unclosed -= 1
333
+ continue
334
+ unclosed = 0
335
+ kept.append(tok.string)
336
+ except (tokenize.TokenError, SyntaxError):
337
+ pass
338
+ if end >= (len(rows), len(rows[-1].rstrip())): # 分到了片段末尾
339
+ return " ".join(kept)
340
+ for row, col in comments: # 注释到行尾为止:从注释起点截断那一行
341
+ rows[row - 1] = rows[row - 1][:col]
342
+ return " ".join("\n".join(rows).split())
343
+
344
+
345
+ def _text_pos(lines: list[str], start: ast.AST, lineno: int, col: int) -> _Pos:
346
+ """源码位置(行、UTF-8 字节列)在从 start 起的头部原文里的位置(_Pos)。"""
347
+ row = lines[lineno - 1].encode()[:col]
348
+ if lineno == start.lineno:
349
+ row = row[start.col_offset:]
350
+ return (lineno - start.lineno + 1, len(row.decode()))
351
+
352
+
353
+ def _head(lines: list[str], start: ast.AST, end: ast.AST | None = None,
354
+ targets: Iterable[tuple[ast.expr, ast.expr]] = ()) -> _Head:
355
+ """从 start 的起点到 end(省略时同 start)的终点的语句头部。targets:头部里不参与 sid 的 as 目标,每项是
356
+ (上下文表达式,它的 as 目标)。"""
357
+ end = end or start
358
+ try:
359
+ rows = [r.encode() for r in lines[start.lineno - 1: end.end_lineno]]
360
+ rows[-1] = rows[-1][: end.end_col_offset] # 列号是 UTF-8 字节偏移
361
+ rows[0] = rows[0][start.col_offset:]
362
+ text = "\n".join(r.decode() for r in rows)
363
+ skip = tuple((_text_pos(lines, start, e.end_lineno, e.end_col_offset),
364
+ _text_pos(lines, start, t.end_lineno, t.end_col_offset)) for e, t in targets)
365
+ except (AttributeError, IndexError, TypeError, UnicodeDecodeError): # 同 _source:没有位置信息或行号越界
366
+ text, skip = ast.unparse(end), ()
367
+ return _Head(start.lineno, start.col_offset, text, skip)
368
+
369
+
370
+ def _head_sid(node_type: NodeType, head: _Head) -> str:
371
+ """节点的稳定标识(未编号):类型加头部记号流(_head_tokens)的 sha1 前 8 位。"""
372
+ tokens = _head_tokens(head.text, head.skip)
373
+ return f"{node_type}:{hashlib.sha1(tokens.encode('utf-8')).hexdigest()[:8]}"
374
+
375
+
376
+ def _join_label(a: str, b: str) -> str:
377
+ return " · ".join(x for x in (a, b) if x)
378
+
379
+
380
+ def _code_label(text: str) -> tuple[str, str]:
381
+ """连线标签里的源码原文:合并空白,超长截断。返回(标签,被截断时的完整形式(最长 FULL_LIMIT),否则 "")。
382
+ 不用 clean:它去掉的 ` 和 ** 在模式里有意义({"k": 1, **rest})。"""
383
+ s = " ".join(text.split())
384
+ return cut(s, COND_LIMIT), (cut(s, FULL_LIMIT) if len(s) > COND_LIMIT else "")
385
+
386
+
387
+ def _redirect(outs: list[_Out], kind: EdgeKind) -> list[_Out]:
388
+ """把出边改成 kind(break / loop_back / finally / raise),原来的"是 / 否"写进 label(case 连线的 label 本来就是
389
+ 模式,照旧,label_full 也照旧)。branch 不变;改成 raise 时清空:异常连线不是分支。异常连线(raise)保持原样;
390
+ 改成其他类型时内层循环的 loop_exit 也保持原样:每个循环节点都要有自己的 loop_exit。"""
391
+ keep = ("raise",) if kind == "raise" else ("raise", "loop_exit")
392
+ return [o if o.kind in keep else replace(o, kind=kind, label=_join_label(o.label, _BRANCH_LABELS.get(o.kind, "")),
393
+ branch="" if kind == "raise" else o.branch)
394
+ for o in outs]
395
+
396
+
397
+ def _loop_head(lines: list[str], st: ast.For | ast.AsyncFor | ast.While) -> str:
398
+ """循环头源码,如 "for i in range(n)"、"while x"。"""
399
+ if isinstance(st, ast.While):
400
+ return f"while {_source(lines, st.test)}"
401
+ prefix = "async for" if isinstance(st, ast.AsyncFor) else "for"
402
+ return f"{prefix} {_source(lines, st.target)} in {_source(lines, st.iter)}"
403
+
404
+
405
+ # FastAPI / Starlette 的 HTTP 异常(fastapi.HTTPException 就是 starlette 那个的子类)
406
+ _HTTP_EXCEPTIONS = frozenset({"fastapi.HTTPException", "fastapi.exceptions.HTTPException",
407
+ "starlette.exceptions.HTTPException"})
408
+
409
+
410
+ def _call_arg(call: ast.Call, pos: int, name: str) -> ast.expr | None:
411
+ """调用的第 pos 个位置参数或关键字参数 name;前面有 *args 展开时位置对不上,不认。"""
412
+ if len(call.args) > pos and not any(isinstance(a, ast.Starred) for a in call.args[: pos + 1]):
413
+ return call.args[pos]
414
+ return next((k.value for k in call.keywords if k.arg == name), None)
415
+
416
+
417
+ def _status_code(e: ast.expr | None) -> int | None:
418
+ """HTTP 状态码:整数字面量,或名字形如 HTTP_404_NOT_FOUND 的常量(fastapi / starlette 的 status 模块)。"""
419
+ if isinstance(e, ast.Constant) and type(e.value) is int:
420
+ return e.value
421
+ name = e.attr if isinstance(e, ast.Attribute) else e.id if isinstance(e, ast.Name) else ""
422
+ m = re.fullmatch(r"HTTP_(\d{3})_\w+", name)
423
+ return int(m.group(1)) if m else None
424
+
425
+
426
+ def _is_dict_key(root: ast.expr, node: ast.Constant) -> bool:
427
+ """node 是 root 里某个字典字面量的键({"error": "…"} 的 "error")。"""
428
+ return any(isinstance(d, ast.Dict) and any(k is node for k in d.keys) for d in ast.walk(root))
429
+
430
+
431
+ # ---------- 建图 ----------
432
+
433
+
434
+ class _Builder:
435
+ def __init__(self, fn: FunctionInfo, index: ProjectIndex, rules: ActiveRules,
436
+ resolver: Resolver, config: ProjectConfig):
437
+ self.fn = fn
438
+ self.index = index
439
+ self.rules = rules
440
+ self.resolver = resolver
441
+ self.config = config
442
+ self.lines = index.modules[fn.file].lines
443
+ self.nodes: list[Node] = []
444
+ self.edges: list[Edge] = []
445
+ self._heads: dict[str, _Head] = {} # 节点 id -> 它代表的语句头部(隐含节点没有)
446
+ self._refs: dict[int, CallRef] = {} # id(调用节点) -> CallRef,每个调用只解析一次
447
+ self._run: dict[int, ast.Call] = {} # id(调用节点) -> 实际执行的调用(交给线程的包装换成被执行的函数)
448
+ self._no_title: set[int] = set() # id(CallRef):不给步骤当标题的调用(见 _calls)
449
+ self._constructors: set[int] = set() # 构造项目内类的调用(target 是 __init__)的 id
450
+ self._decorator_calls: dict[int, ast.Call] = {} # id(装饰器表达式) -> 代表"应用装饰器"的调用节点
451
+ self._awaited = {id(n.value) for st in fn.node.body for n in ast.walk(st)
452
+ if isinstance(n, ast.Await) and isinstance(n.value, ast.Call)}
453
+ self._conditional = {id(c) for st in fn.node.body for n in _walk(st)
454
+ for part in _short_circuited(n) for c in _iter_calls(part)}
455
+ # 没有 await 的调用里落在项目外对象上的(db.execute、requests.post)也算步骤,见 external.py
456
+ self._external = ExternalCalls(fn, rules.external) if config.external_calls else None
457
+ self._entry = rules.classify(fn)
458
+ self._loops: list[_LoopCtx] = [] # 正在生成的循环,内层在后
459
+ self._jump_ids = count(1) # _Out.jump 的编号
460
+ # 只有结局、没被捕获的异常进去的 finally 体的出口:不往后接,外层还有 finally 时进外层的(见 _emit_try)
461
+ self._leaving: list[_Out] = []
462
+
463
+ def build(self) -> FunctionGraph:
464
+ fn = self.fn
465
+ entry = self._entry
466
+ whole = entry.title or fn.doc_title or fn.node.name # 文档注释的整个第一行;标题只取它的第一句
467
+ text = entry.title or first_sentence(fn.doc_title) or fn.node.name
468
+ title, title_full = clean(text, TITLE_LIMIT), _full_form(text, whole)
469
+ start = self._place([], "start", text, sid="start", line=fn.line, end_line=fn.line, full=whole)
470
+ pending = self._emit(self._structure(fn.node.body), [_Out(start, "next")])
471
+ live = self._reachable(start) # 所有路径都已结束之后的死代码不补"执行到函数末尾"
472
+ pending = [o for o in pending if o.src in live]
473
+ if pending:
474
+ self._place(pending, "end", FELL_OFF_TITLE, sid="end:implicit", end_kind="ok")
475
+ self._place([], "end", UNCAUGHT_RETRY_TITLE if entry.retries else UNCAUGHT_TITLE, sid="end:uncaught",
476
+ end_kind="exception")
477
+ self._number_sids()
478
+ return FunctionGraph(
479
+ key=fn.key, file=fn.file, qualname=fn.qualname, line=fn.line, end_line=fn.end_line,
480
+ kind=entry.kind, title=title, is_async=fn.is_async, marked=entry.marked, group=entry.group,
481
+ route=entry.route, retries=entry.retries, parent=fn.parent, nodes=self.nodes, edges=self.edges,
482
+ call_targets=self._call_targets(), unresolved=self._unresolved(), rule=entry.rule, name=entry.name,
483
+ version=entry.version, title_full=title_full)
484
+
485
+ # ---------- 调用 ----------
486
+
487
+ def _is_outcome(self, e: ast.expr | None) -> bool:
488
+ """pystepkit 的结局辅助函数 outcome(...):经本模块的 import 来自 pystepkit(from pystepkit import outcome、fk.outcome)。"""
489
+ return isinstance(e, ast.Call) and pystepkit_name(e.func, self.index.modules[self.fn.file]) == "outcome"
490
+
491
+ def _executed(self, call: ast.Call) -> ast.Call:
492
+ """call 实际执行的调用:asyncio.to_thread(f, …)、run_in_executor(执行器, f, …) 是对 f 的调用(f 是
493
+ lambda: g(…) 时是对 g 的调用),其余是它自己。"""
494
+ run = self._run.get(id(call))
495
+ if run is None:
496
+ run = self._run[id(call)] = unwrap_thread_call(call, self.index.modules[self.fn.file])
497
+ return run
498
+
499
+ def _ref(self, call: ast.Call) -> CallRef:
500
+ """调用的 CallRef(按实际执行的调用解析)。"""
501
+ ref = self._refs.get(id(call))
502
+ if ref is None:
503
+ run = self._executed(call)
504
+ d = self.rules.dispatch(run, self.fn, self.resolver)
505
+ conditional = id(call) in self._conditional
506
+ if d is None:
507
+ r = self.resolver.resolve(run, self.fn)
508
+ ref = CallRef(r.display, r.target, r.how, conditional=conditional)
509
+ if r.constructor:
510
+ self._constructors.add(id(call))
511
+ else:
512
+ ref = CallRef(f"派发 {d.name or '未知任务'}", d.target, d.how, is_dispatch=True, conditional=conditional)
513
+ self._refs[id(call)] = ref
514
+ return ref
515
+
516
+ def _calls(self, roots: Iterable[ast.AST]) -> list[CallRef]:
517
+ """roots 里有意义的调用,按源码位置排序。派发调用接收者链上的调用(如 kicker(t).kiq() 里的
518
+ kicker(t))由派发代表,不单独列出。构造对象不是业务步骤:构造调用只进 call_targets,不进节点。"""
519
+ found = _by_position(c for root in roots for c in _iter_calls(root))
520
+ chain = {id(c) for d in found if self._ref(d).is_dispatch for c in _iter_calls(d.func)}
521
+ refs = []
522
+ for call in found:
523
+ ref = self._ref(call)
524
+ if id(call) in self._constructors:
525
+ continue
526
+ run = self._executed(call)
527
+ # is_noise 把与内置函数同名的裸名都算噪音;已解析到项目内函数的(如项目自己的 format)不算
528
+ shadows_builtin = isinstance(run.func, ast.Name) and self._callee(ref) is not None
529
+ noise = self.rules.is_noise(run) and not shadows_builtin
530
+ if id(call) in chain or noise or self._listed_noise(run, ref):
531
+ continue
532
+ if ref.is_dispatch or ref.resolution in ("exact", "guessed") or id(call) in self._awaited \
533
+ or (self._external is not None and self._external.is_step(run)):
534
+ refs.append(ref)
535
+ # await get_redis().delete(key_of(x)):这一步做的事是目标不明的 .delete,get_redis() 只是取对象、key_of(x) 只是
536
+ # 算参数——它们的文档注释说的不是这一步,不拿来当标题(标题退到上方注释或调用的显示名)
537
+ listed = {id(r) for r in refs}
538
+ for outer in found:
539
+ ref = self._ref(outer)
540
+ if id(ref) in listed and not ref.is_dispatch and self._callee(ref) is None \
541
+ and any(self._callee(self._ref(c)) is not None for c in _iter_calls(outer.func)):
542
+ self._no_title |= {id(self._ref(c)) for c in _iter_calls(outer) if c is not outer}
543
+ return refs
544
+
545
+ def _listed_noise(self, call: ast.Call, ref: CallRef) -> bool:
546
+ """config.noise_functions:按被调用的名字或目标函数的限定名匹配。"""
547
+ names = self.config.noise_functions
548
+ if not names:
549
+ return False
550
+ f = call.func
551
+ called = f.id if isinstance(f, ast.Name) else f.attr if isinstance(f, ast.Attribute) else None
552
+ if called in names:
553
+ return True
554
+ callee = self._callee(ref)
555
+ return callee is not None and callee.qualname in names
556
+
557
+ def _callee(self, ref: CallRef) -> FunctionInfo | None:
558
+ """被调用的项目内函数;派发的目标是被派发的任务,不算被调用。"""
559
+ if ref.is_dispatch or ref.target is None:
560
+ return None
561
+ return self.index.functions.get(ref.target)
562
+
563
+ def _frame_calls(self, into_lambda: bool) -> list[ast.Call]:
564
+ """在本函数的帧里执行的全部调用,按源码位置排序:函数体里的(不含嵌套函数、类的体;是否含 lambda 体由
565
+ into_lambda 决定),加上嵌套定义的装饰器、参数默认值、类的基类里的调用,以及直接写名字的装饰器
566
+ (@deco)的应用——它们都在外层帧执行。"""
567
+ found = [c for st in self.fn.node.body for c in _iter_calls(st, into_lambda)]
568
+ for st in self.fn.node.body:
569
+ for expr, is_decorator in _nested_headers(st):
570
+ found += _iter_calls(expr, into_lambda)
571
+ if is_decorator and isinstance(expr, ast.Name | ast.Attribute):
572
+ found.append(self._decorator_call(expr))
573
+ return _by_position(found)
574
+
575
+ def _decorator_call(self, expr: ast.Name | ast.Attribute) -> ast.Call:
576
+ """@deco 应用时等于在外层帧调用 deco(被装饰的函数):造一个位置相同的调用节点交给解析器(每个装饰器只造一次)。"""
577
+ call = self._decorator_calls.get(id(expr))
578
+ if call is None:
579
+ call = self._decorator_calls[id(expr)] = ast.copy_location(ast.Call(func=expr, args=[], keywords=[]), expr)
580
+ call.end_lineno, call.end_col_offset = expr.end_lineno, expr.end_col_offset
581
+ return call
582
+
583
+ def _call_targets(self) -> list[str]:
584
+ """在本函数帧里执行的调用(含 lambda 体里的)解析到的项目内函数(含构造调用的 __init__),按源码位置首次
585
+ 出现的顺序去重。"""
586
+ seen: dict[str, None] = {}
587
+ for call in self._frame_calls(into_lambda=True):
588
+ ref = self._ref(call)
589
+ if not ref.is_dispatch and ref.resolution in ("exact", "guessed") and ref.target:
590
+ seen.setdefault(ref.target, None)
591
+ return list(seen)
592
+
593
+ def _unresolved(self) -> list[UnresolvedCall]:
594
+ """在本函数帧里执行、无法判断目标的调用(不论是否被 await、是否进了节点):所在行和显示名,按源码顺序、
595
+ (行, 名字) 去重。lambda 体里的调用在 lambda 自己的帧里执行,不算。"""
596
+ seen: dict[tuple[int, str], None] = {}
597
+ for call in self._frame_calls(into_lambda=False):
598
+ ref = self._ref(call)
599
+ if ref.resolution == "unresolved":
600
+ seen.setdefault((call.lineno, ref.name), None)
601
+ return [UnresolvedCall(line, name) for line, name in seen]
602
+
603
+ # ---------- 第一段:语句 → 结构树 ----------
604
+
605
+ def _structure(self, stmts: list[ast.stmt]) -> list[_Item]:
606
+ items: list[_Item] = []
607
+ for st in stmts:
608
+ items += self._statement(st)
609
+ return items
610
+
611
+ def _statement(self, st: ast.stmt) -> list[_Item]:
612
+ if isinstance(st, _SCOPES):
613
+ return []
614
+ if isinstance(st, ast.If):
615
+ return self._if(st)
616
+ if isinstance(st, ast.Return):
617
+ return self._return(st)
618
+ if isinstance(st, ast.With | ast.AsyncWith): # 不出节点,里面的语句接在主线上
619
+ # 头部到最后一个上下文表达式为止;前面各项的 as 目标也不参与 sid
620
+ targets = [(i.context_expr, i.optional_vars) for i in st.items[:-1] if i.optional_vars is not None]
621
+ return self._step(st, [i.context_expr for i in st.items], targets) + self._structure(st.body)
622
+ if isinstance(st, ast.Match):
623
+ return self._match(st)
624
+ if isinstance(st, ast.For | ast.AsyncFor | ast.While):
625
+ return self._loop(st)
626
+ if isinstance(st, ast.Try | ast.TryStar):
627
+ return self._try(st)
628
+ if isinstance(st, ast.Raise):
629
+ return self._raise(st)
630
+ if isinstance(st, ast.Break):
631
+ return [_Break()]
632
+ if isinstance(st, ast.Continue):
633
+ return [_Continue()]
634
+ return self._step(st, [st])
635
+
636
+ def _step(self, at: ast.stmt, roots: list[ast.AST],
637
+ targets: Iterable[tuple[ast.expr, ast.expr]] = ()) -> list[_Item]:
638
+ """roots(语句本身或复合语句的头部)里有意义的调用合成一个步骤;没有则不出节点。targets 见 _head。"""
639
+ calls = self._calls(roots)
640
+ if not calls:
641
+ return []
642
+ last = max(roots, key=lambda r: (r.end_lineno, r.end_col_offset))
643
+ return [_Step(at.lineno, last.end_lineno, calls, _head(self.lines, at, last, targets))]
644
+
645
+ def _if(self, st: ast.If) -> list[_Item]:
646
+ body, orelse = self._structure(st.body), self._structure(st.orelse)
647
+ quiet = {branch: text for branch, stmts, kept in (("yes", st.body, body), ("no", st.orelse, orelse))
648
+ if not kept and (text := self._assignments(stmts))}
649
+ if body or orelse:
650
+ return [_If(st, self._calls([st.test]), body, orelse, quiet)]
651
+ steps = self._step(st, [st.test]) # 两个分支都折叠掉了:只剩条件里的调用
652
+ for step in steps:
653
+ step.quiet = quiet
654
+ return steps
655
+
656
+ def _assignments(self, stmts: list[ast.stmt]) -> str:
657
+ """折叠掉的分支里的赋值语句原文(按源码顺序,";"连接);没有赋值时 ""。分支只写日志、只有 pass 时不用说。"""
658
+ found = [n for st in stmts for n in _walk(st) if isinstance(n, ast.Assign | ast.AugAssign | ast.AnnAssign)]
659
+ found.sort(key=lambda n: (n.lineno, n.col_offset))
660
+ return clean(";".join(_source(self.lines, n) for n in found), COND_LIMIT)
661
+
662
+ def _return(self, st: ast.Return) -> list[_Item]:
663
+ v = st.value
664
+ if v is None:
665
+ roots = []
666
+ elif self._is_outcome(v): # outcome(...) 本身只是构造结局,只看它的实参
667
+ roots = [*v.args, *(kw.value for kw in v.keywords)]
668
+ else:
669
+ roots = [v]
670
+ calls = self._calls(roots)
671
+ step = [_Step(st.lineno, st.end_lineno, calls, _head(self.lines, st))] if calls else []
672
+ return [*step, _Return(st)]
673
+
674
+ def _raise(self, st: ast.Raise) -> list[_Item]:
675
+ calls = self._calls([r for r in (st.exc, st.cause) if r is not None])
676
+ step = [_Step(st.lineno, st.end_lineno, calls, _head(self.lines, st))] if calls else []
677
+ return [*step, _Raise(st)]
678
+
679
+ def _match(self, st: ast.Match) -> list[_Item]:
680
+ """match 是一个判断节点,守卫不单独出节点:主语和守卫里的调用都记在判断节点上。"""
681
+ cases = [_Case(*self._case_label(case), self._structure(case.body)) for case in st.cases]
682
+ calls = self._calls([st.subject, *(case.guard for case in st.cases if case.guard is not None)])
683
+ if not any(c.body for c in cases): # 所有分支都折叠掉了:只剩主语和守卫里的调用(同 if)
684
+ return [_Step(st.lineno, st.subject.end_lineno, calls, _head(self.lines, st, st.subject))] if calls else []
685
+ exhaustive = any(case.guard is None and _irrefutable(case.pattern) for case in st.cases)
686
+ return [_Match(st, calls, cases, exhaustive)]
687
+
688
+ def _case_label(self, case: ast.match_case) -> tuple[str, str]:
689
+ """(label,被截断时的完整形式),见 _code_label。"""
690
+ text = _source(self.lines, case.pattern)
691
+ if case.guard is not None:
692
+ text += f" if {_source(self.lines, case.guard)}"
693
+ return _code_label(text)
694
+
695
+ def _loop(self, st: ast.For | ast.AsyncFor | ast.While) -> list[_Item]:
696
+ calls = self._calls([st.test] if isinstance(st, ast.While) else [st.target, st.iter])
697
+ body, orelse = self._structure(st.body), self._structure(st.orelse)
698
+ if not calls and not orelse and all(isinstance(it, _Break | _Continue) for it in body):
699
+ return [] # 循环体里只有 break / continue(或什么都没有),循环头里也没有有意义的调用
700
+ return [_Loop(st, calls, body, orelse)]
701
+
702
+ def _try(self, st: ast.Try | ast.TryStar) -> list[_Item]:
703
+ t = _Try(self._structure(st.body), [_Handler(h, self._structure(h.body)) for h in st.handlers],
704
+ self._structure(st.orelse), self._structure(st.finalbody))
705
+ return [t] if t.body or t.orelse or t.final or any(h.body for h in t.handlers) else []
706
+
707
+ # ---------- 第二段:结构树 → 节点和连线 ----------
708
+
709
+ def _place(self, pending: list[_Out], node_type: NodeType, title: str, head: _Head | None = None,
710
+ **attrs) -> str:
711
+ """新建节点,把悬空的出边接到它上面,返回节点 id。title 和 attrs 里的 subtitle 是原文,在这里清理、截断(标题和
712
+ 步骤的副标题到 TITLE_LIMIT,判断、循环、捕获的副标题到 COND_LIMIT),被截断时另记完整形式(title_full、
713
+ subtitle_full)。head:节点代表的语句头部(隐含节点没有,sid 由调用方给)。"""
714
+ nid = f"n{len(self.nodes) + 1}"
715
+ if head is not None:
716
+ attrs["sid"] = _head_sid(node_type, head)
717
+ self._heads[nid] = head
718
+ sub = attrs.pop("subtitle", "")
719
+ full = attrs.pop("full", None) # 标题只取了文档注释第一句时:整个第一行(进 title_full)
720
+ sub_limit = TITLE_LIMIT if node_type == "step" else COND_LIMIT
721
+ self.nodes.append(Node(nid, node_type, clean(title, TITLE_LIMIT), subtitle=clean(sub, sub_limit),
722
+ title_full=_full_form(title, full or title), subtitle_full=clean_full(sub, sub_limit),
723
+ **attrs))
724
+ self._connect(pending, nid)
725
+ return nid
726
+
727
+ def _number_sids(self) -> None:
728
+ """有语句头部的节点按源码位置排好,sid 相同的从第二个起加 #2、#3(见 Node.sid)。"""
729
+ by_id = {n.id: n for n in self.nodes}
730
+ placed = sorted(self._heads, key=lambda nid: (self._heads[nid].line, self._heads[nid].col))
731
+ for nid, sid in zip(placed, numbered(by_id[nid].sid for nid in placed)):
732
+ by_id[nid].sid = sid
733
+
734
+ def _connect(self, outs: list[_Out], dst: str) -> None:
735
+ """把出边接到 dst(可以是已有节点),去重(label_full 不参与:label 相同的就是同一条,留先接上的)。同一起点到
736
+ dst 至多一条异常连线(raise,不论标签);已有别的类型的连线时照样画:它标出异常的落脚点(如 try 体以 if 开头,
737
+ "条件不成立"的连线和异常连线落在同一处)。"""
738
+ for o in dict.fromkeys(outs):
739
+ if o.kind == "raise" and any(e.src == o.src and e.dst == dst and e.kind == "raise" for e in self.edges):
740
+ continue
741
+ key = (o.src, dst, o.kind, o.label, o.branch)
742
+ if not any((e.src, e.dst, e.kind, e.label, e.branch) == key for e in self.edges):
743
+ self.edges.append(Edge(*key, label_full=o.label_full))
744
+
745
+ def _reachable(self, start: str) -> set[str]:
746
+ """从 start 沿连线能走到的节点。"""
747
+ nexts: dict[str, list[str]] = {}
748
+ for e in self.edges:
749
+ nexts.setdefault(e.src, []).append(e.dst)
750
+ seen, stack = {start}, [start]
751
+ while stack:
752
+ for dst in nexts.get(stack.pop(), []):
753
+ if dst not in seen:
754
+ seen.add(dst)
755
+ stack.append(dst)
756
+ return seen
757
+
758
+ def _emit(self, items: list[_Item], pending: list[_Out]) -> list[_Out]:
759
+ """依次生成 items 的节点和连线,pending 接到第一个节点上;返回之后仍悬空的出边。"""
760
+ for it in items:
761
+ if isinstance(it, _Step):
762
+ nid = self._place(pending, "step", self._step_title(it), it.head, full=self._step_title(it, whole=True),
763
+ subtitle=" + ".join(c.name for c in it.calls),
764
+ line=it.line, end_line=it.end_line, calls=it.calls, quiet=it.quiet)
765
+ pending = [_Out(nid, "next")]
766
+ elif isinstance(it, _If):
767
+ st = it.stmt
768
+ test = _source(self.lines, st.test)
769
+ nid = self._place(pending, "cond", self._cond_title(st.lineno, st.test, test),
770
+ _head(self.lines, st, st.test), subtitle=test,
771
+ line=st.lineno, end_line=st.test.end_lineno, calls=it.calls, quiet=it.quiet)
772
+ pending = (self._emit(it.body, [_Out(nid, "yes", branch="yes")])
773
+ + self._emit(it.orelse, [_Out(nid, "no", branch="no")]))
774
+ elif isinstance(it, _Match):
775
+ pending = self._emit_match(it, pending)
776
+ elif isinstance(it, _Loop):
777
+ pending = self._emit_loop(it, pending)
778
+ elif isinstance(it, _Try):
779
+ pending = self._emit_try(it, pending)
780
+ elif isinstance(it, _Break | _Continue):
781
+ pending = self._jump(it, pending)
782
+ elif isinstance(it, _Raise):
783
+ self._place(pending, "end", **self._raise_end(it.stmt))
784
+ pending = []
785
+ else:
786
+ self._place(pending, "end", **self._end(it.stmt))
787
+ pending = []
788
+ return pending
789
+
790
+ def _emit_loop(self, lp: _Loop, pending: list[_Out]) -> list[_Out]:
791
+ """循环节点 → 循环体(loop_each);循环体的正常出口回到循环节点(loop_back);循环节点的 loop_exit
792
+ 接 else 体,break 的出边越过 else 接到循环之后。"""
793
+ st = lp.stmt
794
+ head = _loop_head(self.lines, st)
795
+ last = st.test if isinstance(st, ast.While) else st.iter
796
+ nid = self._place(pending, "loop", comment_above(self.lines, st.lineno) or self._marked_title(last) or head,
797
+ _head(self.lines, st, last), subtitle=head, line=st.lineno,
798
+ end_line=last.end_lineno, calls=lp.calls)
799
+ self._loops.append(_LoopCtx(nid, [], [], []))
800
+ body_out = self._emit(lp.body, [_Out(nid, "loop_each")])
801
+ ctx = self._loops.pop()
802
+ self._connect(_redirect(body_out, "loop_back"), nid)
803
+ return self._emit(lp.orelse, [_Out(nid, "loop_exit")]) + ctx.breaks
804
+
805
+ def _jump(self, it: _Break | _Continue, pending: list[_Out]) -> list[_Out]:
806
+ """break / continue 的出边:先经过它和所属循环之间每个有 finally 体的 try 的 finally 体(见 _leave)。"""
807
+ if not self._loops: # 循环外的 break / continue 编译不过,这里只是不崩溃
808
+ return pending
809
+ ctx = self._loops[-1]
810
+ ctx.jumped += pending
811
+ self._leave(ctx, pending, isinstance(it, _Break))
812
+ return []
813
+
814
+ def _leave(self, ctx: _LoopCtx, outs: list[_Out], is_break: bool) -> None:
815
+ """跳转的出边往外走一层:被有 finally 体的 try 包住时记到最内层的那个 try,等它的 finally 体生成时接进去
816
+ (_emit_finally);没有时到目标——break 留到循环之后再接,continue 连回循环节点。"""
817
+ if ctx.finals:
818
+ jumps = ctx.finals[-1]
819
+ (jumps.breaks if is_break else jumps.continues).extend(outs)
820
+ elif is_break:
821
+ ctx.breaks += _redirect(outs, "break")
822
+ else:
823
+ self._connect(_redirect(outs, "loop_back"), ctx.head)
824
+
825
+ def _emit_try(self, t: _Try, pending: list[_Out]) -> list[_Out]:
826
+ """try 体照常接在主线上。"这一段里抛出了异常"的出边(thrown,见 _thrown)连到每个捕获节点;只写日志的
827
+ except 吞掉异常后照常往下走,thrown 也接到后面。有 finally 时,正常出口、thrown(没被捕获的异常同样
828
+ 经过 finally)、try / except / else 里每个结局和越过它的 break / continue 都进入 finally 体(_emit_finally)。
829
+ 进 finally 体的只有结局和没被捕获的异常时(try / except / else 没有正常出口,也没有 break / continue 穿过),出了 finally 体函数就结束了
830
+ (return 生效,或者异常接着往外抛):finally 体的出口不往后接,外层还有 finally 时进外层的 finally 体。"""
831
+ mark = len(self.nodes)
832
+ ctx = self._loops[-1] if self._loops else _LoopCtx("", [], [], []) # 不在循环里:没有 break / continue 可记
833
+ jumps = _Jumps([], [])
834
+ if t.final:
835
+ ctx.finals.append(jumps)
836
+ jumped = len(ctx.jumped) # try 体生成前已记下的数量
837
+ leaving = len(self._leaving)
838
+ body_out = self._emit(t.body, pending)
839
+ thrown = self._thrown(mark, body_out + ctx.jumped[jumped:])
840
+ outs = self._emit(t.orelse, body_out)
841
+ for h in t.handlers:
842
+ if h.body:
843
+ catch = self._place(thrown, "catch", **self._catch(h.handler))
844
+ outs += self._emit(h.body, [_Out(catch, "next")])
845
+ else:
846
+ outs += thrown
847
+ if not t.final:
848
+ return outs
849
+ ctx.finals.pop()
850
+ ends = [_Out(n.id, "finally") for n in self.nodes[mark:] if n.type == "end"]
851
+ inner = _redirect(self._leaving[leaving:], "finally") # 里层 finally 体走完、接着往外离开的
852
+ del self._leaving[leaving:]
853
+ fin_out = self._emit_finally(t.final, outs + thrown + ends + inner, jumps, ctx)
854
+ # 有 break / continue 穿过时照旧(finally 体的出口已经接到跳转目标,见 _emit_finally)
855
+ if outs or jumps.breaks or jumps.continues:
856
+ return fin_out
857
+ self._leaving += fin_out
858
+ return []
859
+
860
+ def _emit_finally(self, final: list[_Item], pending: list[_Out], jumps: _Jumps, ctx: _LoopCtx) -> list[_Out]:
861
+ """finally 体只画一份。pending(正常出口、异常、结局)和 jumps 里越过这个 finally 的 break / continue 的出边
862
+ 一起进入 finally 体,后者的连线类型是 finally("是 / 否"写进 label)。有跳转时,finally 体的每个出口再往外走
863
+ 一层(_leave:外面还有包住跳转的 finally 时进那个 finally,否则到跳转目标)。finally 体里没经过节点的路径上,
864
+ 跳转的出边原样穿过:按 jump 编号认出,同样往外走。返回正常往后走的出边(原有的出口不变)。"""
865
+ mark = len(self.nodes)
866
+ groups: list[tuple[int, list[_Out], bool]] = [] # (编号, 跳转的出边, 是否 break)
867
+ for outs, is_break in ((jumps.breaks, True), (jumps.continues, False)):
868
+ if outs:
869
+ groups.append((next(self._jump_ids), outs, is_break))
870
+ entries = [replace(o, jump=gid) for gid, outs, _ in groups for o in _redirect(outs, "finally")]
871
+ fin_out = self._emit(final, pending + entries)
872
+ inside = {n.id for n in self.nodes[mark:]}
873
+ exits = [o for o in fin_out if o.src in inside]
874
+ for gid, _, is_break in groups:
875
+ self._leave(ctx, exits + [o for o in fin_out if o.jump == gid], is_break)
876
+ ids = {gid for gid, _, _ in groups}
877
+ return [o for o in fin_out if o.jump not in ids]
878
+
879
+ def _thrown(self, mark: int, leaving: list[_Out]) -> list[_Out]:
880
+ """try 体(节点 mark 起)里抛出异常的 raise 出边。起点合起来要拦住每条经过 try 体的路径:
881
+ - try 体里每个有连线从外面进来的节点(入口;通常只有第一个节点,就是它)。第一个创建的节点不一定是入口:
882
+ 例如 try 体以"try 体没有节点"的内层 try 开头时,它是内层的捕获节点。入口都是 try 体里新建的节点,
883
+ 出边被 _connect 去重时同一起点总有另一条连线接到它,所以按连线找入口不会漏。
884
+ - leaving(try 体生成完时悬空的出边,以及期间新记下的 break / continue 出边)里起点在 try 体外的:
885
+ 这些路径没经过任何节点就离开了 try 体;try 体没有节点时就是 try 之前的前驱。连线可能被去重,
886
+ 所以这一类只看记下的出边,不看连线。"""
887
+ inside = {n.id for n in self.nodes[mark:]}
888
+ entered = {e.dst for e in self.edges if e.dst in inside and e.src not in inside}
889
+ crossed = [o for o in leaving if o.src not in inside]
890
+ return [_Out(n.id, "raise") for n in self.nodes[mark:] if n.id in entered] + _redirect(crossed, "raise")
891
+
892
+ def _emit_match(self, m: _Match, pending: list[_Out]) -> list[_Out]:
893
+ """判断节点 → 每个 case 一条 case 连线(label 是模式,带守卫时加"if 守卫";branch 同 label),分支体为空时这条
894
+ 连线直接越过 match;没有兜底分支时再加一条"都不匹配"的 case 连线越过 match(branch 为 else)。守卫不成立时
895
+ 落到后面的分支:判断节点到后面各分支都有连线,不另画节点。"""
896
+ st = m.stmt
897
+ head = f"match {_source(self.lines, st.subject)}"
898
+ nid = self._place(pending, "cond", self._cond_title(st.lineno, st.subject, head),
899
+ _head(self.lines, st, st.subject), subtitle=head, line=st.lineno,
900
+ end_line=st.subject.end_lineno, calls=m.calls)
901
+ outs: list[_Out] = [] # 某个分支执行完、越过 match 的出边
902
+ for case in m.cases:
903
+ outs += self._emit(case.body, [_Out(nid, "case", case.label, branch=case.label,
904
+ label_full=case.label_full)])
905
+ return outs if m.exhaustive else [*outs, _Out(nid, "case", NO_MATCH_LABEL, branch=NO_MATCH_BRANCH)]
906
+
907
+ # ---------- 标题与结局 ----------
908
+
909
+ def _callee_title(self, ref: CallRef, whole: bool = False) -> str:
910
+ """被调用函数的规则标题 → 它的文档注释第一行的第一句(whole:整个第一行)。按名字推测(guessed)的调用不取:
911
+ 目标不一定是它,标题同无法判断目标的调用(上方注释或调用的显示名)。"""
912
+ callee = self._callee(ref)
913
+ if callee is None or ref.resolution == "guessed":
914
+ return ""
915
+ return self.rules.classify(callee).title or (callee.doc_title if whole else first_sentence(callee.doc_title))
916
+
917
+ def _step_title(self, step: _Step, whole: bool = False) -> str:
918
+ """步骤标题的原文(_place 清理、截断)。whole:取自文档注释时用整个第一行(完整形式用),否则只用第一句。"""
919
+ if len(step.calls) == 1 and step.calls[0].is_dispatch: # 只有一个派发
920
+ ref = step.calls[0]
921
+ task = self.index.functions.get(ref.target) if ref.target else None
922
+ if task is None:
923
+ return "派发 未知任务"
924
+ if ref.resolution == "guessed": # 只按任务名对应上的:目标不一定是它,不取它的标题(同副标题"派发 任务名")
925
+ return ref.name
926
+ doc = task.doc_title if whole else first_sentence(task.doc_title)
927
+ return "派发:" + (self.rules.classify(task).title or doc or task.node.name)
928
+ for ref in step.calls:
929
+ title = "" if id(ref) in self._no_title else self._callee_title(ref, whole)
930
+ if title:
931
+ return title
932
+ return comment_above(self.lines, step.line) or " + ".join(c.name for c in step.calls)
933
+
934
+ def _cond_title(self, line: int, test: ast.expr, text: str) -> str:
935
+ """判断节点(第 line 行,条件 test:if 的条件、match 的主语)标题的原文:条件是对 condition 类型函数的单个调用
936
+ (可带 await)时取它的标题 → 上方注释 → 条件原文 text(match 是"match 主语")。"""
937
+ call = test.value if isinstance(test, ast.Await) else test
938
+ title = ""
939
+ if isinstance(call, ast.Call):
940
+ ref = self._ref(call)
941
+ callee = self._callee(ref)
942
+ if callee is not None and self.rules.classify(callee).kind == "condition":
943
+ title = self._callee_title(ref)
944
+ return title or comment_above(self.lines, line) or self._marked_title(test) or text
945
+
946
+ def _marked_title(self, e: ast.expr | None) -> str:
947
+ """e 是对一个带规则标题的项目内函数(@step、@condition 这样标了标题的)的单个调用(可带 await)时,那个标题;
948
+ 不是时 ""。循环头、判断条件、return 的值整个就是这样一个调用时,节点标题用它而不是源码。文档注释不算:
949
+ 那是按名字借来的说明,只在步骤节点上用。按名字推测的目标也不算。"""
950
+ call = e.value if isinstance(e, ast.Await) else e
951
+ if not isinstance(call, ast.Call) or self._is_outcome(call):
952
+ return ""
953
+ ref = self._ref(call)
954
+ callee = self._callee(ref)
955
+ if callee is None or ref.resolution == "guessed" or ref.is_dispatch:
956
+ return ""
957
+ return self.rules.classify(callee).title
958
+
959
+ def _end(self, st: ast.Return) -> dict:
960
+ v = st.value
961
+ title = ""
962
+ end_kind: EndKind | None = None
963
+ pairs: list[tuple[str, ast.expr | str]] = []
964
+ if isinstance(v, ast.Dict):
965
+ pairs = [(k.value, val) for k, val in zip(v.keys, v.values)
966
+ if isinstance(k, ast.Constant) and isinstance(k.value, str)]
967
+ elif self._is_outcome(v):
968
+ args = _outcome_args(v)
969
+ given = args.get("title")
970
+ if isinstance(given, ast.Constant) and isinstance(given.value, str):
971
+ title = given.value
972
+ end_kind = _outcome_kind(args["kind"])
973
+ pairs = list(args.items())
974
+ fields = {name: self._field_value(val) for name, val in pairs if name in self.config.outcome_fields}
975
+ status = self._status_return(v)
976
+ if status is not None and end_kind is None and not fields:
977
+ title, end_kind = status, "failed"
978
+ if not title:
979
+ marked = self._marked_title(v)
980
+ # 带结局字段(status、reason……)的字典也写出返回的内容:一律写"结束"时,同一个函数里的几个结局分不清
981
+ title = "结束" if fields and not isinstance(v, ast.Dict) else f"返回「{marked}」的结果" if marked else \
982
+ "返回 " + ("None" if v is None else _source(self.lines, v))
983
+ return {"title": title, "head": _head(self.lines, st), "line": st.lineno,
984
+ "end_line": st.end_lineno, "end_kind": end_kind or self._end_kind(fields), "fields": fields,
985
+ "passthrough": self._passthrough(v)}
986
+
987
+ def _status_return(self, v: ast.expr | None) -> str | None:
988
+ """接口函数里 `return 响应, 状态码`(Flask 的写法)、状态码是 400 及以上时的结局标题"状态码 说明",如
989
+ "400 标题不能为空";不是这种写法时 None。说明取响应里第一个字符串(jsonify(error="…")、{"error": "…"}),
990
+ 没有时写状态码的标准说法。"""
991
+ if self._entry.kind != "route" and not self._entry.route:
992
+ return None
993
+ if not isinstance(v, ast.Tuple) or len(v.elts) < 2:
994
+ return None
995
+ code = _status_code(v.elts[1])
996
+ if code is None or code < 400:
997
+ return None
998
+ said = next((n.value for n in ast.walk(v.elts[0])
999
+ if isinstance(n, ast.Constant) and isinstance(n.value, str) and n.value.strip()
1000
+ and not _is_dict_key(v.elts[0], n)), None)
1001
+ if said is None:
1002
+ try:
1003
+ said = HTTPStatus(code).phrase
1004
+ except ValueError:
1005
+ said = ""
1006
+ return f"{code} {said}".strip()
1007
+
1008
+ def _raise_end(self, st: ast.Raise) -> dict:
1009
+ text = _source(self.lines, st.exc) if st.exc is not None else "原异常"
1010
+ title = self._http_error_title(st.exc) or f"抛出 {text}"
1011
+ return {"title": title, "head": _head(self.lines, st), "line": st.lineno,
1012
+ "end_line": st.end_lineno, "end_kind": "failed"}
1013
+
1014
+ def _http_error_title(self, exc: ast.expr | None) -> str | None:
1015
+ """raise HTTPException(...)(FastAPI / Starlette 的,按本模块的 import 认)的结局标题"状态码 说明",如
1016
+ "404 用户不存在":接口的调用方看到的就是这两样。状态码认整数字面量和 status.HTTP_404_NOT_FOUND 这样的常量,
1017
+ 看不出来时 None(照旧写"抛出 源码");说明认字符串、f-string({…} 照写)、只赋值过一次的变量(看赋的值),别的表达式写源码,没给时写状态码的
1018
+ 标准说法(Starlette 的默认说明)。"""
1019
+ if not isinstance(exc, ast.Call) or \
1020
+ dotted_name_of(exc.func, self.index.modules[self.fn.file]) not in _HTTP_EXCEPTIONS:
1021
+ return None
1022
+ code = _status_code(_call_arg(exc, 0, "status_code"))
1023
+ if code is None:
1024
+ return None
1025
+ detail = _call_arg(exc, 1, "detail")
1026
+ if isinstance(detail, ast.Name): # detail=msg,msg 只赋值过一次:看那次赋的值
1027
+ detail = self._sole_value(detail.id) or detail
1028
+ if detail is None or (isinstance(detail, ast.Constant) and detail.value is None):
1029
+ try:
1030
+ said = HTTPStatus(code).phrase
1031
+ except ValueError:
1032
+ said = ""
1033
+ elif isinstance(detail, ast.Constant) and isinstance(detail.value, str):
1034
+ said = detail.value
1035
+ elif isinstance(detail, ast.JoinedStr):
1036
+ said = "".join(v.value if isinstance(v, ast.Constant) and isinstance(v.value, str)
1037
+ else "{" + _source(self.lines, v.value) + "}" if isinstance(v, ast.FormattedValue)
1038
+ else _source(self.lines, v) for v in detail.values)
1039
+ else:
1040
+ said = _source(self.lines, detail)
1041
+ return f"{code} {said}".strip()
1042
+
1043
+ def _catch(self, h: ast.ExceptHandler) -> dict:
1044
+ kind = _source(self.lines, h.type) if h.type is not None else "任意异常"
1045
+ head = _head(self.lines, h, h.type) if h.type is not None else _Head(h.lineno, h.col_offset, "except")
1046
+ return {"title": f"捕获 {kind}", "head": head, "subtitle": kind,
1047
+ "line": h.lineno, "end_line": h.type.end_lineno if h.type is not None else h.lineno}
1048
+
1049
+ def _passthrough(self, v: ast.expr | None) -> str | None:
1050
+ """转交返回:return f(...) / return await f(...),或 return x 且 x 是这样一个调用的结果;
1051
+ f 须解析(exact / guessed)到项目内函数,派发不算。返回 f 的 key。"""
1052
+ if isinstance(v, ast.Name):
1053
+ v = self._sole_value(v.id)
1054
+ if isinstance(v, ast.Await):
1055
+ v = v.value
1056
+ if not isinstance(v, ast.Call) or self._is_outcome(v):
1057
+ return None
1058
+ ref = self._ref(v)
1059
+ if ref.is_dispatch or ref.resolution not in ("exact", "guessed") or id(v) in self._constructors:
1060
+ return None # 返回新构造的对象不是转交返回
1061
+ return ref.target
1062
+
1063
+ def _sole_value(self, name: str) -> ast.expr | None:
1064
+ """name 在本函数里(不含嵌套定义)只绑定一次、且那次是 name = 值 时返回那个值。参数也算一次绑定。"""
1065
+ a = self.fn.node.args
1066
+ if name in {p.arg for p in (*a.posonlyargs, *a.args, *a.kwonlyargs, a.vararg, a.kwarg) if p}:
1067
+ return None
1068
+ values: dict[int, ast.expr] = {} # id(赋值目标) -> 右边
1069
+ binds: list[ast.AST] = []
1070
+ for st in self.fn.node.body:
1071
+ for n in _walk(st):
1072
+ if isinstance(n, ast.Assign) and len(n.targets) == 1:
1073
+ values[id(n.targets[0])] = n.value
1074
+ elif isinstance(n, ast.AnnAssign) and n.value is not None:
1075
+ values[id(n.target)] = n.value
1076
+ if _binds(n, name):
1077
+ binds.append(n)
1078
+ return values.get(id(binds[0])) if len(binds) == 1 else None
1079
+
1080
+ def _field_value(self, v: ast.expr | str) -> str:
1081
+ """字段值:常量取其值,否则取源码。"""
1082
+ if isinstance(v, str):
1083
+ return v
1084
+ if isinstance(v, ast.Constant):
1085
+ return v.value if isinstance(v.value, str) else str(v.value)
1086
+ return _source(self.lines, v)
1087
+
1088
+ def _end_kind(self, fields: dict[str, str]) -> EndKind:
1089
+ """按 config.outcome_kinds 的顺序匹配字段值,先匹配到的为准;都不匹配为 "ok"。"""
1090
+ for name, mapping in self.config.outcome_kinds.items():
1091
+ value = fields.get(name)
1092
+ if value is not None and value in mapping:
1093
+ return mapping[value]
1094
+ return "ok"
1095
+
1096
+
1097
+ def build_function_graph(fn: FunctionInfo, index: ProjectIndex, rules: ActiveRules,
1098
+ resolver: Resolver, config: ProjectConfig) -> FunctionGraph:
1099
+ """把一个函数画成图:start、step、cond、loop、catch、end 节点和它们之间的连线。节点的 sid 在这里算好;函数的 sid
1100
+ 要看同一文件里的全部定义,这里留空,由 analyze 填。"""
1101
+ return _Builder(fn, index, rules, resolver, config).build()