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/progress.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"""运行中的进度:测试跑着的时候,读记录插件(trace.py)正在写的记录文件,算出到现在为止跑完了几个测试、哪些正在跑、
|
|
2
|
+
最近跑完的几个,以及图里每个函数执行了几次、执行过哪些行。平台在测试命令跑着的时候用它(server 的 live.py);只用
|
|
3
|
+
标准库,读文件、不执行任何东西。
|
|
4
|
+
|
|
5
|
+
TraceProgress(path).poll():每次只读上次之后新追加的字节(一次最多 budget 个,积压很多时分几次读完),只处理完整的行
|
|
6
|
+
(最后半行留到下次)。容忍:文件还不存在(什么都没有)、后来被删掉(留着读到的)、坏行(不是 JSON、不是对象、字段
|
|
7
|
+
不对:跳过——读的是正在写的文件,不报错)、文件被换掉(设备号 / inode 变了)或截短(比读到的位置短):从头再读。
|
|
8
|
+
一行长得没有尽头(超过 max_line 个字节还没有换行)时丢掉它,接着找下一个换行。
|
|
9
|
+
|
|
10
|
+
认的行(字段见 trace.py 的说明;别的行——版本头、插件错误——不看):
|
|
11
|
+
- {"collected": N}:收集到的用例数;pytest-xdist 每个工作进程一行,取最大的。没有时 None;
|
|
12
|
+
- {"start": 测试 id}:开始跑一个测试(参数化的几个用例 id 相同:每个 id 一个计数,开始加一、结束减一,减到 0 不算在跑);
|
|
13
|
+
- 测试结果行 {"test", "outcome", "seconds", "n"}:done 加 n,passed / failed / skipped / errors(outcome error)各加 n,
|
|
14
|
+
这个 id 的计数减 n;最近跑完的 RECENT 个 {test, outcome, seconds},新的在前;
|
|
15
|
+
- 执行记录 {"fn", "lines", "n"}:这个函数执行了几次(n 相加)、执行过的行号(lines 的并集)。给了 functions(图里的
|
|
16
|
+
函数 key)时只留其中的。
|
|
17
|
+
|
|
18
|
+
只留标识(测试 id、函数 key)、计数、行号、秒数、结果种类;异常类型名、调用、耗时、别的字段都不留。内存跟着图走
|
|
19
|
+
(每个函数一个行号集合,执行再多次也不变大),不跟着记录文件的大小走。不是线程安全的:调用的一方加锁。
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import json
|
|
25
|
+
import math
|
|
26
|
+
import os
|
|
27
|
+
from collections import deque
|
|
28
|
+
from collections.abc import Container
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
|
|
31
|
+
RECENT = 8 # 最近跑完的测试留几个
|
|
32
|
+
BUDGET = 16 << 20 # 一次 poll 最多读多少字节
|
|
33
|
+
MAX_LINE = 64 << 20 # 一行最长多少字节(再长就丢掉)
|
|
34
|
+
_CHUNK = 1 << 20
|
|
35
|
+
_OUTCOMES = {"passed": "passed", "failed": "failed", "skipped": "skipped", "error": "errors"}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class TraceProgress:
|
|
39
|
+
"""一个记录文件的进度。poll() 读新追加的部分,返回到现在为止的进度(见模块说明)。"""
|
|
40
|
+
|
|
41
|
+
def __init__(self, path: str | os.PathLike, *, functions: Container[str] | None = None, budget: int = BUDGET,
|
|
42
|
+
max_line: int = MAX_LINE) -> None:
|
|
43
|
+
self._path = Path(path)
|
|
44
|
+
self._functions = functions
|
|
45
|
+
self._budget = budget
|
|
46
|
+
self._max_line = max_line
|
|
47
|
+
self._start_over()
|
|
48
|
+
|
|
49
|
+
def _start_over(self) -> None:
|
|
50
|
+
self._ident: tuple[int, int] | None = None # 正在读的文件(设备号,inode)
|
|
51
|
+
self._offset = 0 # 读到了第几个字节
|
|
52
|
+
self._rest = b"" # 还没遇到换行的半行
|
|
53
|
+
self._skipping = False # 正在丢一行太长的
|
|
54
|
+
self._collected: int | None = None
|
|
55
|
+
self._counts = dict.fromkeys(("done", "passed", "failed", "skipped", "errors"), 0)
|
|
56
|
+
self._running: dict[str, int] = {} # 测试 id -> 开始了还没结束的个数(按开始的先后)
|
|
57
|
+
self._recent: deque[dict] = deque(maxlen=RECENT) # 新的在左边
|
|
58
|
+
self._executions: dict[str, int] = {}
|
|
59
|
+
self._lines: dict[str, set[int]] = {}
|
|
60
|
+
self._frozen: dict[str, frozenset[int]] = {} # 上次给出去的行号集合(没变的不重新复制)
|
|
61
|
+
self._changed: set[str] = set()
|
|
62
|
+
|
|
63
|
+
def poll(self) -> dict:
|
|
64
|
+
"""读新追加的部分,返回 {"collected", "done", "passed", "failed", "skipped", "errors", "running": [测试 id,
|
|
65
|
+
按开始的先后], "recent": [{test, outcome, seconds},新的在前], "functions": {函数 key: {"executions",
|
|
66
|
+
"lines": frozenset}}}。"""
|
|
67
|
+
self._read()
|
|
68
|
+
for key in self._changed:
|
|
69
|
+
self._frozen[key] = frozenset(self._lines[key])
|
|
70
|
+
self._changed.clear()
|
|
71
|
+
return {"collected": self._collected, **self._counts, "running": list(self._running),
|
|
72
|
+
"recent": [dict(r) for r in self._recent],
|
|
73
|
+
"functions": {k: {"executions": n, "lines": self._frozen[k]} for k, n in self._executions.items()}}
|
|
74
|
+
|
|
75
|
+
# ---- 读 ----
|
|
76
|
+
|
|
77
|
+
def _read(self) -> None:
|
|
78
|
+
try:
|
|
79
|
+
f = open(self._path, "rb") # noqa: SIM115 —— 下面的 with 关
|
|
80
|
+
except OSError: # 还没有,或者已经删掉了:留着读到的
|
|
81
|
+
return
|
|
82
|
+
with f:
|
|
83
|
+
st = os.fstat(f.fileno())
|
|
84
|
+
ident = (st.st_dev, st.st_ino)
|
|
85
|
+
if self._ident is not None and (ident != self._ident or st.st_size < self._offset):
|
|
86
|
+
self._start_over() # 换了一个文件,或者截短了
|
|
87
|
+
self._ident = ident
|
|
88
|
+
f.seek(self._offset)
|
|
89
|
+
left = self._budget
|
|
90
|
+
while left > 0:
|
|
91
|
+
chunk = f.read(min(_CHUNK, left))
|
|
92
|
+
if not chunk:
|
|
93
|
+
break
|
|
94
|
+
left -= len(chunk)
|
|
95
|
+
self._offset += len(chunk)
|
|
96
|
+
self._feed(chunk)
|
|
97
|
+
|
|
98
|
+
def _feed(self, chunk: bytes) -> None:
|
|
99
|
+
end = chunk.rfind(b"\n")
|
|
100
|
+
if end < 0:
|
|
101
|
+
self._keep(chunk)
|
|
102
|
+
return
|
|
103
|
+
data = self._rest + chunk[:end] if self._rest else chunk[:end]
|
|
104
|
+
rows = data.split(b"\n")
|
|
105
|
+
if self._skipping: # 第一行是那行太长的结尾
|
|
106
|
+
rows = rows[1:]
|
|
107
|
+
self._skipping = False
|
|
108
|
+
self._rest = b""
|
|
109
|
+
for raw in rows:
|
|
110
|
+
self._take(raw)
|
|
111
|
+
self._keep(chunk[end + 1:])
|
|
112
|
+
|
|
113
|
+
def _keep(self, tail: bytes) -> None:
|
|
114
|
+
"""还没遇到换行的部分:留到下次;太长了就丢掉,直到下一个换行。"""
|
|
115
|
+
if self._skipping or not tail:
|
|
116
|
+
return
|
|
117
|
+
if len(self._rest) + len(tail) > self._max_line:
|
|
118
|
+
self._rest = b""
|
|
119
|
+
self._skipping = True
|
|
120
|
+
else:
|
|
121
|
+
self._rest += tail
|
|
122
|
+
|
|
123
|
+
def _take(self, raw: bytes) -> None:
|
|
124
|
+
if not raw.strip():
|
|
125
|
+
return
|
|
126
|
+
try:
|
|
127
|
+
rec = json.loads(raw)
|
|
128
|
+
except (ValueError, RecursionError): # 不是 JSON(UnicodeDecodeError 也是 ValueError)、嵌套太深
|
|
129
|
+
return
|
|
130
|
+
if not isinstance(rec, dict):
|
|
131
|
+
return
|
|
132
|
+
if "fn" in rec:
|
|
133
|
+
self._execution(rec)
|
|
134
|
+
elif "outcome" in rec:
|
|
135
|
+
self._result(rec)
|
|
136
|
+
elif "start" in rec:
|
|
137
|
+
test = rec["start"]
|
|
138
|
+
if isinstance(test, str):
|
|
139
|
+
self._running[test] = self._running.get(test, 0) + 1
|
|
140
|
+
elif "collected" in rec:
|
|
141
|
+
n = rec["collected"]
|
|
142
|
+
if type(n) is int and n >= 0 and (self._collected is None or n > self._collected):
|
|
143
|
+
self._collected = n
|
|
144
|
+
|
|
145
|
+
def _execution(self, rec: dict) -> None:
|
|
146
|
+
key, lines, n = rec.get("fn"), rec.get("lines"), rec.get("n", 1)
|
|
147
|
+
if not (isinstance(key, str) and isinstance(lines, list) and type(n) is int and n > 0
|
|
148
|
+
and all(type(x) is int for x in lines)):
|
|
149
|
+
return
|
|
150
|
+
if self._functions is not None and key not in self._functions:
|
|
151
|
+
return
|
|
152
|
+
self._executions[key] = self._executions.get(key, 0) + n
|
|
153
|
+
seen = self._lines.get(key)
|
|
154
|
+
if seen is None:
|
|
155
|
+
seen = self._lines[key] = set()
|
|
156
|
+
if not seen.issuperset(lines):
|
|
157
|
+
seen.update(lines)
|
|
158
|
+
self._changed.add(key)
|
|
159
|
+
elif key not in self._frozen:
|
|
160
|
+
self._changed.add(key)
|
|
161
|
+
|
|
162
|
+
def _result(self, rec: dict) -> None:
|
|
163
|
+
test, outcome, seconds, n = rec.get("test"), rec.get("outcome"), rec.get("seconds"), rec.get("n", 1)
|
|
164
|
+
if not (isinstance(test, str) and outcome in _OUTCOMES and type(seconds) in (int, float)
|
|
165
|
+
and math.isfinite(seconds) and seconds >= 0 and type(n) is int and n > 0):
|
|
166
|
+
return
|
|
167
|
+
self._counts["done"] += n
|
|
168
|
+
self._counts[_OUTCOMES[outcome]] += n
|
|
169
|
+
left = self._running.get(test, 0) - n
|
|
170
|
+
if left > 0:
|
|
171
|
+
self._running[test] = left
|
|
172
|
+
else:
|
|
173
|
+
self._running.pop(test, None)
|
|
174
|
+
self._recent.appendleft({"test": test, "outcome": outcome, "seconds": seconds})
|
pystepmap/query.py
ADDED
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
"""读图的查询:功能线涉及哪些函数、函数和文件在哪些功能线上;按文件:行或函数名反查节点,函数图里到某个节点的路径,
|
|
2
|
+
功能线里从根任务到某个函数的调用链,找结局。都是只读的函数,除了 find_by_location 为认出装饰器行、match 守卫行会读一次
|
|
3
|
+
源文件(见 _source_lines),都只读图。"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import ast
|
|
8
|
+
import hashlib
|
|
9
|
+
import heapq
|
|
10
|
+
import os
|
|
11
|
+
import posixpath
|
|
12
|
+
import re
|
|
13
|
+
import stat
|
|
14
|
+
from collections import deque
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Literal
|
|
18
|
+
|
|
19
|
+
from .model import Edge, FlowLine, FunctionGraph, LineTask, Node, ProjectGraph
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def line_functions(graph: ProjectGraph, line: FlowLine) -> list[str]:
|
|
23
|
+
"""这条线涉及的函数 key:派发树上的每个任务(先序),每个任务之后紧跟从它出发沿 call_targets 能到的所有函数
|
|
24
|
+
(深度优先、按源码顺序);按发现顺序,不重复。环(互相调用、任务派发自己)各只走一次;不在图里的 key 跳过。"""
|
|
25
|
+
out: list[str] = []
|
|
26
|
+
seen: set[str] = set()
|
|
27
|
+
tasks = [line.root]
|
|
28
|
+
while tasks:
|
|
29
|
+
task = tasks.pop()
|
|
30
|
+
stack = [task.function]
|
|
31
|
+
while stack:
|
|
32
|
+
key = stack.pop()
|
|
33
|
+
if key in seen or key not in graph.functions:
|
|
34
|
+
continue
|
|
35
|
+
seen.add(key)
|
|
36
|
+
out.append(key)
|
|
37
|
+
stack.extend(reversed(graph.functions[key].call_targets))
|
|
38
|
+
tasks.extend(reversed(task.children))
|
|
39
|
+
return out
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def lines_of_functions(graph: ProjectGraph) -> dict[str, list[str]]:
|
|
43
|
+
"""函数 key → 涉及它的功能线 id,按 graph.lines 的顺序;没有线涉及的函数不在里面。"""
|
|
44
|
+
out: dict[str, list[str]] = {}
|
|
45
|
+
for line in graph.lines:
|
|
46
|
+
for key in line_functions(graph, line):
|
|
47
|
+
out.setdefault(key, []).append(line.id)
|
|
48
|
+
return out
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def file_lines(graph: ProjectGraph) -> dict[str, list[str]]:
|
|
52
|
+
"""相对路径 → 涉及这个文件里任一函数的功能线 sid,按 graph.lines 的顺序;按路径排序,没有线涉及的文件不在里面。"""
|
|
53
|
+
out: dict[str, list[str]] = {}
|
|
54
|
+
for line in graph.lines:
|
|
55
|
+
for file in dict.fromkeys(graph.functions[key].file for key in line_functions(graph, line)):
|
|
56
|
+
out.setdefault(file, []).append(line.sid)
|
|
57
|
+
return dict(sorted(out.items()))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
# ---------- 反查节点 ----------
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
@dataclass(frozen=True)
|
|
64
|
+
class NodeHit:
|
|
65
|
+
function: str # 函数 key
|
|
66
|
+
node: str # 节点 id
|
|
67
|
+
how: Literal["covers", "nearest", "definition", "call_site"]
|
|
68
|
+
lines: tuple[str, ...] # 涉及这个函数的功能线 id,按 graph.lines 的顺序
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _relative(graph: ProjectGraph, file: str) -> str | None:
|
|
72
|
+
"""相对 root 的路径("/" 分隔、规范化);绝对路径要在 root 下(经过指向 root 的符号链接给出的也认:比较所在目录的
|
|
73
|
+
真实路径,文件本身不解析)。指到 root 之外的(含 "..")为 None。"""
|
|
74
|
+
path = file.replace("\\", "/")
|
|
75
|
+
root = graph.root.replace("\\", "/").rstrip("/")
|
|
76
|
+
if path.startswith("/"):
|
|
77
|
+
path = posixpath.normpath(path)
|
|
78
|
+
if path.startswith(root + "/"):
|
|
79
|
+
path = path[len(root) + 1:]
|
|
80
|
+
else:
|
|
81
|
+
real_dir, real_root = os.path.realpath(posixpath.dirname(path)), os.path.realpath(root)
|
|
82
|
+
if real_dir != real_root and not real_dir.startswith(real_root.rstrip(os.sep) + os.sep):
|
|
83
|
+
return None
|
|
84
|
+
path = posixpath.join(os.path.relpath(real_dir, real_root).replace(os.sep, "/"), posixpath.basename(path))
|
|
85
|
+
path = posixpath.normpath(path)
|
|
86
|
+
if path in (".", "", "..") or path.startswith(("../", "/")):
|
|
87
|
+
return None
|
|
88
|
+
return path
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
MAX_SOURCE_BYTES = 2 * 1024 * 1024 # find_by_location 读源文件的上限,超过的不读
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _read_analysed(graph: ProjectGraph, file: str) -> bytes | None:
|
|
95
|
+
"""读图里记了指纹的这个文件:解析后的真实路径要仍在 root 里;打开一次(不跟随符号链接、不因 FIFO 阻塞),按打开的
|
|
96
|
+
描述符确认是普通文件、不超过 MAX_SOURCE_BYTES 再读;内容的 sha256 要和图里记的相同(改过的文件行号对不上图)。
|
|
97
|
+
任何一条不满足、读不了都为 None。"""
|
|
98
|
+
recorded = graph.file_hashes.get(file)
|
|
99
|
+
if recorded is None:
|
|
100
|
+
return None
|
|
101
|
+
try:
|
|
102
|
+
root = Path(graph.root).resolve(strict=True)
|
|
103
|
+
path = (root / file).resolve(strict=True)
|
|
104
|
+
path.relative_to(root)
|
|
105
|
+
fd = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0))
|
|
106
|
+
except (OSError, ValueError, RuntimeError):
|
|
107
|
+
return None
|
|
108
|
+
try:
|
|
109
|
+
info = os.fstat(fd)
|
|
110
|
+
if not stat.S_ISREG(info.st_mode) or info.st_size > MAX_SOURCE_BYTES:
|
|
111
|
+
return None
|
|
112
|
+
with os.fdopen(fd, "rb", closefd=False) as f:
|
|
113
|
+
raw = f.read(MAX_SOURCE_BYTES + 1)
|
|
114
|
+
except OSError:
|
|
115
|
+
return None
|
|
116
|
+
finally:
|
|
117
|
+
os.close(fd)
|
|
118
|
+
if len(raw) > MAX_SOURCE_BYTES or hashlib.sha256(raw).hexdigest() != recorded:
|
|
119
|
+
return None
|
|
120
|
+
return raw
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _source_lines(graph: ProjectGraph, file: str) -> tuple[dict[int, int], list[tuple[int, int, int]]]:
|
|
124
|
+
"""从源文件补图里没有的两样行号:(def 行 → 第一个装饰器所在行, [(match 行, 守卫起始行, 守卫结束行)])。
|
|
125
|
+
文件按 _read_analysed 的条件读;读不了、解析不了都当作没有(({}, []))。不执行任何代码。"""
|
|
126
|
+
raw = _read_analysed(graph, file)
|
|
127
|
+
if raw is None:
|
|
128
|
+
return {}, []
|
|
129
|
+
try:
|
|
130
|
+
tree = ast.parse(raw)
|
|
131
|
+
except (SyntaxError, ValueError, RecursionError):
|
|
132
|
+
return {}, []
|
|
133
|
+
decorated: dict[int, int] = {}
|
|
134
|
+
guards: list[tuple[int, int, int]] = []
|
|
135
|
+
for node in ast.walk(tree):
|
|
136
|
+
if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef) and node.decorator_list:
|
|
137
|
+
decorated[node.lineno] = min(d.lineno for d in node.decorator_list)
|
|
138
|
+
elif isinstance(node, ast.Match):
|
|
139
|
+
guards += [(node.lineno, c.guard.lineno, c.guard.end_lineno or c.guard.lineno)
|
|
140
|
+
for c in node.cases if c.guard is not None]
|
|
141
|
+
return decorated, guards
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def find_by_location(graph: ProjectGraph, file: str, line: int) -> list[NodeHit]:
|
|
145
|
+
"""文件 file(相对 root,或以 root 开头的绝对路径)第 line 行对应的节点。找包住这一行的最内层函数(从 def 行——
|
|
146
|
+
含装饰器行——到 end_line):
|
|
147
|
+
- 行落在某些节点的 [line, end_line] 里 → 这些节点,how="covers";match 守卫所在的行算 match 判断节点的(守卫里的
|
|
148
|
+
调用记在判断节点上);装饰器行算开始节点的;
|
|
149
|
+
- 没有节点包住这一行 → 行号不大于它的最近的节点(同一行有几个时都给),how="nearest"(赋值、日志等不出节点的语句);
|
|
150
|
+
- 行不在任何函数里、文件不在图里、路径指到 root 之外 → 空表。
|
|
151
|
+
装饰器行、守卫行要读源文件才知道(见 _source_lines);文件在分析之后改过时不读,只按图里的行号。已经有节点包住这一行、
|
|
152
|
+
这一行又不可能是守卫行(函数里没有在它之前开始的 match)时不读:节点行不会是装饰器行。"""
|
|
153
|
+
rel = _relative(graph, file)
|
|
154
|
+
if rel is None:
|
|
155
|
+
return []
|
|
156
|
+
fns = [fg for fg in graph.functions.values() if fg.file == rel]
|
|
157
|
+
if not fns:
|
|
158
|
+
return []
|
|
159
|
+
plain = [fg for fg in fns if fg.line <= line <= fg.end_line]
|
|
160
|
+
if plain:
|
|
161
|
+
inner = max(plain, key=lambda f: (f.line, f.key))
|
|
162
|
+
covers = [n for n in inner.nodes if n.line and n.line <= line <= n.end_line]
|
|
163
|
+
guard_possible = any(n.type == "cond" and n.subtitle.startswith("match ") and n.line < line
|
|
164
|
+
for n in inner.nodes)
|
|
165
|
+
if covers and not guard_possible:
|
|
166
|
+
lines = tuple(lines_of_functions(graph).get(inner.key, []))
|
|
167
|
+
return [NodeHit(inner.key, n.id, "covers", lines) for n in covers]
|
|
168
|
+
decorated, guards = _source_lines(graph, rel)
|
|
169
|
+
around = [fg for fg in fns if decorated.get(fg.line, fg.line) <= line <= fg.end_line]
|
|
170
|
+
if not around:
|
|
171
|
+
return []
|
|
172
|
+
fg = max(around, key=lambda f: (f.line, f.key)) # 最内层:定义得最晚的那个(范围是嵌套的)
|
|
173
|
+
lines = tuple(lines_of_functions(graph).get(fg.key, []))
|
|
174
|
+
covers = [n for n in fg.nodes if n.line and n.line <= line <= n.end_line]
|
|
175
|
+
if line < fg.line: # 装饰器行
|
|
176
|
+
covers = [n for n in fg.nodes if n.type == "start"]
|
|
177
|
+
matches = {m for m, start, end in guards if start <= line <= end}
|
|
178
|
+
covers += [n for n in fg.nodes if n.type == "cond" and n.line in matches and n.subtitle.startswith("match ")
|
|
179
|
+
and n not in covers]
|
|
180
|
+
if covers:
|
|
181
|
+
return [NodeHit(fg.key, n.id, "covers", lines) for n in covers]
|
|
182
|
+
before = [n for n in fg.nodes if n.line and n.line <= line]
|
|
183
|
+
if not before:
|
|
184
|
+
return []
|
|
185
|
+
top = max(n.line for n in before)
|
|
186
|
+
return [NodeHit(fg.key, n.id, "nearest", lines) for n in before if n.line == top]
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _named(fg: FunctionGraph, name: str) -> bool:
|
|
190
|
+
return name in (fg.key, fg.sid, fg.qualname, fg.qualname.rsplit(".", 1)[-1])
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def find_by_function(graph: ProjectGraph, name: str) -> list[NodeHit]:
|
|
194
|
+
"""name 是函数 sid、key、限定名(Svc.run)或最后一段名字(run)。每个匹配的函数(按 key 的顺序):它的开始节点
|
|
195
|
+
how="definition",接着是别的函数里 calls[].target 是它的节点 how="call_site"(含派发;按调用方 key、节点顺序)。"""
|
|
196
|
+
by_fn = lines_of_functions(graph)
|
|
197
|
+
out: list[NodeHit] = []
|
|
198
|
+
for key, fg in graph.functions.items():
|
|
199
|
+
if not _named(fg, name):
|
|
200
|
+
continue
|
|
201
|
+
start = next((n for n in fg.nodes if n.type == "start"), None)
|
|
202
|
+
if start is not None:
|
|
203
|
+
out.append(NodeHit(key, start.id, "definition", tuple(by_fn.get(key, []))))
|
|
204
|
+
for caller_key, caller in graph.functions.items():
|
|
205
|
+
if caller_key == key:
|
|
206
|
+
continue
|
|
207
|
+
for n in caller.nodes:
|
|
208
|
+
if any(ref.target == key for ref in n.calls):
|
|
209
|
+
out.append(NodeHit(caller_key, n.id, "call_site", tuple(by_fn.get(caller_key, []))))
|
|
210
|
+
return out
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
# ---------- 路径 ----------
|
|
214
|
+
|
|
215
|
+
MAX_PATH_WORK = 200_000 # paths_to 最多展开这么多条部分路径,超出时按已找到的截断
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
@dataclass(frozen=True)
|
|
219
|
+
class PathStep:
|
|
220
|
+
node: str
|
|
221
|
+
kind: str = "" # 从这个节点出去走的那条连线;终点那一步三项为空
|
|
222
|
+
label: str = ""
|
|
223
|
+
branch: str = ""
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def paths_to(graph: ProjectGraph, function: str, node: str, *, limit: int = 20) -> tuple[list[list[PathStep]], bool]:
|
|
227
|
+
"""函数图里从开始节点到 node 的路径(到 node 即止,不再往后走):每条连线在一条路径里至多走一次(所以循环至多走
|
|
228
|
+
一圈);短的在前(一样长的先后不作保证,通常按连线在图里的顺序)。超过 limit 条时只给前 limit 条,第二项为 True;展开的部分路径超过
|
|
229
|
+
MAX_PATH_WORK 条时同样截断。函数、节点不存在或走不到时为 ([], False);limit 不是正数时抛 ValueError。
|
|
230
|
+
一样长的部分路径先展开走得深的(往终点钻),平衡的分支再多也很快找到前几条。"""
|
|
231
|
+
if limit <= 0:
|
|
232
|
+
raise ValueError(f"limit 必须是正整数:{limit}")
|
|
233
|
+
fg = graph.functions.get(function)
|
|
234
|
+
if fg is None or all(n.id != node for n in fg.nodes):
|
|
235
|
+
return [], False
|
|
236
|
+
start = next((n.id for n in fg.nodes if n.type == "start"), None)
|
|
237
|
+
if start is None:
|
|
238
|
+
return [], False
|
|
239
|
+
outs: dict[str, list[int]] = {}
|
|
240
|
+
ins: dict[str, list[str]] = {}
|
|
241
|
+
for i, e in enumerate(fg.edges):
|
|
242
|
+
outs.setdefault(e.src, []).append(i)
|
|
243
|
+
ins.setdefault(e.dst, []).append(e.src)
|
|
244
|
+
dist = {node: 0} # 到 node 的最少连线数:既用来剪掉走不到 node 的,也是 A* 的下界
|
|
245
|
+
queue = deque([node])
|
|
246
|
+
while queue:
|
|
247
|
+
cur = queue.popleft()
|
|
248
|
+
for src in ins.get(cur, []):
|
|
249
|
+
if src not in dist:
|
|
250
|
+
dist[src] = dist[cur] + 1
|
|
251
|
+
queue.append(src)
|
|
252
|
+
if start not in dist:
|
|
253
|
+
return [], False
|
|
254
|
+
found: list[list[PathStep]] = []
|
|
255
|
+
seq = 0
|
|
256
|
+
heap: list[tuple[int, int, int, str, tuple[int, ...]]] = [(dist[start], 0, seq, start, ())]
|
|
257
|
+
work = 0
|
|
258
|
+
while heap:
|
|
259
|
+
_, _, _, cur, used = heapq.heappop(heap)
|
|
260
|
+
if cur == node:
|
|
261
|
+
if len(found) == limit:
|
|
262
|
+
return found, True
|
|
263
|
+
found.append(_steps(fg.edges, used, node))
|
|
264
|
+
continue
|
|
265
|
+
work += 1
|
|
266
|
+
if work > MAX_PATH_WORK:
|
|
267
|
+
return found, True
|
|
268
|
+
for i in outs.get(cur, []):
|
|
269
|
+
dst = fg.edges[i].dst
|
|
270
|
+
if i in used or dst not in dist:
|
|
271
|
+
continue
|
|
272
|
+
seq += 1
|
|
273
|
+
heapq.heappush(heap, (len(used) + 1 + dist[dst], -(len(used) + 1), seq, dst, (*used, i)))
|
|
274
|
+
return found, False
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _steps(edges: list[Edge], used: tuple[int, ...], last: str) -> list[PathStep]:
|
|
278
|
+
return [PathStep(edges[i].src, edges[i].kind, edges[i].label, edges[i].branch) for i in used] + [PathStep(last)]
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
# ---------- 功能线里的调用链 ----------
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
@dataclass(frozen=True)
|
|
285
|
+
class ChainLink:
|
|
286
|
+
function: str # 函数 key
|
|
287
|
+
node: str # 在这个节点上派发 / 调用了下一环
|
|
288
|
+
how: Literal["dispatch", "call"]
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _tree_tasks(task: LineTask) -> set[str]:
|
|
292
|
+
out, stack = set(), [task]
|
|
293
|
+
while stack:
|
|
294
|
+
t = stack.pop()
|
|
295
|
+
out.add(t.function)
|
|
296
|
+
stack.extend(t.children)
|
|
297
|
+
return out
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def entry_chain(graph: ProjectGraph, line: FlowLine, function: str) -> list[ChainLink] | None:
|
|
301
|
+
"""从功能线的根任务到 function 最短的一条链(按环数;一样短的按函数发现顺序、节点顺序):每一环是"在这个函数的这个
|
|
302
|
+
节点上派发 / 调用了下一环"。派发只走到这条线派发树上的任务,调用只走到这条线涉及的函数(line_functions)。
|
|
303
|
+
调用不在任何节点上的(折叠掉的分支、构造对象调用的 __init__ 等,只在 call_targets 里)记在开始节点上。
|
|
304
|
+
function 就是根任务时为 [];这条线不涉及它时为 None。"""
|
|
305
|
+
involved = set(line_functions(graph, line))
|
|
306
|
+
if function not in involved:
|
|
307
|
+
return None
|
|
308
|
+
root = line.root.function
|
|
309
|
+
if function == root:
|
|
310
|
+
return []
|
|
311
|
+
tasks = _tree_tasks(line.root)
|
|
312
|
+
prev: dict[str, tuple[str, str, Literal["dispatch", "call"]] | None] = {root: None}
|
|
313
|
+
queue = deque([root])
|
|
314
|
+
while queue:
|
|
315
|
+
key = queue.popleft()
|
|
316
|
+
fg = graph.functions[key]
|
|
317
|
+
hops: list[tuple[str, str, Literal["dispatch", "call"]]] = []
|
|
318
|
+
for n in fg.nodes:
|
|
319
|
+
for ref in n.calls:
|
|
320
|
+
if ref.target is not None and (not ref.is_dispatch or ref.target in tasks):
|
|
321
|
+
hops.append((ref.target, n.id, "dispatch" if ref.is_dispatch else "call"))
|
|
322
|
+
start = next((n.id for n in fg.nodes if n.type == "start"), "")
|
|
323
|
+
hops += [(t, start, "call") for t in fg.call_targets]
|
|
324
|
+
for target, node, how in hops:
|
|
325
|
+
if target in prev or target not in involved:
|
|
326
|
+
continue
|
|
327
|
+
prev[target] = (key, node, how)
|
|
328
|
+
if target == function:
|
|
329
|
+
chain: list[ChainLink] = []
|
|
330
|
+
cur = target
|
|
331
|
+
while (step := prev[cur]) is not None:
|
|
332
|
+
chain.append(ChainLink(*step))
|
|
333
|
+
cur = step[0]
|
|
334
|
+
return chain[::-1]
|
|
335
|
+
queue.append(target)
|
|
336
|
+
return None # line_functions 能到的这里一定能到;防御
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
_RAISED = re.compile(r"抛出 ([A-Za-z_][\w.]*)")
|
|
340
|
+
_CATCH_ALL = {"Exception", "BaseException", "任意异常"}
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def caught_on_chain(graph: ProjectGraph, chain: list[ChainLink], end: Node) -> tuple[str, Node] | None:
|
|
344
|
+
"""end 是被调函数里的一个 `raise X(...)` 结局、chain 是从功能线入口到那个函数的调用链时:这个异常在链上哪里被接住
|
|
345
|
+
——(函数 key, 捕获节点);没被接住(或者看不出来)时 None。从离它最近的调用处往上找:调用处的节点有"出错"的连线
|
|
346
|
+
通到捕获节点,捕获的类型里写着这个异常的类名,或者是 Exception / BaseException / 不写类型。被接住的异常不会让
|
|
347
|
+
功能线以它结束(接住它的函数接着往下走),所以不是这条线的结局。派发出去的任务里抛的异常传不回派发它的函数,
|
|
348
|
+
找到派发那一环为止。只按类名的字面比:父类捕获子类(except LookupError 接 KeyError)看不出来,算没接住。"""
|
|
349
|
+
m = _RAISED.match(end.title_full or end.title) if end.type == "end" else None
|
|
350
|
+
if m is None:
|
|
351
|
+
return None
|
|
352
|
+
name = m.group(1).rsplit(".", 1)[-1]
|
|
353
|
+
for link in reversed(chain):
|
|
354
|
+
if link.how != "call":
|
|
355
|
+
return None
|
|
356
|
+
fg = graph.functions[link.function]
|
|
357
|
+
by_id = {n.id: n for n in fg.nodes}
|
|
358
|
+
seen, todo = set(), [link.node]
|
|
359
|
+
while todo: # 一个 try 的几个 except 可能串着连
|
|
360
|
+
src = todo.pop()
|
|
361
|
+
for e in fg.edges:
|
|
362
|
+
if e.src != src or e.kind != "raise" or e.dst in seen or e.dst not in by_id:
|
|
363
|
+
continue
|
|
364
|
+
seen.add(e.dst)
|
|
365
|
+
catch = by_id[e.dst]
|
|
366
|
+
if catch.type != "catch":
|
|
367
|
+
continue
|
|
368
|
+
kinds = {k.rsplit(".", 1)[-1] for k in re.findall(r"[A-Za-z_][\w.]*", catch.subtitle_full or catch.subtitle)}
|
|
369
|
+
if name in kinds or kinds & _CATCH_ALL or "任意异常" in (catch.subtitle or ""):
|
|
370
|
+
return link.function, catch
|
|
371
|
+
todo.append(catch.id)
|
|
372
|
+
return None
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def find_outcomes(graph: ProjectGraph, line: FlowLine, text: str) -> list[tuple[str, str]]:
|
|
376
|
+
"""这条线涉及的函数里(line_functions 的顺序),标题含 text(不分大小写,完整标题)或 end_kind 等于 text 的结局
|
|
377
|
+
节点:[(函数 key, 节点 id)],函数内按节点顺序。text 为空时为空表。"""
|
|
378
|
+
if not text:
|
|
379
|
+
return []
|
|
380
|
+
needle = text.casefold()
|
|
381
|
+
out: list[tuple[str, str]] = []
|
|
382
|
+
for key in line_functions(graph, line):
|
|
383
|
+
for n in graph.functions[key].nodes:
|
|
384
|
+
if n.type == "end" and (needle in (n.title_full or n.title).casefold() or n.end_kind == text):
|
|
385
|
+
out.append((key, n.id))
|
|
386
|
+
return out
|