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/verify.py ADDED
@@ -0,0 +1,968 @@
1
+ """执行路径核对:把 pytest 插件(trace.py)记下的真实执行,逐步放到静态图上走一遍,报告现实走了、图上却没有的每一步。
2
+
3
+ 一条记录的核对分三步:
4
+ 1. 行 → 节点行:执行到的每一行映射到它所属语句的起始行(多行语句只在后面的行上产生事件),只保留图上有节点的行,
5
+ 连续重复的合并。CPython 有几类行事件并不表示"执行了这一句",映射前先去掉:
6
+ - with 语句在离开时(调用 __exit__)回到头部的行:头部行事件紧跟在 with 体里的行之后,就是离开;
7
+ - 没匹配上的 except / case 子句头部:头部之后的下一个事件不在它的子句体里,说明没进入这个子句。
8
+ 子句体和头部写在同一行时看不出来,这一行记为"可以不经过"。
9
+ 进入了的只写日志的 except(不画捕获节点)在序列里留一个标记(负的头部行号),作为异常被吞掉的证据。
10
+ 写在一行的 except 的头部行不论是否匹配都会出现,是否吞掉了异常要看后面:之后(跳过这一行、with 头部和异常
11
+ 往外传时经过的 finally 体)的第一行是 except 头部时没有吞掉(不匹配,或子句体又抛出),不留标记;否则留一个
12
+ 标记(画了捕获节点的也留,挂在这一行之后)。
13
+ 没有节点的行落在某个 try 语句的 try 体里时也留一个标记(负的 try 起始行号,两个节点行之间每个 try 至多一个),
14
+ 作为执行不经过节点就进入了这个 try 体的证据。
15
+ 2. 走图:从 start 出发,每到一行依次经过该行的节点(按节点编号顺序)。一行有多个节点(如 if x: return y、
16
+ for 写成一行)时,事件分不出走了其中哪几个,所以每行可以只走一个前缀,"可以不经过"的行还可以整行不走;
17
+ 在所有走法里取不符最少、其次近似最少的一种(先列长的前缀,同样好时取先列出的)。
18
+ 每一步前一个节点 A 到当前节点 B 要有连线。没有连线时只看这一步自己的起点和终点(没有跨步的状态):
19
+ - 异常与收尾入口(近似):有一个 try 语句 T,A 在 T 的 try 体里且 B 是 T 的捕获节点、T 的 finally 体的入口,
20
+ 或(T 有只写日志、不画捕获节点的 except,或 T 只有 finally 时)T 之后的第一个节点;或者 A 在 T 的某个
21
+ except 体或 else 体里且 B 是 T 的 finally 体的入口;并且 B 有 raise / finally 类型的入边。落到只写日志的
22
+ except 之后(异常被吞掉)还要有证据:原始行号里 A 之后、B 之前出现了那个 except 的头部行。
23
+ A 不在 T 的 try 体里时(try 体开头是不产生节点的语句,异常从那里抛出,A 还停在 try 之前),B 的条件同上,
24
+ 另外要有证据:原始行号里 A 之后、B 之前出现了 T 的 try 体里的行(T 自己的 try 行、except 头部和 except 体、
25
+ else 体、finally 体里的行都不算)。
26
+ (异常画法近似:raise 连线只从 try 体的入口画出。except / else 体里抛出的异常 Python 不会交给同一个 try 的
27
+ 其他 except,所以从它们出发只认 finally。内层 try 没接住、往外层传的异常,A 也在外层 try 体里,或者
28
+ 这一步之间出现了外层 try 体里的行。)
29
+ - 其余都是不符。try / finally 里的 break / continue 建图时如实画成"跳转处 → finally 体 → 跳转目标",
30
+ return 画成"结局 → finally 体",离开 finally 体的这些路径都有连线,不需要近似。范围都按语法树里的行号算。
31
+ 沿连线到达结局(return / raise 语句)算在结局里,不计步数;近似和不符都计步数,并逐处记下位置。
32
+ 3. 结局:以 return 离开时,最后的节点要是结局、或者有连线到"执行到函数末尾"、或者经过 return 语句的结局 R 之后
33
+ 只走了 finally 里的节点。其间经过 R 正在经过的 finally 体 F 里的 raise 语句的结局时,要有那个异常在 F 里被
34
+ 吞掉的证据,R 才继续:之后经过的节点都还在 F 里,直到经过 F 里写成多行的 except 的捕获节点,或者原始行号里
35
+ 出现 F 里只写日志的 except、写在一行的 except 吞掉了异常的标记(见第 1 步;结局:最后的节点之后出现也算)。
36
+ 写在一行的 except 的头部行和捕获节点本身不算证据。没有这样的证据就离开了 F、或者到最后也没有时,异常逃出
37
+ 了 F,R 已被取消,不算。只经过 raise 语句的结局也不算:那个异常被吞掉了,函数是正常返回的。否则是结局不符。
38
+ 以 raise 离开时,停在 raise 语句的结局上(之后只走 finally 也算)是正常的,否则计为未捕获异常退出(图上有
39
+ 隐含的未捕获异常结局,不算不符)。
40
+ 吞掉的异常落到"执行到函数末尾"也算合法结局,记一次入口近似(终点行记为 0):T 有只写日志的 except、吞掉的
41
+ 异常落到函数末尾,最后的节点在 T 的 try 体里、或者它之后的原始行号里出现了 T 的 try 体里的行,并且它之后
42
+ 出现了那个 except 的头部行。
43
+ 截断的记录不核对结局;
44
+ 一个节点行都没有的记录只看结局:起点能走到某个结局就算合法。
45
+ 调用:记录里的每个"调用方在第 L 行 → 被调函数"依次判断:
46
+ 1. 在调用方的 call_targets 里,或被调函数是调用方的内部函数 → 在图上;
47
+ 2. 被调函数是属性访问器(@property、@cached_property、@x.setter / getter / deleter)或 __init__、__call__
48
+ 以外的魔术方法 → 隐式调用(Python 替代码调用的,源码里没有调用语法),单独列出,不算不符;
49
+ 3. 第 L 行所属的语句把被调函数的名字作为参数(不是调用)传了出去,如 sorted(xs, key=rank)、map(helper, xs)
50
+ → 动态调用(强匹配,回调);
51
+ 4. 第 L 行所属的语句里有无法判断目标的调用(图的 unresolved 里、行号映射到同一条语句的条目:回调参数、
52
+ 存在属性里的函数、没有类型的接收者)→ 动态调用,单独列出,不算不符;其中某个调用的名字最后一段正是
53
+ 被调函数的名字时为强匹配,否则为弱匹配。同一函数别的语句里有无法判断目标的调用不算数;
54
+ 5. 否则是不符。
55
+ 记录少记调用(经生成器表达式、lambda、库包装的调用不在 calls 里——它们是 icalls,核对不看),所以从不因为"没调用"
56
+ 报告任何东西。
57
+ 所有计数都乘以记录的 n。
58
+ 记录文件的格式见 trace.py 的模块说明。核对只看执行记录(有 fn 的行)里的 fn、lines、exit、calls、n、truncated:
59
+ 耗时 ns、测试结果行、以后加的字段和没有 fn 的行都不影响核对的结论。
60
+ walk_record 是第 1、2、3 步对一条执行记录的结果(依次经过的节点、停在哪个节点),verify 和运行路径(runpath)共用它。
61
+ """
62
+
63
+ from __future__ import annotations
64
+
65
+ import ast
66
+ import hashlib
67
+ import json
68
+ import math
69
+ from collections import Counter
70
+ from collections.abc import Iterable, Iterator
71
+ from dataclasses import dataclass, field, replace
72
+ from pathlib import Path
73
+ from typing import Literal
74
+
75
+ from .model import FunctionGraph, ProjectGraph
76
+
77
+ MismatchKind = Literal["edge", "end", "call"]
78
+ _KIND_ORDER = {"edge": 0, "end": 1, "call": 2}
79
+ _LANDING = frozenset({"raise", "finally"}) # 异常和收尾落脚的连线类型
80
+ _FuncNode = ast.FunctionDef | ast.AsyncFunctionDef
81
+ Span = tuple[int, int] # 行范围(含两端)
82
+
83
+
84
+ @dataclass
85
+ class Mismatch:
86
+ kind: MismatchKind
87
+ fn: str
88
+ from_line: int # edge:前一个节点的行;end:最后所在节点的行;call:调用发生时调用方所在的行
89
+ to_line: int # edge:当前节点的行;end:0;call:被调函数的 def 行
90
+ detail: str
91
+ count: int
92
+
93
+
94
+ @dataclass
95
+ class Approximation:
96
+ fn: str
97
+ from_line: int # 前一个节点的行
98
+ to_line: int # 当前节点的行;0 表示"执行到函数末尾"
99
+ kind: Literal["entry"] # 异常与收尾入口
100
+ count: int
101
+
102
+
103
+ @dataclass
104
+ class ImplicitCall:
105
+ caller: str
106
+ callee: str
107
+ reason: Literal["property", "dunder"] # 属性访问器 / 魔术方法
108
+ count: int
109
+
110
+
111
+ @dataclass
112
+ class DynamicCall:
113
+ caller: str
114
+ callee: str
115
+ line: int # 调用发生时调用方所在的行
116
+ strong: bool # 被调函数的名字正是该语句里某个无法判断目标的调用的名字(最后一段),或被作为参数传出(回调)
117
+ names: list[str] # 该语句里无法判断目标的调用的显示名;回调时是作为参数传出的名字
118
+ callback: bool # 该语句把被调函数的名字作为参数传了出去
119
+ count: int
120
+
121
+
122
+ @dataclass
123
+ class VerifyReport:
124
+ functions_in_graph: int
125
+ functions_seen: int
126
+ distinct_paths: int # 不同的 (函数, 节点行序列, 离开方式)
127
+ steps_total: int
128
+ steps_on_graph: int
129
+ approx_entries: int # 异常与收尾入口(近似画法,不算错)
130
+ uncaught_exits: int # 以未捕获异常退出(对应图上的隐含结局)
131
+ calls_total: int
132
+ implicit_calls: int # 属性访问器、魔术方法(源码里没有调用语法)
133
+ dynamic_calls: int # 调用方有无法判断目标的调用
134
+ truncated_records: int
135
+ unknown_functions: int # 记录里出现、图里没有的函数(个数)
136
+ plugin_errors: int
137
+ mismatches: list[Mismatch] = field(default_factory=list) # 按次数从多到少
138
+ approx_list: list[Approximation] = field(default_factory=list) # 按次数从多到少
139
+ implicit_call_list: list[ImplicitCall] = field(default_factory=list) # 按次数从多到少
140
+ dynamic_call_list: list[DynamicCall] = field(default_factory=list) # 按次数从多到少
141
+ plugin_error_list: list[str] = field(default_factory=list)
142
+
143
+ @property
144
+ def ok(self) -> bool:
145
+ return not self.mismatches
146
+
147
+
148
+ class StaleGraphError(Exception):
149
+ """图分析之后源码改过或读不到了:行号对不上,核对没有意义。"""
150
+
151
+ def __init__(self, changed: list[str], unreadable: list[str]):
152
+ super().__init__("图已过期:" + "、".join(changed + unreadable))
153
+ self.changed = changed # 内容变了
154
+ self.unreadable = unreadable # 读不到(删除、移动、没有权限)
155
+ self.files = sorted(changed + unreadable)
156
+
157
+
158
+ class RecordError(ValueError):
159
+ """记录文件里有一行读不了。"""
160
+
161
+
162
+ TRACE_FORMAT = "pystepmap-trace"
163
+ TRACE_VERSION = 1 # 能读的记录格式的最高版本
164
+ TEST_OUTCOMES = frozenset({"passed", "failed", "skipped", "error"}) # 测试结果行的 outcome
165
+
166
+
167
+ @dataclass(frozen=True)
168
+ class Walked:
169
+ """一条执行记录在图上走出来的样子(见模块说明第 1–3 步,和 verify 用的是同一个走法)。"""
170
+
171
+ nodes: tuple[str, ...] # 依次经过的节点 id:n1(开始)起,循环里重复出现;以"执行到函数末尾"结束时最后是它
172
+ # 每个节点从 lines 里的第几项开始(开始节点为 0;执行到函数末尾为 len(lines))。同一行上的几个节点(return f()、
173
+ # if c: return 0)从同一个行事件开始,位置相同;这一段的时间归谁由使用者定(runpath 归给最后一个不是结局的)
174
+ line_index: tuple[int, ...]
175
+ # 停在哪个节点:以 return 离开时是 return 语句的结局(之后只走了 finally 也是它)或"执行到函数末尾";以 raise 离开时
176
+ # 是 raise 语句的结局(同上),没有对应的结局时是"未捕获异常退出"(它没有入边,不放进 nodes)。结局不符时是最后
177
+ # 所在的节点;截断的记录不知道停在哪里,为空串
178
+ exit_node: str
179
+ on_graph: bool # 核对不报任何不符:每一步都有连线(异常与收尾入口的近似算在图上)、结局也在图上
180
+ truncated: bool
181
+
182
+
183
+ # ---------- 对外接口 ----------
184
+
185
+
186
+ def stale_files(graph: ProjectGraph) -> tuple[list[str], list[str]]:
187
+ """(内容与分析时不同的文件, 读不到的文件),都是相对路径、排序。"""
188
+ root = Path(graph.root)
189
+ changed, unreadable = [], []
190
+ for rel, digest in sorted(graph.file_hashes.items()):
191
+ try:
192
+ actual = hashlib.sha256((root / rel).read_bytes()).hexdigest()
193
+ except OSError:
194
+ unreadable.append(rel)
195
+ continue
196
+ if actual != digest:
197
+ changed.append(rel)
198
+ return changed, unreadable
199
+
200
+
201
+ def read_records(path: str | Path) -> Iterator[dict]:
202
+ """逐行读记录文件(可能有几百 MB,不整个读入)。给出执行记录(有 fn)、测试结果行和插件错误行(有 error);
203
+ 不认识的字段原样留着。格式只加不改,所以空行、版本头、不认识的测试结果(以后加的 outcome、字段不对的)和其余
204
+ 没有 fn / error 的 JSON 对象都跳过。某行不是 JSON、是 JSON 但不是对象、执行记录不合法、版本比能读的新时抛
205
+ RecordError。"""
206
+ with open(path, "rb") as f:
207
+ for no, raw in enumerate(f, 1):
208
+ try:
209
+ text = raw.decode("utf-8")
210
+ rec = json.loads(text) if text.strip() else None
211
+ except (UnicodeDecodeError, json.JSONDecodeError) as e:
212
+ raise RecordError(f"第 {no} 行不是合法的 JSON:{e}") from None
213
+ if rec is None:
214
+ continue
215
+ if isinstance(rec, dict) and rec.get("format") == TRACE_FORMAT: # 版本头(可以没有,也可能有几行)
216
+ if not (type(rec.get("v")) is int and 1 <= rec["v"] <= TRACE_VERSION):
217
+ raise RecordError(f"第 {no} 行:记录格式版本 {rec.get('v')!r} 不是这个 pystepmap 能读的"
218
+ f"(最高 {TRACE_VERSION}),请升级 pystepmap")
219
+ continue
220
+ if not isinstance(rec, dict) or ("error" not in rec and "fn" in rec and not _well_formed(rec)):
221
+ raise RecordError(f"第 {no} 行不是执行记录:{text.strip()[:80]}")
222
+ if "error" not in rec and "fn" not in rec and not _test_result(rec):
223
+ continue
224
+ yield rec
225
+
226
+
227
+ def walk_record(graph: ProjectGraph, record: dict, cache: dict | None = None) -> Walked | None:
228
+ """把一条执行记录放到图上走一遍(同 verify)。函数不在图里时为 None。cache:批量调用时传同一个字典(只用于这一张
229
+ 图),复用解析过的源码、每个函数的源码事实和走图结果。"""
230
+ hit = _walk_cached(graph, record, {} if cache is None else cache)
231
+ if hit is None:
232
+ return None
233
+ _, _, w, index = hit
234
+ nodes = tuple(nid for nid, _ in w.path)
235
+ at = tuple(0 if pos < 0 else index[pos] if pos < len(index) else len(record["lines"]) for _, pos in w.path)
236
+ return Walked(nodes, at, w.exit_node, not w.problems, bool(record.get("truncated")))
237
+
238
+
239
+ def verify(graph: ProjectGraph, records: Iterable[dict], *, allow_stale: bool = False) -> VerifyReport:
240
+ """把记录逐条放到图上核对。图过期时抛 StaleGraphError(allow_stale 为真时照样核对)。"""
241
+ if not allow_stale:
242
+ changed, unreadable = stale_files(graph)
243
+ if changed or unreadable:
244
+ raise StaleGraphError(changed, unreadable)
245
+ cache: dict = {}
246
+ sources = _cache_sources(graph, cache)
247
+ verdicts: dict[tuple[str, str, int], tuple | None] = {} # (调用方, 被调, 调用所在行) -> 判定
248
+ totals: Counter[str] = Counter()
249
+ problems: Counter[tuple] = Counter()
250
+ approximations: Counter[tuple] = Counter()
251
+ implicit: Counter[tuple] = Counter()
252
+ dynamic: Counter[tuple] = Counter()
253
+ seen: set[str] = set()
254
+ unknown: set[str] = set()
255
+ errors: list[str] = []
256
+ for rec in records:
257
+ if "error" in rec:
258
+ errors.append(str(rec["error"]))
259
+ continue
260
+ if "fn" not in rec: # 测试结果行等:不是执行记录
261
+ continue
262
+ name = rec["fn"]
263
+ hit = _walk_cached(graph, rec, cache)
264
+ if hit is None:
265
+ unknown.add(name)
266
+ continue
267
+ fn, _, w, _ = hit
268
+ seen.add(name)
269
+ n = rec.get("n", 1)
270
+ truncated = bool(rec.get("truncated"))
271
+ totals["steps"] += w.steps * n
272
+ totals["on_graph"] += w.on_graph * n
273
+ totals["approx_in"] += w.approx_in * n
274
+ totals["uncaught"] += w.uncaught * n
275
+ totals["truncated"] += truncated * n
276
+ for kind, a, b, detail in w.problems:
277
+ problems[(kind, name, a, b, detail)] += n
278
+ for a, b, kind in w.approximations:
279
+ approximations[(name, a, b, kind)] += n
280
+ for callee, call_line in rec.get("calls", ()):
281
+ totals["calls"] += n
282
+ vkey = (name, callee, call_line)
283
+ if vkey not in verdicts:
284
+ verdicts[vkey] = _call_verdict(graph, sources, fn, callee, call_line)
285
+ v = verdicts[vkey]
286
+ if v is None:
287
+ continue
288
+ if v[0] == "implicit":
289
+ implicit[(name, callee, v[1])] += n
290
+ elif v[0] == "dynamic":
291
+ dynamic[(name, callee, call_line)] += n
292
+ else:
293
+ problems[("call", name, call_line, v[1], callee)] += n
294
+ mismatches = [Mismatch(kind, fn_, a, b, detail, c) for (kind, fn_, a, b, detail), c in problems.items()]
295
+ mismatches.sort(key=lambda m: (-m.count, _KIND_ORDER[m.kind], m.fn, m.from_line, m.to_line, m.detail))
296
+ approx = [Approximation(fn_, a, b, kind, c) for (fn_, a, b, kind), c in approximations.items()]
297
+ approx.sort(key=lambda x: (-x.count, x.fn, x.from_line, x.to_line, x.kind))
298
+ imp = [ImplicitCall(caller, callee, reason, c) for (caller, callee, reason), c in implicit.items()]
299
+ imp.sort(key=lambda d: (-d.count, d.caller, d.callee))
300
+ dyn = [DynamicCall(caller, callee, ln, *verdicts[(caller, callee, ln)][1:], c)
301
+ for (caller, callee, ln), c in dynamic.items()]
302
+ dyn.sort(key=lambda d: (-d.count, d.caller, d.callee, d.line))
303
+ return VerifyReport(
304
+ functions_in_graph=len(graph.functions), functions_seen=len(seen),
305
+ distinct_paths=len({k[:3] for k in cache.get("walks", ())}), steps_total=totals["steps"],
306
+ steps_on_graph=totals["on_graph"], approx_entries=totals["approx_in"], uncaught_exits=totals["uncaught"],
307
+ calls_total=totals["calls"], implicit_calls=sum(implicit.values()), dynamic_calls=sum(dynamic.values()),
308
+ truncated_records=totals["truncated"], unknown_functions=len(unknown),
309
+ plugin_errors=len(errors), mismatches=mismatches, approx_list=approx, implicit_call_list=imp,
310
+ dynamic_call_list=dyn,
311
+ plugin_error_list=errors)
312
+
313
+
314
+ def _cache_sources(graph: ProjectGraph, cache: dict) -> _Sources:
315
+ sources = cache.get("sources")
316
+ if sources is None:
317
+ sources = cache["sources"] = _Sources(Path(graph.root))
318
+ return sources
319
+
320
+
321
+ def _walk_cached(graph: ProjectGraph, rec: dict, cache: dict) -> tuple[_Fn, tuple, _Walk, tuple[int, ...]] | None:
322
+ """(函数, 走图结果的键, 走图结果, 节点行序列每一项在 lines 里的位置);函数不在图里时为 None。走图结果按
323
+ (函数, 节点行序列, 离开方式, 是否截断) 缓存在 cache["walks"] 里(verify 用它数不同的路径)。"""
324
+ name = rec["fn"]
325
+ g = graph.functions.get(name)
326
+ if g is None:
327
+ return None
328
+ fns = cache.setdefault("fns", {})
329
+ fn = fns.get(name)
330
+ if fn is None:
331
+ fn = fns[name] = _Fn(g, _cache_sources(graph, cache).function(g))
332
+ truncated = bool(rec.get("truncated"))
333
+ seq, index = fn.node_lines_at(rec["lines"])
334
+ wkey = (name, seq, rec["exit"], truncated)
335
+ walks = cache.setdefault("walks", {})
336
+ w = walks.get(wkey)
337
+ if w is None:
338
+ w = walks[wkey] = fn.walk(seq, rec["exit"], truncated)
339
+ return fn, wkey, w, index
340
+
341
+
342
+ # ---------- 记录格式 ----------
343
+
344
+
345
+ def _well_formed(rec: dict) -> bool:
346
+ n = rec.get("n", 1)
347
+ return (isinstance(rec.get("fn"), str) and isinstance(rec.get("lines"), list)
348
+ and all(type(x) is int for x in rec["lines"]) and rec.get("exit") in ("return", "raise")
349
+ and isinstance(rec.get("calls", []), list) and all(_call_pair(c) for c in rec.get("calls", []))
350
+ and type(n) is int and n > 0 and ("ns" not in rec or _times(rec["ns"], len(rec["lines"]))))
351
+
352
+
353
+ def _times(ns: object, length: int) -> bool:
354
+ """执行记录的 ns:和 lines 等长的非负整数列表。"""
355
+ return isinstance(ns, list) and len(ns) == length and all(type(x) is int and x >= 0 for x in ns)
356
+
357
+
358
+ def _test_result(rec: dict) -> bool:
359
+ """测试结果行:{"test": node id, "outcome": ..., "seconds": 非负数, "n": 正整数},可以有 "exc": 异常类型名。"""
360
+ seconds, n, exc = rec.get("seconds"), rec.get("n", 1), rec.get("exc")
361
+ return (isinstance(rec.get("test"), str) and rec.get("outcome") in TEST_OUTCOMES
362
+ and type(seconds) in (int, float) and math.isfinite(seconds) and seconds >= 0
363
+ and type(n) is int and n > 0 and (exc is None or isinstance(exc, str)))
364
+
365
+
366
+ _NOT_IMPLICIT = frozenset({"__init__", "__call__"}) # 有调用语法(Cls(...)、obj(...)),图上应当有
367
+ _ACCESSOR_DECORATORS = frozenset({"property", "cached_property"})
368
+ _ACCESSOR_ATTRS = frozenset({"cached_property", "setter", "getter", "deleter"})
369
+
370
+
371
+ def _call_pair(c: object) -> bool:
372
+ """[被调函数 key, 调用方所在行]。"""
373
+ return isinstance(c, list) and len(c) == 2 and isinstance(c[0], str) and type(c[1]) is int
374
+
375
+
376
+ def _call_verdict(graph: ProjectGraph, sources: _Sources, caller: _Fn, callee: str, line: int) -> tuple | None:
377
+ """None:图上有这个调用;("implicit", 原因);("dynamic", 是否强匹配, 名字列表, 是否回调);
378
+ ("call", 被调函数 def 行):不符。line 是调用发生时调用方所在的行。"""
379
+ if callee in caller.call_targets:
380
+ return None
381
+ cg = graph.functions.get(callee)
382
+ if cg is not None and cg.parent == caller.g.key:
383
+ return None
384
+ name = _simple_name(callee)
385
+ if name.startswith("__") and name.endswith("__") and len(name) > 4 and name not in _NOT_IMPLICIT:
386
+ return ("implicit", "dunder")
387
+ node = sources.function(cg) if cg is not None else None
388
+ if node is not None and _is_accessor(node):
389
+ return ("implicit", "property")
390
+ if name in caller.references_in_statement(line):
391
+ return ("dynamic", True, [name], True)
392
+ names = caller.unresolved_in_statement(line)
393
+ if names:
394
+ return ("dynamic", any(n.rsplit(".", 1)[-1] == name for n in names), names, False)
395
+ return ("call", cg.line if cg is not None else _def_line(callee))
396
+
397
+
398
+ def _is_accessor(node: _FuncNode) -> bool:
399
+ """@property、@cached_property / @functools.cached_property、@x.setter / getter / deleter。"""
400
+ for d in node.decorator_list:
401
+ if isinstance(d, ast.Name) and d.id in _ACCESSOR_DECORATORS:
402
+ return True
403
+ if isinstance(d, ast.Attribute) and d.attr in _ACCESSOR_ATTRS:
404
+ return True
405
+ return False
406
+
407
+
408
+ def _simple_name(key: str) -> str:
409
+ """函数 key 里限定名的最后一段:app/a.py::Svc.handle@3 -> handle。"""
410
+ return key.split("::", 1)[-1].rsplit("@", 1)[0].rsplit(".", 1)[-1]
411
+
412
+
413
+ def _def_line(key: str) -> int:
414
+ try:
415
+ return int(key.rsplit("@", 1)[1])
416
+ except (IndexError, ValueError):
417
+ return 0
418
+
419
+
420
+ # ---------- 源码 ----------
421
+
422
+
423
+ class _Sources:
424
+ """每个源文件只解析一次。"""
425
+
426
+ def __init__(self, root: Path):
427
+ self.root = root
428
+ self._defs: dict[str, dict[int, _FuncNode]] = {}
429
+
430
+ def function(self, g: FunctionGraph) -> _FuncNode | None:
431
+ """图里函数对应的语法树节点;文件读不了、解析不了或对不上(图过期)时为 None。"""
432
+ defs = self._defs.get(g.file)
433
+ if defs is None:
434
+ defs = self._defs[g.file] = self._parse(g.file)
435
+ node = defs.get(g.line)
436
+ return node if node is not None and node.name == _simple_name(g.key) else None
437
+
438
+ def _parse(self, rel: str) -> dict[int, _FuncNode]:
439
+ try:
440
+ tree = ast.parse((self.root / rel).read_bytes()) # 字节:编码声明、BOM 由解析器处理
441
+ except (OSError, SyntaxError, ValueError, RecursionError):
442
+ return {}
443
+ return {n.lineno: n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef | ast.AsyncFunctionDef)}
444
+
445
+
446
+ def _header_end(st: ast.stmt) -> int:
447
+ """语句头部的结束行:简单语句取整条;if / while 到条件结束;for 到迭代表达式结束;with 到最后一个上下文
448
+ 表达式(含 as 目标)结束;try 只有 try: 这一行;match 到主语表达式结束。"""
449
+ if isinstance(st, ast.If | ast.While):
450
+ return st.test.end_lineno
451
+ if isinstance(st, ast.For | ast.AsyncFor):
452
+ return st.iter.end_lineno
453
+ if isinstance(st, ast.With | ast.AsyncWith):
454
+ return max(max(i.context_expr.end_lineno, i.optional_vars.end_lineno if i.optional_vars else 0)
455
+ for i in st.items)
456
+ if isinstance(st, ast.Try | ast.TryStar):
457
+ return st.lineno
458
+ if isinstance(st, ast.Match):
459
+ return st.subject.end_lineno
460
+ return st.end_lineno
461
+
462
+
463
+ @dataclass
464
+ class _TryRanges:
465
+ """一个 try 语句各部分的行范围。"""
466
+
467
+ whole: Span
468
+ body: Span
469
+ others: list[Span] # 各 except 体(含 except 头)和 else 体
470
+ catch_lines: list[int] # 各 except 头所在的行(画出的捕获节点就在这一行)
471
+ final: Span | None
472
+
473
+
474
+ @dataclass
475
+ class _TryFacts:
476
+ """一个 try 语句在图上的近似落脚点。"""
477
+
478
+ ranges: _TryRanges
479
+ from_body: set[str] # A 在 try 体里时可以近似到达的节点:捕获节点、finally 入口、(只有 finally 时)try 之后
480
+ swallowed: set[str] # A 在 try 体里、异常被只写日志的 except 吞掉后落到的 try 之后的节点(要有头部行作证)
481
+ log_only_lines: frozenset[int] # 只写日志、不画捕获节点的 except 的头部行
482
+ from_others: set[str] # A 在 except / else 体里时:finally 入口
483
+ swallow_to_end: bool # 有只写日志的 except,吞掉的异常落到函数末尾(要有头部行作证)
484
+
485
+
486
+ def _inside(line: int, span: Span | None) -> bool:
487
+ return span is not None and span[0] <= line <= span[1]
488
+
489
+
490
+ @dataclass
491
+ class _Scope:
492
+ """一个函数自己的帧里的源码事实(不含嵌套的函数、类、lambda 的体;嵌套定义的装饰器、默认值算外层的)。"""
493
+
494
+ line_map: dict[int, int] # 行 -> 所属语句(或 except 子句头、case 守卫、嵌套定义的头部)的起始行
495
+ withs: dict[int, tuple[int, int, int, int]] # with 头部的每一行 -> (头部起, 头部止, 体起, 体止)
496
+ clauses: dict[int, tuple[int, int, int, int]] # except / case 子句头部的每一行 -> 同上(体不在头部行上的子句)
497
+ one_line_clauses: list[Span] # 体写在头部行上的子句的头部范围
498
+ tries: list[_TryRanges]
499
+ references: list[tuple[int, str]] # 作为调用的参数传出(不是调用)的名字:(所在行, 名字或属性名)
500
+ one_line_excepts: set[int] = field(default_factory=set) # 体写在头部行上的 except 子句的头部起始行
501
+ raise_lines: set[int] = field(default_factory=set) # raise 语句的起始行
502
+ return_lines: set[int] = field(default_factory=set) # return 语句的起始行
503
+
504
+ @property
505
+ def finals(self) -> list[Span]:
506
+ return [t.final for t in self.tries if t.final is not None]
507
+
508
+
509
+ def _span(stmts: list[ast.stmt]) -> Span:
510
+ return stmts[0].lineno, stmts[-1].end_lineno
511
+
512
+
513
+ def _def_header(n: ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef) -> list[ast.expr]:
514
+ """嵌套定义里在外层帧执行的部分:装饰器、参数默认值;类的基类和关键字参数。"""
515
+ if isinstance(n, ast.ClassDef):
516
+ return [*n.decorator_list, *n.bases, *(k.value for k in n.keywords)]
517
+ return [*n.decorator_list, *n.args.defaults, *(d for d in n.args.kw_defaults if d is not None)]
518
+
519
+
520
+ def _scope(fn: _FuncNode | None) -> _Scope:
521
+ scope = _Scope({}, {}, {}, [], [], [])
522
+ if fn is None:
523
+ return scope
524
+ spans: list[Span] = []
525
+
526
+ def clause(hlo: int, hhi: int, body: list[ast.stmt]) -> None:
527
+ spans.append((hlo, hhi))
528
+ blo, bhi = body[0].lineno, body[-1].end_lineno
529
+ if blo <= hhi:
530
+ scope.one_line_clauses.append((hlo, hhi))
531
+ else:
532
+ for ln in range(hlo, hhi + 1):
533
+ scope.clauses[ln] = (hlo, hhi, blo, bhi)
534
+
535
+ stack: list[ast.AST] = list(reversed(fn.body))
536
+ while stack:
537
+ n = stack.pop()
538
+ if isinstance(n, ast.Lambda):
539
+ continue
540
+ if isinstance(n, ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef): # 体是别的帧;头部在这一帧执行
541
+ header = _def_header(n)
542
+ spans.append((min([n.lineno, *(e.lineno for e in header)]), max([n.lineno, *(e.end_lineno for e in header)])))
543
+ stack.extend(reversed(header))
544
+ continue
545
+ if isinstance(n, ast.stmt):
546
+ end = _header_end(n)
547
+ spans.append((n.lineno, end))
548
+ if isinstance(n, ast.Raise):
549
+ scope.raise_lines.add(n.lineno)
550
+ elif isinstance(n, ast.Return):
551
+ scope.return_lines.add(n.lineno)
552
+ if isinstance(n, ast.With | ast.AsyncWith):
553
+ for ln in range(n.lineno, end + 1):
554
+ scope.withs[ln] = (n.lineno, end, n.body[0].lineno, n.body[-1].end_lineno)
555
+ elif isinstance(n, ast.Try | ast.TryStar):
556
+ scope.tries.append(_TryRanges(
557
+ (n.lineno, n.end_lineno), _span(n.body),
558
+ [(h.lineno, h.end_lineno) for h in n.handlers] + ([_span(n.orelse)] if n.orelse else []),
559
+ [h.lineno for h in n.handlers], _span(n.finalbody) if n.finalbody else None))
560
+ elif isinstance(n, ast.Call):
561
+ for arg in [*n.args, *(k.value for k in n.keywords)]:
562
+ arg = arg.value if isinstance(arg, ast.Starred) else arg
563
+ if isinstance(arg, ast.Name):
564
+ scope.references.append((arg.lineno, arg.id))
565
+ elif isinstance(arg, ast.Attribute):
566
+ scope.references.append((arg.lineno, arg.attr))
567
+ elif isinstance(n, ast.excepthandler):
568
+ hhi = n.type.end_lineno if n.type is not None else n.lineno
569
+ clause(n.lineno, hhi, n.body)
570
+ if n.body[0].lineno <= hhi:
571
+ scope.one_line_excepts.add(n.lineno)
572
+ elif isinstance(n, ast.match_case):
573
+ if n.guard is not None:
574
+ spans.append((n.guard.lineno, n.guard.end_lineno))
575
+ clause(n.pattern.lineno, (n.guard or n.pattern).end_lineno, n.body)
576
+ stack.extend(reversed(list(ast.iter_child_nodes(n))))
577
+ for lo, hi in sorted(spans, key=lambda s: s[1] - s[0], reverse=True): # 小的范围(内层)覆盖大的
578
+ for ln in range(lo, hi + 1):
579
+ scope.line_map[ln] = lo
580
+ return scope
581
+
582
+
583
+ # ---------- 走图 ----------
584
+
585
+
586
+ @dataclass
587
+ class _Walk:
588
+ steps: int = 0
589
+ on_graph: int = 0
590
+ approx_in: int = 0
591
+ uncaught: bool = False
592
+ problems: tuple[tuple[str, int, int, str], ...] = ()
593
+ approximations: tuple[tuple[int, int, str], ...] = () # (前一个节点的行, 当前节点的行, "entry")
594
+ # 选中的走法依次经过的 (节点 id, 节点行序列里的位置):开始节点的位置是 -1;最后补上的"执行到函数末尾"是 len(序列)
595
+ path: tuple[tuple[str, int], ...] = ()
596
+ exit_node: str = "" # 见 Walked.exit_node
597
+
598
+
599
+ def _unlink(link: tuple | None) -> tuple:
600
+ """(条目, 前面的链) 串成的链 → 按先后顺序的元组。"""
601
+ out = []
602
+ while link is not None:
603
+ out.append(link[0])
604
+ link = link[1]
605
+ return tuple(reversed(out))
606
+
607
+
608
+ @dataclass
609
+ class _Trail:
610
+ """一种走法走到某一行为止的状态。problems / approximations 是 (条目, 前面的链) 串成的链,避免每步复制。"""
611
+
612
+ node: str
613
+ tail: str | None # 最后经过的结局节点,且之后只走了 finally 里的节点;否则 None(以 raise 离开时看它)
614
+ # 上一个经过的节点之后的证据:只写日志的 except 头部行(异常被吞掉)、try 体里的行所属的 try 的起始行(进入了 try 体)
615
+ markers: frozenset[int] = frozenset()
616
+ cost: tuple[int, int] = (0, 0) # (不符数, 近似数)
617
+ steps: int = 0
618
+ on_graph: int = 0
619
+ approx_in: int = 0
620
+ problems: tuple | None = None
621
+ approximations: tuple | None = None
622
+ ret: str | None = None # 最后经过的 return 语句的结局,且之后只走了 finally 里的节点(以 return 离开时看它)
623
+ wait: Span | None = None # 经过了 ret 正在经过的 finally 体里的 raise 结局、异常还没被吞掉:那个 finally 体
624
+ path: tuple | None = None # 经过的 (节点 id, 节点行序列里的位置) 串成的链,不参与去重和比较代价
625
+
626
+
627
+ def _state(t: _Trail) -> tuple:
628
+ """走法的去重键:同一节点、同样的结局状态和证据的走法只留代价最小的一种。"""
629
+ return t.node, t.tail, t.ret, t.wait, t.markers
630
+
631
+
632
+ class _Fn:
633
+ """一个函数的图和源码事实,核对它的每条记录。"""
634
+
635
+ def __init__(self, g: FunctionGraph, node: _FuncNode | None):
636
+ self.g = g
637
+ self.title = {n.id: n.title for n in g.nodes}
638
+ self.line = {n.id: n.line for n in g.nodes}
639
+ self.start = next(n.id for n in g.nodes if n.type == "start")
640
+ self.by_line: dict[int, list[str]] = {} # 行 -> 该行的节点,按编号顺序(图里的顺序)
641
+ for n in g.nodes:
642
+ if n.type != "start" and n.line > 0:
643
+ self.by_line.setdefault(n.line, []).append(n.id)
644
+ self.edges: dict[tuple[str, str], frozenset[str]] = {}
645
+ for e in g.edges:
646
+ self.edges[(e.src, e.dst)] = self.edges.get((e.src, e.dst), frozenset()) | {e.kind}
647
+ self.landing = {e.dst for e in g.edges if e.kind in _LANDING} # 有 raise / finally 入边的节点
648
+ self.ends = {n.id for n in g.nodes if n.type == "end"}
649
+ self.failed = {n.id for n in g.nodes if n.type == "end" and n.end_kind == "failed"}
650
+ self.fell_off = {n.id for n in g.nodes if n.type == "end" and n.line == 0 and n.end_kind == "ok"}
651
+ self.fell_off_order = [n.id for n in g.nodes if n.id in self.fell_off]
652
+ self.uncaught_end = next((n.id for n in g.nodes if n.type == "end" and n.end_kind == "exception"), "")
653
+ self.into_fell_off = {src for src, dst in self.edges if dst in self.fell_off}
654
+ self.call_targets = set(g.call_targets)
655
+ self.scope = _scope(node)
656
+ self._unresolved_by_statement: dict[int, list[str]] = {} # 语句起始行 -> 其中无法判断目标的调用名
657
+ for u in g.unresolved:
658
+ names = self._unresolved_by_statement.setdefault(self.statement(u.line), [])
659
+ if u.name not in names:
660
+ names.append(u.name)
661
+ self.finally_nodes = {n.id for n in g.nodes if n.line > 0
662
+ and any(lo <= n.line <= hi for lo, hi in self.scope.finals)}
663
+ # raise 语句的结局(return failed(...) 之类的 return 结局 end_kind 可能相同,按语句区分)
664
+ self.raise_ends = {n.id for n in g.nodes if n.type == "end" and n.line in self.scope.raise_lines
665
+ and n.line not in self.scope.return_lines}
666
+ self.catch_nodes = {n.id for n in g.nodes if n.type == "catch"}
667
+ self.except_headers = {ln for t in self.scope.tries for ln in t.catch_lines}
668
+ # 写在一行的 except 的头部行 -> 异常从它那里往外传时会经过的 finally 体(它所属的 try 和外层 try 的)
669
+ self._one_line_skip: dict[int, list[Span]] = {}
670
+ for t in self.scope.tries:
671
+ spans = [u.final for u in self.scope.tries if u.final is not None and (
672
+ u is t or _inside(t.whole[0], u.body) or any(_inside(t.whole[0], span) for span in u.others))]
673
+ for h in t.catch_lines:
674
+ if h in self.scope.one_line_excepts:
675
+ self._one_line_skip[h] = spans
676
+ self._tries = [self._try_facts(t, g) for t in self.scope.tries]
677
+ self.log_only_headers = {ln for f in self._tries for ln in f.log_only_lines}
678
+ self.try_bodies: dict[int, tuple[int, ...]] = {} # 行 -> try 体包含这一行的 try 语句(起始行)
679
+ for t in self.scope.tries:
680
+ for ln in range(t.body[0], t.body[1] + 1):
681
+ self.try_bodies[ln] = (*self.try_bodies.get(ln, ()), t.whole[0])
682
+ # (A, B) -> 认可这一步的各种条件:(要求进入了 try 体的 try 起始行或 None, 要求的只写日志 except 头部行或 None)
683
+ self._entries: dict[tuple[str, str], list[tuple[int | None, frozenset[int] | None]]] = {}
684
+ self._references_by_statement: dict[int, set[str]] = {} # 语句起始行 -> 其中作为参数传出的名字
685
+ for ln, ref in self.scope.references:
686
+ self._references_by_statement.setdefault(self.statement(ln), set()).add(ref)
687
+ self.optional = {ln for ln in self.by_line
688
+ if any(lo <= ln <= hi for lo, hi in self.scope.one_line_clauses)}
689
+ self.start_reaches_end = bool(self._reachable(self.start) & self.ends)
690
+
691
+ def statement(self, line: int) -> int:
692
+ """行所属语句(或 except 子句头、case 守卫)的起始行,同核对执行路径时的映射。多行语句的每一行都归到它,
693
+ 复合语句只有头部的行归到它(体里的行属于体里各自的语句)。"""
694
+ return self.scope.line_map.get(line, line)
695
+
696
+ def unresolved_in_statement(self, line: int) -> list[str]:
697
+ """line 所属语句里无法判断目标的调用的显示名(行号未知为 0 时为空)。"""
698
+ return self._unresolved_by_statement.get(self.statement(line), []) if line > 0 else []
699
+
700
+ def references_in_statement(self, line: int) -> set[str]:
701
+ """line 所属语句里作为调用参数传出的名字(行号未知为 0 时为空)。"""
702
+ return self._references_by_statement.get(self.statement(line), set()) if line > 0 else set()
703
+
704
+ # ---------- 异常与收尾的近似(见模块说明第 2 步)----------
705
+
706
+ def _try_facts(self, t: _TryRanges, g: FunctionGraph) -> _TryFacts:
707
+ """try 语句 t 在图上的近似落脚点(见模块说明第 2、3 步);落脚点都要求有 raise / finally 入边。"""
708
+ line = self.line
709
+ catch_nodes = [n for n in g.nodes if n.type == "catch" and n.line in t.catch_lines]
710
+ catches = {n.id for n in catch_nodes}
711
+ finals = {b for a, b in self.edges if _inside(line[b], t.final) and not _inside(line[a], t.final)}
712
+ drawn = {n.line for n in catch_nodes}
713
+ log_only_lines = frozenset(ln for ln in t.catch_lines if ln not in drawn)
714
+ after = {b for (a, b), kinds in self.edges.items() # 从 try 里面出来、落到 try 外面的异常与收尾连线的终点
715
+ if kinds & _LANDING and _inside(line[a], t.whole) and line[b] > 0 and not _inside(line[b], t.whole)}
716
+ swallow_to_end = bool(log_only_lines) and any(
717
+ "raise" in kinds and _inside(line[a], t.whole) and b in self.fell_off for (a, b), kinds in self.edges.items())
718
+ return _TryFacts(t, (catches | finals | (after if not t.catch_lines else set())) & self.landing,
719
+ (after if log_only_lines else set()) & self.landing, log_only_lines,
720
+ finals & self.landing, swallow_to_end)
721
+
722
+ def _approx_entry(self, a: str, b: str, evidence: frozenset[int]) -> bool:
723
+ """A → B 没有连线时,是否是某个 try 的异常与收尾入口近似。evidence:A 之后、B 之前原始行号里的证据——出现的
724
+ 只写日志的 except 头部行(异常被吞掉)和 try 体里的行所属的 try 的起始行(执行进入了 try 体)。"""
725
+ conds = self._entries.get((a, b))
726
+ if conds is None:
727
+ conds = self._entries[(a, b)] = self._entry_conditions(a, b)
728
+ return any((body is None or body in evidence) and (header is None or bool(header & evidence))
729
+ for body, header in conds)
730
+
731
+ def _entry_conditions(self, a: str, b: str) -> list[tuple[int | None, frozenset[int] | None]]:
732
+ """A → B 按入口近似认可的条件(见模块说明第 2 步):A 在 T 的 try 体里,或 A 不在、但这一步之间出现了 T 的
733
+ try 体里的行(要求 T 的起始行在证据里);落到只写日志的 except 之后还要求那个 except 的头部行。"""
734
+ ln, conds = self.line[a], []
735
+ for f in self._tries:
736
+ body = None if _inside(ln, f.ranges.body) else f.ranges.whole[0]
737
+ if b in f.from_body:
738
+ conds.append((body, None))
739
+ if b in f.swallowed:
740
+ conds.append((body, f.log_only_lines))
741
+ if b in f.from_others and any(_inside(ln, span) for span in f.ranges.others):
742
+ conds.append((None, None))
743
+ return conds
744
+
745
+ def _return_finally(self, r: str, e: str) -> Span | None:
746
+ """return 结局 r 正在经过的、包含 raise 结局 e 的 finally 体:所属 try 的 try 体 / except / else 包含 r。"""
747
+ lr, le = self.line[r], self.line[e]
748
+ for t in self.scope.tries:
749
+ if _inside(le, t.final) and (_inside(lr, t.body) or any(_inside(lr, span) for span in t.others)):
750
+ return t.final
751
+ return None
752
+
753
+ def _swallowed_in(self, span: Span, nid: str | None, evidence: frozenset[int]) -> bool:
754
+ """finally 体 span 里的 raise 之后,异常在 span 里被吞掉的证据:这一步走到的节点 nid 是 span 里(写成多行的)
755
+ except 的捕获节点,或者这一步之间(结局:最后的节点之后)出现了 span 里只写日志的 except 的标记、或写在一行的
756
+ except 吞掉了异常的标记(见 _one_line_swallowed)。写在一行的 except 的捕获节点本身不算:它的头部行事件不论
757
+ 是否匹配都会出现。"""
758
+ line = self.line[nid] if nid is not None else 0
759
+ if nid in self.catch_nodes and _inside(line, span) and line not in self.scope.one_line_excepts:
760
+ return True
761
+ return any(_inside(h, span) for h in evidence & (self.log_only_headers | self.scope.one_line_excepts))
762
+
763
+ def _one_line_swallowed(self, raw: list[int], i: int, h: int) -> bool:
764
+ """写在一行的 except(头部行 h,事件是 raw[i])是否吞掉了异常:之后跳过这一行自己、with 头部(离开时的
765
+ __exit__)和异常往外传时经过的 finally 体,第一行是 except 头部时没有(不匹配,或子句体又抛出了异常)。"""
766
+ skip = self._one_line_skip[h]
767
+ for ln in raw[i + 1:]:
768
+ m = self.statement(ln)
769
+ if m == h or ln in self.scope.withs or any(_inside(ln, span) for span in skip):
770
+ continue
771
+ return m not in self.except_headers
772
+ return True
773
+
774
+ def _approx_to_end(self, a: str, evidence: frozenset[int]) -> tuple[int, int, str] | None:
775
+ """以 return 离开、停在 A 时,吞掉的异常落到"执行到函数末尾"的入口近似(见模块说明第 3 步);不是时为 None。
776
+ evidence:A 之后原始行号里的证据(同 _approx_entry)。"""
777
+ la = self.line[a]
778
+ for f in self._tries:
779
+ if f.swallow_to_end and (_inside(la, f.ranges.body) or f.ranges.whole[0] in evidence) \
780
+ and f.log_only_lines & evidence:
781
+ return (la, 0, "entry")
782
+ return None
783
+
784
+ def _reachable(self, src: str) -> set[str]:
785
+ nexts: dict[str, list[str]] = {}
786
+ for a, b in self.edges:
787
+ nexts.setdefault(a, []).append(b)
788
+ seen, stack = {src}, [src]
789
+ while stack:
790
+ for dst in nexts.get(stack.pop(), ()):
791
+ if dst not in seen:
792
+ seen.add(dst)
793
+ stack.append(dst)
794
+ return seen
795
+
796
+ # ---------- 行 → 节点行 ----------
797
+
798
+ def node_lines(self, raw: list[int]) -> tuple[int, ...]:
799
+ """执行到的行 → 节点所在的语句起始行序列(见模块说明第 1 步),其中夹着证据标记(负数):只写日志的 except
800
+ 的标记、写在一行的 except 吞掉了异常的标记(负的头部行号),以及进入了 try 体的标记(负的 try 起始行号,
801
+ 两个节点行之间每个 try 至多一个)。
802
+ 连续的头部行事件作为一串,只在第一个上判断。进入 try 体的标记先挂起,下一项是别的节点行、except 标记或
803
+ 记录结束时才写出;同一节点行再次出现时照旧合并,挂起的标记丢掉(它们属于一个不存在的步子)。"""
804
+ return self.node_lines_at(raw)[0]
805
+
806
+ def node_lines_at(self, raw: list[int]) -> tuple[tuple[int, ...], tuple[int, ...]]:
807
+ """(node_lines(raw), 序列里每一项在 raw 里的位置):节点行是它(合并之前)第一次出现的位置,标记为 -1。"""
808
+ sc, by_line = self.scope, self.by_line
809
+ out: list[int] = []
810
+ at: list[int] = []
811
+ pending: list[int] = [] # 上一个节点行之后、还没写出的进入 try 体的标记
812
+ prev: int | None = None
813
+ leaving = entered = False
814
+ for i, ln in enumerate(raw):
815
+ p, prev = prev, ln
816
+ w = sc.withs.get(ln)
817
+ if w is not None:
818
+ if p is None or not w[0] <= p <= w[1]:
819
+ leaving = p is not None and w[2] <= p <= w[3] # 刚在 with 体里:这是离开时的 __exit__
820
+ if leaving:
821
+ continue
822
+ c = sc.clauses.get(ln)
823
+ if c is not None:
824
+ if p is None or not c[0] <= p <= c[1]:
825
+ j = i + 1
826
+ while j < len(raw) and c[0] <= raw[j] <= c[1]:
827
+ j += 1
828
+ entered = j < len(raw) and c[2] <= raw[j] <= c[3]
829
+ if not entered:
830
+ continue
831
+ m = sc.line_map.get(ln, ln)
832
+ one_line = m in sc.one_line_excepts and self._one_line_swallowed(raw, i, m) # 写在一行、吞掉了异常
833
+ if m in by_line:
834
+ if out and out[-1] == m: # 同一节点行再次出现、中间没有节点:合并(写在一行的 except 的标记留着)
835
+ pending[:] = [x for x in pending if -x in sc.one_line_excepts]
836
+ continue
837
+ out += pending
838
+ at += [-1] * len(pending)
839
+ pending.clear()
840
+ out.append(m)
841
+ at.append(i)
842
+ if one_line: # 写在一行、画了捕获节点的 except 吞掉了异常:标记挂在这一行之后
843
+ pending.append(-m)
844
+ continue
845
+ for t in self.try_bodies.get(ln, ()): # 不经过节点就进入了 try 体:作为异常从 try 体开头抛出的证据
846
+ if -t not in pending:
847
+ pending.append(-t)
848
+ if m not in self.log_only_headers or (m in sc.one_line_excepts and not one_line):
849
+ continue
850
+ m = -m # 进入了只写日志的 except:留一个标记,作为异常被吞掉的证据
851
+ out += pending
852
+ at += [-1] * len(pending)
853
+ pending.clear()
854
+ if not out or out[-1] != m:
855
+ out.append(m)
856
+ at.append(-1)
857
+ return tuple(out + pending), tuple(at + [-1] * len(pending))
858
+
859
+ # ---------- 走图 ----------
860
+
861
+ def walk(self, seq: tuple[int, ...], exit_kind: str, truncated: bool) -> _Walk:
862
+ """在所有走法(每行取一个前缀,可选行可以不走)里取不符最少、其次近似最少的一种(见模块说明第 2、3 步)。"""
863
+ start = _Trail(self.start, None, path=((self.start, -1), None))
864
+ states: dict[tuple, _Trail] = {_state(start): start}
865
+ for pos, ln in enumerate(seq):
866
+ if ln < 0: # 证据标记(只写日志的 except 头部行、进入了 try 体的 try 起始行)
867
+ marked = (replace(t, markers=t.markers | {-ln}) for t in states.values())
868
+ states = {_state(t): t for t in marked}
869
+ continue
870
+ nodes = self.by_line[ln]
871
+ options = [nodes[:j] for j in range(len(nodes), 0, -1)] + ([[]] if ln in self.optional else [])
872
+ nxt: dict[tuple, _Trail] = {}
873
+ for trail in states.values():
874
+ for opt in options:
875
+ t = self._advance(trail, opt, pos)
876
+ k = _state(t)
877
+ if k not in nxt or t.cost < nxt[k].cost:
878
+ nxt[k] = t
879
+ states = nxt
880
+ best: tuple[tuple, _Trail, tuple | None, bool, tuple | None] | None = None
881
+ no_lines = not any(ln > 0 for ln in seq)
882
+ for trail in states.values():
883
+ end_problem, uncaught, approx = (None, False, None) if truncated else self._outcome(trail, exit_kind, no_lines)
884
+ cost = (trail.cost[0] + (end_problem is not None), trail.cost[1] + (approx is not None))
885
+ if best is None or cost < best[0]:
886
+ best = (cost, trail, end_problem, uncaught, approx)
887
+ _, trail, end_problem, uncaught, approx = best
888
+ found = _unlink(trail.problems) + ((end_problem,) if end_problem is not None else ())
889
+ approxs = _unlink(trail.approximations) + ((approx,) if approx is not None else ())
890
+ path = _unlink(trail.path)
891
+ exit_node = "" if truncated else self._exit_node(trail, exit_kind, no_lines, end_problem, approx)
892
+ if exit_node in self.fell_off and path[-1][0] != exit_node:
893
+ path += ((exit_node, len(seq)),)
894
+ return _Walk(trail.steps + (approx is not None), trail.on_graph, trail.approx_in + (approx is not None),
895
+ uncaught, found, approxs, path, exit_node)
896
+
897
+ def _exit_node(self, t: _Trail, exit_kind: str, no_lines: bool, end_problem: tuple | None,
898
+ approx: tuple | None) -> str:
899
+ """选中的走法停在哪个节点(见 Walked.exit_node),和 _outcome 的判断一致。"""
900
+ if exit_kind == "raise":
901
+ return t.tail if t.tail is not None and t.tail in self.failed else self.uncaught_end
902
+ if end_problem is not None:
903
+ return t.node
904
+ if no_lines: # 只看结局:一个节点行都没走,就是执行到了函数末尾
905
+ return next((f for f in self.fell_off_order if (t.node, f) in self.edges),
906
+ self.fell_off_order[0] if self.fell_off_order else t.node)
907
+ if t.ret is not None and (t.wait is None or self._swallowed_in(t.wait, None, t.markers)):
908
+ return t.ret
909
+ if approx is not None: # 吞掉的异常落到函数末尾
910
+ return self.fell_off_order[0]
911
+ return next((f for f in self.fell_off_order if (t.node, f) in self.edges), t.node) # 沿连线到函数末尾
912
+
913
+ def _advance(self, t: _Trail, nodes: list[str], pos: int) -> _Trail:
914
+ """沿 nodes 走一段。缺连线的一步只看它自己的起点和终点:入口近似,或不符。"""
915
+ cur, tail, ret, wait, evidence = t.node, t.tail, t.ret, t.wait, t.markers # 证据只属于进入这一行的第一步
916
+ mism, approx = t.cost
917
+ steps, on_graph, ain = t.steps, t.on_graph, t.approx_in
918
+ problems, approxs, path = t.problems, t.approximations, t.path
919
+ for nid in nodes:
920
+ path = ((nid, pos), path)
921
+ if self.edges.get((cur, nid)):
922
+ if nid not in self.ends: # 沿连线到达结局算在结局里,不计步数
923
+ steps += 1
924
+ on_graph += 1
925
+ else:
926
+ steps += 1
927
+ if self._approx_entry(cur, nid, evidence):
928
+ ain += 1
929
+ approx += 1
930
+ approxs = ((self.line[cur], self.line[nid], "entry"), approxs)
931
+ else:
932
+ mism += 1
933
+ problems = (("edge", self.line[cur], self.line[nid],
934
+ f"{self.title[cur]} → {self.title[nid]}"), problems)
935
+ if nid in self.ends:
936
+ tail = nid
937
+ elif nid not in self.finally_nodes:
938
+ tail = None
939
+ if wait is not None: # 经过了 finally 体 wait 里的 raise 结局:异常要在 wait 里被吞掉,return 才继续
940
+ if self._swallowed_in(wait, nid, evidence):
941
+ wait = None
942
+ elif not _inside(self.line[nid], wait): # 异常还没被吞掉就离开了 wait:return 已被取消
943
+ ret = wait = None
944
+ if nid in self.ends and nid not in self.raise_ends:
945
+ ret, wait = nid, None
946
+ elif nid not in self.finally_nodes:
947
+ ret = wait = None
948
+ elif ret is not None and nid in self.raise_ends:
949
+ wait = self._return_finally(ret, nid)
950
+ if wait is None:
951
+ ret = None
952
+ cur, evidence = nid, frozenset()
953
+ markers = evidence if not nodes else frozenset() # 整行不走时证据留给下一步
954
+ return _Trail(cur, tail, markers, (mism, approx), steps, on_graph, ain, problems, approxs, ret, wait, path)
955
+
956
+ def _outcome(self, t: _Trail, exit_kind: str, no_lines: bool) -> tuple[tuple | None, bool, tuple | None]:
957
+ """(结局不符, 是否未捕获异常退出, 吞掉的异常落到函数末尾的近似)。"""
958
+ if exit_kind == "raise":
959
+ return None, not (t.tail is not None and t.tail in self.failed), None
960
+ # 以 return 离开:只认 return 语句的结局之后只走 finally;raise 语句的结局说明那个异常被吞掉了,不说明函数在这里结束
961
+ ret = t.ret is not None and (t.wait is None or self._swallowed_in(t.wait, None, t.markers))
962
+ ok = self.start_reaches_end if no_lines else (ret or t.node in self.into_fell_off)
963
+ if ok:
964
+ return None, False, None
965
+ approx = None if no_lines else self._approx_to_end(t.node, t.markers)
966
+ if approx is not None:
967
+ return None, False, approx
968
+ return ("end", self.line[t.node], 0, f"以 return 离开,但停在「{self.title[t.node]}」"), False, None