lemmascript 0.6.11 → 0.6.13

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.
@@ -21,8 +21,20 @@ function lookup(env, name) {
21
21
  return undefined;
22
22
  return env.name === name ? env.ty : lookup(env.parent, name);
23
23
  }
24
+ function storageLookup(env, name) {
25
+ const entry = binding(env, name);
26
+ return entry ? (entry.storageTy ?? entry.ty) : undefined;
27
+ }
24
28
  function extend(env, name, ty) {
25
- return { name, ty, parent: env };
29
+ return { name, ty, storageTy: ty, parent: env };
30
+ }
31
+ /** A quantified variable that reuses the name of a binding in scope is emitted
32
+ * under a fresh name, so no later pass confuses it with that binding. */
33
+ function quantified(env, name, ty) {
34
+ const frame = extend(env, name, ty);
35
+ if (binding(env, name))
36
+ frame.emittedName = freshName(name);
37
+ return frame;
26
38
  }
27
39
  /** Shadow a binding with a narrowed type, keeping its callback state.
28
40
  * Dropping that state would let the body reference a renamed parameter by its
@@ -40,7 +52,7 @@ function refine(env, name, ty) {
40
52
  break;
41
53
  }
42
54
  }
43
- return { ...entry, name: entry?.name ?? name, ty, parent: env };
55
+ return { ...entry, name: entry?.name ?? name, ty, storageTy: entry?.storageTy ?? entry?.ty ?? ty, parent: env };
44
56
  }
45
57
  function asRawAccessPath(e) {
46
58
  if (e.kind === "var")
@@ -187,6 +199,60 @@ function negatedVarPresence(cond) {
187
199
  /** Collect all optional narrowings from an early-return condition.
188
200
  * Handles single checks (x === undefined) and compound || chains
189
201
  * (x === undefined || y === undefined). */
202
+ /** Extract field-path or optional-chain narrowings guaranteed after an early
203
+ * return (`if (d.b === undefined) return;` or `if (b?.tag !== 1) return;`, #354). */
204
+ function collectEarlyReturnPathNarrowings(cond) {
205
+ if (cond.kind === "binop" && cond.op === "||") {
206
+ return [
207
+ ...collectEarlyReturnPathNarrowings(cond.left),
208
+ ...collectEarlyReturnPathNarrowings(cond.right),
209
+ ];
210
+ }
211
+ // Negated field-path presence: `d.b === undefined` or `!d.b`
212
+ const f = presentFact(cond);
213
+ if (f && f.negated && f.scrutinee.kind === "field") {
214
+ const path = asTExprAccessPath(f.scrutinee);
215
+ if (path)
216
+ return [{ path, narrowedTy: f.innerTy }];
217
+ }
218
+ // Optional-chain comparison with non-undefined: `b?.tag !== 1` or `1 !== b?.tag`
219
+ // If `b` were undefined, `b?.tag` is undefined !== 1 (true -> returns early),
220
+ // so after the early return `b` is definitely present.
221
+ if (cond.kind === "binop" && cond.op === "!==") {
222
+ const [ocSide, otherSide] = cond.left.kind === "optChain"
223
+ ? [cond.left, cond.right]
224
+ : cond.right.kind === "optChain"
225
+ ? [cond.right, cond.left]
226
+ : [null, null];
227
+ if (ocSide && otherSide && !(otherSide.kind === "var" && otherSide.name === "undefined") &&
228
+ otherSide.ty.kind !== "optional" && otherSide.ty.kind !== "void" &&
229
+ ocSide.obj.ty.kind === "optional") {
230
+ const path = asTExprAccessPath(ocSide.obj);
231
+ if (path)
232
+ return [{ path, narrowedTy: ocSide.obj.ty.inner }];
233
+ }
234
+ }
235
+ // Bare negated optional chain `!b?.flag` or `b?.tag === undefined`
236
+ if (cond.kind === "unop" && cond.op === "!" && cond.expr.kind === "optChain" && cond.expr.obj.ty.kind === "optional") {
237
+ const path = asTExprAccessPath(cond.expr.obj);
238
+ if (path)
239
+ return [{ path, narrowedTy: cond.expr.obj.ty.inner }];
240
+ }
241
+ if (cond.kind === "binop" && cond.op === "===") {
242
+ const [ocSide, otherSide] = cond.left.kind === "optChain"
243
+ ? [cond.left, cond.right]
244
+ : cond.right.kind === "optChain"
245
+ ? [cond.right, cond.left]
246
+ : [null, null];
247
+ if (ocSide && otherSide && otherSide.kind === "var" && otherSide.name === "undefined" &&
248
+ ocSide.obj.ty.kind === "optional") {
249
+ const path = asTExprAccessPath(ocSide.obj);
250
+ if (path)
251
+ return [{ path, narrowedTy: ocSide.obj.ty.inner }];
252
+ }
253
+ }
254
+ return [];
255
+ }
190
256
  function collectEarlyReturnNarrowings(cond) {
191
257
  if (cond.kind === "binop" && cond.op === "||") {
192
258
  return [...collectEarlyReturnNarrowings(cond.left), ...collectEarlyReturnNarrowings(cond.right)];
@@ -295,6 +361,27 @@ function collectAndChainNarrowings(cond, ctx) {
295
361
  }
296
362
  return ctx;
297
363
  }
364
+ /** Walk an `||` chain of negated presence checks (`x === undefined || a.b === undefined || ...`)
365
+ * on the resolved left operand, returning a Ctx where those paths are narrowed
366
+ * for evaluating the right operand of `||` (since the RHS only runs when the
367
+ * LHS was false). Mirrors `collectAndChainNarrowings`. */
368
+ function collectOrChainNarrowings(cond, ctx) {
369
+ if (cond.kind === "binop" && cond.op === "||") {
370
+ const leftCtx = collectOrChainNarrowings(cond.left, ctx);
371
+ return collectOrChainNarrowings(cond.right, leftCtx);
372
+ }
373
+ const f = presentFact(cond);
374
+ if (f && f.negated) {
375
+ if (f.scrutinee.kind === "var") {
376
+ return withEnv(ctx, refine(ctx.env, f.scrutinee.name, f.innerTy));
377
+ }
378
+ const path = asTExprAccessPath(f.scrutinee);
379
+ if (path) {
380
+ return { ...ctx, narrowedPaths: [...ctx.narrowedPaths, { path, narrowedTy: f.innerTy }] };
381
+ }
382
+ }
383
+ return ctx;
384
+ }
298
385
  /** TS reference types that become value types in Dafny/Lean — const bindings need mutable var. */
299
386
  function isRefMutableInTS(ty) {
300
387
  return ty.kind === "array" || ty.kind === "map" || ty.kind === "set";
@@ -640,10 +727,13 @@ function resolveCallback(e, actual, baseArity, ctx) {
640
727
  // binding identities; nested declarations shadow them through ordinary lookup.
641
728
  let env = ctx.env;
642
729
  const frames = e.params.map((p, i) => {
730
+ const paramTy = executesDefault(i)
731
+ ? expandAlias(parseTsType(p.inferredTsType ?? p.tsType ?? "unknown"), ctx.typeDecls)
732
+ : p.rest ? { kind: "unknown" } : slots[i]?.ty ?? { kind: "void" };
643
733
  const frame = {
644
734
  name: p.name, parent: env,
645
- ty: executesDefault(i) ? expandAlias(parseTsType(p.inferredTsType ?? p.tsType ?? "unknown"), ctx.typeDecls)
646
- : p.rest ? { kind: "unknown" } : slots[i]?.ty ?? { kind: "void" },
735
+ ty: paramTy,
736
+ storageTy: paramTy,
647
737
  onRead: () => {
648
738
  captures?.add(i);
649
739
  // A forward reference must never resolve to an outer variable if
@@ -1011,7 +1101,11 @@ function resolveConstEnumMember(obj, name, ctx) {
1011
1101
  }
1012
1102
  function resolveExpr(e, ctx) {
1013
1103
  const expr = resolveExprInner(e, ctx);
1014
- return { ...expr, ty: numericValueType(expr.ty, ctx.typeDecls) };
1104
+ const out = { ...expr, ty: numericValueType(expr.ty, ctx.typeDecls) };
1105
+ if ("freshClone" in e && e.freshClone && (out.kind === "var" || out.kind === "field" || out.kind === "index" || out.kind === "call")) {
1106
+ return { ...out, freshClone: true };
1107
+ }
1108
+ return out;
1015
1109
  }
1016
1110
  function resolveExprInner(e, ctx) {
1017
1111
  switch (e.kind) {
@@ -1056,6 +1150,30 @@ function resolveExprInner(e, ctx) {
1056
1150
  if (e.op === "&&" || e.op === "==>") {
1057
1151
  rightCtx = collectAndChainNarrowings(left, ctx);
1058
1152
  }
1153
+ else if (e.op === "||") {
1154
+ // Preserve direct single-optional var comparisons (`opt === null || x < opt`,
1155
+ // `excludeTag === undefined || getTagId(t) !== excludeTag`) for transform's
1156
+ // native mirrored match lowering, as long as the non-optional side doesn't
1157
+ // also depend on a variable narrowed by `left`; narrow all other RHS shapes
1158
+ // (arithmetic, calls using the narrowed var, nested paths, two-optional
1159
+ // comparisons) via checked reads.
1160
+ const orCtx = collectOrChainNarrowings(left, ctx);
1161
+ const narrowedVars = new Set();
1162
+ for (let cur = orCtx.env; cur && cur !== ctx.env; cur = cur.parent) {
1163
+ narrowedVars.add(cur.name);
1164
+ }
1165
+ const leftIsOptVar = rawRight.kind === "binop" && rawRight.left.kind === "var" &&
1166
+ lookup(ctx.env, rawRight.left.name)?.kind === "optional";
1167
+ const rightIsOptVar = rawRight.kind === "binop" && rawRight.right.kind === "var" &&
1168
+ lookup(ctx.env, rawRight.right.name)?.kind === "optional";
1169
+ const isDirectSingleOptCmp = rawRight.kind === "binop" &&
1170
+ ["===", "!==", "<", "<=", ">", ">="].includes(rawRight.op) &&
1171
+ (leftIsOptVar !== rightIsOptVar) &&
1172
+ !rawExprMentionsAny(leftIsOptVar ? rawRight.right : rawRight.left, narrowedVars);
1173
+ if (!isDirectSingleOptCmp) {
1174
+ rightCtx = orCtx;
1175
+ }
1176
+ }
1059
1177
  let right = resolveExpr(rawRight, rightCtx);
1060
1178
  if (e.op === "===" || e.op === "!==") {
1061
1179
  left = coerceStr(left, right.ty, ctx.typeDecls);
@@ -1308,10 +1426,18 @@ function resolveExprInner(e, ctx) {
1308
1426
  // left ?? right — result type is left's inner (when left is optional)
1309
1427
  // or just left's type, unified with right's type.
1310
1428
  const left = resolveExpr(e.left, ctx);
1429
+ const isLeftUndef = (left.kind === "var" && left.name === "undefined") || left.ty.kind === "void";
1430
+ const isArrayIndex = left.kind === "index" && left.obj.ty.kind === "array";
1311
1431
  const inner = left.ty.kind === "optional" ? left.ty.inner : left.ty;
1312
1432
  // The default shares the result type, so coerce a string literal to a
1313
1433
  // string-union enum (e.g. `availableLevels[0] ?? "off"`).
1314
- const right = coerceToTargetTy(resolveExpr(e.right, ctx), inner, ctx.typeDecls);
1434
+ const right = coerceToTargetTy(resolveExpr(e.right, ctx), isLeftUndef ? { kind: "unknown" } : inner, ctx.typeDecls);
1435
+ // When `left` is non-optional and not an unchecked array index (#352):
1436
+ // `undefined ?? right` has `right`'s type, and `nonOpt ?? right` evaluates
1437
+ // to `left` directly (narrow.ts strips the dead fallback).
1438
+ if (left.ty.kind !== "optional" && !isArrayIndex) {
1439
+ return { kind: "nullish", left, right, ty: isLeftUndef ? right.ty : left.ty };
1440
+ }
1315
1441
  // `??` is only total when its default is: with a nullable right operand
1316
1442
  // (rule-chain style `ruleA(e) ?? ruleB(e) ?? null`), the result stays
1317
1443
  // optional — otherwise the enclosing chain level loses its optionality
@@ -1325,6 +1451,8 @@ function resolveExprInner(e, ctx) {
1325
1451
  // (collapsed: if finalStepTy is already optional, we don't double-wrap).
1326
1452
  // Narrow rewrites this to a someMatch with the chain applied to the binder.
1327
1453
  const obj = resolveExpr(e.obj, ctx);
1454
+ const isObjUndef = (obj.kind === "var" && obj.name === "undefined") || obj.ty.kind === "void";
1455
+ const isObjArrayIndex = obj.kind === "index" && obj.obj.ty.kind === "array";
1328
1456
  let stepInTy = obj.ty.kind === "optional" ? obj.ty.inner : obj.ty;
1329
1457
  const chain = [];
1330
1458
  for (const step of e.chain) {
@@ -1378,7 +1506,11 @@ function resolveExprInner(e, ctx) {
1378
1506
  }
1379
1507
  }
1380
1508
  const finalTy = stepInTy;
1381
- const ty = finalTy.kind === "optional" ? finalTy : { kind: "optional", inner: finalTy };
1509
+ // Non-optional receiver (excluding unchecked array index) never produces
1510
+ // None from the `?.` step itself (#352); narrow.ts lowers it directly.
1511
+ const ty = isObjUndef ? { kind: "void" }
1512
+ : (obj.ty.kind !== "optional" && !isObjArrayIndex) ? finalTy
1513
+ : finalTy.kind === "optional" ? finalTy : { kind: "optional", inner: finalTy };
1382
1514
  return { kind: "optChain", obj, chain, ty };
1383
1515
  }
1384
1516
  case "record": {
@@ -1456,12 +1588,14 @@ function resolveExprInner(e, ctx) {
1456
1588
  case "forall": {
1457
1589
  const varTy = e.varType !== "int" ? parseTsType(e.varType)
1458
1590
  : inferQuantVarType(e.var, e.body, ctx) ?? { kind: "int" };
1459
- return { kind: "forall", var: e.var, varTy, body: resolveExpr(e.body, withEnv(ctx, extend(ctx.env, e.var, varTy))), ty: { kind: "bool" } };
1591
+ const bound = quantified(ctx.env, e.var, varTy);
1592
+ return { kind: "forall", var: bound.emittedName ?? e.var, varTy, body: resolveExpr(e.body, withEnv(ctx, bound)), ty: { kind: "bool" } };
1460
1593
  }
1461
1594
  case "exists": {
1462
1595
  const varTy = e.varType !== "int" ? parseTsType(e.varType)
1463
1596
  : inferQuantVarType(e.var, e.body, ctx) ?? { kind: "int" };
1464
- return { kind: "exists", var: e.var, varTy, body: resolveExpr(e.body, withEnv(ctx, extend(ctx.env, e.var, varTy))), ty: { kind: "bool" } };
1597
+ const bound = quantified(ctx.env, e.var, varTy);
1598
+ return { kind: "exists", var: bound.emittedName ?? e.var, varTy, body: resolveExpr(e.body, withEnv(ctx, bound)), ty: { kind: "bool" } };
1465
1599
  }
1466
1600
  case "arrayLiteral": {
1467
1601
  // Expected-tuple context: type each element against its own slot type and
@@ -1589,6 +1723,136 @@ function splitConj(e) {
1589
1723
  return [e];
1590
1724
  }
1591
1725
  // ── Resolve statements ───────────────────────────────────────
1726
+ /** True if `e` references any variable name in `names`. */
1727
+ function rawExprMentionsAny(e, names) {
1728
+ if (names.size === 0)
1729
+ return false;
1730
+ switch (e.kind) {
1731
+ case "var": return names.has(e.name);
1732
+ case "num":
1733
+ case "bigint":
1734
+ case "str":
1735
+ case "bool":
1736
+ case "havoc": return false;
1737
+ case "binop": return rawExprMentionsAny(e.left, names) || rawExprMentionsAny(e.right, names);
1738
+ case "unop":
1739
+ case "nonNull": return rawExprMentionsAny(e.expr, names);
1740
+ case "field": return rawExprMentionsAny(e.obj, names);
1741
+ case "index": return rawExprMentionsAny(e.obj, names) || rawExprMentionsAny(e.idx, names);
1742
+ case "call": return rawExprMentionsAny(e.fn, names) || e.args.some(a => rawExprMentionsAny(a, names));
1743
+ case "record":
1744
+ return (e.spread ? rawExprMentionsAny(e.spread, names) : false) ||
1745
+ e.fields.some(f => rawExprMentionsAny(f.value, names));
1746
+ case "arrayLiteral": return e.elems.some(el => rawExprMentionsAny(el, names));
1747
+ case "conditional":
1748
+ return rawExprMentionsAny(e.cond, names) || rawExprMentionsAny(e.then, names) || rawExprMentionsAny(e.else, names);
1749
+ case "nullish": return rawExprMentionsAny(e.left, names) || rawExprMentionsAny(e.right, names);
1750
+ case "optChain": return rawExprMentionsAny(e.obj, names);
1751
+ case "forall":
1752
+ case "exists": return rawExprMentionsAny(e.body, names);
1753
+ case "lambda": return false;
1754
+ default: return false;
1755
+ }
1756
+ }
1757
+ /** Collect root variable names assigned anywhere in `stmts` (both direct
1758
+ * assignments `x = ...` and dotted field writes `x.f = ...`). */
1759
+ function collectAssignedRootsRaw(stmts, out = new Set()) {
1760
+ for (const s of stmts) {
1761
+ if (s.kind === "assign") {
1762
+ out.add(s.target.split(".")[0]);
1763
+ }
1764
+ else if (s.kind === "if") {
1765
+ collectAssignedRootsRaw(s.then, out);
1766
+ collectAssignedRootsRaw(s.else, out);
1767
+ }
1768
+ else if (s.kind === "while" || s.kind === "forof") {
1769
+ collectAssignedRootsRaw(s.body, out);
1770
+ }
1771
+ else if (s.kind === "switch") {
1772
+ for (const c of s.cases)
1773
+ collectAssignedRootsRaw(c.body, out);
1774
+ collectAssignedRootsRaw(s.defaultBody, out);
1775
+ }
1776
+ }
1777
+ return out;
1778
+ }
1779
+ /** Restore any narrowed optional variable in `roots` back to its declared
1780
+ * `storageTy`, and drop `narrowedPaths` whose root is in `roots`. Used when
1781
+ * entering a loop (`while`/`forof`) or exiting a control-flow statement that
1782
+ * may reassign or clear a previously narrowed variable. */
1783
+ function invalidateNarrowings(env, narrowedPaths, roots) {
1784
+ if (roots.size === 0)
1785
+ return { env, narrowedPaths };
1786
+ let nextEnv = env;
1787
+ for (const root of roots) {
1788
+ const cur = lookup(nextEnv, root);
1789
+ const storage = storageLookup(nextEnv, root);
1790
+ if (storage?.kind === "optional" && cur && cur.kind !== "optional") {
1791
+ nextEnv = refine(nextEnv, root, storage);
1792
+ }
1793
+ }
1794
+ const nextPaths = narrowedPaths.filter(np => !roots.has(np.path.rootVar));
1795
+ return { env: nextEnv, narrowedPaths: nextPaths };
1796
+ }
1797
+ /** True if `stmts` definitely assigns a non-optional, non-`undefined` value
1798
+ * to `varName` (without subsequently clearing or shadowing it) on every
1799
+ * non-terminating exit path. Used for `#340` assignment narrowing:
1800
+ * `if (v === undefined) { v = 6; } return v + 3;`. */
1801
+ function definitelyAssignsNonOptional(stmts, varName, ctx) {
1802
+ let assigned = false;
1803
+ let env = ctx.env;
1804
+ const targetStorage = storageLookup(env, varName);
1805
+ for (const st of stmts) {
1806
+ if (isTerminatorKind(st.kind))
1807
+ return true;
1808
+ if (st.kind === "let") {
1809
+ // Inner `let` shadowing `varName` prevents outer assignment tracking.
1810
+ if (st.name === varName)
1811
+ return assigned;
1812
+ const [, nextEnv] = resolveStmt(st, { ...ctx, env });
1813
+ env = nextEnv;
1814
+ continue;
1815
+ }
1816
+ if (st.kind === "assign" && st.target === varName) {
1817
+ if (st.value.kind === "var" && st.value.name === "undefined") {
1818
+ assigned = false;
1819
+ }
1820
+ else {
1821
+ const rhsCtx = { ...ctx, env, returnTy: targetStorage ?? ctx.returnTy };
1822
+ const rhsTy = resolveExpr(st.value, rhsCtx).ty;
1823
+ assigned = rhsTy.kind !== "optional" && rhsTy.kind !== "void" && rhsTy.kind !== "unknown";
1824
+ }
1825
+ }
1826
+ else if (st.kind === "if") {
1827
+ const subCtx = { ...ctx, env };
1828
+ if (st.else.length > 0 &&
1829
+ definitelyAssignsNonOptional(st.then, varName, subCtx) &&
1830
+ definitelyAssignsNonOptional(st.else, varName, subCtx)) {
1831
+ assigned = true;
1832
+ }
1833
+ else if (collectAssignedRootsRaw(st.then).has(varName) || collectAssignedRootsRaw(st.else).has(varName)) {
1834
+ assigned = false;
1835
+ }
1836
+ }
1837
+ else if (st.kind === "while" || st.kind === "forof") {
1838
+ if (collectAssignedRootsRaw(st.body).has(varName))
1839
+ assigned = false;
1840
+ }
1841
+ else if (st.kind === "switch") {
1842
+ const swAssigned = sHasRootAssignSwitch(st, varName);
1843
+ if (swAssigned)
1844
+ assigned = false;
1845
+ }
1846
+ }
1847
+ return assigned;
1848
+ }
1849
+ function sHasRootAssignSwitch(s, varName) {
1850
+ for (const c of s.cases) {
1851
+ if (collectAssignedRootsRaw(c.body).has(varName))
1852
+ return true;
1853
+ }
1854
+ return collectAssignedRootsRaw(s.defaultBody).has(varName);
1855
+ }
1592
1856
  function resolveBlock(stmts, ctx) {
1593
1857
  const result = [];
1594
1858
  let env = ctx.env;
@@ -1599,6 +1863,45 @@ function resolveBlock(stmts, ctx) {
1599
1863
  const [typed, nextEnv] = resolveStmt(s, currentCtx);
1600
1864
  result.push(typed);
1601
1865
  env = nextEnv;
1866
+ // Assignment narrowing (#340): assigning a non-optional value to an optional
1867
+ // variable narrows it for subsequent statements; assigning `undefined` or an
1868
+ // optional restores its declared optional storage type. Also drop stale
1869
+ // narrowedPaths rooted at any assigned target (including field writes).
1870
+ if (s.kind === "assign") {
1871
+ const root = s.target.split(".")[0];
1872
+ narrowedPaths = narrowedPaths.filter(np => np.path.rootVar !== root);
1873
+ if (!s.target.includes(".")) {
1874
+ const storage = storageLookup(env, s.target);
1875
+ if (storage?.kind === "optional") {
1876
+ const isUndef = s.value.kind === "var" && s.value.name === "undefined";
1877
+ const rhsCtx = { ...currentCtx, returnTy: storage };
1878
+ const rawTy = isUndef ? { kind: "void" } : resolveExpr(s.value, rhsCtx).ty;
1879
+ if (!isUndef && rawTy.kind !== "optional" && rawTy.kind !== "void" && rawTy.kind !== "unknown") {
1880
+ env = refine(env, s.target, storage.inner);
1881
+ }
1882
+ else {
1883
+ env = refine(env, s.target, storage);
1884
+ }
1885
+ }
1886
+ }
1887
+ }
1888
+ // Control-flow invalidation: if an `if`/`while`/`forof`/`switch` may assign
1889
+ // a narrowed variable or path, restore its declared optional storage type
1890
+ // before subsequent statements (definite-assignment guards re-narrow below).
1891
+ if (s.kind === "if" || s.kind === "while" || s.kind === "forof" || s.kind === "switch") {
1892
+ const mutated = collectAssignedRootsRaw([s]);
1893
+ const inv = invalidateNarrowings(env, narrowedPaths, mutated);
1894
+ env = inv.env;
1895
+ narrowedPaths = inv.narrowedPaths;
1896
+ }
1897
+ // Definite-assignment guard (#340): `if (v === undefined) { v = nonOpt; }`
1898
+ // guarantees `v` is present after the `if` on both branches.
1899
+ if (s.kind === "if" && typed.kind === "if" && s.else.length === 0) {
1900
+ const neg = negatedVarPresence(typed.cond);
1901
+ if (neg && definitelyAssignsNonOptional(s.then, neg.varName, currentCtx)) {
1902
+ env = refine(env, neg.varName, neg.innerTy);
1903
+ }
1904
+ }
1602
1905
  // Flow narrowing: if (x === undefined) { return } narrows x for rest of block.
1603
1906
  // Also handles compound: if (x === undefined || y === undefined) { return }
1604
1907
  // Any terminator counts (return/throw/break/continue — same set as narrow's
@@ -1611,6 +1914,14 @@ function resolveBlock(stmts, ctx) {
1611
1914
  for (const n of collectEarlyReturnNarrowings(typed.cond)) {
1612
1915
  env = refine(env, n.varName, n.innerTy);
1613
1916
  }
1917
+ for (const np of collectEarlyReturnPathNarrowings(typed.cond)) {
1918
+ if (np.path.fields.length === 0) {
1919
+ env = refine(env, np.path.rootVar, np.narrowedTy);
1920
+ }
1921
+ else {
1922
+ narrowedPaths = [...narrowedPaths, np];
1923
+ }
1924
+ }
1614
1925
  const nv = negatedVariantCheck(typed.cond);
1615
1926
  if (nv)
1616
1927
  narrowedPaths = [...narrowedPaths, nv];
@@ -1700,7 +2011,10 @@ function resolveStmt(s, ctx) {
1700
2011
  throw new Error(`assignment to callback binding '${s.target}' requires materializing its argument value`);
1701
2012
  }
1702
2013
  entry?.onRead?.();
1703
- const targetTy = lookup(ctx.env, s.target) ?? { kind: "unknown" };
2014
+ // Coerce RHS against the variable's declared storage type (not a narrowed
2015
+ // flow type) so reassignments like `v = 7` or `v = undefined` stay typed
2016
+ // as `Option<T>`.
2017
+ const targetTy = storageLookup(ctx.env, s.target) ?? { kind: "unknown" };
1704
2018
  // Propagate the target's type as returnTy, mirroring the annotated-let
1705
2019
  // case, so record/union literals and array literals in the RHS resolve
1706
2020
  // to their named datatypes.
@@ -1739,14 +2053,21 @@ function resolveStmt(s, ctx) {
1739
2053
  return [{ kind: "if", cond: resolvedCond, then: resolveBlock(s.then, thenCtx), else: resolveBlock(s.else, elseCtx) }, ctx.env];
1740
2054
  }
1741
2055
  case "while": {
1742
- const whileSpecCtx = { ...ctx, inSpec: true };
2056
+ // Any variable or path mutated inside the loop body cannot keep a pre-loop
2057
+ // narrowing across iterations (including inside the loop condition and
2058
+ // invariants on back-edges).
2059
+ const loopMutated = collectAssignedRootsRaw(s.body);
2060
+ const loopInv = invalidateNarrowings(ctx.env, ctx.narrowedPaths, loopMutated);
2061
+ const loopCtx = { ...ctx, env: loopInv.env, narrowedPaths: loopInv.narrowedPaths };
2062
+ const whileSpecCtx = { ...loopCtx, inSpec: true };
1743
2063
  const resolvedInvariants = resolveSpecs(s.invariants, whileSpecCtx);
1744
- // Invariants hold at the top of the body, so any `k in m` atoms among them
1745
- // narrow map index access in the body.
1746
- const bodyCtx = withInAtoms(ctx, resolvedInvariants.flatMap(extractInAtoms));
2064
+ const resolvedCond = resolveExpr(s.cond, loopCtx);
2065
+ // Invariants and presence checks in the `while` condition (#339) both hold
2066
+ // at the top of the loop body.
2067
+ const bodyCtx = collectAndChainNarrowings(resolvedCond, withInAtoms(loopCtx, resolvedInvariants.flatMap(extractInAtoms)));
1747
2068
  return [{
1748
2069
  kind: "while",
1749
- cond: resolveExpr(s.cond, ctx),
2070
+ cond: resolvedCond,
1750
2071
  invariants: resolvedInvariants,
1751
2072
  decreases: s.decreases ? resolveSpec(s.decreases, whileSpecCtx) : null,
1752
2073
  doneWith: s.doneWith ? resolveSpec(s.doneWith, whileSpecCtx) : null,
@@ -1780,16 +2101,22 @@ function resolveStmt(s, ctx) {
1780
2101
  for (const _ of s.names)
1781
2102
  nameTypes.push({ kind: "unknown" });
1782
2103
  }
1783
- // Must match the freshened counter transform mints for this loop, so a
1784
- // spec referencing the loop index resolves to the same name.
1785
- const idxName = freshName(`_${s.names[0]}_idx`);
2104
+ // The loop counter is minted here, once, and recorded on the loop so
2105
+ // transform emits the same name a spec here refers to. The first loop
2106
+ // over a head name in a function gets `_x_idx`, later ones `_x_idx2`, ….
2107
+ const count = ctx.forofCounts.get(s.names[0]) ?? 0;
2108
+ ctx.forofCounts.set(s.names[0], count + 1);
2109
+ const idxName = freshName(`_${s.names[0]}_idx${count === 0 ? "" : count + 1}`);
2110
+ const loopMutated = collectAssignedRootsRaw(s.body);
2111
+ const loopInv = invalidateNarrowings(ctx.env, ctx.narrowedPaths, loopMutated);
2112
+ env = loopInv.env;
1786
2113
  env = extend(env, idxName, { kind: "nat" });
1787
2114
  for (let j = 0; j < s.names.length; j++) {
1788
2115
  env = extend(env, s.names[j], nameTypes[j] ?? { kind: "unknown" });
1789
2116
  }
1790
- const bodyCtx = withEnv(ctx, env);
2117
+ const bodyCtx = { ...ctx, env, narrowedPaths: loopInv.narrowedPaths };
1791
2118
  return [{
1792
- kind: "forof", names: s.names, nameTypes, iterable,
2119
+ kind: "forof", names: s.names, nameTypes, iterable, idx: idxName,
1793
2120
  invariants: resolveSpecs(s.invariants, { ...bodyCtx, inSpec: true }),
1794
2121
  doneWith: s.doneWith ? resolveSpec(s.doneWith, { ...bodyCtx, inSpec: true }) : null,
1795
2122
  body: resolveBlock(s.body, bodyCtx),
@@ -2032,7 +2359,7 @@ function resolveFunction(fn, typeDecls, pureFns, fnParams = new Map(), fnReturns
2032
2359
  env = extend(env, opts.thisBinding.name, opts.thisBinding.ty);
2033
2360
  for (const p of params)
2034
2361
  env = extend(env, p.name, p.ty);
2035
- const baseCtx = { env, typeDecls, overrides, allowResult: false, returnTy, pureFns, fnParams, fnReturns, externs, inSpec: false, inLambda: false, narrowedPaths: [], narrowedIndices: [] };
2362
+ const baseCtx = { env, typeDecls, overrides, allowResult: false, returnTy, pureFns, fnParams, fnReturns, externs, inSpec: false, inLambda: false, narrowedPaths: [], narrowedIndices: [], forofCounts: new Map() };
2036
2363
  const requiresCtx = { ...baseCtx, inSpec: true };
2037
2364
  const ensuresCtx = { ...baseCtx, env: extend(env, "\\result", returnTy), allowResult: true, inSpec: true };
2038
2365
  // Apply type parameter constraints from //@ type T (==) annotations
@@ -2139,7 +2466,7 @@ export function resolveModule(raw) {
2139
2466
  for (let i = 0; i < ext.params.length; i++) {
2140
2467
  env = extend(env, ext.params[i].name, sig.params[i]);
2141
2468
  }
2142
- const baseCtx = { env, typeDecls: raw.typeDecls, overrides: new Map(), allowResult: false, returnTy: sig.returnTy, pureFns, fnParams, fnReturns, externs, inSpec: true, inLambda: false, narrowedPaths: [], narrowedIndices: [] };
2469
+ const baseCtx = { env, typeDecls: raw.typeDecls, overrides: new Map(), allowResult: false, returnTy: sig.returnTy, pureFns, fnParams, fnReturns, externs, inSpec: true, inLambda: false, narrowedPaths: [], narrowedIndices: [], forofCounts: new Map() };
2143
2470
  const ensuresCtx = { ...baseCtx, env: extend(env, "\\result", sig.returnTy), allowResult: true };
2144
2471
  const resolveClauses = (kind, ctx) => ext[kind].map(s => {
2145
2472
  try {
@@ -2161,7 +2488,7 @@ export function resolveModule(raw) {
2161
2488
  impure: ext.impure,
2162
2489
  };
2163
2490
  });
2164
- const emptyCtx = { env: null, typeDecls: raw.typeDecls, overrides: new Map(), allowResult: false, returnTy: { kind: "int" }, pureFns, fnParams, fnReturns, externs, inSpec: false, inLambda: false, narrowedPaths: [], narrowedIndices: [] };
2491
+ const emptyCtx = { env: null, typeDecls: raw.typeDecls, overrides: new Map(), allowResult: false, returnTy: { kind: "int" }, pureFns, fnParams, fnReturns, externs, inSpec: false, inLambda: false, narrowedPaths: [], narrowedIndices: [], forofCounts: new Map() };
2165
2492
  const constants = (raw.constants ?? []).map(c => {
2166
2493
  const declaredTy = expandAlias(parseTsType(c.tsType), raw.typeDecls);
2167
2494
  // Propagate the declared type into the value's resolution context so that
@@ -9,17 +9,23 @@ const MULTI_OPS = ["<==>", "==>", "===", "!==", "==", "!=", ">=", "<=", "&&", "|
9
9
  * allow TypeScript's fractional and exponent forms. */
10
10
  const BIGINT_LITERAL = /^(?:(?:0[xX][0-9a-fA-F](?:_?[0-9a-fA-F])*)|(?:0[bB][01](?:_?[01])*)|(?:0[oO][0-7](?:_?[0-7])*)|(?:[0-9](?:_?[0-9])*))n/;
11
11
  const NUMBER_LITERAL = /^(?:(?:0[xX][0-9a-fA-F](?:_?[0-9a-fA-F])*)|(?:0[bB][01](?:_?[01])*)|(?:0[oO][0-7](?:_?[0-7])*)|(?:(?:[0-9](?:_?[0-9])*)(?:\.(?:[0-9](?:_?[0-9])*)?)?|\.(?:[0-9](?:_?[0-9])*))(?:[eE][+-]?(?:[0-9](?:_?[0-9])*))?)/;
12
- function tokenize(input) {
12
+ function tokenize(input, spans) {
13
13
  const tokens = [];
14
14
  let i = 0;
15
+ let start = 0;
16
+ const push = (token) => {
17
+ tokens.push(token);
18
+ spans?.push({ start, end: i });
19
+ };
15
20
  while (i < input.length) {
16
21
  if (/\s/.test(input[i])) {
17
22
  i++;
18
23
  continue;
19
24
  }
25
+ start = i;
20
26
  if (input[i] === "\\" && input.slice(i + 1, i + 7) === "result") {
21
- tokens.push({ type: "result", value: undefined });
22
27
  i += 7;
28
+ push({ type: "result", value: undefined });
23
29
  continue;
24
30
  }
25
31
  if (input[i] === '"' || input[i] === "'") {
@@ -44,7 +50,7 @@ function tokenize(input) {
44
50
  }
45
51
  if (i < input.length)
46
52
  i++;
47
- tokens.push({ type: "str", value: s });
53
+ push({ type: "str", value: s });
48
54
  continue;
49
55
  }
50
56
  if (/[0-9]/.test(input[i]) || (input[i] === "." && /[0-9]/.test(input[i + 1]))) {
@@ -58,23 +64,23 @@ function tokenize(input) {
58
64
  // The `n` suffix is meaningful, not noise: a BigInt keeps its exact value
59
65
  // as a decimal string instead of being rounded into a double.
60
66
  if (bigintMatch)
61
- tokens.push({ type: "bigint", value: normalizeBigIntLiteral(text) });
67
+ push({ type: "bigint", value: normalizeBigIntLiteral(text) });
62
68
  else
63
- tokens.push({ type: "num", value: Number(text.replace(/_/g, "")) });
69
+ push({ type: "num", value: Number(text.replace(/_/g, "")) });
64
70
  continue;
65
71
  }
66
72
  if (/[a-zA-Z_]/.test(input[i])) {
67
73
  let id = "";
68
74
  while (i < input.length && /[a-zA-Z_0-9]/.test(input[i]))
69
75
  id += input[i++];
70
- tokens.push({ type: "ident", value: id });
76
+ push({ type: "ident", value: id });
71
77
  continue;
72
78
  }
73
79
  let matched = false;
74
80
  for (const op of MULTI_OPS) {
75
81
  if (input.slice(i, i + op.length) === op) {
76
- tokens.push({ type: "op", value: op });
77
82
  i += op.length;
83
+ push({ type: "op", value: op });
78
84
  matched = true;
79
85
  break;
80
86
  }
@@ -82,25 +88,28 @@ function tokenize(input) {
82
88
  if (matched)
83
89
  continue;
84
90
  const ch = input[i];
91
+ i++;
85
92
  if ("+-*/%><!?".includes(ch)) {
86
- tokens.push({ type: "op", value: ch });
93
+ push({ type: "op", value: ch });
87
94
  }
88
95
  else if ("()[],:.{}".includes(ch)) {
89
- tokens.push({ type: "punc", value: ch });
96
+ push({ type: "punc", value: ch });
90
97
  }
91
98
  else {
92
- throw new Error(`Unexpected '${ch}' at ${i} in: ${input}`);
99
+ throw new Error(`Unexpected '${ch}' at ${i - 1} in: ${input}`);
93
100
  }
94
- i++;
95
101
  }
96
102
  return tokens;
97
103
  }
98
104
  // ── Parser ───────────────────────────────────────────────────
99
105
  class Parser {
100
106
  tokens;
107
+ onFreeVariable;
101
108
  pos = 0;
102
- constructor(tokens) {
109
+ bound = new Set();
110
+ constructor(tokens, onFreeVariable) {
103
111
  this.tokens = tokens;
112
+ this.onFreeVariable = onFreeVariable;
104
113
  }
105
114
  peek() { return this.tokens[this.pos]; }
106
115
  advance() { return this.tokens[this.pos++]; }
@@ -304,10 +313,15 @@ class Parser {
304
313
  varType = ty;
305
314
  }
306
315
  this.expect("punc", ",");
316
+ const outer = this.bound;
317
+ this.bound = new Set([...outer, v]);
307
318
  const body = this.parseIff();
319
+ this.bound = outer;
308
320
  this.expect("punc", ")");
309
321
  return { kind: q, var: v, varType, body };
310
322
  }
323
+ if (!this.bound.has(t.value))
324
+ this.onFreeVariable?.(t.value, this.pos);
311
325
  this.advance();
312
326
  return { kind: "var", name: t.value };
313
327
  }
@@ -350,3 +364,18 @@ class Parser {
350
364
  export function parseExpr(input) {
351
365
  return new Parser(tokenize(input)).parse();
352
366
  }
367
+ /** Rewrite only free variable tokens, preserving annotation spelling and
368
+ * leaving fields, record keys, literals, types, and quantifier binders alone. */
369
+ export function renameSpecVariables(input, rename) {
370
+ const spans = [];
371
+ const tokens = tokenize(input, spans);
372
+ const edits = [];
373
+ new Parser(tokens, (name, index) => {
374
+ const replacement = rename(name);
375
+ if (replacement !== name)
376
+ edits.push({ ...spans[index], name: replacement });
377
+ }).parse();
378
+ for (const edit of edits.reverse())
379
+ input = input.slice(0, edit.start) + edit.name + input.slice(edit.end);
380
+ return input;
381
+ }