govrule 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.
- govrule/__init__.py +7 -0
- govrule/__main__.py +3 -0
- govrule/astnodes.py +116 -0
- govrule/baseline.py +105 -0
- govrule/cli.py +175 -0
- govrule/diagnostics.py +72 -0
- govrule/evaluator.py +236 -0
- govrule/facts.py +158 -0
- govrule/lexer.py +127 -0
- govrule/parser.py +376 -0
- govrule/py.typed +0 -0
- govrule/values.py +64 -0
- govrule-0.1.0.dist-info/METADATA +111 -0
- govrule-0.1.0.dist-info/RECORD +18 -0
- govrule-0.1.0.dist-info/WHEEL +5 -0
- govrule-0.1.0.dist-info/entry_points.txt +2 -0
- govrule-0.1.0.dist-info/licenses/LICENSE +16 -0
- govrule-0.1.0.dist-info/top_level.txt +1 -0
govrule/__init__.py
ADDED
govrule/__main__.py
ADDED
govrule/astnodes.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""AST 节点。
|
|
2
|
+
|
|
3
|
+
刻意只有 10 个节点:这门语言的全部表达力都在这 10 个里,没有循环、没有函数定义、
|
|
4
|
+
没有递归。**少不是未完成,是判据**(报告 §5.4:图灵完备换不到任何东西)。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True)
|
|
13
|
+
class Str:
|
|
14
|
+
value: str
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class Int:
|
|
19
|
+
value: int
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class Regex:
|
|
24
|
+
pattern: str
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class Ident:
|
|
29
|
+
name: str
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True)
|
|
33
|
+
class Member:
|
|
34
|
+
obj: "Expr"
|
|
35
|
+
attr: str
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True)
|
|
39
|
+
class Call:
|
|
40
|
+
name: str
|
|
41
|
+
args: tuple["Expr", ...]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True)
|
|
45
|
+
class BinOp:
|
|
46
|
+
op: str
|
|
47
|
+
left: "Expr"
|
|
48
|
+
right: "Expr"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class Unary:
|
|
53
|
+
op: str
|
|
54
|
+
operand: "Expr"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
Expr = Str | Int | Regex | Ident | Member | Call | BinOp | Unary
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass
|
|
61
|
+
class Scope:
|
|
62
|
+
kind: str # 目前只有 "repo"
|
|
63
|
+
pattern: str
|
|
64
|
+
exclude: tuple[str, ...] = ()
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@dataclass
|
|
68
|
+
class Assertion:
|
|
69
|
+
op: str # == <= >= < >
|
|
70
|
+
value: int
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass
|
|
74
|
+
class Exemption:
|
|
75
|
+
"""一条豁免:命中后不再计入阻断,但必须被计数。
|
|
76
|
+
|
|
77
|
+
报告 §5.1 的 `exempt` 抽象:豁免必须**同宽于「谁有权改」**,并且分类可见。
|
|
78
|
+
severity=warn 表示「报告但不阻断」,用于文档类命中(与 g01 的 report-only 同构)。
|
|
79
|
+
"""
|
|
80
|
+
name: str
|
|
81
|
+
when: "Expr"
|
|
82
|
+
severity: str = "exempt" # exempt(不计入)/ warn(计入报告不计入阻断)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@dataclass
|
|
86
|
+
class Evidence:
|
|
87
|
+
cite: Expr | None = None
|
|
88
|
+
expected: str = ""
|
|
89
|
+
found: Expr | None = None
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@dataclass
|
|
93
|
+
class Rule:
|
|
94
|
+
rule_id: str
|
|
95
|
+
line: int
|
|
96
|
+
scope: Scope | None = None
|
|
97
|
+
select: str | None = None # "file" | "line"
|
|
98
|
+
extract: Call | None = None
|
|
99
|
+
where: Expr | None = None
|
|
100
|
+
assertion: Assertion | None = None
|
|
101
|
+
evidence: Evidence = field(default_factory=Evidence)
|
|
102
|
+
severity: str = "blocking"
|
|
103
|
+
platforms: tuple[str, ...] = ("nt", "posix")
|
|
104
|
+
code: str = "F-DEAD-ROOT" # 诊断码,必须是 diagnostics.CODES 里的闭集成员
|
|
105
|
+
exemptions: list[Exemption] = field(default_factory=list)
|
|
106
|
+
|
|
107
|
+
#: 报告里每一条规则都必须能回答「我到底看了什么」
|
|
108
|
+
def describe(self) -> str:
|
|
109
|
+
bits = [self.rule_id]
|
|
110
|
+
if self.scope:
|
|
111
|
+
bits.append(f"scope={self.scope.pattern}")
|
|
112
|
+
if self.extract:
|
|
113
|
+
bits.append(f"extract={self.extract.name}")
|
|
114
|
+
if self.assertion:
|
|
115
|
+
bits.append(f"assert count {self.assertion.op} {self.assertion.value}")
|
|
116
|
+
return " ".join(bits)
|
govrule/baseline.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"""基线棘轮:把「存量」冻结成文件,新增即拦,修好要销账。
|
|
2
|
+
|
|
3
|
+
抄的是三处工业实践里被验证过的同一条纪律(报告 §6.4):
|
|
4
|
+
- **双向拦截**(Go 的 API 文件):加了不记账要红,改了删了也要红;
|
|
5
|
+
- **纯增长拒绝**(g19 的双向棘轮):`旧 ⊂ 新` 说明一条都没修,文件只是胖了 —— 拒绝写入;
|
|
6
|
+
- **stale 判红**(同上):基线里有、当下不再命中的键,是「过期账单」,必须销账。
|
|
7
|
+
|
|
8
|
+
键只用 `规则|路径|行号`,不用内容摘要:**摘要键会让一次无害的格式化把全部存量判成新增**
|
|
9
|
+
(报告 §6.4 的「计数键 vs 摘要键」陷阱)。
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import datetime as _dt
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
Key = tuple[str, str, int]
|
|
19
|
+
|
|
20
|
+
HEADER_PREFIX = "# "
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class Baseline:
|
|
25
|
+
keys: set[Key] = field(default_factory=set)
|
|
26
|
+
meta: dict[str, str] = field(default_factory=dict)
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def has_meta(self) -> bool:
|
|
30
|
+
return bool(self.meta.get("written") and self.meta.get("reason"))
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def load(path: Path) -> Baseline:
|
|
34
|
+
if not path.exists():
|
|
35
|
+
return Baseline()
|
|
36
|
+
keys: set[Key] = set()
|
|
37
|
+
for raw in path.read_text(encoding="utf-8").splitlines():
|
|
38
|
+
line = raw.strip()
|
|
39
|
+
if not line or line.startswith("#"):
|
|
40
|
+
continue
|
|
41
|
+
parts = line.split("|")
|
|
42
|
+
if len(parts) != 3:
|
|
43
|
+
continue
|
|
44
|
+
rule, p, ln = parts
|
|
45
|
+
try:
|
|
46
|
+
keys.add((rule, p, int(ln)))
|
|
47
|
+
except ValueError:
|
|
48
|
+
continue
|
|
49
|
+
return Baseline(keys=keys, meta=_parse_header(path))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _parse_header(path: Path) -> dict[str, str]:
|
|
53
|
+
"""头部按 `key: value` 逐行解析(同一行多字段也支持)。"""
|
|
54
|
+
meta: dict[str, str] = {}
|
|
55
|
+
for raw in path.read_text(encoding="utf-8").splitlines():
|
|
56
|
+
if not raw.startswith("#"):
|
|
57
|
+
continue
|
|
58
|
+
body = raw[1:].strip()
|
|
59
|
+
for field_name in ("written", "commit", "reason"):
|
|
60
|
+
idx = body.find(field_name + ":")
|
|
61
|
+
if idx < 0:
|
|
62
|
+
continue
|
|
63
|
+
rest = body[idx + len(field_name) + 1:].strip()
|
|
64
|
+
for stop in ("written:", "commit:", "reason:"):
|
|
65
|
+
cut = rest.find(" " + stop)
|
|
66
|
+
if cut > 0:
|
|
67
|
+
rest = rest[:cut]
|
|
68
|
+
meta[field_name] = rest.strip()
|
|
69
|
+
return meta
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def save(path: Path, keys: set[Key], reason: str, commit: str = "none") -> None:
|
|
73
|
+
stamp = _dt.datetime.now().astimezone().isoformat(timespec="seconds")
|
|
74
|
+
lines = [
|
|
75
|
+
f"# written: {stamp} commit: {commit} reason: {reason or '未填写'}",
|
|
76
|
+
f"# keys: {len(keys)}",
|
|
77
|
+
]
|
|
78
|
+
lines += [f"{r}|{p}|{ln}" for r, p, ln in sorted(keys)]
|
|
79
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
80
|
+
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@dataclass
|
|
84
|
+
class Diff:
|
|
85
|
+
new: set[Key] = field(default_factory=set) # 当下有、基线没有
|
|
86
|
+
fixed: set[Key] = field(default_factory=set) # 基线有、当下没有
|
|
87
|
+
common: set[Key] = field(default_factory=set)
|
|
88
|
+
old_count: int = 0
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def pure_growth(self) -> bool:
|
|
92
|
+
"""旧 ⊂ 新 且确实有新增:一条都没修,只是账单变长。
|
|
93
|
+
|
|
94
|
+
首次建立基线(old_count == 0)不算增长 —— 否则新仓第一天就写不进基线。
|
|
95
|
+
这是边界条件,不是特例:纯增长禁的是「扩张」,不是「建立」。
|
|
96
|
+
"""
|
|
97
|
+
return self.old_count > 0 and not self.fixed and bool(self.new)
|
|
98
|
+
|
|
99
|
+
def render(self) -> str:
|
|
100
|
+
return f"counts: fixed={len(self.fixed)} new={len(self.new)} common={len(self.common)}"
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def diff(baseline: Baseline, current: set[Key]) -> Diff:
|
|
104
|
+
return Diff(new=current - baseline.keys, fixed=baseline.keys - current,
|
|
105
|
+
common=current & baseline.keys, old_count=len(baseline.keys))
|
govrule/cli.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""CLI:把规则集作用到一个仓,输出四值汇总与退出码。
|
|
2
|
+
|
|
3
|
+
退出码词汇(与 allin-governance 对齐,但把 Unknown 单列):
|
|
4
|
+
|
|
5
|
+
0 全部 Pass
|
|
6
|
+
1 至少一条 Fail
|
|
7
|
+
2 用法错误
|
|
8
|
+
3 Incomplete —— 有 Unknown,或全部 Skip(「没量到」不等于「没问题」)
|
|
9
|
+
|
|
10
|
+
`3` 不给 `1` 是刻意的:如果「没量到」和「量到不合格」共用一个码,CI 日志里就再也
|
|
11
|
+
分不出「要修代码」还是「要修判据」。这正是报告 §5.1 说 Unknown 不能被吞掉的理由。
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import argparse
|
|
17
|
+
import json
|
|
18
|
+
import sys
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
from . import baseline as bl_mod
|
|
22
|
+
from .diagnostics import DiagnosticError
|
|
23
|
+
from .evaluator import RuleResult, evaluate
|
|
24
|
+
from .facts import Repo
|
|
25
|
+
from .parser import parse
|
|
26
|
+
from .values import EXIT_BLOCKING, EXIT_INCOMPLETE, EXIT_OK, EXIT_USAGE, Verdict, combine_all, exit_code
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def load_rules(rules_dir: Path) -> list:
|
|
30
|
+
rules = []
|
|
31
|
+
for p in sorted(rules_dir.glob("*.rule")):
|
|
32
|
+
rules.extend(parse(p.read_text(encoding="utf-8"), str(p)))
|
|
33
|
+
return rules
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def run_rules(rules_dir: Path, root: Path, platform: str = "nt") -> list[RuleResult]:
|
|
37
|
+
rules = load_rules(rules_dir)
|
|
38
|
+
repo = Repo(root)
|
|
39
|
+
return [evaluate(r, repo, platform) for r in rules]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _keys(results: list[RuleResult]) -> set[tuple[str, str, int]]:
|
|
43
|
+
return {(r.rule_id, f.path, f.line) for r in results for f in r.findings}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def aggregate(results: list[RuleResult]) -> tuple[Verdict, int]:
|
|
47
|
+
verdict = combine_all([r.verdict for r in results])
|
|
48
|
+
if all(r.verdict is Verdict.SKIP for r in results) and results:
|
|
49
|
+
return Verdict.SKIP, EXIT_INCOMPLETE
|
|
50
|
+
return verdict, exit_code(verdict)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def main(argv: list[str] | None = None) -> int:
|
|
54
|
+
ap = argparse.ArgumentParser(prog="govrule", description="治理规则 DSL(M0 子集)")
|
|
55
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
56
|
+
|
|
57
|
+
run = sub.add_parser("run", help="跑一个仓")
|
|
58
|
+
run.add_argument("--rules", required=True, type=Path)
|
|
59
|
+
run.add_argument("--root", required=True, type=Path)
|
|
60
|
+
run.add_argument("--platform", default="nt", choices=["nt", "posix"])
|
|
61
|
+
run.add_argument("--json", action="store_true")
|
|
62
|
+
run.add_argument("--quiet", action="store_true", help="只打汇总行")
|
|
63
|
+
run.add_argument("--max-findings", type=int, default=50, help="仅影响显示,不影响判定与退出码")
|
|
64
|
+
run.add_argument("--baseline", type=Path, help="基线文件:命中的存量不阻断,新增即拦")
|
|
65
|
+
run.add_argument("--pass-on-stale", action="store_true", help="允许过期账单通过(CI 下会被拒绝)")
|
|
66
|
+
run.add_argument("--ci", action="store_true", help="CI 模式:人手开关一律 exit 2")
|
|
67
|
+
|
|
68
|
+
bw = sub.add_parser("baseline-write", help="把当下命中写成基线(纯增长会被拒绝)")
|
|
69
|
+
bw.add_argument("--rules", required=True, type=Path)
|
|
70
|
+
bw.add_argument("--root", required=True, type=Path)
|
|
71
|
+
bw.add_argument("--out", required=True, type=Path)
|
|
72
|
+
bw.add_argument("--reason", required=True)
|
|
73
|
+
bw.add_argument("--allow-growth", action="store_true")
|
|
74
|
+
bw.add_argument("--ci", action="store_true")
|
|
75
|
+
bw.add_argument("--platform", default="nt", choices=["nt", "posix"])
|
|
76
|
+
|
|
77
|
+
lst = sub.add_parser("list", help="列出规则与它们声称的判定域")
|
|
78
|
+
lst.add_argument("--rules", required=True, type=Path)
|
|
79
|
+
|
|
80
|
+
args = ap.parse_args(argv)
|
|
81
|
+
|
|
82
|
+
try:
|
|
83
|
+
if args.cmd == "baseline-write":
|
|
84
|
+
if args.ci and args.allow_growth:
|
|
85
|
+
print("CI 下不允许 --allow-growth(人手开关不能进无人值守)", file=sys.stderr)
|
|
86
|
+
return EXIT_USAGE
|
|
87
|
+
results = run_rules(args.rules, args.root, args.platform)
|
|
88
|
+
cur = _keys(results)
|
|
89
|
+
old = bl_mod.load(args.out)
|
|
90
|
+
d = bl_mod.diff(old, cur)
|
|
91
|
+
if d.pure_growth and not args.allow_growth:
|
|
92
|
+
print(f"拒绝写入:纯增长(fixed=0, new={len(d.new)})", file=sys.stderr)
|
|
93
|
+
print(" 「一条都没修,只是账单变长」——要写必须显式 --allow-growth", file=sys.stderr)
|
|
94
|
+
print(" " + d.render(), file=sys.stderr)
|
|
95
|
+
return EXIT_BLOCKING
|
|
96
|
+
bl_mod.save(args.out, cur, args.reason)
|
|
97
|
+
print(f"written {len(cur)} key(s) -> {args.out}")
|
|
98
|
+
print(" " + d.render())
|
|
99
|
+
return EXIT_OK
|
|
100
|
+
|
|
101
|
+
if args.cmd == "list":
|
|
102
|
+
for r in load_rules(args.rules):
|
|
103
|
+
print(f"{r.describe()} platforms={','.join(r.platforms)}")
|
|
104
|
+
return EXIT_OK
|
|
105
|
+
results = run_rules(args.rules, args.root, args.platform)
|
|
106
|
+
except DiagnosticError as e:
|
|
107
|
+
print(e.render_all(), file=sys.stderr)
|
|
108
|
+
return EXIT_USAGE
|
|
109
|
+
|
|
110
|
+
stale_note = ""
|
|
111
|
+
if args.baseline:
|
|
112
|
+
if args.ci and args.pass_on_stale:
|
|
113
|
+
print("CI 下不允许 --pass-on-stale", file=sys.stderr)
|
|
114
|
+
return EXIT_USAGE
|
|
115
|
+
base = bl_mod.load(args.baseline)
|
|
116
|
+
cur = _keys(results)
|
|
117
|
+
d = bl_mod.diff(base, cur)
|
|
118
|
+
if d.fixed:
|
|
119
|
+
print(f"baseline: -fixed {len(d.fixed)}")
|
|
120
|
+
if d.new:
|
|
121
|
+
print(f"baseline: +new {len(d.new)}")
|
|
122
|
+
for r in results:
|
|
123
|
+
r.findings = [f for f in r.findings if (r.rule_id, f.path, f.line) not in base.keys]
|
|
124
|
+
if r.verdict is Verdict.FAIL and not r.findings:
|
|
125
|
+
r.verdict = Verdict.PASS
|
|
126
|
+
if d.fixed and not d.new:
|
|
127
|
+
stale_note = "stale keys are fixed; rewrite the baseline to shrink it"
|
|
128
|
+
if d.fixed and args.pass_on_stale and not args.ci:
|
|
129
|
+
stale_note += " (pass-on-stale)"
|
|
130
|
+
|
|
131
|
+
verdict, code = aggregate(results)
|
|
132
|
+
|
|
133
|
+
if args.baseline and d.fixed and not args.pass_on_stale:
|
|
134
|
+
print(f"baseline stale: {len(d.fixed)} key(s) no longer occur -> exit 1(过期账单必须销账)",
|
|
135
|
+
file=sys.stderr)
|
|
136
|
+
code = EXIT_BLOCKING
|
|
137
|
+
|
|
138
|
+
if args.json:
|
|
139
|
+
print(json.dumps({
|
|
140
|
+
"root": str(args.root),
|
|
141
|
+
"platform": args.platform,
|
|
142
|
+
"verdict": verdict.value,
|
|
143
|
+
"exit": code,
|
|
144
|
+
"rules": [
|
|
145
|
+
{
|
|
146
|
+
"rule": r.rule_id,
|
|
147
|
+
"verdict": r.verdict.value,
|
|
148
|
+
"scanned": r.scanned,
|
|
149
|
+
"matched": r.matched,
|
|
150
|
+
"findings": [f.render() for f in r.findings],
|
|
151
|
+
"note": r.note,
|
|
152
|
+
}
|
|
153
|
+
for r in results
|
|
154
|
+
],
|
|
155
|
+
}, ensure_ascii=False, indent=2))
|
|
156
|
+
return code
|
|
157
|
+
|
|
158
|
+
for r in results:
|
|
159
|
+
print(r.summary())
|
|
160
|
+
if not args.quiet:
|
|
161
|
+
for f in r.findings[:args.max_findings]:
|
|
162
|
+
print(" " + f.render())
|
|
163
|
+
if len(r.findings) > args.max_findings:
|
|
164
|
+
print(f" ... 另有 {len(r.findings) - args.max_findings} 条未显示(判定与退出码仍按全量)")
|
|
165
|
+
if r.note:
|
|
166
|
+
print(" note: " + r.note)
|
|
167
|
+
total_scanned = sum(r.scanned for r in results)
|
|
168
|
+
total_findings = sum(len(r.findings) for r in results)
|
|
169
|
+
print(f"== {args.root} | {len(results)} rule(s) | scanned {total_scanned} | "
|
|
170
|
+
f"blocking {total_findings} | verdict {verdict.value} | exit {code}")
|
|
171
|
+
return code
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
if __name__ == "__main__":
|
|
175
|
+
raise SystemExit(main())
|
govrule/diagnostics.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""诊断:span + 闭集码 + expected/found。
|
|
2
|
+
|
|
3
|
+
现状的门禁 finding 只有 `(path, line, text, kind)` —— **无列、无 span、无期望集**,
|
|
4
|
+
74 个 kind 还是自由字面量(报告 §5.3 / E4)。这里刻意把三件事先做对:
|
|
5
|
+
|
|
6
|
+
1. 每个诊断带 `col`(哪怕只有一个字符),因为「指到行」升级成「指到位置」是
|
|
7
|
+
编辑器与自动修复的前提;
|
|
8
|
+
2. 码是**闭集**:`CODES` 里没有的码直接判红(`E-CODE-UNKNOWN`),新增码必须登记;
|
|
9
|
+
3. `expected / found` 是结构化字段,不是拼进 message 的字符串——这一步决定
|
|
10
|
+
以后能不能被机器消费。
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
|
|
17
|
+
#: 诊断码闭集。新增码 = 改这个表,不允许在代码里裸写字面量。
|
|
18
|
+
CODES: dict[str, str] = {
|
|
19
|
+
"E-LEX-STRING": "字符串未闭合",
|
|
20
|
+
"E-LEX-REGEX": "正则未闭合",
|
|
21
|
+
"E-LEX-CHAR": "无法识别的字符",
|
|
22
|
+
"E-PARSE-TOKEN": "语法错误:此处不应出现该 token",
|
|
23
|
+
"E-PARSE-CLAUSE": "未知的子句",
|
|
24
|
+
"E-PARSE-EXPR": "表达式不完整",
|
|
25
|
+
"E-PARSE-DUP": "同一子句重复声明",
|
|
26
|
+
"E-CODE-UNKNOWN": "诊断码未在闭集登记",
|
|
27
|
+
"E-SEM-VERDICT": "判定结果不可聚合",
|
|
28
|
+
"E-RULE-NOSCOPE": "规则缺少 scope(未声明 = 不可判定,不是全部)",
|
|
29
|
+
"E-RULE-NOASSERT": "规则缺少 assert",
|
|
30
|
+
"E-RULE-NOEXTRACT": "规则缺少 extract",
|
|
31
|
+
"W-RULE-NOAPPLIES": "规则未声明适用平台,按全部平台处理",
|
|
32
|
+
"F-DEAD-ROOT": "源码里出现写死的盘符路径",
|
|
33
|
+
"F-DOCS-EXT": "docs 树内出现非文档扩展名",
|
|
34
|
+
"F-BIG-FILE": "被跟踪文件超过体积阈值",
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True)
|
|
39
|
+
class Diagnostic:
|
|
40
|
+
code: str
|
|
41
|
+
path: str
|
|
42
|
+
line: int
|
|
43
|
+
col: int
|
|
44
|
+
message: str
|
|
45
|
+
expected: str = ""
|
|
46
|
+
found: str = ""
|
|
47
|
+
severity: str = "error"
|
|
48
|
+
|
|
49
|
+
def __post_init__(self) -> None:
|
|
50
|
+
if self.code not in CODES:
|
|
51
|
+
object.__setattr__(self, "code", "E-CODE-UNKNOWN")
|
|
52
|
+
|
|
53
|
+
def render(self) -> str:
|
|
54
|
+
loc = f"{self.path}:{self.line}:{self.col}"
|
|
55
|
+
tail = []
|
|
56
|
+
if self.expected:
|
|
57
|
+
tail.append(f"expected {self.expected}")
|
|
58
|
+
if self.found:
|
|
59
|
+
tail.append(f"found {self.found}")
|
|
60
|
+
suffix = f" ({', '.join(tail)})" if tail else ""
|
|
61
|
+
return f"{loc}: {self.severity}[{self.code}]: {self.message}{suffix}"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class DiagnosticError(Exception):
|
|
65
|
+
"""解析/语义阶段的致命错误:带一条或一组诊断。"""
|
|
66
|
+
|
|
67
|
+
def __init__(self, *diagnostics: Diagnostic):
|
|
68
|
+
self.diagnostics = list(diagnostics)
|
|
69
|
+
super().__init__(self.diagnostics[0].render() if self.diagnostics else "diagnostic error")
|
|
70
|
+
|
|
71
|
+
def render_all(self) -> str:
|
|
72
|
+
return "\n".join(d.render() for d in self.diagnostics)
|