lemmascript 0.6.12 → 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,12 @@ 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 };
26
30
  }
27
31
  /** A quantified variable that reuses the name of a binding in scope is emitted
28
32
  * under a fresh name, so no later pass confuses it with that binding. */
@@ -48,7 +52,7 @@ function refine(env, name, ty) {
48
52
  break;
49
53
  }
50
54
  }
51
- 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 };
52
56
  }
53
57
  function asRawAccessPath(e) {
54
58
  if (e.kind === "var")
@@ -195,6 +199,60 @@ function negatedVarPresence(cond) {
195
199
  /** Collect all optional narrowings from an early-return condition.
196
200
  * Handles single checks (x === undefined) and compound || chains
197
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
+ }
198
256
  function collectEarlyReturnNarrowings(cond) {
199
257
  if (cond.kind === "binop" && cond.op === "||") {
200
258
  return [...collectEarlyReturnNarrowings(cond.left), ...collectEarlyReturnNarrowings(cond.right)];
@@ -303,6 +361,27 @@ function collectAndChainNarrowings(cond, ctx) {
303
361
  }
304
362
  return ctx;
305
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
+ }
306
385
  /** TS reference types that become value types in Dafny/Lean — const bindings need mutable var. */
307
386
  function isRefMutableInTS(ty) {
308
387
  return ty.kind === "array" || ty.kind === "map" || ty.kind === "set";
@@ -648,10 +727,13 @@ function resolveCallback(e, actual, baseArity, ctx) {
648
727
  // binding identities; nested declarations shadow them through ordinary lookup.
649
728
  let env = ctx.env;
650
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" };
651
733
  const frame = {
652
734
  name: p.name, parent: env,
653
- ty: executesDefault(i) ? expandAlias(parseTsType(p.inferredTsType ?? p.tsType ?? "unknown"), ctx.typeDecls)
654
- : p.rest ? { kind: "unknown" } : slots[i]?.ty ?? { kind: "void" },
735
+ ty: paramTy,
736
+ storageTy: paramTy,
655
737
  onRead: () => {
656
738
  captures?.add(i);
657
739
  // A forward reference must never resolve to an outer variable if
@@ -1019,7 +1101,11 @@ function resolveConstEnumMember(obj, name, ctx) {
1019
1101
  }
1020
1102
  function resolveExpr(e, ctx) {
1021
1103
  const expr = resolveExprInner(e, ctx);
1022
- 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;
1023
1109
  }
1024
1110
  function resolveExprInner(e, ctx) {
1025
1111
  switch (e.kind) {
@@ -1064,6 +1150,30 @@ function resolveExprInner(e, ctx) {
1064
1150
  if (e.op === "&&" || e.op === "==>") {
1065
1151
  rightCtx = collectAndChainNarrowings(left, ctx);
1066
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
+ }
1067
1177
  let right = resolveExpr(rawRight, rightCtx);
1068
1178
  if (e.op === "===" || e.op === "!==") {
1069
1179
  left = coerceStr(left, right.ty, ctx.typeDecls);
@@ -1316,10 +1426,18 @@ function resolveExprInner(e, ctx) {
1316
1426
  // left ?? right — result type is left's inner (when left is optional)
1317
1427
  // or just left's type, unified with right's type.
1318
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";
1319
1431
  const inner = left.ty.kind === "optional" ? left.ty.inner : left.ty;
1320
1432
  // The default shares the result type, so coerce a string literal to a
1321
1433
  // string-union enum (e.g. `availableLevels[0] ?? "off"`).
1322
- 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
+ }
1323
1441
  // `??` is only total when its default is: with a nullable right operand
1324
1442
  // (rule-chain style `ruleA(e) ?? ruleB(e) ?? null`), the result stays
1325
1443
  // optional — otherwise the enclosing chain level loses its optionality
@@ -1333,6 +1451,8 @@ function resolveExprInner(e, ctx) {
1333
1451
  // (collapsed: if finalStepTy is already optional, we don't double-wrap).
1334
1452
  // Narrow rewrites this to a someMatch with the chain applied to the binder.
1335
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";
1336
1456
  let stepInTy = obj.ty.kind === "optional" ? obj.ty.inner : obj.ty;
1337
1457
  const chain = [];
1338
1458
  for (const step of e.chain) {
@@ -1386,7 +1506,11 @@ function resolveExprInner(e, ctx) {
1386
1506
  }
1387
1507
  }
1388
1508
  const finalTy = stepInTy;
1389
- 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 };
1390
1514
  return { kind: "optChain", obj, chain, ty };
1391
1515
  }
1392
1516
  case "record": {
@@ -1599,6 +1723,136 @@ function splitConj(e) {
1599
1723
  return [e];
1600
1724
  }
1601
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
+ }
1602
1856
  function resolveBlock(stmts, ctx) {
1603
1857
  const result = [];
1604
1858
  let env = ctx.env;
@@ -1609,6 +1863,45 @@ function resolveBlock(stmts, ctx) {
1609
1863
  const [typed, nextEnv] = resolveStmt(s, currentCtx);
1610
1864
  result.push(typed);
1611
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
+ }
1612
1905
  // Flow narrowing: if (x === undefined) { return } narrows x for rest of block.
1613
1906
  // Also handles compound: if (x === undefined || y === undefined) { return }
1614
1907
  // Any terminator counts (return/throw/break/continue — same set as narrow's
@@ -1621,6 +1914,14 @@ function resolveBlock(stmts, ctx) {
1621
1914
  for (const n of collectEarlyReturnNarrowings(typed.cond)) {
1622
1915
  env = refine(env, n.varName, n.innerTy);
1623
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
+ }
1624
1925
  const nv = negatedVariantCheck(typed.cond);
1625
1926
  if (nv)
1626
1927
  narrowedPaths = [...narrowedPaths, nv];
@@ -1710,7 +2011,10 @@ function resolveStmt(s, ctx) {
1710
2011
  throw new Error(`assignment to callback binding '${s.target}' requires materializing its argument value`);
1711
2012
  }
1712
2013
  entry?.onRead?.();
1713
- 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" };
1714
2018
  // Propagate the target's type as returnTy, mirroring the annotated-let
1715
2019
  // case, so record/union literals and array literals in the RHS resolve
1716
2020
  // to their named datatypes.
@@ -1749,14 +2053,21 @@ function resolveStmt(s, ctx) {
1749
2053
  return [{ kind: "if", cond: resolvedCond, then: resolveBlock(s.then, thenCtx), else: resolveBlock(s.else, elseCtx) }, ctx.env];
1750
2054
  }
1751
2055
  case "while": {
1752
- 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 };
1753
2063
  const resolvedInvariants = resolveSpecs(s.invariants, whileSpecCtx);
1754
- // Invariants hold at the top of the body, so any `k in m` atoms among them
1755
- // narrow map index access in the body.
1756
- 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)));
1757
2068
  return [{
1758
2069
  kind: "while",
1759
- cond: resolveExpr(s.cond, ctx),
2070
+ cond: resolvedCond,
1760
2071
  invariants: resolvedInvariants,
1761
2072
  decreases: s.decreases ? resolveSpec(s.decreases, whileSpecCtx) : null,
1762
2073
  doneWith: s.doneWith ? resolveSpec(s.doneWith, whileSpecCtx) : null,
@@ -1796,11 +2107,14 @@ function resolveStmt(s, ctx) {
1796
2107
  const count = ctx.forofCounts.get(s.names[0]) ?? 0;
1797
2108
  ctx.forofCounts.set(s.names[0], count + 1);
1798
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;
1799
2113
  env = extend(env, idxName, { kind: "nat" });
1800
2114
  for (let j = 0; j < s.names.length; j++) {
1801
2115
  env = extend(env, s.names[j], nameTypes[j] ?? { kind: "unknown" });
1802
2116
  }
1803
- const bodyCtx = withEnv(ctx, env);
2117
+ const bodyCtx = { ...ctx, env, narrowedPaths: loopInv.narrowedPaths };
1804
2118
  return [{
1805
2119
  kind: "forof", names: s.names, nameTypes, iterable, idx: idxName,
1806
2120
  invariants: resolveSpecs(s.invariants, { ...bodyCtx, inSpec: true }),