@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
@@ -0,0 +1,739 @@
1
+ #!/usr/bin/env python3
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ # Copyright 2026 Elench contributors
4
+
5
+ # -*- coding: utf-8 -*-
6
+ """成本表达式与 `while` 上界提取(G29)。
7
+
8
+ 规格里的成本表达式(§7.2):
9
+
10
+ κ ::= 1 | n | x̂ | κ₁ + κ₂ | n · κ | κ₁ ⊔ κ₂ | log₂(x̂) | |x|
11
+
12
+ 本模块只实现「提取上界」需要的那一小块:把条件表达式变成界表达式。
13
+
14
+ **界表达式**比成本表达式更窄——它只有三种形态:
15
+
16
+ B ::= N (常数或符号量)
17
+ | x.length() (尺寸调用)
18
+ | x (变量)
19
+ | a - b (两个符号量之差,用于 log(hi - lo) 这类)
20
+
21
+ **上界提取规则(G29 甲方案:认形状)**
22
+
23
+ | 条件 | 上界 |
24
+ |---|---|
25
+ | `i < e` | `e - i`(i 从初值往上数,圈数约等于 e - i) |
26
+ | `i <= e` | `e - i + 1` |
27
+ | `i > e` | `i - e` |
28
+ | `s.length() > 0` | `s.length()` |
29
+ | `a and b` | `min(B(a), B(b))` |
30
+ | `a or b` | `max(B(a), B(b))` |
31
+ | `P(args)` 且 P 有 repeats | P 的 repeats 表达式,实参代入 |
32
+ | 其它 | `None`(抽不出) |
33
+
34
+ **抽不出时的处理(丙方案的精神)**:**明确返回 `None` 并给出原因**,
35
+ 由调用方决定报错还是记 ⊤——**绝不静默超时**。
36
+ """
37
+
38
+ from typing import List, Optional, Tuple
39
+
40
+ from parser import Node
41
+ from ast_util import descendants as _descendants
42
+
43
+
44
+ # ---------------------------------------------------------------- 界表达式
45
+
46
+ class Bound:
47
+ """界表达式。`kind` 取值:const / size / var / sub / min / max / log2。"""
48
+
49
+ __slots__ = ("kind", "value", "left", "right", "args")
50
+
51
+ def __init__(self, kind: str, value=None, left=None, right=None, args=None):
52
+ self.kind = kind
53
+ self.value = value
54
+ self.left = left
55
+ self.right = right
56
+ self.args = args or []
57
+
58
+ def __repr__(self) -> str:
59
+ return f"Bound({self.render()})"
60
+
61
+ def render(self) -> str:
62
+ if self.kind == "const":
63
+ return str(self.value)
64
+ if self.kind == "size":
65
+ return f"{self.value}.length()"
66
+ if self.kind == "var":
67
+ return str(self.value)
68
+ if self.kind == "sub":
69
+ return f"({self.left.render()} - {self.right.render()})"
70
+ if self.kind == "min":
71
+ return f"min({self.left.render()}, {self.right.render()})"
72
+ if self.kind == "max":
73
+ return f"max({self.left.render()}, {self.right.render()})"
74
+ if self.kind == "log2":
75
+ return f"log2({self.left.render()})"
76
+ if self.kind == "call":
77
+ inner = ", ".join(a.render() for a in self.args)
78
+ return f"{self.value}({inner})"
79
+ return "?"
80
+
81
+ def variables(self) -> List[str]:
82
+ """界表达式里出现的变量名(用于「上界是不是依赖了循环内被改的变量」)。"""
83
+ if self.kind == "var":
84
+ return [self.value]
85
+ if self.kind == "size":
86
+ return [self.value]
87
+ if self.kind == "sub":
88
+ return self.left.variables() + self.right.variables()
89
+ if self.kind in ("min", "max", "log2"):
90
+ return self.left.variables()
91
+ if self.kind == "call":
92
+ out = []
93
+ for a in self.args:
94
+ out.extend(a.variables())
95
+ return out
96
+ return []
97
+
98
+
99
+ SIZE_FNS = ("length", "size", "capacity", "len")
100
+
101
+
102
+ # ---------------------------------------------------------------- 表达式 → 界
103
+
104
+ def expr_to_bound(n: Node) -> Optional[Bound]:
105
+ """把一个**表达式**变成界表达式;认不出返回 None。"""
106
+ if n is None:
107
+ return None
108
+
109
+ if n.kind == "lit-int":
110
+ return Bound("const", value=n.value)
111
+
112
+ if n.kind == "path":
113
+ return Bound("var", value=n.name)
114
+
115
+ if n.kind in ("method-call", "call"):
116
+ fn = (n.name or "").split(".")[-1]
117
+ if fn in SIZE_FNS:
118
+ # xs.length() —— 路径就是被调对象
119
+ target = n.children[0] if n.children and n.children[0].kind == "path" else None
120
+ return Bound("size", value=(target.name if target else "?"))
121
+ # 其它调用:`log(hi - lo)` 之类
122
+ if fn in ("log", "log2"):
123
+ arg = _first_arg(n)
124
+ inner = expr_to_bound(arg) if arg is not None else None
125
+ if inner is not None:
126
+ return Bound("log2", left=inner)
127
+ return None
128
+ return None
129
+
130
+ # `.value` 优先是运算符
131
+ if n.kind == "binary":
132
+ op = n.value or ""
133
+ a, b = (n.children + [None, None])[:2]
134
+ if op == "-":
135
+ la = expr_to_bound(a)
136
+ lb = expr_to_bound(b)
137
+ if la is not None and lb is not None:
138
+ return Bound("sub", left=la, right=lb)
139
+ return None
140
+ # `+` / `*` 不做界(它们的上界需要更多算术推理,留给 M2)。
141
+ # **注意**:`O(a.length() * b.length())` 这种 target 由 cost_interp 单独处理
142
+ # (走 `_target_cost`),不走这里——否则 `while (a * b < 10)` 会被误当计数器比较。
143
+ return None
144
+
145
+ return None
146
+
147
+
148
+ def _first_arg(call: Node) -> Optional[Node]:
149
+ for c in call.children:
150
+ if c.kind in ("args", "arg-list"):
151
+ for a in c.children:
152
+ return a
153
+ return None
154
+ return None
155
+
156
+
157
+ # ---------------------------------------------------------------- 条件 → 上界
158
+
159
+ def bound_of_condition(cond: Node, repeats_of=None,
160
+ zero_vars=frozenset(), dec_vars=frozenset(),
161
+ init_of: Optional[dict] = None) -> Tuple[Optional[Bound], str]:
162
+ """从 `while` 的条件推出迭代次数上界。
163
+
164
+ 返回 `(界, 原因)`;界为 None 时,原因说明为什么抽不出。
165
+ """
166
+ if cond is None:
167
+ return None, "循环条件为空"
168
+
169
+ # ---- and / or
170
+ if cond.kind == "binary" and (cond.value or "") in ("and", "or"):
171
+ a, b = (cond.children + [None, None])[:2]
172
+ ba, ra = bound_of_condition(a, repeats_of, zero_vars, dec_vars, init_of)
173
+ bb, rb = bound_of_condition(b, repeats_of, zero_vars, dec_vars, init_of)
174
+ if ba is not None and bb is not None:
175
+ kind = "min" if cond.value == "and" else "max"
176
+ return Bound(kind, left=ba, right=bb), f"{cond.value} 组合"
177
+ # and:漏掉可推的一侧只会失准;or:同理。
178
+ # **不取"可推的那一侧",因为那可能偏小。**
179
+ return None, f"{ra};{rb}"
180
+
181
+ # ---- 谓词调用 → repeats
182
+ if cond.kind == "call" and cond.name:
183
+ label = cond.name.split(".")[-1]
184
+ rep = repeats_of(label) if repeats_of else None
185
+ if rep is not None:
186
+ return rep, f"谓词 {label} 的 repeats"
187
+ return None, f"谓词 {label} 没有 repeats"
188
+
189
+ # ---- 比较
190
+ if cond.kind == "binary" and (cond.value or "") in ("<", "<=", ">", ">="):
191
+ op = cond.value
192
+ a, b = (cond.children + [None, None])[:2]
193
+ lb = expr_to_bound(b)
194
+ la = expr_to_bound(a)
195
+
196
+ # 归一成 `计数器 op 上界`
197
+ zl = la is not None and la.kind == "var" and la.value in zero_vars
198
+ zr = lb is not None and lb.kind == "var" and lb.value in zero_vars
199
+ # **两侧都必须可推**才算数:只认出一侧就去凑数,是在猜,
200
+ # 而猜出来的"上界"可能偏小,正是我们最怕的失真。
201
+ if la is None and lb is None:
202
+ return None, f"{op} 两侧都不是可推量"
203
+ if la is None:
204
+ return None, f"{op} 比较里左侧不可推"
205
+ if lb is None:
206
+ return None, f"{op} 比较里右侧不可推"
207
+ if op in ("<", "<="):
208
+ return _sub_or_plain(lb, la, op == "<=", zl), f"{op} 比较"
209
+
210
+ # ---- 递减循环(甲):`while (j > 0)` / `while (j >= 1)` 且 j 体内单调递减
211
+ # 上界 = j 的**初值**。这不是猜:j 只减不增,从 v0 出发,最多转 v0 圈。
212
+ if op in (">", ">=") and la is not None and la.kind == "var":
213
+ if la.value in dec_vars:
214
+ init = init_of.get(la.value) if init_of else None
215
+ if init is not None:
216
+ inner = expr_to_bound(init)
217
+ if inner is not None:
218
+ return inner, f"递减循环:{la.value} 从初值单调递减到 0"
219
+
220
+ return _sub_or_plain(la, lb, op == ">=", zr), f"{op} 比较"
221
+
222
+ return None, f"条件形态 {cond.kind} 不可推"
223
+
224
+
225
+ def _sub_or_plain(high: Bound, low: Optional[Bound], incl: bool,
226
+ init_zero: bool = False) -> Bound:
227
+ """`i < e` → `e - i`;若已知 `i` 的初值为 0,直接取 `e`。
228
+
229
+ `incl`(`<=`)多转一圈,但**上界取松不失真**,故不 +1——
230
+ T13-a 规定提前退出的循环按上界算并标注"可能偏松"。
231
+ """
232
+ if init_zero:
233
+ return high
234
+ if low is not None and low.kind in ("const", "var"):
235
+ return Bound("sub", left=high, right=low)
236
+ return high
237
+
238
+
239
+ # ---------------------------------------------------------------- 便利入口
240
+
241
+ def monotone_decreasing(fn: Node) -> dict:
242
+ """本函数里「只做减法」的变量名 → 初值节点。
243
+
244
+ 判据(**保守,不是数据流分析**):
245
+ 1. 声明处初值不是 0(`u64 j = i;`)
246
+ 2. 函数体内对它的赋值**只有** `j = j - <常量>` 这一种形态
247
+ 满足就认为它单调递减,`while (j > 0)` 的迭代次数不超过初值。
248
+
249
+ **E4(2026-11-04)**:以前**循环外**的赋值(如 `i = xs.length()`)也会剔除变量,
250
+ 于是「循环次数由分支决定」的写法完全拿不到上界。现在区分开:
251
+
252
+ - 循环**体内**的赋值:仍按老规则(只许 `j = j - const` / `j = 0`);
253
+ - 循环**体外**的赋值:记成「初值覆盖」,**但只在声明处初值是字面量 0 时采用**
254
+ (`max(0, x) = x`,而 u64 计数器不可能小于 0)。初值非 0 时仍剔除——
255
+ 那种情况要取 max,而这里只能给一个节点,取 max 会失真。
256
+ """
257
+ from parser import Node as _N # noqa: F401
258
+
259
+ init: dict = {}
260
+ for k in ("const-decl", "var-decl"):
261
+ for d in _descendants(fn, k):
262
+ if len(d.children) >= 2:
263
+ init[d.name] = d.children[1]
264
+
265
+ # **循环体内的节点集合**:体内赋值才是"推进量",体外的是"初值"
266
+ in_loop: set = set()
267
+ for w in _descendants(fn, "while"):
268
+ blk = next((c for c in (getattr(w, "children", None) or [])
269
+ if getattr(c, "kind", "") == "block"), None)
270
+ stack = [blk] if blk is not None else []
271
+ while stack:
272
+ nd = stack.pop()
273
+ in_loop.add(id(nd))
274
+ stack.extend(getattr(nd, "children", None) or [])
275
+
276
+ bad: set = set()
277
+ override: dict = {}
278
+ for a in _descendants(fn, "assign"):
279
+ if not a.children or a.children[0].kind != "path":
280
+ continue
281
+ nm = a.children[0].name
282
+ if nm not in init:
283
+ continue
284
+ rhs = a.children[1] if len(a.children) > 1 else None
285
+ # 循环外的赋值 → 只影响"初值",不影响"是否单调"
286
+ if id(a) not in in_loop:
287
+ if rhs is not None:
288
+ override[nm] = rhs
289
+ continue
290
+ ok = False
291
+ if rhs is not None and rhs.kind == "binary" and (rhs.value or "") == "-":
292
+ left, right = (rhs.children + [None, None])[:2]
293
+ if (left is not None and left.kind == "path" and left.name == nm
294
+ and right is not None and right.kind == "lit-int"):
295
+ ok = True
296
+ # `j = 0;` 是「提前退出」的惯用写法(插入排序就这么写)
297
+ if rhs is not None and rhs.kind == "lit-int" and str(rhs.value) == "0":
298
+ ok = True
299
+ if not ok:
300
+ bad.add(nm)
301
+
302
+ out: dict = {}
303
+ for nm, v in init.items():
304
+ if nm in bad:
305
+ continue
306
+ # 初值是字面量 0 才用覆盖(max(0, x) = x)
307
+ if nm in override and v is not None and v.kind == "lit-int" and str(v.value) == "0":
308
+ out[nm] = override[nm]
309
+ else:
310
+ out[nm] = v
311
+ return out
312
+
313
+ def zero_initialised(fn: Node) -> set:
314
+ """本函数里初值为字面量 0 的变量名。
315
+
316
+ 这不是数据流分析:只看声明处 `T i = 0;` 这一种形态。
317
+ 用途单一——`while (i < n)` 里若 i 从 0 起,上界就是 n,不必写成 `n - i`。
318
+ """
319
+ names = set()
320
+ for k in ("const-decl", "var-decl"):
321
+ for d in [d for d in _descendants(fn, k)]:
322
+ if len(d.children) >= 2:
323
+ val = d.children[1]
324
+ if val.kind == "lit-int" and str(val.value) == "0":
325
+ names.add(d.name)
326
+ return names
327
+ def const_bindings(fn: Node) -> dict:
328
+ """本函数里 `const T x = <界表达式>;` 的绑定表。
329
+
330
+ 用途:把 `i < n` 的 `n` 解析回 `xs.length()`,避免上界里出现局部变量名
331
+ (报告里写 `n` 读的人还得回去查 `n` 是什么)。
332
+ """
333
+ out = {}
334
+ for d in _descendants(fn, "const-decl"):
335
+ if len(d.children) >= 2:
336
+ b = expr_to_bound(d.children[1])
337
+ if b is not None:
338
+ out[d.name] = b
339
+ return out
340
+
341
+
342
+ def substitute(b: Optional[Bound], table: dict) -> Optional[Bound]:
343
+ """把界表达式里的自由变量按 const 绑定表展开(只展开一层,防环)。"""
344
+ if b is None:
345
+ return None
346
+ if b.kind == "var" and b.value in table:
347
+ return table[b.value]
348
+ if b.kind == "sub":
349
+ return Bound("sub", left=substitute(b.left, table),
350
+ right=substitute(b.right, table))
351
+ if b.kind in ("min", "max"):
352
+ return Bound(b.kind, left=substitute(b.left, table),
353
+ right=substitute(b.right, table))
354
+ if b.kind == "log2":
355
+ return Bound("log2", left=substitute(b.left, table))
356
+ return b
357
+
358
+
359
+ WAY_OUT = ("三条出路:① 把条件写成尺寸比较 `i < xs.length()`;"
360
+ "② 把条件包成谓词,在它的 spec 里写 repeats;"
361
+ "③ 改写成 for + break")
362
+
363
+
364
+ # ---------------------------------------------------------------- E21:循环必须能推进
365
+ #
366
+ # **为什么需要这个检查**:
367
+ # `while (j > 0) { s = s + 1; }` 的循环体根本不改 `j`,是**死循环**。
368
+ # 但在加这个检查之前,`bound_of_condition` 只看守卫就给上界(`O(n)`)——
369
+ # **上界要求 κ ≥ 真实成本,而死循环的成本是 ∞**,这是 unsound 里最糟的一类:
370
+ # 不是算小了,是**声称一个跑不完的循环会跑完**。
371
+ #
372
+ # **这一层是"必要不充分"的临时缓解**:
373
+ # 只要求「体内出现过对推进量的修改」,
374
+ # 挡不住"修改写在 `if` 里可能不执行"的情形(那要靠 `decreases` + ΔM 校验,见批次 R)。
375
+
376
+ def _counter_of(cond: Optional[Node]):
377
+ """从守卫里找出"推进量":('var', 名) / ('container', 名) / None。"""
378
+ if cond is None:
379
+ return None
380
+ # `and` / `or`:任一分支能给出推进量就够(上界本来取 min/max)
381
+ if cond.kind == "binary" and (cond.value or "") in ("and", "or"):
382
+ for c in cond.children:
383
+ got = _counter_of(c)
384
+ if got is not None:
385
+ return got
386
+ return None
387
+ if cond.kind != "binary" or (cond.value or "") not in ("<", "<=", ">", ">="):
388
+ return None
389
+ left = cond.children[0] if cond.children else None
390
+ if left is None:
391
+ return None
392
+ if left.kind == "path" and left.name:
393
+ return ("var", left.name)
394
+ # `while (q.length() > 0)`:推进量是容器 q 本身
395
+ if left.kind == "method-call" and (left.name or "").split(".")[-1] in ("length", "size"):
396
+ recv = left.children[0] if left.children else None
397
+ if recv is not None and recv.kind == "path" and recv.name:
398
+ return ("container", recv.name)
399
+ return None
400
+
401
+
402
+ def _touched_names(body: Node) -> set:
403
+ """体内所有"可能被改变"的名字:赋值左侧、方法调用接收者、作为实参传入的名字。"""
404
+ got = set()
405
+ for a in _descendants(body, "assign"):
406
+ lhs = a.children[0] if a.children else None
407
+ if lhs is not None and lhs.kind == "path" and lhs.name:
408
+ got.add(lhs.name)
409
+ for mc in _descendants(body, "method-call"):
410
+ recv = mc.children[0] if mc.children else None
411
+ if recv is not None:
412
+ for pth in _descendants(recv, "path"):
413
+ if pth.name:
414
+ got.add(pth.name) # q.pop() / xs.sort() / m.at(i)
415
+ for call in _descendants(body, "call"):
416
+ # **只有按引用传(`&x`)才可能改它**;按值传(`f(i)`)改不了。
417
+ # 这条区分很关键:把按值传也算"碰过",会放过真正的死循环。
418
+ # 注意实参在 AST 里包在 `args` 节点内,所以用 descendant 找 `ref`。
419
+ for r in _descendants(call, "ref"):
420
+ for pth in _descendants(r, "path"):
421
+ if pth.name:
422
+ got.add(pth.name) # apply_top(& values, & operators)
423
+ return got
424
+
425
+
426
+ def progresses(wh: Node) -> Tuple[bool, str]:
427
+ """循环体是否真的在推进守卫里的那个量。返回 (能不能推进, 原因)。
428
+
429
+ 判不出来时**返回 True**(不阻塞)——这一层只是挡住"明显不可能推进"的,
430
+ 不做完整的数据流分析。
431
+ """
432
+ cond = wh.children[0] if wh.children else None
433
+ counter = _counter_of(cond)
434
+ if counter is None:
435
+ return True, "条件里没有可识别的推进量,不检查"
436
+ kind, name = counter
437
+ body = next((c for c in wh.children[1:] if c.kind == "block"), None)
438
+ if body is None:
439
+ return False, f"循环体为空,{name} 不可能变化"
440
+ touched = _touched_names(body)
441
+ if name in touched:
442
+ return True, f"体内修改了 {name}"
443
+ what = "计数器" if kind == "var" else "容器"
444
+ return False, f"{what} {name} 在循环体里从未被修改"
445
+
446
+
447
+
448
+ def _temp_halving(body: Node, var: str):
449
+ """`var = tmp`,且 `tmp` 在循环体里**只定义一次**、形如 `(var ± c) / k`(k≥2)。
450
+
451
+ **判据刻意写窄**(宁可判不出,不可判错):
452
+ 1. `var = tmp` 必须是循环体的**直接子语句**(不在 if 分支里);
453
+ 2. 循环体里对 `var` 的赋值**只能有这一处**;
454
+ 3. `tmp` 在整个循环体里**只被赋值一次**,且在被用之前;
455
+ 4. `tmp` 的右值是 `/ k`(k≥2),分子里出现 `var`。
456
+
457
+ 反例为什么会被挡住:`p = i; i = p;` 违反 3(p 赋值两次);
458
+ `if (c) i = i/2; else i = i-1;` 违反 1;`i = p` 而 `p` 是参数(没在体内定义)违反 3。
459
+ """
460
+ body_children = [c for c in (getattr(body, "children", None) or [])]
461
+ uses = [st for st in body_children
462
+ if getattr(st, "kind", "") == "assign"
463
+ and getattr((st.children or [None])[0], "name", "") == var]
464
+ if len(uses) != 1:
465
+ return None
466
+ st = uses[0]
467
+ rhs = (st.children + [None, None])[1]
468
+ if getattr(rhs, "kind", "") != "path" or not getattr(rhs, "name", None):
469
+ return None
470
+ tmp = rhs.name
471
+ defs = []
472
+ for d in body_children:
473
+ if getattr(d, "kind", "") in ("var-decl", "const-decl") and getattr(d, "name", "") == tmp:
474
+ defs.append(d)
475
+ if getattr(d, "kind", "") == "assign" and getattr((d.children or [None])[0], "name", "") == tmp:
476
+ defs.append(d)
477
+ if len(defs) != 1:
478
+ return None
479
+ # 定义必须在使用之前
480
+ idx_def = body_children.index(defs[0])
481
+ idx_use = body_children.index(st)
482
+ if idx_def > idx_use:
483
+ return None
484
+ expr = defs[0].children[-1]
485
+ while getattr(expr, "kind", "") == "paren" and getattr(expr, "children", None):
486
+ expr = expr.children[0]
487
+ if getattr(expr, "kind", "") != "binary" or (expr.value or "") != "/":
488
+ return None
489
+ num, den = (expr.children + [None, None])[:2]
490
+ if getattr(den, "kind", "") != "lit-int":
491
+ return None
492
+ try:
493
+ if int(den.value) < 2:
494
+ return None
495
+ except (TypeError, ValueError):
496
+ return None
497
+ names = {getattr(x, "name", None) for x in _descendants(num, "path")}
498
+ if var not in names:
499
+ return None
500
+ return tmp
501
+
502
+
503
+ def _log_loop(wh: Node, fn: Node = None):
504
+ """识别「每轮 ×2 / ÷2」的循环,返回 `(Bound, 说明)` 或 None。
505
+
506
+ **为什么需要**(L-01):`while (i < n) { i = i * 2; }` 以前被算成 `n(n)`——
507
+ O(n),带 `O(log n)` target 的**正确程序会被误拒**。
508
+ 减半(`i = i / 2`)更糟:上界成了 `n(i)`,与 target 的 `n` 不是一个量 → **判不了**。
509
+
510
+ 判定只看**形状**:循环体里对计数器有 `i = i * 常数` 或 `i = i / 常数`。
511
+ 界:`<` 型取守卫另一侧,`>` 型取计数器的初值。
512
+ """
513
+ cond = wh.children[0] if (wh.children or []) else None
514
+ if cond is None or getattr(cond, "kind", "") != "binary":
515
+ return None
516
+ op = cond.value or ""
517
+ if op not in ("<", "<=", ">", ">="):
518
+ return None
519
+ left, right = (cond.children + [None, None])[:2]
520
+ if getattr(left, "kind", "") != "path" or not getattr(left, "name", None):
521
+ return None
522
+ var = left.name
523
+
524
+ body = next((c for c in wh.children[1:] if getattr(c, "kind", "") == "block"), None)
525
+ if body is None:
526
+ return None
527
+ # 体里必须有 `var = var * k` / `var = var / k`
528
+ found = None
529
+ # **只看循环体的直接子语句**(2026-11-06 实测的反例):以前用 `_descendants`
530
+ # 会把 `if (c) { i = i / 2; } else { i = i - 1; }` 里的那次减半当成
531
+ # "每轮都减半"——那是**线性**循环,报 log 就是**假上界**。
532
+ for st in [c for c in (getattr(body, "children", None) or [])]:
533
+ lhs, rhs = (st.children + [None, None])[:2]
534
+ if getattr(lhs, "kind", "") != "path" or getattr(lhs, "name", "") != var:
535
+ continue
536
+ if getattr(rhs, "kind", "") != "binary" or (rhs.value or "") not in ("*", "/"):
537
+ continue
538
+ a, b = (rhs.children + [None, None])[:2]
539
+ names = {getattr(a, "name", None), getattr(b, "name", None)}
540
+ has_var = var in names
541
+ has_const = any(getattr(x, "kind", "") == "lit-int" for x in (a, b) if x is not None)
542
+ if has_var and has_const:
543
+ found = rhs.value
544
+ break
545
+ if found is None:
546
+ # **中转变量**:`i = p` 而 `p = (i - 1) / 2`(上滤/二分/快速幂的常见写法)。
547
+ # 只走窄规则,见 `_temp_halving` 的四条判据。
548
+ if _temp_halving(body, var) is not None:
549
+ found = "/"
550
+ if found is None:
551
+ return None
552
+ # **倍增必须检查初值**(2026-11-06 实测的反例):`u64 i = 0; i = i * 2;`
553
+ # 永远不动(0×2=0),是真死循环,可它**形状完全对**——以前被判成
554
+ # `log2(n)` 并**判为达标**,那是一个假上界。这里只接受字面初值 ≥ 1。
555
+ if found == "*":
556
+ _init = None
557
+ if fn is not None:
558
+ for d in _descendants(fn, "var-decl"):
559
+ if getattr(d, "name", "") == var and len(d.children) >= 2:
560
+ _init = d.children[-1]
561
+ break
562
+ if _init is None:
563
+ for d in _descendants(fn, "const-decl"):
564
+ if getattr(d, "name", "") == var and len(d.children) >= 2:
565
+ _init = d.children[-1]
566
+ break
567
+ if getattr(_init, "kind", "") != "lit-int":
568
+ return None
569
+ try:
570
+ if int(_init.value) < 1:
571
+ return None
572
+ except (TypeError, ValueError):
573
+ return None
574
+
575
+ if op in ("<", "<="):
576
+ b = expr_to_bound(right)
577
+ why = f"循环变量 {var} 每轮乘除 2,界取自 {var} {op} 的右侧"
578
+ else:
579
+ # `i > 1` 型:用计数器的初值(`u64 i = n;` → n)
580
+ b = None
581
+ if fn is not None:
582
+ for d in _descendants(fn, "var-decl"):
583
+ if getattr(d, "name", "") == var and len(d.children) >= 2:
584
+ b = expr_to_bound(d.children[-1])
585
+ break
586
+ if b is None:
587
+ # 初值不在函数体里(**参数**,如 `heapify_up(vector& h, u64 i)`):
588
+ # 递减型循环从 i 减半到 0,界就是 `log2(i)` 本身。
589
+ # 它与 target 的 `n` 是否同符号,交给 requires 那条线去解决。
590
+ b = Bound("var", value=var)
591
+ why = f"循环变量 {var} 每轮除以 2,界取自它的初值(无初值时取它自己)"
592
+ if b is None:
593
+ return None
594
+ return Bound("log2", left=b), why
595
+
596
+
597
+ def _gcd_loop(wh: Node, fn: Node = None):
598
+ """欧几里得算法:`while (b != 0) { t = b; b = a % b; a = t; }` ⇒ 步数 ≤ 2·log2(a)。
599
+
600
+ **为什么这条必须靠"认成语"而不是数据流**:圈数来自**数论**(Lamé 定理,1844),
601
+ 不是程序形状——每一步的值是上一次的余数,收敛速度取决于相邻斐波那契数这个最坏情况。
602
+
603
+ 证明骨架:设 a > b > 0,写 a = q·b + r。
604
+ · b ≤ a/2 ⇒ r < b ≤ a/2 —— 一步减半
605
+ · b > a/2 ⇒ q = 1, r = a−b < a/2 —— 两步减半
606
+ 所以每两步规模至少减半 ⇒ 步数 ≤ 2·log2(a)。
607
+
608
+ **判据写死**(只认这一个形状,认不出就不给界):
609
+ · 守卫是 `b != 0` 或 `b > 0`;
610
+ · 循环体恰好三条直接语句:`t = b; b = a % b; a = t;`
611
+ 任何一条不符就返回 None——宁可判不出,不可判错。
612
+ """
613
+ cond = wh.children[0] if (wh.children or []) else None
614
+ if cond is None or getattr(cond, "kind", "") != "binary":
615
+ return None
616
+ if (cond.value or "") not in ("!=", ">"):
617
+ return None
618
+ left, right = (cond.children + [None, None])[:2]
619
+ if getattr(left, "kind", "") != "path" or not getattr(left, "name", None):
620
+ return None
621
+ bvar = left.name
622
+ body = next((c for c in wh.children[1:] if getattr(c, "kind", "") == "block"), None)
623
+ if body is None:
624
+ return None
625
+ sts = [c for c in (getattr(body, "children", None) or [])]
626
+ if len(sts) != 3:
627
+ return None
628
+ d0, d1, d2 = sts
629
+ if [getattr(s, "kind", "") for s in (d0, d1, d2)] != ["var-decl", "assign", "assign"]:
630
+ return None
631
+ tmp = getattr(d0, "name", "")
632
+ if len(d0.children) < 2 or getattr(d0.children[-1], "name", "") != bvar:
633
+ return None
634
+ lhs1, rhs1 = (d1.children + [None, None])[:2]
635
+ if getattr(lhs1, "name", "") != bvar:
636
+ return None
637
+ if getattr(rhs1, "kind", "") != "binary" or (rhs1.value or "") != "%":
638
+ return None
639
+ m1, m2 = (rhs1.children + [None, None])[:2]
640
+ if getattr(m2, "name", "") != bvar or getattr(m1, "kind", "") != "path":
641
+ return None
642
+ avar = m1.name
643
+ if avar == bvar:
644
+ return None
645
+ lhs2, rhs2 = (d2.children + [None, None])[:2]
646
+ if getattr(lhs2, "name", "") != avar or getattr(rhs2, "name", "") != tmp:
647
+ return None
648
+ return Bound("log2", left=Bound("var", value=avar)), \
649
+ f"欧几里得循环({avar} % {bvar}):每两步减半,步数 ≤ 2·log2({avar})"
650
+
651
+
652
+ def _cyclic_loop(wh: Node, fn: Node = None):
653
+ """`i = (i + 1) % LEN` ⇒ 圈数 ≤ LEN(环形计数器)。
654
+
655
+ **口径**:κ 是**对终止执行的**上界。这类循环要么在 LEN 步内找到出口,
656
+ 要么走满一圈回到起点、永不终止——后者没有成本。所以不需要终止性前提。
657
+
658
+ 只认这一个形状:`(i + c) % E`,`E` 能翻译成尺寸量(`X.length()` 或一个名字)。
659
+ """
660
+ body = next((c for c in wh.children[1:] if getattr(c, "kind", "") == "block"), None)
661
+ if body is None:
662
+ return None
663
+ for st in _descendants(body, "assign"):
664
+ lhs, rhs = (st.children + [None, None])[:2]
665
+ if getattr(lhs, "kind", "") != "path" or not getattr(lhs, "name", None):
666
+ continue
667
+ if getattr(rhs, "kind", "") != "binary" or (rhs.value or "") != "%":
668
+ continue
669
+ left, right = (rhs.children + [None, None])[:2]
670
+ # `(i + 1)` 会被解析成 **paren 节点**——先剥括号再判形状。
671
+ while getattr(left, "kind", "") == "paren" and getattr(left, "children", None):
672
+ left = left.children[0]
673
+ if getattr(left, "kind", "") != "binary" or (left.value or "") != "+":
674
+ continue
675
+ a, b = (left.children + [None, None])[:2]
676
+ names = {getattr(a, "name", None), getattr(b, "name", None)}
677
+ if lhs.name not in names:
678
+ continue
679
+ bd = expr_to_bound(right)
680
+ if bd is None:
681
+ continue
682
+ return Bound(bd.kind, value=bd.value, left=bd.left, right=bd.right), \
683
+ f"环形计数器 {lhs.name} = ({lhs.name} + 1) % …,圈数不超过模数"
684
+ return None
685
+
686
+
687
+ def bound_of_while(wh: Node, repeats_of=None, fn: Node = None):
688
+ """`while` 节点的上界:`(界, 原因)`。
689
+
690
+ 抽不出时,**原因里必须带出路**——只说"推不出"等于把问题丢回给生成者。
691
+ """
692
+ cond = wh.children[0] if wh.children else None
693
+ zv = zero_initialised(fn) if fn is not None else frozenset()
694
+ # **先看是不是"每轮 ×2 / ÷2"**(L-01):这类循环的对数界要比一般推导优先。
695
+ lg = _log_loop(wh, fn)
696
+ if lg is not None:
697
+ return lg
698
+ cy = _cyclic_loop(wh, fn)
699
+ if cy is not None:
700
+ return cy
701
+ gd = _gcd_loop(wh, fn)
702
+ if gd is not None:
703
+ return gd
704
+
705
+ ok, prog_why = progresses(wh)
706
+ if not ok:
707
+ return None, f"{prog_why}(循环不会推进 ⇒ 不给上界,E21)"
708
+ b, why = bound_of_condition(cond, repeats_of, zv)
709
+ if b is not None and fn is not None:
710
+ b = substitute(b, const_bindings(fn))
711
+ if b is None:
712
+ why = f"{why}。{WAY_OUT}"
713
+ return b, why
714
+
715
+
716
+ # ---------------------------------------------------------------- 演示
717
+
718
+ if __name__ == "__main__":
719
+ import sys
720
+ from parser import parse_source
721
+
722
+ src = sys.stdin.read() if not sys.stdin.isatty() else ""
723
+ if not src:
724
+ print("用法:python bound.py < 含 while 的 .eln 文件", file=sys.stderr)
725
+ raise SystemExit(2)
726
+ mod = parse_source(src, "x.eln").module
727
+
728
+ def walk(n, kind, acc):
729
+ if n.kind == kind:
730
+ acc.append(n)
731
+ for c in n.children:
732
+ walk(c, kind, acc)
733
+
734
+ ws = []
735
+ walk(mod, "while", ws)
736
+ for w in ws:
737
+ cond = w.children[0] if w.children else None
738
+ b, why = bound_of_condition(cond)
739
+ print(f" L{w.line} 上界 = {b.render() if b else '⊤'} ({why})")