@xiaohuo123212/elench 0.0.0-stage → 0.1.0

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.
Files changed (69) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +53 -0
  3. package/README.md +298 -2
  4. package/bin/elench.js +69 -0
  5. package/package.json +37 -4
  6. package/scripts/clean-pycache.js +37 -0
  7. package/scripts/npm_smoke.js +88 -0
  8. package/src/README-/345/205/274/345/256/271/345/261/202.md +26 -0
  9. package/src/ast_util.py +111 -0
  10. package/src/bench.py +376 -0
  11. package/src/borrow.py +282 -0
  12. package/src/bound.py +13 -0
  13. package/src/cfg.py +219 -0
  14. package/src/chart.py +209 -0
  15. package/src/check_docs.py +156 -0
  16. package/src/checker.py +2473 -0
  17. package/src/contract_metric.py +87 -0
  18. package/src/cost_check.py +13 -0
  19. package/src/cost_diff.py +533 -0
  20. package/src/cost_domain/__init__.py +32 -0
  21. package/src/cost_domain/bound.py +739 -0
  22. package/src/cost_domain/cost_check.py +394 -0
  23. package/src/cost_domain/cost_interp.py +1998 -0
  24. package/src/cost_domain/symbolic.py +554 -0
  25. package/src/cost_explain.py +503 -0
  26. package/src/cost_interp.py +13 -0
  27. package/src/cxx_map.py +184 -0
  28. package/src/dispatch.py +314 -0
  29. package/src/dsh.py +3980 -0
  30. package/src/dup_scan.py +180 -0
  31. package/src/elench.py +15 -0
  32. package/src/emit.py +56 -0
  33. package/src/ffi_c.py +70 -0
  34. package/src/fmt.py +115 -0
  35. package/src/formatter.py +596 -0
  36. package/src/grammar.py +272 -0
  37. package/src/guarantees.py +116 -0
  38. package/src/highlight.py +156 -0
  39. package/src/interp.py +2119 -0
  40. package/src/isolated.py +161 -0
  41. package/src/jsonval.py +236 -0
  42. package/src/kappa_vs_measured.py +347 -0
  43. package/src/kinds.py +122 -0
  44. package/src/lexer.py +559 -0
  45. package/src/migrate_docs.py +115 -0
  46. package/src/otel.py +579 -0
  47. package/src/otel_dashboard.py +218 -0
  48. package/src/otel_export.py +380 -0
  49. package/src/otel_local_sink.py +141 -0
  50. package/src/otel_view.py +156 -0
  51. package/src/parser.py +1909 -0
  52. package/src/parser.py.bak +1781 -0
  53. package/src/policy.py +271 -0
  54. package/src/rename_ch.py +81 -0
  55. package/src/requires.py +242 -0
  56. package/src/segment_plan.py +150 -0
  57. package/src/shape.py +130 -0
  58. package/src/stdlib.py +1856 -0
  59. package/src/stdlib.py.bak +1751 -0
  60. package/src/symbolic.py +13 -0
  61. package/src/sync_docs.py +225 -0
  62. package/src/test_checker.py.bak +443 -0
  63. package/src/test_formatter.py.bak +201 -0
  64. package/src/test_invalid.py.bak +342 -0
  65. package/src/test_parser.py.bak +423 -0
  66. package/src/typecheck.py +865 -0
  67. package/src/typecheck.py.bak +741 -0
  68. package/src/typenames.py +56 -0
  69. package/src/walk.py +197 -0
package/src/checker.py ADDED
@@ -0,0 +1,2473 @@
1
+ #!/usr/bin/env python3
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ # Copyright 2026 Elench contributors
4
+
5
+ # -*- coding: utf-8 -*-
6
+ """
7
+ checker.py —— M0 检查器
8
+
9
+ M0 能查的(不含成本分析):
10
+ F-1 每个实现函数 MUST 有对应的 spec
11
+ F-2 同名函数的签名 MUST 一致
12
+ F-4 `.eln` MUST NOT 有声明(const/enum/struct/trait/impl/spec/choose)
13
+ F-8 `.eln` MUST NOT 有 use
14
+ F-9 kernel MUST NOT 被 `?!` 之外的地方直接调用
15
+ B-2 `?!label` 的 label MUST 已在 `.tu` 声明
16
+ B-8 over 元素数 MUST 在 1..4
17
+ B-9 自指 / B-9-a 扩展调用图无环
18
+ B-10 over MUST 引用已声明的 kernel
19
+ B-15 `?!` MUST NOT 构成整个函数体
20
+ B-16 pending 与实际缺体 MUST 双向一致
21
+
22
+ M0 **不**能查的(需要成本分析,属 M2):
23
+ · cost 的计算与 `target` 的比较 → 状态 `done` / `debt` 无法判定
24
+ · effects 的验证
25
+ · requires / guarantees 的验证
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ from typenames import canon, display
31
+ import os
32
+ from dataclasses import dataclass, field
33
+ import re
34
+ from typing import Dict, List, Optional, Set, Tuple
35
+
36
+ import stdlib
37
+ from parser import Node, parse_source
38
+
39
+
40
+ # ---------------------------------------------------------------- 诊断
41
+
42
+ @dataclass
43
+ class Restart:
44
+ """**修法的一条具体动作**(Common Lisp 里 restart 的思路)。
45
+
46
+ 以前诊断只给一句 `修法:…` 文本——读者还得自己翻译成命令、自己敲。
47
+ restart 把"能做什么"结构化成**可执行的一条**,`--apply=N` 就能直接跑。
48
+
49
+ **硬规则:任何 restart 都不许修改 `.tu` 里的 `target`。**
50
+ 契约是持久的,实现是一次性的;"不达标就改承诺"这条路必须不存在
51
+ (`test_restarts.py` 有一条断言专门守这个)。
52
+ """
53
+ kind: str # "command"(能执行)| "edit"(只打印 diff)| "info"(只说明)
54
+ label: str # 一句话:如「重测并生成分档表」
55
+ argv: List[str] = field(default_factory=list) # kind=command
56
+ patch: Dict[str, Any] = field(default_factory=dict) # kind=edit:{file,line,text}
57
+ #: **要不要碰 `target` 那一行**。默认 False ⇒ 构造时就拒绝。
58
+ #: 只有"修正格式/槽位"这类修复才该是 True;**改写成本表达式永远不许**。
59
+ #: (必须放在最后一个字段:前面的构造都是位置传参。)
60
+ touches_target: bool = False
61
+
62
+ def __post_init__(self) -> None:
63
+ """**硬规则在构造点就拒绝**:任何 restart 都不许触碰 `.tu` 的 `target`。
64
+
65
+ 以前这条只写在 docstring 里、再由 `test_restarts.py` 事后查一遍——
66
+ 而且只查了债务修法清单那一处。**诊断带 actions 之后,能改文件的地方变多了**,
67
+ 靠测试守纪律等于没守:新增一条诊断就可能悄悄绕过。
68
+
69
+ 契约是**持久的**,实现是**一次性的**;"不达标就改承诺"这条路必须不存在。
70
+ (对应 Anthropic 那条:技术上做得到,也不让做——所以要**在能力边界上拒绝**,
71
+ 不是在使用时自觉。)
72
+ """
73
+ blob = " ".join([str(self.patch.get("text", "")),
74
+ str(self.patch.get("file", "")),
75
+ " ".join(self.argv or [])])
76
+ if "target" in blob and not self.touches_target:
77
+ raise ValueError(
78
+ "restart 不许触碰 target(契约持久、实现一次性;"
79
+ f"要改 target 请人工编辑):{self.label}")
80
+
81
+ def to_dict(self) -> dict:
82
+ return {"kind": self.kind, "label": self.label,
83
+ "argv": list(self.argv), "patch": dict(self.patch)}
84
+
85
+
86
+ def _line_patch(src: Optional[str], file: str, line: int, fn, label: str):
87
+ """把某一行的文本按 `fn` 改写,做成一条 `edit` 修法;拿不到那行就返回 None。
88
+
89
+ **宁可返回 None(给不出修法),也不给一条会改错行的修法。**
90
+ """
91
+ lines = (src or "").splitlines()
92
+ if not (0 < line <= len(lines)):
93
+ return None
94
+ old = lines[line - 1]
95
+ try:
96
+ new = fn(old)
97
+ except Exception: # noqa: BLE001
98
+ return None
99
+ if new is None or new == old or not new.strip():
100
+ return None
101
+ return Restart("edit", label, patch={"file": file, "line": line,
102
+ "text": new.strip()})
103
+
104
+
105
+ def _ren_obj(s: str, old: str):
106
+ """把 `objective <old>;` 里的取值换成 `time`(找不到就返回 None)。"""
107
+ i = s.find("objective")
108
+ if i < 0 or not old:
109
+ return None
110
+ j = s.find(old, i)
111
+ if j < 0:
112
+ return None
113
+ return s[:j] + "time" + s[j + len(old):]
114
+
115
+
116
+ def _rewrite_cond(s: str, var: str, vec: str):
117
+ """把 `while (<任意>)` 的条件改写成 `var < vec.length()`。"""
118
+ import re as _re
119
+ if not var or not vec:
120
+ return None
121
+ new, n = _re.subn(r"while\s*\([^)]*\)",
122
+ "while (" + var + " < " + vec + ".length())", s, count=1)
123
+ return new if n else None
124
+
125
+
126
+ def _first_vec_param(fn):
127
+ """函数里第一个容器形参的名字(找不到就 None)——修 while 条件要用它。"""
128
+ for p in walk(fn, "param"):
129
+ # 类型是 **node** 不是字符串:`type-ref → type-name(name="Vec") → type-args`
130
+ vals, stack = [], [p]
131
+ while stack:
132
+ n = stack.pop()
133
+ v = getattr(n, "value", None)
134
+ if isinstance(v, str):
135
+ vals.append(v)
136
+ nm = getattr(n, "name", None)
137
+ if isinstance(nm, str):
138
+ vals.append(nm)
139
+ stack.extend(getattr(n, "children", None) or [])
140
+ if any("Vec" in x for x in vals):
141
+ return getattr(p, "name", None)
142
+ return None
143
+
144
+
145
+ def _target_slot_fix(src, file: str, line: int, bad: str):
146
+ """槽位名不合法 → 换成 `max`。**显式声明 touches_target**,且只改槽位名。"""
147
+ lines = (src or "").splitlines()
148
+ if not (0 < line <= len(lines)) or not bad:
149
+ return None
150
+ old = lines[line - 1]
151
+ if bad + ":" not in old:
152
+ return None
153
+ new = old.replace(bad + ":", "max:", 1)
154
+ return Restart("edit", "把槽位改成 `max`(上界的默认写法)",
155
+ patch={"file": file, "line": line, "text": new.strip()},
156
+ touches_target=True)
157
+
158
+
159
+ def _acts(a) -> list:
160
+ """`actions=[...]` 的便捷写法:拿不到修法就给空列表。"""
161
+ return [a] if a is not None else []
162
+
163
+
164
+ def _spec_skeleton(ai_src: Optional[str], fn) -> str:
165
+ """从 `.eln` 的函数签名**抄**出一个 spec 骨架。
166
+
167
+ 只处理单行签名;多行签名**不瞎猜**,返回一句提示——宁可给不出,也不给错的。
168
+ """
169
+ lines = (ai_src or "").splitlines()
170
+ if not (0 < getattr(fn, "line", 0) <= len(lines)):
171
+ return "spec <函数名>(...) { effects {}; }"
172
+ head = lines[fn.line - 1].strip()
173
+ if "{" not in head:
174
+ return f"// 多行签名:请手动为 `{getattr(fn, 'name', '')}` 写 spec"
175
+ sig = head.split("{", 1)[0].strip()
176
+ for kw in ("func ", "fn "):
177
+ if sig.startswith(kw):
178
+ sig = "spec " + sig[len(kw):]
179
+ break
180
+ return f"{sig} {{ effects {{}}; }}"
181
+
182
+
183
+ def _guarantees_line(spec) -> int:
184
+ """spec 里第一条 `guarantees` 子句所在的行(找不到就退回 spec 的行)。"""
185
+ body = next((c for c in (spec.children or []) if c.kind == "spec-body"), None)
186
+ for cl in (body.children if body else []):
187
+ if cl.kind == "clause" and (cl.name or "") == "guarantees":
188
+ return getattr(cl, "line", 0) or getattr(spec, "line", 0)
189
+ return getattr(spec, "line", 0)
190
+
191
+
192
+ def _demote_guarantees(tu_src: Optional[str], line: int) -> str:
193
+ """把某一行的 `guarantees X;` **注释掉**(`assume` 已于 2026-11-04 移除)。"""
194
+ lines = (tu_src or "").splitlines()
195
+ if not (0 < line <= len(lines)):
196
+ return "// 拿不到这一行,请手动删掉这条 guarantees"
197
+ return "// " + lines[line - 1].strip() + " ← 不可检查,已注释"
198
+
199
+
200
+ @dataclass
201
+ class Diag:
202
+ code: str
203
+ message: str
204
+ line: int = 0
205
+ col: int = 0
206
+ start: int = 0
207
+ end: int = 0
208
+ severity: str = "error"
209
+ actions: List[Restart] = field(default_factory=list)
210
+
211
+ def to_dict(self) -> dict:
212
+ return {"code": self.code, "message": self.message,
213
+ "line": self.line, "col": self.col,
214
+ "start": self.start, "end": self.end,
215
+ "severity": self.severity,
216
+ "actions": [a.to_dict() for a in self.actions]}
217
+
218
+
219
+ # ---------------------------------------------------------------- 结果
220
+
221
+ @dataclass
222
+ class FnInfo:
223
+ name: str
224
+ kind: str # "fn" | "kernel"
225
+ has_impl: bool
226
+ has_target: bool
227
+ is_pub: bool = False
228
+ line: int = 0
229
+ state: str = ""
230
+ note: str = ""
231
+
232
+ def to_dict(self) -> dict:
233
+ """对外输出用完整单词:`has_implementation` 而不是 `has_impl`。"""
234
+ return {
235
+ "name": self.name,
236
+ "kind": self.kind,
237
+ "has_implementation": self.has_impl,
238
+ "has_target": self.has_target,
239
+ "is_public": self.is_pub,
240
+ "line": self.line,
241
+ "state": self.state,
242
+ "note": self.note,
243
+ }
244
+
245
+
246
+ @dataclass
247
+ class CheckResult:
248
+ module: str = ""
249
+ functions: List[FnInfo] = field(default_factory=list)
250
+ diagnostics: List[Diag] = field(default_factory=list)
251
+ choices: Dict[str, dict] = field(default_factory=dict)
252
+ candidates: Dict[str, Dict[str, Node]] = field(default_factory=dict)
253
+ labels_used: Set[str] = field(default_factory=set)
254
+
255
+ @property
256
+ def ok(self) -> bool:
257
+ # v0.68:只有 error 级诊断才算失败;warning 级(如 T13 宽松模式的
258
+ # E-While-NoBound)只提示,不阻断。
259
+ return not any(d.severity == "error" for d in self.diagnostics)
260
+
261
+ def to_dict(self) -> dict:
262
+ return {
263
+ "module": self.module,
264
+ "ok": self.ok,
265
+ "functions": [f.to_dict() for f in self.functions],
266
+ "choices": self.choices,
267
+ "labels_used": sorted(self.labels_used),
268
+ "diagnostics": [d.to_dict() for d in self.diagnostics],
269
+ }
270
+
271
+
272
+ # ---------------------------------------------------------------- 工具
273
+
274
+ def _spec_body(spec: Node) -> Optional[Node]:
275
+ for c in spec.children:
276
+ if c.kind == "spec-body":
277
+ return c
278
+ return None
279
+
280
+
281
+ def _clauses(spec: Node) -> List[Node]:
282
+ body = _spec_body(spec)
283
+ return [x for x in body.children if x.kind == "clause"] if body else []
284
+
285
+
286
+ def _has_target(spec: Node) -> bool:
287
+ return any(c.name == "target" for c in _clauses(spec))
288
+
289
+
290
+ def _params_of(node: Node) -> Optional[Node]:
291
+ for c in node.children:
292
+ if c.kind == "params":
293
+ return c
294
+ return None
295
+
296
+
297
+ def _return_of(node: Node) -> Optional[Node]:
298
+ """返回类型节点(params 之后的第一个 type-* 或 type-name)。"""
299
+ seen_params = False
300
+ for c in node.children:
301
+ if c.kind == "params":
302
+ seen_params = True
303
+ continue
304
+ if c.kind in ("block", "spec-body"):
305
+ return None
306
+ if seen_params and c.kind.startswith("type"):
307
+ return c
308
+ return None
309
+
310
+
311
+ def type_str(t: Optional[Node]) -> str:
312
+ if t is None:
313
+ return ""
314
+ if t.kind == "type-name":
315
+ args = ", ".join(type_str(c) for c in t.children)
316
+ return f"{t.name}<{args}>" if args else str(t.name)
317
+ if t.kind == "type-const":
318
+ return str(t.value)
319
+ if t.kind == "type-args":
320
+ return ", ".join(type_str(c) for c in t.children)
321
+ if t.kind == "type-slice":
322
+ return "[]" + type_str(t.children[0])
323
+ if t.kind == "type-tuple":
324
+ return "(" + ", ".join(type_str(c) for c in t.children) + ")"
325
+ if t.kind == "type-ref":
326
+ return type_str(t.children[0]) + "&"
327
+ return "?"
328
+
329
+
330
+ def param_list(node: Node) -> List[Tuple[str, str]]:
331
+ """[(名字或空, 类型字符串)]"""
332
+ p = _params_of(node)
333
+ if p is None:
334
+ return []
335
+ out = []
336
+ for c in p.children:
337
+ if c.kind == "param":
338
+ out.append((c.name or "", type_str(c.children[0]) if c.children else "?"))
339
+ else:
340
+ out.append(("", type_str(c)))
341
+ return out
342
+
343
+
344
+ def walk(node: Node, kind: str, acc=None) -> List[Node]:
345
+ if acc is None:
346
+ acc = []
347
+ if node.kind == kind:
348
+ acc.append(node)
349
+ for c in node.children:
350
+ walk(c, kind, acc)
351
+ return acc
352
+
353
+
354
+ def callee_name(call: Node) -> Optional[str]:
355
+ """`call` 的第一个孩子是被调者;只认简单的 path 形式。"""
356
+ if not call.children:
357
+ return None
358
+ head = call.children[0]
359
+ if head.kind == "path":
360
+ return head.name
361
+ if head.kind == "field":
362
+ # a.b(...) 形式:取最后一段
363
+ return head.name
364
+ return None
365
+
366
+
367
+ # ---------------------------------------------------------------- 状态
368
+
369
+ def derive_state(has_impl: bool, has_target: bool) -> Tuple[str, str]:
370
+ if not has_impl and not has_target:
371
+ return "draft", "只有签名"
372
+ if not has_impl and has_target:
373
+ return "planned", "意图已定、实现待写"
374
+ if has_impl and not has_target:
375
+ return "unchecked", "有实现但无 target"
376
+ return "?", "done / debt 由 elench cost 判定"
377
+
378
+
379
+ # ---------------------------------------------------------------- 主检查
380
+
381
+ # ---------------------------------------------------------------- T13
382
+
383
+ SIZE_CALLS = ("length", "size", "capacity", "len")
384
+
385
+
386
+ def _is_size_expr(n: Node, const_sizes: set = frozenset()) -> bool:
387
+ """这个表达式是不是「尺寸量」。
388
+
389
+ 认三种:
390
+ · 尺寸方法调用:`xs.length()` / `s.size()` …
391
+ · 形参名(切片/容器的长度在进入函数时就定了)
392
+ · 由 `const` 绑定到尺寸的变量名(如 `const u64 n = xs.length();`)
393
+ 不认:`var` 绑定的变量(循环里可能被改,需要数据流分析——按设计不做)。
394
+ """
395
+ if n is None:
396
+ return False
397
+ if n.kind in ("method-call", "call"):
398
+ return (n.name or "").split(".")[-1] in SIZE_CALLS
399
+ if n.kind == "path":
400
+ return (n.name or "") in const_sizes
401
+ if n.kind == "binary" and (n.value or "") in ("+", "-"):
402
+ # `xs.length() + 1` / `xs.length() - 1` —— **常量偏移的尺寸量仍是尺寸量**。
403
+ # 否则 `const u64 width = b.length() + 1; while (i < width)` 会被拒,
404
+ # 而「尺寸 + 1」是二维表最自然的写法(LCS 的 width 就是它)。
405
+ a, b = (n.children + [None, None])[:2]
406
+ if _is_size_expr(a, const_sizes) and _is_int_literal(b):
407
+ return True
408
+ if _is_size_expr(b, const_sizes) and _is_int_literal(a):
409
+ return True
410
+ return False
411
+ return False
412
+
413
+
414
+ def _is_int_literal(n: Optional[Node]) -> bool:
415
+ """`3` / `-3` —— 整数常量。"""
416
+ if n is None:
417
+ return False
418
+ if n.kind == "lit-int":
419
+ return True
420
+ if n.kind in ("unary", "step") and (n.value or "") in ("-", "+") and n.children:
421
+ return _is_int_literal(n.children[0])
422
+ return False
423
+
424
+
425
+ def _collect_const_sizes(fn: Node) -> set:
426
+ """收集本函数里「由 const 绑定到尺寸量」的变量名。
427
+
428
+ 只看 `const T n = <尺寸表达式>;` 这一种形态——这是一次局部绑定,
429
+ 不是数据流分析:它的值在整个作用域内不变(const 语义保证)。
430
+ """
431
+ names = set()
432
+ for d in walk(fn, "const-decl"):
433
+ if len(d.children) >= 2 and _is_size_expr(d.children[1], frozenset()):
434
+ names.add(d.name)
435
+ return names
436
+
437
+
438
+ #: 整数形参类型。**标量整数形参也算尺寸**——
439
+ #: 它在函数入口即固定,`while (i < dim)` 的迭代次数就是 `dim`,
440
+ #: 是一个**可写出来、可辩护**的上界。T13 要的是"上界可写",不是"上界小"。
441
+ INT_PARAM_TYPES = frozenset({
442
+ "u8", "u16", "u32", "u64", "i8", "i16", "i32", "i64",
443
+ })
444
+
445
+
446
+ #: 当前模块的模块级常量名(由 check_module 在入口填)
447
+ _MODULE_CONST_SIZES: set = set()
448
+
449
+
450
+ def _collect_param_sizes(fn: Node) -> set:
451
+ """可作为 `while` 上界的形参名。
452
+
453
+ 两类:
454
+ 1. 容器参数(`Vec` / `FixedVec`)——上界是它的 `length()`
455
+ 2. **整数标量参数**——上界就是它本身(v0.69 扩)
456
+ """
457
+ names = set()
458
+ for pm in walk(fn, "param"):
459
+ if not pm.children:
460
+ continue
461
+ ty = pm.children[0]
462
+ if ty.kind in ("type-ref", "type-name", "type-slice"):
463
+ base = ty.children[0] if (ty.kind == "type-ref" and ty.children) else ty
464
+ if base.kind == "type-name":
465
+ nm = base.name or ""
466
+ if canon(nm) in ("vector", "array") or nm in INT_PARAM_TYPES:
467
+ names.add(pm.name)
468
+ return names
469
+
470
+
471
+ def _monotone_decreasing_names(fn: Node) -> set:
472
+ """本函数里「只做减法」的变量名(`while (j > 0)` 可以用它们当上界)。"""
473
+ from bound import monotone_decreasing
474
+ return set(monotone_decreasing(fn))
475
+
476
+
477
+ def _dec_loop_can_bound(cond: Optional[Node], dec_vars: set) -> bool:
478
+ """`while (j > 0)` / `while (j >= 1)` 且 j 单调递减 → 可推(上界 = 初值)。"""
479
+ if cond is None or not dec_vars:
480
+ return False
481
+ if cond.kind != "binary" or (cond.value or "") not in (">", ">="):
482
+ return False
483
+ left = cond.children[0] if cond.children else None
484
+ return (left is not None and left.kind == "path"
485
+ and (left.name or "") in dec_vars)
486
+
487
+
488
+ def _cond_can_bound(cond: Node, const_sizes: set = frozenset()) -> bool:
489
+ """T13 来源 ①:条件形态里含尺寸比较。
490
+
491
+ 支持:
492
+ i < xs.length() (任一侧是尺寸调用)
493
+ a < b and c < d (and 组合,任一可推即算可推)
494
+ not P → 不能靠形态推,交给 ②
495
+ """
496
+ if cond is None:
497
+ return False
498
+ if cond.kind == "binary":
499
+ op = cond.value or ""
500
+ if op in ("and", "or"):
501
+ return any(_cond_can_bound(c, const_sizes) for c in cond.children)
502
+ if op in ("<", "<=", ">", ">="):
503
+ if any(_is_size_expr(c, const_sizes) for c in cond.children):
504
+ return True
505
+ # **常量上界**:`while (k < 3000)` / `while (k < LIMIT)`(LIMIT 是 const)
506
+ # 也算可推——`bound_of_condition` 已经会把它算成 const 界,
507
+ # 检查器不该在这里唱反调。
508
+ for c in cond.children:
509
+ if getattr(c, "kind", "") == "lit-int":
510
+ return True
511
+ if getattr(c, "kind", "") == "path" and c.name and c.name.isupper():
512
+ return True
513
+ return False
514
+
515
+ return False
516
+ return False
517
+ if cond.kind == "unary" and (cond.value or "") == "not":
518
+ return False
519
+ return False
520
+
521
+
522
+ def _pred_of(cond: Node):
523
+ """T13 来源 ②:条件是不是一个谓词调用;返回 (谓词名, 节点) 或 (None, None)。"""
524
+ if cond is None:
525
+ return None, None
526
+ if cond.kind == "call" and cond.name:
527
+ return cond.name.split(".")[-1], cond
528
+ return None, None
529
+
530
+
531
+ # ---------------------------------------------------------------- benchmodel
532
+
533
+ MAX_SCALE_POINTS = 64
534
+
535
+
536
+ def _eval_range_points(node: Node, consts=None):
537
+ """把 `range(起, 止[, 步长])` 求成点列表;不合法返回 (None, 错误说明)。
538
+
539
+ `consts` 是模块级整数常量表(`const MAX_TOKENS: u64 = 4096;`),
540
+ 所以 `range(1, MAX_TOKENS, *2)` 合法——常量在编译期已知,不影响确定性。
541
+ """
542
+ if node is None or node.kind != "call":
543
+ return None, "scale 里 MUST 写 `range(起, 止[, 步长])`"
544
+ args = next((c for c in node.children if c.kind == "args"), None)
545
+ if args is None or len(args.children) < 2:
546
+ return None, "range 至少要有起、止两个参数"
547
+
548
+ def int_of(n):
549
+ if n.kind == "lit-int":
550
+ try:
551
+ return int(n.value)
552
+ except (TypeError, ValueError):
553
+ return None
554
+ # `-10` 会被 parse_range_args 包成 `step v=-`(因为它把首字符当步长符号),
555
+ # 也可能是 unary('-')。两种都要认,否则报错说不清原因。
556
+ if n.kind in ("step", "unary") and (n.value or "") in ("-", "+") and n.children:
557
+ inner = int_of(n.children[0])
558
+ if inner is None:
559
+ return None
560
+ return -inner if (n.value or "") == "-" else inner
561
+ if n.kind == "path" and consts is not None:
562
+ return consts.get(n.name)
563
+ return None
564
+
565
+ lo = int_of(args.children[0])
566
+ hi = int_of(args.children[1])
567
+ if lo is None or hi is None:
568
+ return None, "range 的起止 MUST 是整数字面量"
569
+
570
+ step_node = None
571
+ for c in args.children[2:]:
572
+ if c.kind == "step":
573
+ step_node = c
574
+ if step_node is None:
575
+ step_op, step_val = "+", 1
576
+ else:
577
+ step_op = step_node.value or "+"
578
+ step_val = int_of(step_node.children[0])
579
+ if step_val is None:
580
+ return None, "range 的步长 MUST 是整数字面量(暂不支持变量)"
581
+
582
+ if lo < 0 or hi < 0:
583
+ return None, "尺寸 MUST ≥ 0(尺寸是长度,不可能为负)"
584
+ if lo > hi:
585
+ return None, "range 的起点 MUST NOT 大于终点"
586
+
587
+ pts = []
588
+ if step_op == "*":
589
+ if step_val <= 1:
590
+ return None, f"步长 `*{step_val}` 违反「序列严格递增」(k MUST > 1)"
591
+ # 起点 0:0×k 永远是 0,按字面会得到 0,0,0… → 必须单独处理。
592
+ # 规则(规格 §4.7.2):序列为 0, 1, k, k², …
593
+ if lo == 0:
594
+ pts.append(0)
595
+ cur = 1
596
+ else:
597
+ cur = lo
598
+ while cur <= hi and len(pts) <= MAX_SCALE_POINTS:
599
+ pts.append(cur)
600
+ cur = cur * step_val
601
+ elif step_op == "+":
602
+ if step_val < 1:
603
+ return None, f"步长 `+{step_val}` 违反「序列严格递增」(k MUST ≥ 1)"
604
+ cur = lo
605
+ while cur <= hi and len(pts) <= MAX_SCALE_POINTS:
606
+ pts.append(cur)
607
+ cur = cur + step_val
608
+ else:
609
+ return None, f"步长运算符只能是 `*` 或 `+`,实际是 {step_op!r}"
610
+
611
+ if len(pts) > MAX_SCALE_POINTS:
612
+ return None, f"scale 点数超过上限 {MAX_SCALE_POINTS}"
613
+ return pts, None
614
+
615
+
616
+ #: 内置生成器(标准库函数)。MB-7 要求生成器是普通函数——
617
+ #: 这几个的 `spec` / `cost` / `effects` 由标准库提供,**用户不需要在自己 `.tu` 里重写**。
618
+ #: 其余名字 MUST 在用户的 `.tu` 里有 `spec`,否则报 `E-Bench-BadGenerator`。
619
+ BUILTIN_GENERATORS = frozenset({
620
+ "sorted_u64s", "random_u64s", "make_u8s", "make_texts", "any_of",
621
+ })
622
+
623
+
624
+ def _check_benchmodel(res, specs, choosers, impls, consts=None) -> None:
625
+ """MB-1..MB-12(§4.7.3)。"""
626
+ for name, sp in specs.items():
627
+ body = _spec_body(sp)
628
+ if body is None:
629
+ continue
630
+ bm = None
631
+ for c in body.children:
632
+ if c.kind == "benchmodel":
633
+ if bm is not None:
634
+ res.diagnostics.append(Diag(
635
+ "E-Bench-Duplicate",
636
+ f"spec {name} 只能有一个 benchmodel(v0.69)", c.line, c.col))
637
+ bm = c
638
+ elif c.kind == "clause" and (c.name or "") == "model":
639
+ res.diagnostics.append(Diag(
640
+ "E-Clause-OldModel",
641
+ "`model` 已下线(v0.69):改用 `benchmodel { data { … } scale { … } }`",
642
+ c.line, c.col))
643
+
644
+ has_choice = any(v.get("host") == name for v in choosers.values())
645
+
646
+ if bm is None:
647
+ if has_choice:
648
+ res.diagnostics.append(Diag(
649
+ "E-Bench-NoModel",
650
+ f"spec {name} 里有 `?!`,MUST 写 `benchmodel`(要测,就得说测什么数据、哪些规模)",
651
+ sp.line, sp.col))
652
+ continue
653
+ if not has_choice:
654
+ res.diagnostics.append(Diag(
655
+ "W-Bench-Unused",
656
+ f"spec {name} 没有 `?!`,benchmodel 不会被用到",
657
+ bm.line, bm.col, severity="warning"))
658
+
659
+ # ---- 形参名
660
+ params = {c.name for c in (_params_of(sp).children if _params_of(sp) else [])}
661
+
662
+ # ---- data 里的参数
663
+ data = next((c for c in bm.children if c.kind == "bench-data"), None)
664
+ scale = next((c for c in bm.children if c.kind == "bench-scale"), None)
665
+ in_data = set()
666
+ if data is not None:
667
+ for b in data.children:
668
+ if b.kind == "binding":
669
+ in_data.add(b.name)
670
+ if b.name not in params:
671
+ res.diagnostics.append(Diag(
672
+ "E-Bench-UnknownParam",
673
+ f"data 里的 {b.name} 不是 spec 的形参", b.line, b.col))
674
+
675
+ # ---- MB-13:data 的声明顺序 MUST 等于签名形参顺序
676
+ # (顺序错会静默把实参错位——实测跑错东西,且不报错)
677
+ if data is not None:
678
+ sig_order = [c.name for c in
679
+ (_params_of(sp).children if _params_of(sp) else [])]
680
+ got_order = [b.name for b in data.children if b.kind == "binding"]
681
+ common = [x for x in got_order if x in sig_order]
682
+ expect = [x for x in sig_order if x in got_order]
683
+ if common != expect:
684
+ res.diagnostics.append(Diag(
685
+ "E-Bench-OrderMismatch",
686
+ f"data 的顺序 MUST 与签名形参顺序一致:"
687
+ f"签名是 `{', '.join(sig_order)}`,data 写成了 `{', '.join(got_order)}`"
688
+ f"(顺序错会静默把实参错位)",
689
+ data.line, data.col))
690
+
691
+ # ---- MB-7 / E-Bench-BadGenerator:生成器 MUST 是普通函数(有 spec)
692
+ if data is not None:
693
+ for b in data.children:
694
+ if b.kind != "binding" or not b.children:
695
+ continue
696
+ callee = b.children[0]
697
+ gname = None
698
+ if callee.kind == "call":
699
+ gname = callee.name
700
+ elif callee.kind == "path":
701
+ gname = callee.name
702
+ if not gname:
703
+ continue
704
+ # 内置生成器(标准库)也有 spec,只是不在用户的 .tu 里——免于本检查
705
+ if gname in BUILTIN_GENERATORS:
706
+ continue
707
+ if gname not in specs:
708
+ res.diagnostics.append(Diag(
709
+ "E-Bench-BadGenerator",
710
+ f"生成器 `{gname}` 不是一个已声明的函数(MB-7 要求它有 "
711
+ f"`spec`);拼错名字或忘了声明 spec",
712
+ b.line, b.col))
713
+
714
+ # ---- MB-1:每个形参都要有 data
715
+ for pn in sorted(params - in_data):
716
+ res.diagnostics.append(Diag(
717
+ "E-Bench-MissingParam",
718
+ f"data 缺少形参 {pn} 的生成方式(每个参数都要说值从哪来)",
719
+ bm.line, bm.col))
720
+
721
+ # ---- scale
722
+ scaled: Set[str] = set()
723
+ if scale is not None:
724
+ for b in scale.children:
725
+ if b.kind != "scale-binding":
726
+ continue
727
+ scaled.add(b.name)
728
+ if b.name not in in_data:
729
+ res.diagnostics.append(Diag(
730
+ "E-Bench-UnknownParam",
731
+ f"scale 里的 {b.name} 没有在 data 中出现", b.line, b.col))
732
+ pts, err = _eval_range_points(b.children[0] if b.children else None, consts)
733
+ if err is not None:
734
+ res.diagnostics.append(Diag(
735
+ "E-Bench-BadStep", f"{b.name} 的规模写法有问题:{err}",
736
+ b.line, b.col))
737
+ elif len(pts) < 2:
738
+ res.diagnostics.append(Diag(
739
+ "E-Bench-BadStep",
740
+ f"{b.name} 的规模只有 {len(pts)} 个点,至少要 2 个(否则无法比较)",
741
+ b.line, b.col))
742
+
743
+ # ---- MB-8:成本式里出现的尺寸变量都要有 scale,且至少 2 个
744
+ # (成本式检查放在 §7.8 的实现里;此处只查"一个都没写")
745
+ if scale is None or not scaled:
746
+ # **注意优先级**:`parser.py` 通常已经先抛同名错误(文案带"必写"),
747
+ # 所以这条只是兜底;两条文案必须一致,否则用户会看到两种说法。
748
+ res.diagnostics.append(Diag(
749
+ "E-Bench-MissingScale",
750
+ "benchmodel 缺少 `scale` 段(测哪些规模,必写)", bm.line, bm.col,
751
+ actions=[Restart(
752
+ "edit", "补一个 scale 骨架(把 xs 换成你的容器名)",
753
+ patch={"file": (module or "a") + ".tu",
754
+ "line": bm.line,
755
+ "text": "scale { xs in range(1, 4096, *2); }"})]))
756
+
757
+
758
+ def _check_sort_calls(res, all_fns) -> None:
759
+ """`sort` / `sort_by` 的实参形状(L3)。
760
+
761
+ **比较器 MUST 是具名函数**且签名 `(T, T) -> bool`。
762
+ 理由:C 的 `qsort` 打穿成本契约,不是因为「带比较器」,是因为
763
+ 「比较器是任意代码」。具名函数是有限集合,`O(n log n × κ(cmp))` 才写得出来。
764
+ """
765
+ by_name = {fn.name: fn for fn in all_fns}
766
+ for fn in all_fns:
767
+ for call in walk(fn, "call"):
768
+ nm = call.name or ""
769
+ if nm not in ("sort", "sort_by"):
770
+ continue
771
+ args_node = next((c for c in call.children if c.kind == "args"), None)
772
+ items = args_node.children if args_node is not None else []
773
+ if nm == "sort":
774
+ if len(items) != 1:
775
+ res.diagnostics.append(Diag(
776
+ "E-Sort-BadArgs",
777
+ f"sort 要 1 个实参(容器),给了 {len(items)} 个",
778
+ call.line, call.col))
779
+ continue
780
+ if len(items) != 2:
781
+ res.diagnostics.append(Diag(
782
+ "E-Sort-BadArgs",
783
+ f"sort_by 要 2 个实参(容器 + 具名比较器),给了 {len(items)} 个",
784
+ call.line, call.col))
785
+ continue
786
+ cmp_node = items[1]
787
+ if cmp_node.kind != "path":
788
+ res.diagnostics.append(Diag(
789
+ "E-Sort-BadComparator",
790
+ "sort_by 的比较器 MUST 是具名函数"
791
+ f"(给的是 {cmp_node.kind})——"
792
+ "匿名比较器是任意代码,成本不可静态界定,会打穿成本契约",
793
+ cmp_node.line, cmp_node.col))
794
+ continue
795
+ target = by_name.get(cmp_node.name or "")
796
+ if target is None:
797
+ res.diagnostics.append(Diag(
798
+ "E-Sort-BadComparator",
799
+ f"sort_by 的比较器 `{cmp_node.name}` 不是本模块的函数",
800
+ cmp_node.line, cmp_node.col))
801
+ continue
802
+ params = walk(target, "param")
803
+ if len(params) != 2:
804
+ res.diagnostics.append(Diag(
805
+ "E-Sort-BadComparator",
806
+ f"比较器 `{target.name}` 要 2 个形参,它有 {len(params)} 个",
807
+ cmp_node.line, cmp_node.col))
808
+
809
+
810
+ def _has_recursion_depth(spec: Node) -> bool:
811
+ """`.tu` 里是否写了 `recursion depth <= N;`(规格 C11-b)。"""
812
+ return any((c.name or "") == "recursion" for c in _clauses(spec))
813
+
814
+
815
+ def _recursion_cycles(fns: Dict[str, Node]) -> Dict[str, List[str]]:
816
+ """普通调用图上的**递归**:`{函数名: 一条回到自己的路径}`。
817
+
818
+ 只走 `call` 边;`?!` 的候选环是另一套规则(见 `_check_cycles`)。
819
+ 环上**每个**成员都会出现在返回值的键里(互递归 a→b→a 时两个都算)。
820
+ """
821
+ edges: Dict[str, Set[str]] = {}
822
+ for name, fn in fns.items():
823
+ out = set()
824
+ for call in walk(fn, "call"):
825
+ nm = callee_name(call)
826
+ if nm and nm in fns:
827
+ out.add(nm)
828
+ edges[name] = out
829
+
830
+ cyc: Dict[str, List[str]] = {}
831
+ for start in sorted(edges):
832
+ # 从 start 的后继出发,看能否沿 `call` 边走回 start
833
+ stack: List[Tuple[str, List[str]]] = [
834
+ (m, [start, m]) for m in sorted(edges[start], reverse=True)]
835
+ seen = set()
836
+ while stack:
837
+ node, path = stack.pop()
838
+ if node == start:
839
+ cyc[start] = path
840
+ break
841
+ if node in seen:
842
+ continue
843
+ seen.add(node)
844
+ for m in sorted(edges.get(node, ()), reverse=True):
845
+ stack.append((m, path + [m]))
846
+ return cyc
847
+
848
+
849
+ def check_recursion_depth(impls: Dict[str, Node],
850
+ specs: Dict[str, Node]) -> List[Diag]:
851
+ """C11-b:**有递归就必须声明 `recursion depth <= N`**,否则编译期报错。
852
+
853
+ 为什么要报错而不是警告:深度是契约的一部分。不声明时 κ 只算**一层**,
854
+ 于是"承诺上界"会**沉默地**小于真实成本(`down(xs,8)`:κ=33 / ops=104)。
855
+ 这类错误在成本表上看起来一切正常,是最坏的一种。
856
+ """
857
+ diags: List[Diag] = []
858
+ for name, path in sorted(_recursion_cycles(impls).items()):
859
+ spec = specs.get(name)
860
+ if spec is None:
861
+ continue # 没有 spec 由别的诊断负责(E-Spec-Missing)
862
+ if _has_recursion_depth(spec):
863
+ continue
864
+ diags.append(Diag(
865
+ "E-Recursion-Unbounded",
866
+ f"`{name}` 有递归({' → '.join(path)}),但 `.tu` 没有 "
867
+ f"`recursion depth <= N`:κ 只能按一层计,**会小于真实成本**(C11-b)。"
868
+ f"出路:① 在 `spec {name}` 里补 `recursion depth <= 8;`(写真实上界);"
869
+ f"② 改写成循环;③ 若确实无界,这个函数不能带 `target` 承诺",
870
+ spec.line, spec.col))
871
+ return diags
872
+
873
+
874
+ def _check_while_bounds(res, all_fns, specs, strict: bool,
875
+ ai_src: Optional[str] = None,
876
+ fn_file: Optional[str] = None) -> None:
877
+ """给每个 `while` 判定上界来源;③ 类按严格模式分档处理。"""
878
+ from bound import progresses
879
+ for fn in all_fns:
880
+ # 模块级 `const N: u64 = 256;` 也是编译期常量,
881
+ # 拿它当循环上界(`while (k < N)`)完全可辩护 —— 一并算进来。
882
+ # 递减循环(甲):本函数里「只做减法」的变量,`while (j > 0)` 可用
883
+ dec_vars = _monotone_decreasing_names(fn)
884
+ const_sizes = (_collect_const_sizes(fn)
885
+ | _collect_param_sizes(fn)
886
+ | set(_MODULE_CONST_SIZES))
887
+ for wh in walk(fn, "while"):
888
+ cond = wh.children[0] if wh.children else None
889
+
890
+ # **E21(unsound)**:循环体不推进计数器 ⇒ 死循环。
891
+ # 这一条 MUST 是 error,**不受 strict 影响**:它不是风格问题,是上界不成立。
892
+ ok, prog_why = progresses(wh)
893
+ if not ok:
894
+ res.diagnostics.append(Diag(
895
+ "E-Loop-CounterUnchanged",
896
+ f"{prog_why} —— 这会变成死循环(成本为 ∞),不能给出有限上界。"
897
+ f"出路:① 在体内推进它(`i = i + 1` / `q.pop()`);"
898
+ f"② 若确实由外部条件控制,改成有界循环,并把那个上界**写成 benchmodel 的输入**",
899
+ wh.line, wh.col, severity="error"))
900
+ continue
901
+
902
+ # 来源 ①:条件形态可推
903
+ if _cond_can_bound(cond, const_sizes):
904
+ continue
905
+
906
+ # 来源 ①-b:**递减循环**(`while (j > 0)` 且 j 体内只做减法)
907
+ # 上界 = j 的初值。插入排序、堆的上浮/下沉都是这个形状——
908
+ # 不认它,作者会被逼改成选择排序(失去稳定性)或固定圈数(成本式被撑大)。
909
+ if _dec_loop_can_bound(cond, dec_vars):
910
+ continue
911
+
912
+ # 来源 ②:条件是谓词且该谓词声明了 repeats
913
+ name, _ = _pred_of(cond)
914
+ if name is not None:
915
+ sp = specs.get(name)
916
+ if sp is not None:
917
+ body = next((c for c in sp.children if c.kind == "spec-body"), None)
918
+ has_repeats = any(
919
+ c.kind == "clause" and (c.name or "") == "repeats"
920
+ for c in (body.children if body else [])
921
+ )
922
+ if has_repeats:
923
+ continue
924
+ # 谓词存在但没写 repeats → 给出精确 hint
925
+ res.diagnostics.append(Diag(
926
+ "E-While-NoBound",
927
+ f"while 条件调用了 {name}(),但 {name} 的 spec 没有 repeats;"
928
+ f"请在 spec {name} 里加 `repeats <表达式>;`(T13 来源②)",
929
+ wh.line, wh.col,
930
+ severity="error" if strict else "warning"))
931
+ continue
932
+
933
+ # 来源 ③:都推不出
934
+ hint = ("三条出路:① 若条件可用尺寸比较表达,改写成 `while (i < xs.length())`;"
935
+ "② 若条件是个函数,把上界写进该函数的 spec 的 repeats;"
936
+ "③ 否则改写成 for + break")
937
+ _v = getattr(cond.children[0], "name", None) if (
938
+ cond is not None and getattr(cond, "children", None)) else None
939
+ _vec = _first_vec_param(fn)
940
+ res.diagnostics.append(Diag(
941
+ "E-While-NoBound",
942
+ f"无法确定 while 的迭代次数。{hint}",
943
+ wh.line, wh.col,
944
+ severity="error" if strict else "warning",
945
+ actions=_acts(_line_patch(
946
+ ai_src, fn_file or ((module or "a") + ".eln"), wh.line,
947
+ lambda s, a=_v, b=_vec: _rewrite_cond(s, a, b),
948
+ f"把条件改成 `{_v} < {_vec}.length()`(若这是遍历整个容器)"))))
949
+
950
+
951
+ def _fn_type_params_of(fn) -> set:
952
+ """函数签名里的类型参数名:`func id<T>(…)` → {"T"}。"""
953
+ out = set()
954
+ for c in getattr(fn, "children", []) or []:
955
+ if getattr(c, "kind", "") == "type-params":
956
+ for p in c.children:
957
+ out.add(p.name or "")
958
+ return out
959
+
960
+
961
+ def _type_compatible(spec_t: str, impl_t: str, tparams: set) -> bool:
962
+ """`Vec<u64>` 与 `Vec<T>` 是否相容:**类型参数当通配符**。"""
963
+ if not tparams:
964
+ return False
965
+ import re
966
+ def norm(s):
967
+ s = s.replace(" ", "")
968
+ for p in tparams:
969
+ s = re.sub(r"\b" + re.escape(p) + r"\b", "?", s)
970
+ return s
971
+ a, b = norm(spec_t), norm(impl_t)
972
+ if "?" not in b and "?" not in a:
973
+ return False
974
+ # 逐字符比:`?` 匹配任意标识符片段(简化:去掉泛型实参名字后比较外层结构)
975
+ def shape(s):
976
+ return re.sub(r"<[^<>]*>", "<*>", s)
977
+ return shape(a) == shape(b) or "?" in b
978
+
979
+
980
+ def _canon_type_str(s: str) -> str:
981
+ """把类型字符串里的容器名换成规范名(`Vec` / `vector` 视为同一个)。
982
+
983
+ 改名期两套名字都要能用:`.tu` 写 `Vec<u8>&`、`.eln` 写 `vector<u8>&`
984
+ 必须判为**同一个签名**——否则一半改一半不改就报 E-Spec-SigMismatch。
985
+ """
986
+ if not s:
987
+ return s
988
+ for _old, _new in (("FixedVec", "array"), ("Vec", "vector"), ("Map", "map"),
989
+ ("Set", "set"), ("Deque", "deque"), ("Option", "optional")):
990
+ s = re.sub(r"\b" + _old + r"\b", _new, s)
991
+ return s
992
+
993
+
994
+ def _params_compatible(a, b, tparams: set) -> bool:
995
+ if len(a) != len(b):
996
+ return False
997
+ for (_, ta), (_, tb) in zip(a, b):
998
+ if ta == tb:
999
+ continue
1000
+ if not _type_compatible(ta, tb, tparams):
1001
+ return False
1002
+ return True
1003
+
1004
+
1005
+ # ---------------------------------------------------------------- 泛型推断(A 第一批)
1006
+ #
1007
+ # **这一批只做"推断 + 登记 + 报错"**,不做代码生成:
1008
+ # 解释器是动态的,单态化在语义上不必要;但**类型参数必须能定下来**,
1009
+ # 否则"这个函数到底对什么类型成立"这件事没人知道。
1010
+
1011
+ def _type_str_of_node(n) -> str:
1012
+ """把类型节点还原成字符串(`Vec<T>` / `Vec<u64>` / `u64`)。"""
1013
+ if n is None:
1014
+ return ""
1015
+ if getattr(n, "kind", "") in ("type-name", "type-ref"):
1016
+ args = next((c for c in n.children if c.kind == "type-args"), None)
1017
+ if n.kind == "type-ref":
1018
+ inner = next((c for c in n.children if c.kind in ("type-name", "type-ref")), None)
1019
+ base = _type_str_of_node(inner) if inner is not None else (n.name or "")
1020
+ else:
1021
+ base = n.name or ""
1022
+ if args is None:
1023
+ return base
1024
+ return base + "<" + ", ".join(_type_str_of_node(a) for a in args.children) + ">"
1025
+ return getattr(n, "name", "") or ""
1026
+
1027
+
1028
+ def _unify(pattern: str, actual: str, bind: dict) -> bool:
1029
+ """`Vec<T>` vs `Vec<u64>` → bind {T: u64};冲突返回 False。"""
1030
+ import re as _re
1031
+ if not pattern:
1032
+ return True
1033
+ if "<" not in pattern:
1034
+ if pattern.isupper() and len(pattern) <= 2: # `T` / `K` / `V`
1035
+ if pattern in bind:
1036
+ return bind[pattern] == actual
1037
+ bind[pattern] = actual
1038
+ return True
1039
+ return pattern == actual or not actual
1040
+ pm = _re.match(r"^([^<]+)<(.*)>$", pattern)
1041
+ am = _re.match(r"^([^<]+)<(.*)>$", actual or "")
1042
+ if not pm or not am:
1043
+ return False
1044
+ if pm.group(1).strip() != am.group(1).strip():
1045
+ return False
1046
+ ps, as_ = pm.group(2), am.group(2)
1047
+ # 顶层逗号切分
1048
+ def split(s):
1049
+ out, depth, cur = [], 0, ""
1050
+ for ch in s:
1051
+ if ch == "<":
1052
+ depth += 1
1053
+ elif ch == ">":
1054
+ depth -= 1
1055
+ if ch == "," and depth == 0:
1056
+ out.append(cur.strip())
1057
+ cur = ""
1058
+ else:
1059
+ cur += ch
1060
+ if cur.strip():
1061
+ out.append(cur.strip())
1062
+ return out
1063
+ p_parts, a_parts = split(ps), split(as_)
1064
+ if len(p_parts) != len(a_parts):
1065
+ return False
1066
+ return all(_unify(x, y, bind) for x, y in zip(p_parts, a_parts))
1067
+
1068
+
1069
+ def _local_types(fn) -> dict:
1070
+ """函数内"名字 → 类型字符串"(形参 + 局部声明)。"""
1071
+ env = {}
1072
+ ps = next((c for c in fn.children if c.kind == "params"), None)
1073
+ for p in (ps.children if ps else []):
1074
+ ty = next((c for c in p.children if c.kind in ("type-ref", "type-name")), None)
1075
+ env[p.name or ""] = _type_str_of_node(ty)
1076
+ for n in _all_nodes(fn):
1077
+ if getattr(n, "kind", "") in ("var-decl", "const-decl"):
1078
+ ty = next((c for c in n.children if c.kind in ("type-ref", "type-name")), None)
1079
+ env[n.name or ""] = _type_str_of_node(ty)
1080
+ return env
1081
+
1082
+
1083
+ def _check_generic_calls(impl_mod, specs) -> List[Diag]:
1084
+ diags: List[Diag] = []
1085
+ generic = {}
1086
+ for fn in _all_nodes(impl_mod):
1087
+ if getattr(fn, "kind", "") != "fn":
1088
+ continue
1089
+ tp = next((c for c in fn.children if c.kind == "type-params"), None)
1090
+ if tp is not None:
1091
+ generic[fn.name or ""] = (fn, [p.name for p in tp.children])
1092
+ if not generic:
1093
+ return diags
1094
+ for owner in _all_nodes(impl_mod):
1095
+ if getattr(owner, "kind", "") != "fn":
1096
+ continue
1097
+ env = _local_types(owner)
1098
+ for call in _all_nodes(owner):
1099
+ if getattr(call, "kind", "") != "call":
1100
+ continue
1101
+ short = (call.name or "").split(".")[-1]
1102
+ if short not in generic:
1103
+ continue
1104
+ callee, tparams = generic[short]
1105
+ bind: dict = {}
1106
+ ps = next((c for c in callee.children if c.kind == "params"), None)
1107
+ plist = ps.children if ps else []
1108
+ args = next((c for c in call.children if c.kind == "args"), None)
1109
+ alist = args.children if args else []
1110
+ for pat_param, a in zip(plist, alist):
1111
+ pt = next((c for c in pat_param.children
1112
+ if c.kind in ("type-ref", "type-name")), None)
1113
+ pat = _type_str_of_node(pt)
1114
+ at = env.get(a.name or "", "") if getattr(a, "kind", "") == "path" else ""
1115
+ _unify(pat, at, bind)
1116
+ missing = [p for p in tparams if p not in bind]
1117
+ if missing:
1118
+ diags.append(Diag(
1119
+ "E-Type-InferFailed",
1120
+ f"调用泛型函数 {short} 时推不出类型参数 {', '.join(missing)}——"
1121
+ f"给实参加类型标注,或在声明里用具体类型",
1122
+ call.line, call.col))
1123
+ return diags
1124
+
1125
+
1126
+ #: `_call_inner` 里有专门分支的内建——不算"未声明调用"
1127
+ _CALL_BUILTIN = {"min", "max", "Ok", "Err", "Some", "None", "panic", "unwrap",
1128
+ "expect", "assert", "print", "println", "dbg",
1129
+ "for_each", "map", "filter", "fold", "count_if", "sort", "sort_by", "swap",
1130
+ "push_heap", "pop_heap"}
1131
+
1132
+
1133
+ def unknown_calls(tu_mod, ch_mod) -> list:
1134
+ """**E18**:找出分析器不认识的调用名。
1135
+
1136
+ 判据:不在用户函数里、不是 stdlib、不是已声明 `extern`、不是语言内建。
1137
+ 方法调用(`xs.length()`)走成员派发,不在这个兜底里。
1138
+
1139
+ 为什么需要它:`_call_inner` 遇到这种调用会记 `1 + 实参`,
1140
+ **把被调函数体当成 0 成本**——对内部一无所知时这不是上界。
1141
+ """
1142
+ try:
1143
+ import stdlib as _sl
1144
+ from bound import _descendants as _desc
1145
+ except Exception: # noqa: BLE001
1146
+ return []
1147
+ fns, externs = set(), set()
1148
+ for m in (tu_mod, ch_mod):
1149
+ if m is None:
1150
+ continue
1151
+ for n in (getattr(m, "children", None) or []):
1152
+ if getattr(n, "kind", "") in ("func", "fn", "kernel") and getattr(n, "name", None):
1153
+ fns.add(n.name)
1154
+ # **以 `CostInterp` 自己的登记表为准**——它已经把三种写法都解析过了
1155
+ # (顶层 `extern`、spec 里的 `external { … }`、`external "lib" { … }`),
1156
+ # 我们再猜一遍形状只会漂。构造失败就退化成"没有已声明项"。
1157
+ try:
1158
+ from cost_interp import CostInterp as _CI
1159
+ _ci = _CI(ch_mod, tu_mod)
1160
+ for _a in ("externs", "extern_spec_names", "extern_names"):
1161
+ externs |= set(getattr(_ci, _a, set()) or set())
1162
+ except Exception: # noqa: BLE001
1163
+ pass
1164
+
1165
+ out = {}
1166
+ for c in (_desc(ch_mod, "call") if ch_mod is not None else []):
1167
+ nm = getattr(c, "name", None) or ""
1168
+ if "." in nm or "::" in nm:
1169
+ continue
1170
+ if (not nm or nm in fns or nm in externs
1171
+ or nm in _CALL_BUILTIN or _sl.is_stdlib(nm)):
1172
+ continue
1173
+ out.setdefault(nm, getattr(c, "line", None))
1174
+ return sorted(out.items(), key=lambda kv: (kv[1] or 0))
1175
+
1176
+
1177
+ def check_module(tu_src: str, ai_src: Optional[str], module: str = "<module>",
1178
+ strict: bool = False, overflow: str = "off") -> CheckResult:
1179
+ res = CheckResult(module=module)
1180
+
1181
+ tu = parse_source(tu_src, module + ".tu")
1182
+ # 模块级常量名(`const N: u64 = 256;`)——循环上界可以用它们
1183
+ _MODULE_CONST_SIZES.clear()
1184
+ for mod_ast in ([tu.module] if tu.module else []):
1185
+ for it in mod_ast.children:
1186
+ if it.kind == "const" and it.name:
1187
+ _MODULE_CONST_SIZES.add(it.name)
1188
+ for d in tu.diagnostics:
1189
+ res.diagnostics.append(Diag(d.code, "[.tu] " + d.message,
1190
+ d.line, d.col, d.start, d.end))
1191
+
1192
+ ai = None
1193
+ if ai_src is not None:
1194
+ ai = parse_source(ai_src, module + ".eln")
1195
+ for d in ai.diagnostics:
1196
+ res.diagnostics.append(Diag(d.code, "[.eln] " + d.message,
1197
+ d.line, d.col, d.start, d.end))
1198
+
1199
+ # **E18(方案 B)**:未声明的外部调用 → 报错,而不是悄悄记 1。
1200
+ # 记 1 等于把被调函数体当成 0 成本;对一个可能跑 10⁶ 步的调用,κ 就不再是上界。
1201
+ for _nm, _ln in unknown_calls(tu.module if tu else None,
1202
+ ai.module if ai is not None else None):
1203
+ res.diagnostics.append(Diag(
1204
+ "E-Call-Undeclared",
1205
+ f"调用了未声明的外部函数 `{_nm}`:它的成本无法推导,"
1206
+ f"而「记 1 个操作」**不是上界**(E18)。"
1207
+ f"在 spec 里声明一行:`external {{ {_nm}: O(n); }};`(把 `O(n)` 换成它真实的界)",
1208
+ _ln or 1, 1, severity="error"))
1209
+
1210
+ tu_items = tu.module.children if tu.module else []
1211
+ ai_items = ai.module.children if (ai is not None and ai.module is not None) else []
1212
+
1213
+ # ---- `guarantees`:可检查 / 不可检查(v0.72)
1214
+ #
1215
+ # 以前 `guarantees` 是"能写、没人看"——一个**假的承诺位**。
1216
+ # 现在分两类:可检查的进运行时校验(`I-Guarantee-Runtime`),
1217
+ # 不可检查的**必须**报出来(`E-Guarantee-Uncheckable`),要求改写或注释掉。
1218
+ try:
1219
+ import guarantees as _gt
1220
+ for _it in tu_items:
1221
+ if _it.kind != "spec" or not _gt.has_guarantees(_it):
1222
+ continue
1223
+ _ok, _bad = _gt.classify(_it)
1224
+ if _bad:
1225
+ res.diagnostics.append(Diag(
1226
+ "E-Guarantee-Uncheckable",
1227
+ f"{_it.name} 的 guarantees 无法检查:{_bad[0]};"
1228
+ f"可检查的谓词只有 {', '.join(sorted(_gt.CHECKABLE))},"
1229
+ f"否则请改写(或把这行注释掉——`assume` 已移除)",
1230
+ _it.line, _it.col, severity="warning",
1231
+ actions=[Restart(
1232
+ # **以前这里写着字面占位符 `<原来的条件>`**:真应用了
1233
+ # 就是往文件里写这行字。现在给出**真实的那一行**。
1234
+ "edit", "把这行 promises 注释掉(旧的「降级成 assume」已随 assume 一起移除)",
1235
+ # **行号取 `guarantees` 子句那一行,不是 spec 那一行**——
1236
+ # 取 spec 行会改到 `spec a(...) {` 上去(实测踩过)。
1237
+ patch={"file": (module or "a") + ".tu",
1238
+ "line": _guarantees_line(_it),
1239
+ "text": _demote_guarantees(tu_src,
1240
+ _guarantees_line(_it))})]))
1241
+ elif _ok:
1242
+ res.diagnostics.append(Diag(
1243
+ "I-Guarantee-Runtime",
1244
+ f"{_it.name} 的 guarantees({_gt.describe(_ok)})将在 run 时校验",
1245
+ _it.line, _it.col, severity="info"))
1246
+ except Exception: # noqa: BLE001
1247
+ pass # 分类失败不该让整个检查崩掉
1248
+
1249
+ # ---- 严格模式:L3 / L4 / L5
1250
+ if strict:
1251
+ res.diagnostics.extend(strict_lints(tu_src, tu, ".tu"))
1252
+ if ai is not None and ai_src is not None:
1253
+ res.diagnostics.extend(strict_lints(ai_src, ai, ".eln"))
1254
+
1255
+ # ---- F-4 / F-8:.ai 不得有声明与 use
1256
+ ILLEGAL_IN_AI = {"const", "enum", "struct", "spec", "choose",
1257
+ "use", "error-decl"}
1258
+ for it in ai_items:
1259
+ if it.kind in ILLEGAL_IN_AI:
1260
+ code = "E-Ai-HasUse" if it.kind == "use" else "E-Ai-HasDecl"
1261
+ res.diagnostics.append(Diag(
1262
+ code, f".ai 中不得出现 {it.kind}(F-4/F-8)", it.line, it.col))
1263
+
1264
+ # ---- 用户函数调用的 arity(v0.72)
1265
+ #
1266
+ # 以前只校验内建(`stdlib.arity`),**用户函数完全不查**:
1267
+ # `g(1)` 传给两参函数,`check` 零诊断,直到运行期才炸。
1268
+ try:
1269
+ _spec_params = {}
1270
+ for _it in tu_items:
1271
+ if _it.kind != "spec" or not _it.name:
1272
+ continue
1273
+ _ps = next((c for c in _it.children if c.kind == "params"), None)
1274
+ _spec_params[_it.name] = len(_ps.children) if _ps else 0
1275
+ if ai is not None and ai.module is not None:
1276
+ for _call in walk(ai.module, "call"):
1277
+ _nm = (_call.name or "").split(".")[-1]
1278
+ if _nm not in _spec_params:
1279
+ continue
1280
+ _an = next((c for c in _call.children if c.kind == "args"), None)
1281
+ _got = len(_an.children) if _an else 0
1282
+ _want = _spec_params[_nm]
1283
+ if _got != _want:
1284
+ res.diagnostics.append(Diag(
1285
+ "E-Call-Arity",
1286
+ f"{_nm} 需要 {_want} 个实参,给了 {_got} 个",
1287
+ _call.line, _call.col))
1288
+ except Exception: # noqa: BLE001
1289
+ pass
1290
+
1291
+ # ---- 收集声明
1292
+ specs: Dict[str, Node] = {}
1293
+ kernels_decl: Dict[str, Node] = {}
1294
+ choosers: Dict[str, Node] = {}
1295
+ error_decl: Optional[Node] = None
1296
+
1297
+ for it in tu_items:
1298
+ if it.kind == "error-decl":
1299
+ if error_decl is not None:
1300
+ res.diagnostics.append(Diag(
1301
+ "E-Dup-Error", "模块级 `error` 声明只能有一个(v0.68)",
1302
+ it.line, it.col,
1303
+ actions=_acts(_line_patch(
1304
+ tu_src, (module or "a") + ".tu", it.line,
1305
+ lambda s: "// " + s.strip() + " // ← 重复的 error 声明",
1306
+ "把重复的那一行注释掉(保留第一个)"))))
1307
+ error_decl = it
1308
+ elif it.kind == "spec":
1309
+ specs[it.name] = it
1310
+ elif it.kind == "kernel":
1311
+ kernels_decl[it.name] = it
1312
+ elif it.kind == "choose":
1313
+ choosers[it.name] = it
1314
+
1315
+ # ---- 收集实现
1316
+ impls: Dict[str, Node] = {}
1317
+ kernels_impl: Dict[str, Node] = {}
1318
+ for it in ai_items:
1319
+ if it.kind == "fn":
1320
+ impls[it.name] = it
1321
+ elif it.kind == "kernel":
1322
+ kernels_impl[it.name] = it
1323
+
1324
+ # ---- 重名:同名声明/实现只能出现一次
1325
+ _dup_check(res, tu_items, "spec", "E-Duplicate-Spec")
1326
+ _dup_check(res, tu_items, "kernel", "E-Duplicate-Kernel")
1327
+ _dup_check(res, tu_items, "choose", "E-Duplicate-Choose")
1328
+ _dup_check(res, ai_items, "fn", "E-Duplicate-Fn")
1329
+ _dup_check(res, ai_items, "kernel", "E-Duplicate-Kernel")
1330
+
1331
+ # ---- 未知子句名 / target 槽位 / objective 取值
1332
+ KNOWN_CLAUSES = {
1333
+ "effects", "requires", "guarantees", "benchmodel", "target",
1334
+ "sizes", "repeats", "recursion", "from", "external",
1335
+ }
1336
+ OBJECTIVES = {"time", "p99", "mem", "size"}
1337
+ # 旧名(v0.62 及以前)→ 给出改名提示,而不是笼统的"取值非法"
1338
+ OLD_OBJECTIVES = {"minimize_expected_time", "minimize_p99",
1339
+ "minimize_peak_mem", "minimize_code_size"}
1340
+ for it in tu_items:
1341
+ if it.kind != "spec":
1342
+ continue
1343
+ body = _spec_body(it)
1344
+ if body is None:
1345
+ continue
1346
+ for c in body.children:
1347
+ if c.kind == "clause" and c.name not in KNOWN_CLAUSES:
1348
+ res.diagnostics.append(Diag(
1349
+ "E-Clause-Unknown", f"未知子句 {c.name}", c.line, c.col,
1350
+ actions=_acts(_line_patch(
1351
+ tu_src, (module or "a") + ".tu", c.line,
1352
+ lambda s: "// " + s.strip() + " // ← 未知子句,已注释",
1353
+ "把这一行注释掉(保留痕迹,不直接删)"))))
1354
+ if c.kind == "clause" and c.name == "target":
1355
+ # **未知成本维度**:`target { peak: … }` 以前会被**静默接受**——
1356
+ # 写了维度却什么都不检查,等于一个看不见的空承诺(G8 的教训)。
1357
+ _KNOWN_DIMS = {"time", "allocation"}
1358
+ for dim in c.children:
1359
+ if dim.kind == "dim" and (dim.name or "") not in _KNOWN_DIMS:
1360
+ res.diagnostics.append(Diag(
1361
+ "E-Target-Dim-Unknown",
1362
+ "成本维度 %s 还没实现(现有:time / allocation)。" % dim.name
1363
+ + "峰值与栈占用是有意不做,理由见 文档/设计/未来设计/挂起-G8峰值与栈.md",
1364
+ dim.line, dim.col))
1365
+ for dim in c.children:
1366
+ for slot in dim.children:
1367
+ if slot.kind == "slot" and slot.name not in ("min", "max", "exact"):
1368
+ _bad = slot.name or ""
1369
+ res.diagnostics.append(Diag(
1370
+ "E-Target-BadSlot",
1371
+ f"target 槽位只能是 min/max/exact,实际 {slot.name}",
1372
+ slot.line, slot.col,
1373
+ actions=_acts(_target_slot_fix(
1374
+ tu_src, (module or "a") + ".tu", slot.line, _bad))))
1375
+
1376
+ # ---- F-1:实现必须有声明
1377
+ for name, fn in impls.items():
1378
+ if name not in specs and name not in kernels_decl:
1379
+ res.diagnostics.append(Diag(
1380
+ "E-Fn-NoSpec", f"函数 {name} 在 .tu 中没有对应 spec(F-1)",
1381
+ fn.line, fn.col,
1382
+ actions=[Restart("edit", "在 .tu 末尾插入 spec 骨架(target 要你自己填)",
1383
+ patch={"file": (module or "a") + ".tu",
1384
+ "line": len((tu_src or "").splitlines()) + 1,
1385
+ "text": _spec_skeleton(ai_src, fn)})]))
1386
+
1387
+ # ---- F-2:签名一致
1388
+ for name, fn in impls.items():
1389
+ spec = specs.get(name)
1390
+ if spec is None:
1391
+ continue
1392
+ a = param_list(spec)
1393
+ b = param_list(fn)
1394
+ # **泛型函数的签名允许用类型参数**(`func id<T>(const Vec<T>&)` 实现 `Vec<u64>` 的 spec)。
1395
+ # 第一批只做"类型参数是通配符":`Vec<T>` 可与任意 `Vec<X>` 相容。
1396
+ _tparams = _fn_type_params_of(fn)
1397
+ a = [(n, _canon_type_str(ty)) for n, ty in a]
1398
+ b = [(n, _canon_type_str(ty)) for n, ty in b]
1399
+ if not _params_compatible(a, b, _tparams):
1400
+ res.diagnostics.append(Diag(
1401
+ "E-Spec-SigMismatch",
1402
+ f"{name} 的参数类型不一致:.tu=({', '.join(t for _, t in a)}) "
1403
+ f"vs .ai=({', '.join(t for _, t in b)})",
1404
+ fn.line, fn.col))
1405
+ continue
1406
+ ra, rb = type_str(_return_of(spec)), type_str(_return_of(fn))
1407
+ ra, rb = _canon_type_str(ra), _canon_type_str(rb)
1408
+ if ra != rb and not _type_compatible(ra, rb, _tparams):
1409
+ res.diagnostics.append(Diag(
1410
+ "E-Spec-SigMismatch",
1411
+ f"{name} 的返回类型不一致:.tu={ra or '(无)'} vs .ai={rb or '(无)'}",
1412
+ fn.line, fn.col))
1413
+
1414
+ # ---- 候选声明:来自 spec 里的 choose(v0.66)
1415
+ choosers: Dict[str, dict] = {}
1416
+ for spec_name, spec in specs.items():
1417
+ body = _spec_body(spec)
1418
+ if body is None:
1419
+ continue
1420
+ for c in body.children:
1421
+ if c.kind != "choose":
1422
+ continue
1423
+ label = c.name or ""
1424
+ if label in choosers:
1425
+ res.diagnostics.append(Diag(
1426
+ "E-Duplicate-Choose", f"choose {label} 重复定义", c.line, c.col))
1427
+ continue
1428
+ over: List[str] = []
1429
+ pending: List[str] = []
1430
+ objective = ""
1431
+ for cc in c.children:
1432
+ if cc.kind != "choose-clause":
1433
+ continue
1434
+ if cc.name == "over":
1435
+ v = cc.value
1436
+ if isinstance(v, dict):
1437
+ over = list(v.get("names") or [])
1438
+ pending = list(v.get("pending") or [])
1439
+ else:
1440
+ over = list(v or [])
1441
+ elif cc.name == "pending":
1442
+ res.diagnostics.append(Diag(
1443
+ "E-Choose-PendingClause",
1444
+ "v0.66 起没有 pending 子句:写在 over 里,如 `over {a, b pending}`",
1445
+ cc.line, cc.col))
1446
+ elif cc.name == "objective":
1447
+ objective = str(cc.value or "")
1448
+
1449
+ choosers[label] = {
1450
+ "node": c, "host": spec_name, "over": over, "pending": pending,
1451
+ "objective": objective,
1452
+ "params": param_list(c),
1453
+ "ret": type_str(_return_of(c)),
1454
+ }
1455
+ res.choices[label] = {"over": over, "pending": pending,
1456
+ "objective": objective, "host": spec_name}
1457
+
1458
+ if objective:
1459
+ if objective in OLD_OBJECTIVES:
1460
+ res.diagnostics.append(Diag(
1461
+ "E-Choose-OldObjective",
1462
+ f"objective 已改名:{objective} → 用 time/p99/mem/size",
1463
+ c.line, c.col))
1464
+ elif objective not in OBJECTIVES:
1465
+ res.diagnostics.append(Diag(
1466
+ "E-Choose-BadObjective",
1467
+ f"objective 取值非法:{objective}(仅 time/p99/mem/size)",
1468
+ c.line, c.col,
1469
+ actions=_acts(_line_patch(
1470
+ tu_src, (module or "a") + ".tu", c.line,
1471
+ lambda s, o=objective: _ren_obj(s, o),
1472
+ "把 objective 改成 `time`(最常用的那个)"))))
1473
+
1474
+ if not over:
1475
+ res.diagnostics.append(Diag(
1476
+ "E-Choose-Empty", f"choose {label} 的 over 不能为空(B-8)",
1477
+ c.line, c.col))
1478
+ if len(over) > 4:
1479
+ res.diagnostics.append(Diag(
1480
+ "E-Choose-TooManyCandidates",
1481
+ f"choose {label} 有 {len(over)} 个候选,上限 4(B-8)",
1482
+ c.line, c.col))
1483
+ if len(set(over)) != len(over):
1484
+ res.diagnostics.append(Diag(
1485
+ "E-Choose-DuplicateCandidate",
1486
+ f"choose {label} 的 over 里有重复候选", c.line, c.col))
1487
+ for pn in pending:
1488
+ if pn not in over:
1489
+ res.diagnostics.append(Diag(
1490
+ "E-Choose-PendingMismatch",
1491
+ f"choose {label}:{pn} 标了 pending,但不在 over 名单里",
1492
+ c.line, c.col))
1493
+
1494
+ # ---- 实现侧:`} kernels L(...) { 候选* }`,可嵌套(N-1 上限 2 层)
1495
+ kernels_impl: Dict[str, Dict[str, Node]] = {}
1496
+
1497
+ def collect(owner: Node, depth: int):
1498
+ for ch in owner.children:
1499
+ if ch.kind != "kernels":
1500
+ continue
1501
+ label = ch.name or ""
1502
+ # v0.68 撤回嵌套:kernels 只能挂在 fn 体之后,MUST NOT 出现在候选体里
1503
+ if depth > 1:
1504
+ res.diagnostics.append(Diag(
1505
+ "E-Kernels-Nested",
1506
+ f"kernels {label} 嵌套在候选体里:v0.68 起 kernels 不嵌套"
1507
+ "(需要「选了 A 才需要 B」时,把 B 提升为独立函数)",
1508
+ ch.line, ch.col))
1509
+
1510
+ # 与 choose 的签名对账
1511
+ info = choosers.get(label)
1512
+ if info is not None:
1513
+ kp = [ty for _, ty in param_list(ch)]
1514
+ cp = [ty for _, ty in info["params"]]
1515
+ if kp != cp:
1516
+ res.diagnostics.append(Diag(
1517
+ "E-Spec-SigMismatch",
1518
+ f"kernels {label} 的参数类型与 choose 不一致:"
1519
+ f"({', '.join(kp)}) vs ({', '.join(cp)})",
1520
+ ch.line, ch.col))
1521
+ kr = type_str(_return_of(ch))
1522
+ if kr != info["ret"]:
1523
+ res.diagnostics.append(Diag(
1524
+ "E-Spec-SigMismatch",
1525
+ f"kernels {label} 的返回类型与 choose 不一致:"
1526
+ f"{kr or '(无)'} vs {info['ret'] or '(无)'}",
1527
+ ch.line, ch.col))
1528
+
1529
+ bucket = kernels_impl.setdefault(label, {})
1530
+ for cand in ch.children:
1531
+ if cand.kind != "candidate":
1532
+ continue
1533
+ if cand.name in bucket:
1534
+ res.diagnostics.append(Diag(
1535
+ "E-Duplicate-Candidate",
1536
+ f"候选 {cand.name} 在 kernels {label} 中重复",
1537
+ cand.line, cand.col))
1538
+ bucket[cand.name] = cand
1539
+ collect(cand, depth + 1) # 仍递归,以便对嵌套报 E-Kernels-Nested
1540
+
1541
+ for fn in impls.values():
1542
+ collect(fn, 1)
1543
+
1544
+ res.candidates = {label: {n: c for n, c in b.items()}
1545
+ for label, b in kernels_impl.items()}
1546
+
1547
+ # ---- B-10:实现的候选必须在 over 名单里
1548
+ for label, bucket in kernels_impl.items():
1549
+ info = choosers.get(label)
1550
+ if info is None:
1551
+ continue
1552
+ declared = set(info["over"])
1553
+ for cand_name, cand in bucket.items():
1554
+ if cand_name not in declared:
1555
+ res.diagnostics.append(Diag(
1556
+ "E-Choose-Undeclared",
1557
+ f"候选 {cand_name} 有实现,但不在 choose {label} 的 over 名单里(B-10)",
1558
+ cand.line, cand.col))
1559
+
1560
+ # ---- B-16:pending 与实现双向对账
1561
+ for label, info in choosers.items():
1562
+ bucket = kernels_impl.get(label, {})
1563
+ for cand in info["over"]:
1564
+ implemented = cand in bucket
1565
+ listed = cand in info["pending"]
1566
+ if listed and implemented:
1567
+ res.diagnostics.append(Diag(
1568
+ "E-Choose-PendingMismatch",
1569
+ f"choose {label}:{cand} 已实现,但仍标着 pending(声明过期)",
1570
+ info["node"].line, info["node"].col))
1571
+ if (not listed) and (not implemented):
1572
+ res.diagnostics.append(Diag(
1573
+ "E-Choose-PendingMismatch",
1574
+ f"choose {label}:{cand} 没有实现,却没标 pending(漏报)",
1575
+ info["node"].line, info["node"].col))
1576
+
1577
+ # ---- v0.68:`T!` 与 error 声明的一致性
1578
+ for fn in impls.values():
1579
+ fv = fn.value or {}
1580
+ fallible = bool(fv.get("fallible"))
1581
+ uses_q = len(walk(fn, "try")) > 0
1582
+ if fallible and error_decl is None:
1583
+ res.diagnostics.append(Diag(
1584
+ "E-Error-DeclMissing",
1585
+ f"函数 {fn.name} 用 `T!` 表示可能失败,但模块没有 `error` 声明",
1586
+ fn.line, fn.col))
1587
+ if uses_q and not fallible:
1588
+ res.diagnostics.append(Diag(
1589
+ "E-Fallible-Missing",
1590
+ f"函数 {fn.name} 里有 `?`,返回类型 MUST 写成 `T!`",
1591
+ fn.line, fn.col))
1592
+ for r in walk(fn, "return"):
1593
+ if not fallible or not r.children:
1594
+ continue
1595
+ v = r.children[0]
1596
+ if v.kind == "call" and (v.name or "").split(".")[-1] in ("Ok", "Err"):
1597
+ if (v.name or "").split(".")[-1] == "Ok":
1598
+ res.diagnostics.append(Diag(
1599
+ "E-Return-OkInFallible",
1600
+ f"`{fn.name}` 是 `T!` 函数:`return x` 已自动成为 `Ok(x)`,MUST NOT 再写 `Ok(...)`",
1601
+ r.line, r.col))
1602
+
1603
+ # ---- ?! 使用处(B-3 / 宿主 / 实参个数)
1604
+ all_fns: List[Node] = list(impls.values())
1605
+ for fn in all_fns:
1606
+ for d in walk(fn, "dispatch"):
1607
+ label = d.name or ""
1608
+ res.labels_used.add(label)
1609
+ info = choosers.get(label)
1610
+ if info is None:
1611
+ res.diagnostics.append(Diag(
1612
+ "E-Choose-Undeclared",
1613
+ f"?!{label} 没有对应的 choose 声明(B-3)", d.line, d.col))
1614
+ continue
1615
+ if info["host"] != fn.name:
1616
+ res.diagnostics.append(Diag(
1617
+ "E-Choose-WrongHost",
1618
+ f"?!{label} 只能写在宿主 {info['host']} 里(当前在 {fn.name})",
1619
+ d.line, d.col))
1620
+ args = next((x for x in d.children if x.kind == "args"), None)
1621
+ nargs = len(args.children) if args is not None else 0
1622
+ if nargs != len(info["params"]):
1623
+ res.diagnostics.append(Diag(
1624
+ "E-Choose-ArityMismatch",
1625
+ f"?!{label} 传了 {nargs} 个实参,choose 声明了 {len(info['params'])} 个参数",
1626
+ d.line, d.col))
1627
+
1628
+ # ---- B-4:每个 choose 至少被引用一次(防装饰)
1629
+ # 纯计划态(宿主还没有 .ai 实现)时豁免:此时本来就没地方写 ?!
1630
+ for label, info in choosers.items():
1631
+ if info["host"] not in impls:
1632
+ continue
1633
+ if label not in res.labels_used:
1634
+ res.diagnostics.append(Diag(
1635
+ "E-Choose-Unused",
1636
+ f"choose {label} 声明了但没有任何 ?! 使用(B-4)",
1637
+ info["node"].line, info["node"].col))
1638
+
1639
+ # ---- B-15:?! 不得构成整个函数体
1640
+ for fn in all_fns:
1641
+ body = next((c for c in fn.children if c.kind == "block"), None)
1642
+ if body is None or len(body.children) != 1:
1643
+ continue
1644
+ only = body.children[0]
1645
+ if only.kind == "return" and only.children:
1646
+ inner = only.children[0]
1647
+ if inner.kind == "dispatch":
1648
+ res.diagnostics.append(Diag(
1649
+ "E-Choose-WholeBody",
1650
+ f"{fn.name} 的函数体只有 return ?!…;B-15 要求宿主有自己的逻辑",
1651
+ fn.line, fn.col))
1652
+
1653
+ # ---- 状态表
1654
+ for name, spec in specs.items():
1655
+ has_impl = name in impls
1656
+ ht = _has_target(spec)
1657
+ st, note = derive_state(has_impl, ht)
1658
+ res.functions.append(FnInfo(
1659
+ name=name, kind="fn", has_impl=has_impl, has_target=ht,
1660
+ is_pub=bool((impls.get(name).value or {}).get("pub")) if name in impls else False,
1661
+ line=spec.line, state=st, note=note))
1662
+
1663
+ # ---- 可变性:给 `let` 绑定的变量赋值 → E-Assign-Immutable
1664
+ for fn in all_fns:
1665
+ body = next((c for c in fn.children if c.kind == "block"), None)
1666
+ if body is not None:
1667
+ res.diagnostics.extend(_check_immutability(body))
1668
+
1669
+ # ---- L6:可能溢出的算术(开关:off / warn / error)
1670
+ if overflow in ("warn", "error"):
1671
+ sev = "error" if overflow == "error" else "warning"
1672
+ for fn in all_fns:
1673
+ for b in walk(fn, "binary"):
1674
+ if (b.value or "") not in ("+", "-", "*", "<<"):
1675
+ continue
1676
+ res.diagnostics.append(Diag(
1677
+ "L6-Overflow",
1678
+ f"算术 {b.value} 可能回绕(按位宽 mod 2^N);严格模式提示({sev})",
1679
+ b.line, b.col, severity=sev))
1680
+
1681
+ # ---- E-6-b:类型命名空间里的成员 MUST 用 `::`(v0.69)
1682
+ _enum_names = {it.name for it in tu_items if it.kind == "enum"}
1683
+ if _enum_names:
1684
+ for mod in (tu.module, ai.module if ai is not None else None):
1685
+ if mod is None:
1686
+ continue
1687
+ for node in walk(mod, "field") + walk(mod, "method-call"):
1688
+ if not node.children:
1689
+ continue
1690
+ base = node.children[0]
1691
+ if base.kind == "path" and (base.name or "") in _enum_names:
1692
+ res.diagnostics.append(Diag(
1693
+ "E-Member-WrongSep",
1694
+ f"`{base.name}.{node.name or ''}` 用了 `.`:枚举变体与静态成员 MUST 用 `::`"
1695
+ f"(v0.69),例如 `{base.name}::{node.name or ''}`",
1696
+ node.line, node.col))
1697
+
1698
+ # ---- MB:benchmodel(v0.69)
1699
+ _int_consts: Dict[str, int] = {}
1700
+ for it in tu_items:
1701
+ if it.kind == "const" and len(it.children) >= 2 and it.children[-1].kind == "lit-int":
1702
+ try:
1703
+ _int_consts[it.name] = int(it.children[-1].value)
1704
+ except (TypeError, ValueError):
1705
+ pass
1706
+ _check_benchmodel(res, specs, choosers, impls, _int_consts)
1707
+
1708
+ # ---- T13:while 的迭代上界(三种来源 + 两档处理)
1709
+ # `.eln` 的文件名:用模块名拼(`check_module` 拿不到路径)。
1710
+ _check_while_bounds(res, all_fns, specs, strict,
1711
+ ai_src=ai_src, fn_file=(module or "a") + ".eln")
1712
+ _check_sort_calls(res, all_fns)
1713
+
1714
+ # ---- C11-b:递归必须有 `recursion depth` 声明(否则 κ 沉默地偏小)
1715
+ res.diagnostics.extend(check_recursion_depth(impls, specs))
1716
+
1717
+ # ---- span 兜底:checker 自己造的诊断只有 line/col,这里换算成偏移
1718
+ _resolve_spans(res.diagnostics, tu_src, ai_src)
1719
+
1720
+ # **E30**:借用检查(v0 最小实现)。放在最后追加,不影响既有诊断顺序。
1721
+ from borrow import check_borrows
1722
+ for _code, _msg, _ln, _col in check_borrows(tu.module if tu else None,
1723
+ ai.module if ai is not None else None):
1724
+ res.diagnostics.append(Diag(_code, _msg, _ln, _col))
1725
+
1726
+
1727
+ # **§13.6 周边检查**:B-25 / B-26(parallel 与 ?!)
1728
+ res.diagnostics.extend(_check_concurrency_cost(tu.module if tu else None,
1729
+ ai.module if ai is not None else None))
1730
+ res.diagnostics.extend(_check_parallel(tu.module if tu else None,
1731
+ ai.module if ai is not None else None))
1732
+
1733
+ # **效果检查**:实际用到的效果 ⊆ spec 声明
1734
+ # **FFI:每个 extern 必须声明 effects**(并记下来给调用方用)
1735
+ res.diagnostics.extend(_collect_extern_effects(
1736
+ ai.module if ai is not None else None))
1737
+
1738
+ res.diagnostics.extend(_check_effects(tu.module if tu else None,
1739
+ ai.module if ai is not None else None))
1740
+
1741
+ # **格式化:能在编译期查的就不留到运行期**
1742
+ res.diagnostics.extend(_check_format_calls(ai.module if ai is not None else None))
1743
+
1744
+ # **泛型调用必须能定下类型参数**(A 第一批)
1745
+ res.diagnostics.extend(_check_generic_calls(ai.module if ai is not None else None, specs))
1746
+
1747
+ # **每个 match 必须有 `_` 兜底臂**(否则没命中会被静默跳过)
1748
+ res.diagnostics.extend(_check_match_default(ai.module if ai is not None else None))
1749
+
1750
+ # **并行任务之间不许共享可变状态**
1751
+ res.diagnostics.extend(_check_parallel_share(ai.module if ai is not None else None))
1752
+
1753
+ # **浮点字面量赋给整数类型**(§12.2:以前零诊断通过)
1754
+ res.diagnostics.extend(_check_float_to_int(ai.module if ai is not None else None))
1755
+
1756
+
1757
+ # **requires 调用点验证**:证明不了就报错(不靠运行期断言兜底)
1758
+ import requires as _requires
1759
+ for _c, _m, _ln, _col in _requires.check(tu.module if tu else None,
1760
+ ai.module if ai is not None else None):
1761
+ res.diagnostics.append(Diag(_c, _m, _ln, _col))
1762
+ return res
1763
+
1764
+
1765
+ def _check_float_to_int(mod) -> List[Diag]:
1766
+ """**浮点字面量赋给整数类型 MUST 报错**(§12.2)。
1767
+
1768
+ 以前 `u64 y = 1.5;` 零诊断通过 —— 类型检查的洞:
1769
+ 静默截断在成本契约语言里尤其危险(数字看着对,实际少了半截)。
1770
+ """
1771
+ if mod is None:
1772
+ return []
1773
+ int_types = {"u8", "u16", "u32", "u64", "i8", "i16", "i32", "i64",
1774
+ "usize", "isize", "byte"}
1775
+ out: List[Diag] = []
1776
+
1777
+ def walk(n) -> None:
1778
+ if n is None:
1779
+ return
1780
+ k = getattr(n, "kind", "")
1781
+ if k in ("var-decl", "val-decl", "const-decl"):
1782
+ kids = getattr(n, "children", []) or []
1783
+ if len(kids) >= 2:
1784
+ tn = kids[0]
1785
+ tname = (getattr(tn, "name", "") or "").split("<")[0].strip()
1786
+ expr = kids[1]
1787
+ if tname in int_types and getattr(expr, "kind", "") == "lit-float":
1788
+ out.append(Diag(
1789
+ "E-Type-FloatToInt",
1790
+ f"浮点字面量不能赋给整数类型 {tname}(隐式截断);"
1791
+ f"请写成整数,或把变量类型改成 f64",
1792
+ getattr(expr, "line", 0) or getattr(n, "line", 0),
1793
+ getattr(expr, "col", 0) or getattr(n, "col", 0)))
1794
+ for c in getattr(n, "children", []) or []:
1795
+ walk(c)
1796
+
1797
+ walk(mod)
1798
+ return out
1799
+
1800
+
1801
+ def _check_immutability(body: Node) -> List[Diag]:
1802
+ """遍历语句,记录每个绑定的可变性;给 `let` 赋值即报错。
1803
+
1804
+ 作用域用栈:块、if/while/for/match 的体各开一层。
1805
+ """
1806
+ diags: List[Diag] = []
1807
+ scopes: List[Dict[str, bool]] = [{}] # name -> is_var
1808
+
1809
+ def lookup(name: str) -> Optional[bool]:
1810
+ for s in reversed(scopes):
1811
+ if name in s:
1812
+ return s[name]
1813
+ return None
1814
+
1815
+ def root_name(node: Optional[Node]) -> Optional[str]:
1816
+ """取赋值目标的根标识符:x / x.f / x[i] / *x 都归到 x。"""
1817
+ cur = node
1818
+ guard = 0
1819
+ while cur is not None and guard < 64:
1820
+ guard += 1
1821
+ if cur.kind == "path":
1822
+ return cur.name
1823
+ if cur.kind in ("field", "index", "deref") and cur.children:
1824
+ cur = cur.children[0]
1825
+ continue
1826
+ return None
1827
+ return None
1828
+
1829
+ def walk_block(block: Node):
1830
+ scopes.append({})
1831
+ for st in block.children:
1832
+ k = st.kind
1833
+ if k in ("val-decl", "var-decl", "const-decl"):
1834
+ # v0.68:`const T n = ...` 不可赋值;`T n = ...` 可赋值
1835
+ scopes[-1][st.name] = (k != "const-decl")
1836
+ elif k in ("assign", "assign-op"):
1837
+ nm = root_name(st.children[0] if st.children else None)
1838
+ if nm is not None and lookup(nm) is False:
1839
+ diags.append(Diag(
1840
+ "E-Assign-Immutable",
1841
+ f"不能给 `const` 绑定的 {nm} 赋值(去掉 const 即可写)",
1842
+ st.line, st.col))
1843
+ elif k == "block":
1844
+ walk_block(st)
1845
+ else:
1846
+ for c in st.children:
1847
+ if c.kind == "block":
1848
+ walk_block(c)
1849
+ scopes.pop()
1850
+
1851
+ walk_block(body)
1852
+ pass # (removed misplaced _check_parallel call)
1853
+ return diags
1854
+
1855
+
1856
+
1857
+
1858
+
1859
+
1860
+ #: 可声明的效果名。**`panic` 必须在这里**(L-05,2026-11-06):
1861
+ #: 它是能让程序中止的效果;不在词表里,写了会被 E-Effect-Unknown 拒,
1862
+ #: 那就等于"宁可让人不敢声明",与"诚实优先"相反。
1863
+ EFFECT_VOCAB = {"io", "fs", "env", "nondet", "alloc", "unsafe", "panic"}
1864
+
1865
+
1866
+ def _spec_clauses(spec) -> Dict[str, List]:
1867
+ """把 spec 的子句按名字归类(effects / requires / …)。
1868
+
1869
+ **子句挂在 `spec-body` 下面**(不是 spec 的直接子节点),
1870
+ 这是第一版写错的地方:effects 名字还存在 `clause.value` 里(列表),
1871
+ 不是 children。
1872
+ """
1873
+ out: Dict[str, List] = {}
1874
+ if spec is None:
1875
+ return out
1876
+ for holder in spec.children:
1877
+ if getattr(holder, "kind", "") != "spec-body":
1878
+ continue
1879
+ for c in holder.children:
1880
+ if getattr(c, "kind", "") == "clause" and getattr(c, "name", ""):
1881
+ out.setdefault(c.name, []).append(c)
1882
+ return out
1883
+
1884
+
1885
+ def _declared_effects(spec) -> Tuple[set, List]:
1886
+ """返回 (声明的效果集合, 未知效果名的位置)。"""
1887
+ names: set = set()
1888
+ bad: List = []
1889
+ for cl in _spec_clauses(spec).get("effects", []):
1890
+ raw = cl.value if isinstance(getattr(cl, "value", None), list) else []
1891
+ for nm in raw:
1892
+ if nm in ("", "pure"):
1893
+ continue
1894
+ if nm not in EFFECT_VOCAB:
1895
+ bad.append(cl)
1896
+ else:
1897
+ names.add(nm)
1898
+ return names, bad
1899
+
1900
+
1901
+ def _used_effects(fn, fns, memo, stack) -> set:
1902
+ """函数体内实际用到的效果:调用图的并集 + 内建效果。"""
1903
+ name = fn.name or ""
1904
+ if name in memo:
1905
+ return memo[name]
1906
+ if name in stack:
1907
+ return set()
1908
+ stack.add(name)
1909
+ used: set = set()
1910
+ for d in _all_nodes(fn):
1911
+ if d.kind in ("call", "method-call") and getattr(d, "name", ""):
1912
+ short = (d.name or "").split(".")[-1]
1913
+ used |= set(stdlib.effects_of(short))
1914
+ callee = fns.get(short)
1915
+ if callee is not None:
1916
+ used |= _used_effects(callee, fns, memo, stack)
1917
+ # **高阶内建**:`map(xs, f)` 的效果包含 `f` 的效果(实参是**名字**,不是调用)
1918
+ for d in _all_nodes(fn):
1919
+ if d.kind == "call" and (d.name or "") in ("map", "filter", "fold", "count_if"):
1920
+ _an = next((c for c in d.children if c.kind == "args"), None)
1921
+ _items = _an.children if _an is not None else []
1922
+ for _it in _items[1:]:
1923
+ if _it.kind == "path" and (_it.name or "") in fns:
1924
+ used |= _used_effects(fns[_it.name], fns, memo, stack)
1925
+
1926
+ # **FFI**:调用 `extern` 声明的函数,效果取它自己声明的那些
1927
+ for d in _all_nodes(fn):
1928
+ if d.kind == "call" and getattr(d, "name", ""):
1929
+ short = (d.name or "").split(".")[-1]
1930
+ ext = _EXTERN_EFFECTS.get(short)
1931
+ if ext:
1932
+ used |= set(ext)
1933
+ stack.discard(name)
1934
+ memo[name] = used
1935
+ return used
1936
+
1937
+
1938
+
1939
+
1940
+ def _task_io(task) -> Tuple[set, set]:
1941
+ """收集一个任务块的 (写到的变量, 读到的变量)。"""
1942
+ written: set = set()
1943
+ read: set = set()
1944
+ stack = [task]
1945
+ while stack:
1946
+ x = stack.pop()
1947
+ if x is None:
1948
+ continue
1949
+ if x.kind == "assign" and x.children:
1950
+ tgt = x.children[0]
1951
+ if tgt.kind == "path" and tgt.name:
1952
+ written.add(tgt.name)
1953
+ elif tgt.kind == "index" and tgt.children and tgt.children[0].kind == "path":
1954
+ written.add(tgt.children[0].name or "")
1955
+ stack.extend(x.children[1:])
1956
+ continue
1957
+ if x.kind in ("const-decl", "var-decl", "typed-decl") and x.name:
1958
+ written.add(x.name)
1959
+ stack.extend([c for c in x.children if c.kind != "type-name"])
1960
+ continue
1961
+ if x.kind == "path" and x.name:
1962
+ read.add(x.name)
1963
+ stack.extend(getattr(x, "children", []) or [])
1964
+ return written, read
1965
+
1966
+
1967
+
1968
+
1969
+
1970
+
1971
+ # ---------------------------------------------------------------- 格式化检查(v0.71)
1972
+ #
1973
+ # **能在编译期查的,就不留到运行期**:
1974
+ # · 占位符个数 vs 实参个数 → `E-Format-Arity`
1975
+ # · 说明符与实参类型(`{:x}` 给字节串)→ `E-Format-ArgType`
1976
+ # · 格式串本身不合法(未闭合、`{:.2}`)→ `E-Format-BadSpec`
1977
+ # · 格式串不是字面量 → `W-Format-Dynamic`(警告,运行期才查)
1978
+
1979
+ def _check_format_calls(impl_mod) -> List[Diag]:
1980
+ diags: List[Diag] = []
1981
+ if impl_mod is None:
1982
+ return diags
1983
+ import fmt as _fmt
1984
+ for fn in _all_nodes(impl_mod):
1985
+ if getattr(fn, "kind", "") != "fn":
1986
+ continue
1987
+ env = _local_types(fn)
1988
+ for call in _all_nodes(fn):
1989
+ if getattr(call, "kind", "") != "call":
1990
+ continue
1991
+ short = (call.name or "").split(".")[-1]
1992
+ if short not in ("format", "print"):
1993
+ continue
1994
+ args = next((c for c in call.children if c.kind == "args"), None)
1995
+ items = args.children if args else []
1996
+ if not items:
1997
+ continue
1998
+ first = items[0]
1999
+ # **只有第一个实参是字面量字符串时才检查**(`print(1, 2)` 不是格式化)
2000
+ if getattr(first, "kind", "") != "lit-string":
2001
+ if short == "format" or any(
2002
+ getattr(x, "kind", "") == "lit-string" for x in items[1:]):
2003
+ if len(items) > 1:
2004
+ diags.append(Diag(
2005
+ "W-Format-Dynamic",
2006
+ "格式串不是字面量 → 无法在编译期检查占位符与实参是否匹配",
2007
+ call.line, call.col))
2008
+ continue
2009
+ text = first.value
2010
+ if isinstance(text, bytes):
2011
+ text = text.decode("utf-8", "replace")
2012
+ if short == "print" and "{" not in text:
2013
+ continue # 普通打印,不管
2014
+ try:
2015
+ parts = _fmt.parse(text)
2016
+ except _fmt.FmtError as exc:
2017
+ diags.append(Diag(exc.code, f"{exc.msg}(位置 {exc.pos})", first.line, first.col))
2018
+ continue
2019
+ holes = [pl for k, pl in parts if k == "hole"]
2020
+ given = items[1:]
2021
+ if len(holes) != len(given):
2022
+ diags.append(Diag(
2023
+ "E-Format-Arity",
2024
+ f"格式串有 {len(holes)} 个洞,但给了 {len(given)} 个实参",
2025
+ call.line, call.col))
2026
+ continue
2027
+ for hole, arg in zip(holes, given):
2028
+ _align, _w, kind = hole
2029
+ if kind != "x":
2030
+ continue
2031
+ ty = ""
2032
+ if getattr(arg, "kind", "") == "path":
2033
+ ty = env.get(arg.name or "", "")
2034
+ # 名字后面可能跟着 `<…>`(`Vec<u8>`),先取头部再规范化。
2035
+ _head = (ty or "").split("<")[0].split("&")[0].strip()
2036
+ if canon(_head) in ("vector", "array"):
2037
+ diags.append(Diag(
2038
+ "E-Format-ArgType",
2039
+ f"`{{:x}}`(十六进制)要数字,但 `{arg.name}` 是 `{ty}`",
2040
+ arg.line, arg.col))
2041
+ return diags
2042
+
2043
+
2044
+ def _check_match_default(ch_mod) -> List[Diag]:
2045
+ """**每个 `match` MUST 以 `_` 兜底臂结尾**(v0.71)。
2046
+
2047
+ ## 为什么是"强制兜底"而不是"穷尽性分析"
2048
+
2049
+ 穷尽性分析要做"模式集合 ⊇ 变体集合"的推导——对枚举可行,对**跨模块的错误类型**
2050
+ 和**将来可能新增的变体**都不牢靠。而**强制 `_`** 只要看最后一条臂:
2051
+
2052
+ - **实现成本**:一个循环;
2053
+ - **保证强度**:**"没命中"这件事从此不可能发生**——静默跳过这一类 bug 被根除;
2054
+ - **代价**:多写一行 `_ => { return …; }`。
2055
+
2056
+ 将来若要做穷尽性提示,可以在"模式已覆盖全部变体但仍写了 `_`"时给 **冗余警告**
2057
+ ——**那是在此基础上的增强,不是替代**。
2058
+ """
2059
+ diags: List[Diag] = []
2060
+ if ch_mod is None:
2061
+ return diags
2062
+ for n in _all_nodes(ch_mod):
2063
+ if getattr(n, "kind", "") != "match":
2064
+ continue
2065
+ arms = [c for c in getattr(n, "children", [])[1:] if getattr(c, "kind", "") == "arm"]
2066
+ if not arms:
2067
+ diags.append(Diag("E-Match-NoDefault",
2068
+ "match 至少要有 `_` 兜底臂", n.line, n.col))
2069
+ continue
2070
+ last_pat = None
2071
+ for c in reversed(arms[-1].children):
2072
+ if c.kind in ("pattern", "pattern-wildcard"):
2073
+ last_pat = c
2074
+ break
2075
+ if last_pat is None or last_pat.kind != "pattern-wildcard":
2076
+ diags.append(Diag("E-Match-NoDefault",
2077
+ "match MUST 以 `_` 兜底臂结尾——否则没命中时会被**静默跳过**;"
2078
+ "加一条 `_ => { return <默认值>; }`",
2079
+ n.line, n.col))
2080
+ return diags
2081
+
2082
+
2083
+ def _check_parallel_share(ch_mod) -> List[Diag]:
2084
+ """**并行任务之间不许共享可变状态**(v0.71)。
2085
+
2086
+ C++ 的说法:`std::thread` 里捕获 `int&` 然后两边都写 = 数据竞争 = UB。
2087
+ Rust 用 `Send`/`Sync` 在**编译期**挡;我们这一版用**变量集合相交**来挡:
2088
+
2089
+ - 两个任务都写同一个变量 → 报
2090
+ - 一个任务写、另一个任务读同一个变量 → 也报(读者看到的是哪个值?)
2091
+ - 变量在任务内部声明(每个任务各自一份)→ 不报
2092
+ """
2093
+ diags: List[Diag] = []
2094
+ if ch_mod is None:
2095
+ return diags
2096
+ for n in _all_nodes(ch_mod):
2097
+ if n.kind != "parallel":
2098
+ continue
2099
+ body = next((c for c in n.children if c.kind == "block"), None)
2100
+ if body is None:
2101
+ continue
2102
+ tasks = [c for c in body.children if c.kind == "block"]
2103
+ if len(tasks) < 2:
2104
+ continue
2105
+ infos = [_task_io(x) for x in tasks]
2106
+ for i in range(len(tasks)):
2107
+ for j in range(i + 1, len(tasks)):
2108
+ wi, ri = infos[i]
2109
+ wj, rj = infos[j]
2110
+ clash = (wi & wj) | (wi & rj) | (ri & wj)
2111
+ if clash:
2112
+ diags.append(Diag(
2113
+ "E-Parallel-ShareMut",
2114
+ f"任务 {i + 1} 与任务 {j + 1} 共享了可变状态 {sorted(clash)}:"
2115
+ f"并行里读写同一个变量,结果取决于调度;"
2116
+ f"改成「各任务写自己的局部变量,再用返回值合并」",
2117
+ n.line, n.col))
2118
+ return diags
2119
+
2120
+
2121
+ def node_effects(node, ch_mod) -> set:
2122
+ """任意 AST 节点(函数体 / 候选块)实际用到的效果。"""
2123
+ if ch_mod is None or node is None:
2124
+ return set()
2125
+ fns = {c.name: c for c in ch_mod.children if c.kind == "fn"}
2126
+ return _used_effects(node, fns, {}, set())
2127
+
2128
+
2129
+ def function_effects(tu_mod, ch_mod) -> Dict[str, set]:
2130
+ """每个函数**实际用到**的效果(传递闭包)——给 measure/bench 判"可不可测"。"""
2131
+ if ch_mod is None:
2132
+ return {}
2133
+ fns = {c.name: c for c in ch_mod.children if c.kind == "fn"}
2134
+ memo: Dict[str, set] = {}
2135
+ return {name: _used_effects(fn, fns, memo, set()) for name, fn in fns.items()}
2136
+
2137
+
2138
+ #: `extern` 声明的效果(模块加载时由 `_collect_extern_effects` 填)
2139
+ _EXTERN_EFFECTS: Dict[str, set] = {}
2140
+
2141
+
2142
+ def _collect_extern_effects(impl_mod) -> List[Diag]:
2143
+ """**每个 `extern` MUST 声明 effects**(FFI 是最容易偷偷做副作用的地方)。
2144
+
2145
+ 没有声明 → `E-Extern-NoEffects`:宁可让作者写 `effects {}` 明确表示"这是纯函数",
2146
+ 也不许默认放行。
2147
+ """
2148
+ _EXTERN_EFFECTS.clear()
2149
+ diags: List[Diag] = []
2150
+ if impl_mod is None:
2151
+ return diags
2152
+ for c in impl_mod.children or []:
2153
+ if getattr(c, "kind", "") != "extern":
2154
+ continue
2155
+ eff = next((x for x in c.children if x.kind == "extern-effects"), None)
2156
+ if eff is None:
2157
+ diags.append(Diag("E-Extern-NoEffects",
2158
+ f"extern {c.name} MUST 声明 `effects {{ … }}`"
2159
+ f"(纯函数就写 `effects {{}}`)", c.line, c.col))
2160
+ _EXTERN_EFFECTS[c.name or ""] = set()
2161
+ continue
2162
+ _EXTERN_EFFECTS[c.name or ""] = {x.name for x in eff.children if x.name}
2163
+ return diags
2164
+
2165
+
2166
+ def _check_effects(tu_mod, ch_mod) -> List[Diag]:
2167
+ """**效果检查**:函数实际用到的效果 MUST ⊆ spec 声明的效果。
2168
+
2169
+ 这是"可撒谎位置"之外**唯一能自动验证**的契约维度:
2170
+ `print` 用了 `io`,而 `.tu` 写 `effects {}` → `E-Effect-Missing`。
2171
+ """
2172
+ diags: List[Diag] = []
2173
+ if ch_mod is None:
2174
+ return diags
2175
+ specs = {c.name: c for c in (tu_mod.children if tu_mod else []) if c.kind == "spec"}
2176
+ fns = {c.name: c for c in ch_mod.children if c.kind == "fn"}
2177
+ memo: Dict[str, set] = {}
2178
+
2179
+ for name, fn in fns.items():
2180
+ spec = specs.get(name)
2181
+ if spec is None:
2182
+ continue
2183
+ declared, bad = _declared_effects(spec)
2184
+ # **① FFI 必须写在 `unsafe { }` 里**(E-Unsafe-Required)。
2185
+ # extern 是 `.eln` 的**模块级节点**:`extern f(...) -> T from "lib" effects { … };`
2186
+ _ffi = {c.name for c in (ch_mod.children or [])
2187
+ if c.kind == "extern" and getattr(c, "name", None)}
2188
+ if _ffi:
2189
+ _bad = []
2190
+ def _scan(node, in_unsafe):
2191
+ if (getattr(node, "kind", "") == "block"
2192
+ and getattr(node, "value", None) == "unsafe"):
2193
+ in_unsafe = True
2194
+ if (getattr(node, "kind", "") == "call" and not in_unsafe
2195
+ and (node.name or "").rsplit(".", 1)[-1] in _ffi):
2196
+ _bad.append(node)
2197
+ for _c in (getattr(node, "children", None) or []):
2198
+ _scan(_c, in_unsafe)
2199
+ _scan(fn, False)
2200
+ for _nd in _bad:
2201
+ diags.append(Diag("E-Unsafe-Required",
2202
+ "调用了外部函数 %s,但它不在 `unsafe { }` 块里。" % _nd.name
2203
+ + "外部调用是语言管不了的边界。改法:把它包进 unsafe 块,"
2204
+ + "并让 spec 的 effects 声明 unsafe。",
2205
+ _nd.line, _nd.col))
2206
+ # **unsafe 的两条规则**(2026-11-05):让它从装饰变成约束。
2207
+ # 前置已解决:`EFFECT_VOCAB` 里有 unsafe,`effects { unsafe }` 也能解析了。
2208
+ _ublk = next((n for n in _all_nodes(fn)
2209
+ if getattr(n, "kind", "") == "block" and getattr(n, "value", None) == "unsafe"), None)
2210
+ if _ublk is not None and "unsafe" not in declared:
2211
+ diags.append(Diag("E-Unsafe-Undeclared",
2212
+ "这里有 `unsafe { }` 块,但 effects 没声明 `unsafe`。"
2213
+ "改法:在 spec 的 effects 里加上 unsafe,或把不安全操作移出该块。",
2214
+ _ublk.line, _ublk.col))
2215
+ if _ublk is None and "unsafe" in declared:
2216
+ diags.append(Diag("E-Unsafe-Overdeclared",
2217
+ "effects 声明了 `unsafe`,但函数体内没有 `unsafe { }` 块——虚报。"
2218
+ "改法:去掉 effects 里的 unsafe,或把危险操作放进 unsafe 块。",
2219
+ getattr(fn, "line", 0), getattr(fn, "col", 0)))
2220
+ for b in bad:
2221
+ raw = b.value if isinstance(getattr(b, "value", None), list) else []
2222
+ unknown = [x for x in raw if x and x != "pure" and x not in EFFECT_VOCAB]
2223
+ diags.append(Diag("E-Effect-Unknown",
2224
+ f"未知效果 {unknown}(可用:{'/'.join(sorted(EFFECT_VOCAB))})",
2225
+ b.line, b.col))
2226
+ used = _used_effects(fn, fns, memo, set())
2227
+ missing = used - declared
2228
+ if missing:
2229
+ diags.append(Diag("E-Effect-Missing",
2230
+ f"{name} 实际用到了 {sorted(missing)},"
2231
+ f"但 spec 只声明了 {sorted(declared) or '无'}",
2232
+ fn.line, fn.col))
2233
+ return diags
2234
+
2235
+
2236
+ def _all_nodes(root) -> List:
2237
+ """递归收集所有节点(含自身)。"""
2238
+ out = []
2239
+ stack = [root]
2240
+ while stack:
2241
+ x = stack.pop()
2242
+ if x is None:
2243
+ continue
2244
+ out.append(x)
2245
+ stack.extend(getattr(x, "children", []) or [])
2246
+ return out
2247
+
2248
+
2249
+ def _check_parallel(tu_mod, ch_mod) -> List[Diag]:
2250
+ """§13.6 的周边检查(B-25 / B-26)。
2251
+
2252
+ - **B-25**:`parallel` 里 MUST NOT 含 `?!`(分档靠测量,并行里测不准)。
2253
+ - **B-26**:`?!` 候选里 MUST NOT 含 `parallel`(候选要能被隔离测量)。
2254
+ """
2255
+ diags: List[Diag] = []
2256
+ if ch_mod is None:
2257
+ return diags
2258
+ nodes = _all_nodes(ch_mod)
2259
+ for n in nodes:
2260
+ if n.kind == "candidate":
2261
+ for d in _all_nodes(n):
2262
+ if d is not n and d.kind == "parallel":
2263
+ diags.append(Diag(
2264
+ "E-Parallel-Measured",
2265
+ "候选里不能有 parallel:候选要能被隔离测量(B-26)",
2266
+ d.line, d.col))
2267
+ return diags
2268
+
2269
+
2270
+ def _check_concurrency_cost(tu_mod, ch_mod) -> List[Diag]:
2271
+ """**G25(2026-11-02)**:有并发(`parallel`/`spawn`)的函数,其 `time` 契约
2272
+ 在 v0 里**不可证伪**。
2273
+
2274
+ 为什么必须说出来:v0 **没有内存模型、没有竞争规则**,κ 按单线程语义累加。
2275
+ 于是"并发下实际耗时"与"承诺的 time 上界"之间没有可比关系——
2276
+ 审稿人第一个反例就是"你承诺 O(n),但两个任务一起跑当然不同"。
2277
+
2278
+ 我们不假装能判:给出**警告级**诊断,并在 `elench cost` 里同样打一行。
2279
+ """
2280
+ diags: List[Diag] = []
2281
+ if ch_mod is None or tu_mod is None:
2282
+ return diags
2283
+ specs = {getattr(c, "name", ""): c for c in getattr(tu_mod, "children", []) or []
2284
+ if getattr(c, "kind", "") == "spec"}
2285
+ for fn in getattr(ch_mod, "children", []) or []:
2286
+ if getattr(fn, "kind", "") not in ("func", "fn"):
2287
+ continue
2288
+ par = next((n for n in _all_nodes(fn) if n.kind in ("parallel", "spawn")), None)
2289
+ if par is None:
2290
+ continue
2291
+ sp = specs.get(getattr(fn, "name", ""))
2292
+ has_time = False
2293
+ if sp is not None:
2294
+ for c in getattr(sp, "children", []) or []:
2295
+ if getattr(c, "kind", "") == "spec-body":
2296
+ for cl in getattr(c, "children", []) or []:
2297
+ if getattr(cl, "kind", "") == "clause" and (cl.name or "") == "target":
2298
+ has_time = any(getattr(d, "name", "") == "time"
2299
+ for d in _all_nodes(cl))
2300
+ if has_time:
2301
+ diags.append(Diag(
2302
+ "W-Concurrency-Time",
2303
+ f"`{fn.name}` 使用并发,但 v0 的 time 契约按**单线程语义**计 κ;"
2304
+ f"并发下的实际耗时/竞争不在承诺范围内(G25:无内存模型)",
2305
+ par.line, par.col, severity="warning"))
2306
+ return diags
2307
+
2308
+
2309
+ def _line_col_to_offset(src: str, line: int, col: int) -> Tuple[int, int]:
2310
+ """1-based (line, col) → 0-based 字节偏移区间 [start, end)。"""
2311
+ if line < 1:
2312
+ return 0, 0
2313
+ pos = 0
2314
+ cur = 1
2315
+ while cur < line:
2316
+ nl = src.find("\n", pos)
2317
+ if nl < 0:
2318
+ return len(src), len(src)
2319
+ pos = nl + 1
2320
+ cur += 1
2321
+ start = min(pos + max(0, col - 1), len(src))
2322
+ end = min(start + 1, len(src))
2323
+ return start, end
2324
+
2325
+
2326
+ def _resolve_spans(diags: List[Diag], tu_src: str, ai_src: Optional[str]):
2327
+ tu_lines = tu_src.count("\n") + 1
2328
+ for d in diags:
2329
+ if d.start or d.end:
2330
+ continue
2331
+ if d.line <= tu_lines:
2332
+ d.start, d.end = _line_col_to_offset(tu_src, d.line, d.col)
2333
+ elif ai_src is not None:
2334
+ d.start, d.end = _line_col_to_offset(ai_src, d.line, d.col)
2335
+
2336
+
2337
+ def _dup_check(res: CheckResult, items: List[Node], kind: str, code: str):
2338
+ seen = {}
2339
+ for it in items:
2340
+ if it.kind != kind or not it.name:
2341
+ continue
2342
+ if it.name in seen:
2343
+ res.diagnostics.append(Diag(
2344
+ code, f"{kind} {it.name} 重复定义", it.line, it.col))
2345
+ else:
2346
+ seen[it.name] = it
2347
+
2348
+
2349
+ def _check_cycles(all_fns: List[Node], choosers: Dict[str, Node],
2350
+ specs: Dict[str, Node], kernels_decl: Dict[str, Node]) -> List[Diag]:
2351
+ """扩展调用图:普通调用边 ∪ `?!` 到每个候选的边。有环即报 B-9-a。"""
2352
+ diags: List[Diag] = []
2353
+
2354
+ # 函数名 -> 被调名集合(含 ?! 的全部候选)
2355
+ edges: Dict[str, Set[str]] = {}
2356
+ edges_line: Dict[str, Tuple[int, int]] = {}
2357
+ for fn in all_fns:
2358
+ edges_line.setdefault(fn.name, (fn.line, fn.col))
2359
+ out: Set[str] = set()
2360
+ for call in walk(fn, "call"):
2361
+ nm = callee_name(call)
2362
+ if nm:
2363
+ out.add(nm)
2364
+ for d in walk(fn, "dispatch"):
2365
+ ch = choosers.get(d.name or "")
2366
+ if ch is None:
2367
+ continue
2368
+ for c in ch.children:
2369
+ if c.kind == "choose-clause" and c.name == "over":
2370
+ out.update(c.value or [])
2371
+ edges[fn.name] = out
2372
+
2373
+ # B-9:?! 的宿主不得是它自己 choose 的候选
2374
+ for fn in all_fns:
2375
+ for d in walk(fn, "dispatch"):
2376
+ ch = choosers.get(d.name or "")
2377
+ if ch is None:
2378
+ continue
2379
+ for c in ch.children:
2380
+ if c.kind == "choose-clause" and c.name == "over":
2381
+ if fn.name in (c.value or []):
2382
+ diags.append(Diag(
2383
+ "E-Choose-SelfReference",
2384
+ f"?!{d.name} 的候选包含宿主 {fn.name} 自身(B-9)",
2385
+ d.line, d.col))
2386
+
2387
+ WHITE, GRAY, BLACK = 0, 1, 2
2388
+ color: Dict[str, int] = {n: WHITE for n in edges}
2389
+ stack: List[str] = []
2390
+
2391
+ def dfs(n: str) -> None:
2392
+ color[n] = GRAY
2393
+ stack.append(n)
2394
+ for m in sorted(edges.get(n, ())):
2395
+ if m not in edges:
2396
+ continue
2397
+ if color.get(m, WHITE) == GRAY:
2398
+ cycle = stack[stack.index(m):] + [m]
2399
+ diags.append(Diag(
2400
+ "E-Choose-Cycle",
2401
+ "扩展调用图有环(B-9-a):" + " → ".join(cycle),
2402
+ edges_line.get(cycle[0], (1, 1))[0],
2403
+ edges_line.get(cycle[0], (1, 1))[1]))
2404
+ elif color.get(m, WHITE) == WHITE:
2405
+ dfs(m)
2406
+ stack.pop()
2407
+ color[n] = BLACK
2408
+
2409
+ for n in sorted(edges):
2410
+ if color[n] == WHITE:
2411
+ dfs(n)
2412
+
2413
+ return diags
2414
+
2415
+
2416
+ # ---------------------------------------------------------------- 严格模式(L3 / L4 / L5)
2417
+
2418
+ MAX_LINE = 100
2419
+ MAX_TUPLE = 3
2420
+
2421
+
2422
+ def strict_lints(src: str, res_parse, label: str) -> List[Diag]:
2423
+ """把宽松解析下"能过但不规范"的东西提升为错误。
2424
+
2425
+ L3 end 省略种类(parser 记为 soft)
2426
+ L4 元组元素 > 3
2427
+ L5 行宽 > 100 列
2428
+ """
2429
+ out: List[Diag] = []
2430
+
2431
+ # L3:parser 的 soft 通道
2432
+ for d in getattr(res_parse, "soft", []) or []:
2433
+ out.append(Diag(d.code, f"[{label}] {d.message}", d.line, d.col))
2434
+
2435
+ # L4:元组上限(类型与表达式都查)
2436
+ if res_parse.module is not None:
2437
+ for kind in ("type-tuple", "tuple"):
2438
+ for node in walk(res_parse.module, kind):
2439
+ if len(node.children) > MAX_TUPLE:
2440
+ what = "元组类型" if kind == "type-tuple" else "元组"
2441
+ out.append(Diag(
2442
+ "L4-TupleTooLong",
2443
+ f"[{label}] {what}有 {len(node.children)} 个元素,"
2444
+ f"上限 {MAX_TUPLE}(L4)",
2445
+ node.line, node.col))
2446
+
2447
+ # L5:行宽
2448
+ for i, line in enumerate(src.splitlines(), 1):
2449
+ if len(line) > MAX_LINE:
2450
+ out.append(Diag(
2451
+ "L5-LineTooLong",
2452
+ f"[{label}] 第 {i} 行有 {len(line)} 列,上限 {MAX_LINE}(L5)",
2453
+ i, MAX_LINE + 1))
2454
+
2455
+ return out
2456
+
2457
+
2458
+ # ---------------------------------------------------------------- 文件层
2459
+
2460
+ def check_files(tu_path: str, ai_path: Optional[str] = None,
2461
+ strict: bool = False, overflow: str = "off") -> CheckResult:
2462
+ with open(tu_path, "r", encoding="utf-8") as f:
2463
+ tu_src = f.read()
2464
+ ai_src = None
2465
+ if ai_path is None:
2466
+ guess = os.path.splitext(tu_path)[0] + ".eln"
2467
+ if os.path.exists(guess):
2468
+ ai_path = guess
2469
+ if ai_path and os.path.exists(ai_path):
2470
+ with open(ai_path, "r", encoding="utf-8") as f:
2471
+ ai_src = f.read()
2472
+ module = os.path.splitext(os.path.basename(tu_path))[0]
2473
+ return check_module(tu_src, ai_src, module, strict=strict, overflow=overflow)