lemmascript 0.6.14 → 0.6.16

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.
@@ -7,12 +7,12 @@
7
7
  import { isBigInt, optAbsent, tyEqual } from "./typedir.js";
8
8
  import { anyExpr, anyExprInStmts, pWild, pCtor, pLiteral, patternBinders, patternCtor } from "./ir.js";
9
9
  import { parseTsType } from "./types.js";
10
- import { freshName } from "./names.js";
10
+ import { freshName, freshNameWhere, isUserName } from "./names.js";
11
11
  import { builtinSpec } from "./builtins.js";
12
12
  import { lowerIndexedCallback } from "./callback-lowering.js";
13
13
  import { isFalsyCapableTy } from "./condition-facts.js";
14
- import { declOf, declOfKind, declOfTy, unionDeclOfTy, declWithVariant, tyBaseName } from "./typedecls.js";
15
- import { buildNestedFieldExpr, collectAssignedIrTargets, describeReceiver, emitWriteBacksForTarget, findActiveUnwrapFrame, isMutatingCollectionMethod, makeUnwrapFrame, makeVariantFrame, resolveWriteTargetThroughFrames, } from "./place-lowering.js";
14
+ import { declOf, declOfKind, declOfTy, unionDeclOfTy, tyBaseName, remainingVariant } from "./typedecls.js";
15
+ import { buildNestedFieldExpr, collectAssignedIrTargets, describeReceiver, emitWriteBacksForTarget, findActiveUnwrapFrame, isMutatingCollectionMethod, makeUnwrapFrame, resolveWriteTargetThroughFrames, } from "./place-lowering.js";
16
16
  // ── Generic IR walkers ──────────────────────────────────────
17
17
  /**
18
18
  * Map over all sub-expressions in an Expr. `f` is called on each node;
@@ -80,15 +80,69 @@ function mapStmt(s, f) {
80
80
  const scr = r(s.scrutinee);
81
81
  return { ...s, scrutinee: scr, arms: s.arms.map(a => ({ ...a, body: a.body.map(t => mapStmt(t, f)) })) };
82
82
  }
83
- case "while": return { ...s, cond: r(s.cond), invariants: s.invariants.map(r), body: s.body.map(t => mapStmt(t, f)) };
84
- case "forin": return { ...s, bound: r(s.bound), invariants: s.invariants.map(r), body: s.body.map(t => mapStmt(t, f)) };
83
+ case "while": return { ...s, cond: r(s.cond), invariants: s.invariants.map(r),
84
+ decreasing: s.decreasing ? r(s.decreasing) : null,
85
+ doneWith: s.doneWith ? r(s.doneWith) : null,
86
+ body: s.body.map(t => mapStmt(t, f)) };
87
+ case "forin": return { ...s, bound: r(s.bound), invariants: s.invariants.map(r),
88
+ body: s.body.map(t => mapStmt(t, f)) };
85
89
  case "ghostLet": return { ...s, value: r(s.value) };
86
90
  case "ghostAssign": return { ...s, value: r(s.value) };
87
91
  case "assert": return { ...s, expr: r(s.expr) };
88
92
  }
89
93
  }
90
94
  const varE = (name) => ({ kind: "var", name });
91
- /** Map over all sub-expressions in a TExpr (typed IR). */
95
+ /** Map `f` over a lambda body unless a parameter rebinds `name`. `mapExpr`
96
+ * doesn't descend into lambda bodies, so substitutions that must reach
97
+ * closures call this. Statement binders are tracked only at the body's top
98
+ * level: a `let`/`let-bind`/`ghostLet` of `name` shadows it for the rest of
99
+ * the body, and a `for-in` index of `name` shadows it inside that loop. */
100
+ function mapLambdaBody(x, name, f) {
101
+ if (x.params.some(p => p.name === name))
102
+ return x;
103
+ const body = [];
104
+ let shadowed = false;
105
+ for (const s of x.body) {
106
+ if (shadowed) {
107
+ body.push(s);
108
+ continue;
109
+ }
110
+ body.push(s.kind === "forin" && s.idx === name
111
+ ? { ...s, bound: mapExpr(s.bound, f) }
112
+ : mapStmt(s, f));
113
+ if ((s.kind === "let" || s.kind === "let-bind" || s.kind === "ghostLet") && s.name === name)
114
+ shadowed = true;
115
+ }
116
+ return { ...x, body };
117
+ }
118
+ /** Rename free occurrences of `from` to `to`, stopping at every construct that
119
+ * rebinds `from` — lambda params, `let`/`let-bind`/`ghostLet` (shadows the
120
+ * rest of the block), `match` arm patterns, `forall`/`exists`, and `for-in`
121
+ * indices. Capture-avoiding: a nested scope that reintroduces `from` keeps its
122
+ * own binding untouched. Lambda bodies are walked by `mapLambdaBody`. */
123
+ function renameFreeVar(e, from, to) {
124
+ const f = (x) => {
125
+ if (x.kind === "var")
126
+ return x.name === from ? { ...x, name: to } : x;
127
+ // let-expression: `value` is in the outer scope (rename), `body` sees the
128
+ // rebound `from` (leave it), so handle the recursion here to stop descent.
129
+ if (x.kind === "let" && x.name === from)
130
+ return { ...x, value: mapExpr(x.value, f) };
131
+ if ((x.kind === "forall" || x.kind === "exists") && x.var === from)
132
+ return x;
133
+ if (x.kind === "match") {
134
+ return { ...x, scrutinee: mapExpr(x.scrutinee, f), arms: x.arms.map(a => patternBinders(a.pattern).includes(from) ? a : { ...a, body: mapExpr(a.body, f) }) };
135
+ }
136
+ if (x.kind === "lambda")
137
+ return mapLambdaBody(x, from, f);
138
+ return null;
139
+ };
140
+ return mapExpr(e, f);
141
+ }
142
+ /** Map over all sub-expressions in a TExpr (typed IR), including lambda
143
+ * defaults and bodies. Extraction leaves no binding that shadows another
144
+ * (see LexicalNames), so callers substituting for a narrowed name can rely
145
+ * on names identifying their variables across nested scopes (#353). */
92
146
  function mapTExpr(e, f) {
93
147
  const hit = f(e);
94
148
  if (hit)
@@ -121,7 +175,9 @@ function mapTExpr(e, f) {
121
175
  fallthrough: e.fallthrough ? r(e.fallthrough) : null };
122
176
  case "forall": return { ...e, body: r(e.body) };
123
177
  case "exists": return { ...e, body: r(e.body) };
124
- case "lambda": return e;
178
+ case "lambda": return { ...e,
179
+ params: e.params.map(p => p.defaultValue ? { ...p, defaultValue: r(p.defaultValue) } : p),
180
+ body: e.body.map(s => mapTStmt(s, f)) };
125
181
  }
126
182
  }
127
183
  /** Map over all expressions in a TStmt tree (typed IR). */
@@ -199,16 +255,24 @@ function kindHelperDecl(decl) {
199
255
  * collisions in nested matches on different variables. `freshName` closes
200
256
  * the residual gap: a user variable literally named `_value`/`_x_field` in an
201
257
  * arm body would still be captured, so prime on any module-wide collision.
202
- * Deterministic, so the pattern binder and its body substitutions agree. */
203
- function matchBinder(fieldName, prefix) {
258
+ * Deterministic, so the pattern binder and its body substitutions agree.
259
+ * `taken` adds names the arm already reads, such as an outer narrowing's
260
+ * binder substituted into the arm before this match was lowered. */
261
+ function matchBinder(fieldName, prefix, taken) {
204
262
  const safePrefix = prefix === "\\result"
205
263
  ? "result"
206
264
  : prefix?.replace(/[^A-Za-z0-9_]/g, "_");
207
- return freshName(safePrefix ? `_${safePrefix}_${fieldName}` : `_${fieldName}`);
265
+ const base = safePrefix ? `_${safePrefix}_${fieldName}` : `_${fieldName}`;
266
+ return taken ? freshNameWhere(base, n => isUserName(n) || taken(n)) : freshName(base);
208
267
  }
209
268
  /** Build a match arm pattern like `.VariantName _v_field1 _v_field2` from variant info. */
210
- function buildMatchPattern(variantName, fields, scopePrefix) {
211
- return pCtor(variantName, ...fields.map(f => matchBinder(f.name, scopePrefix)));
269
+ function buildMatchPattern(variantName, fields, scopePrefix, taken) {
270
+ return pCtor(variantName, ...fields.map(f => matchBinder(f.name, scopePrefix, taken)));
271
+ }
272
+ /** Build a binder-free wildcard match pattern like `.VariantName _ _` for
273
+ * imperative union matches that read and update live storage directly (#405). */
274
+ function buildWildcardMatchPattern(variantName, fields) {
275
+ return pCtor(variantName, ...fields.map(() => "_"));
212
276
  }
213
277
  const _forofCounters = new Map();
214
278
  function isNat(ty) { return ty.kind === "nat"; }
@@ -458,6 +522,31 @@ function promoteAssignedLets(stmts) {
458
522
  });
459
523
  return fix(stmts);
460
524
  }
525
+ /** Lower an in-place write assigning `newVal` to any writable Place receiver
526
+ * (`var`, `field` chain, or `checkedUnwrap` around either). */
527
+ function buildPlaceWrite(recv, newVal) {
528
+ if (recv.kind === "var")
529
+ return { target: recv.name, value: newVal };
530
+ if (recv.kind === "field") {
531
+ const upd = buildNestedFieldUpdate(recv, newVal);
532
+ return upd ? { target: upd.root, value: upd.value } : null;
533
+ }
534
+ if (recv.kind === "checkedUnwrap") {
535
+ const wrapped = wrapCheckedUnwrapValue(newVal, recv.expr.ty);
536
+ return buildPlaceWrite(recv.expr, wrapped);
537
+ }
538
+ return null;
539
+ }
540
+ /** Root variable of a writable Place receiver (`var`, `field` chain, or `checkedUnwrap`). */
541
+ function placeRootVar(recv) {
542
+ if (recv.kind === "var")
543
+ return recv.name;
544
+ if (recv.kind === "field")
545
+ return placeRootVar(recv.obj);
546
+ if (recv.kind === "checkedUnwrap")
547
+ return placeRootVar(recv.expr);
548
+ return null;
549
+ }
461
550
  /** Build a nested record-update assigning `newVal` to a field-path receiver
462
551
  * rooted at a var: `b.a.items` → `b := b.(a := b.a.(items := newVal))`.
463
552
  * Handles `checkedUnwrap` hops along the path by wrapping the updated record
@@ -466,7 +555,16 @@ function promoteAssignedLets(stmts) {
466
555
  function buildNestedFieldUpdate(recv, newVal) {
467
556
  if (recv.kind !== "field")
468
557
  return null;
469
- const upd = { kind: "record", spread: lowerExpr(recv.obj, null), fields: [{ name: recv.field, value: newVal }] };
558
+ const objTy = recv.obj.ty.kind === "optional" || recv.obj.ty.kind === "nullish" ? recv.obj.ty.inner : recv.obj.ty;
559
+ const unionBase = objTy.kind === "user" && declOfKind(_typeDecls, tyBaseName(objTy.name), "discriminated-union")
560
+ ? tyBaseName(objTy.name)
561
+ : undefined;
562
+ const upd = {
563
+ kind: "record",
564
+ spread: lowerExpr(recv.obj, null),
565
+ fields: [{ name: recv.field, value: newVal }],
566
+ ...(unionBase ? { ctor: recv.ofVariant, ctorOf: unionBase } : {}),
567
+ };
470
568
  if (recv.obj.kind === "var")
471
569
  return { root: recv.obj.name, value: upd };
472
570
  if (recv.obj.kind === "field")
@@ -1120,16 +1218,19 @@ function lowerExpr(e, binds) {
1120
1218
  const owners = decl?.variants?.filter(v => v.fields.some(f => f.name === e.field)) ?? [];
1121
1219
  if (owners.length > 0) {
1122
1220
  // Shared field name with differing declared types: those destructors
1123
- // are renamed per-constructor, and the read's own resolved type
1124
- // identifies the owning variant (the types differ exactly when the
1125
- // rename happens). Pin it so emitters use the renamed destructor.
1221
+ // are renamed per-constructor (e.g. `value` → `value_a`, `value_a` →
1222
+ // `value_a_a`), so falling through to plain `sh.<field>` can resolve to
1223
+ // a different renamed destructor and verify a false contract. Require a
1224
+ // known variant (`e.ofVariant`) for mixed-type union projections.
1126
1225
  const ownerTy = (v) => v.fields.find(f => f.name === e.field)?.type;
1127
1226
  const differ = owners.some(v => {
1128
1227
  const a = ownerTy(v), b = ownerTy(owners[0]);
1129
1228
  return a && b && !tyEqual(a, b);
1130
1229
  });
1131
- const matching = differ ? owners.filter(v => { const t = ownerTy(v); return t && tyEqual(t, e.ty); }) : [];
1132
- const ctor = e.ofVariant ?? (matching.length === 1 ? matching[0].name : undefined);
1230
+ if (differ && !e.ofVariant) {
1231
+ throw new Error(`cannot read '${e.field}' on '${baseName}' without narrowing to a variant first (variants give '${e.field}' different types)`);
1232
+ }
1233
+ const ctor = e.ofVariant;
1133
1234
  return { kind: "field", obj: transformExpr(e.obj), field: e.field, fromUnion: baseName, ctor, datatypeField: true };
1134
1235
  }
1135
1236
  }
@@ -1250,18 +1351,28 @@ function lowerExpr(e, binds) {
1250
1351
  }
1251
1352
  // Math.floor(x):
1252
1353
  // - a / b on integral operands → integer floor division, kept in
1253
- // integer arithmetic (JSFloorDiv on Dafny; native Int/Nat `/` floors
1254
- // on Lean). Checked first: after resolve, `a / b` is typed `real`, so
1255
- // the real branch below would otherwise drag it into real arithmetic.
1354
+ // integer arithmetic (JSFloorDiv on Dafny; on Lean, native `/` is
1355
+ // Euclidean `Int.ediv` which matches floor division only when the
1356
+ // divisor is non-negative, so signed/negative divisors emit
1357
+ // qualified `Int.fdiv` directly to avoid colliding with a user
1358
+ // function named `JSFloorDiv`). Checked first: after resolve, `a / b`
1359
+ // is typed `real`, so the real branch below would otherwise drag it
1360
+ // into real arithmetic.
1256
1361
  // - real arg → FloorReal (Dafny's .Floor)
1257
1362
  // - int arg → identity
1258
1363
  if (e.fn.kind === "field" && e.fn.field === "floor" && e.fn.obj.kind === "var" && e.fn.obj.name === "Math" && e.args.length === 1) {
1259
1364
  const arg = e.args[0];
1260
1365
  if (arg.kind === "binop" && arg.op === "/" && isIntegral(arg.left.ty) && isIntegral(arg.right.ty)) {
1261
1366
  const l = lowerExpr(arg.left, binds), r = lowerExpr(arg.right, binds);
1262
- return _opts.backend === "dafny"
1263
- ? { kind: "app", fn: "JSFloorDiv", args: [l, r] }
1264
- : { kind: "binop", op: "/", left: l, right: r };
1367
+ if (_opts.backend === "dafny") {
1368
+ return { kind: "app", fn: "JSFloorDiv", args: [l, r] };
1369
+ }
1370
+ const nonnegDivisor = isNat(arg.right.ty) ||
1371
+ (arg.right.kind === "num" && arg.right.value > 0) ||
1372
+ (arg.right.kind === "bigint" && BigInt(arg.right.value) > 0n);
1373
+ return nonnegDivisor
1374
+ ? { kind: "binop", op: "/", left: l, right: r }
1375
+ : { kind: "app", fn: "Int.fdiv", args: [l, r] };
1265
1376
  }
1266
1377
  if (arg.ty.kind === "real")
1267
1378
  return { kind: "app", fn: "FloorReal", args: [lowerExpr(arg, binds)] };
@@ -1385,9 +1496,43 @@ function lowerExpr(e, binds) {
1385
1496
  };
1386
1497
  }
1387
1498
  const prefix = e.callKind === "spec-pure" && _opts.backend === "lean" ? "Pure." : "";
1388
- return { kind: "app", fn: prefix + e.fn.name, args: e.args.map(a => lowerExpr(a, binds)) };
1499
+ const callArgs = e.args.map(a => lowerExpr(a, binds));
1500
+ // Zero-parameter closures are emitted as `fun () => ...` in Lean (`Unit → T`),
1501
+ // so calling one must supply `()`. Top-level 0-arg defs/methods do not carry
1502
+ // a `fn` variable type and stay bare names.
1503
+ if (_opts.backend === "lean" && callArgs.length === 0 && e.fn.ty.kind === "fn" && e.fn.ty.params.length === 0) {
1504
+ callArgs.push({ kind: "var", name: "()" });
1505
+ }
1506
+ return { kind: "app", fn: prefix + e.fn.name, args: callArgs };
1389
1507
  }
1390
1508
  case "record": {
1509
+ const lowerTypedField = (rawVal, declaredTy) => {
1510
+ const fieldValue = declaredTy && rawVal.ty.kind === "unknown"
1511
+ ? { ...rawVal, ty: declaredTy }
1512
+ : rawVal;
1513
+ let value = lowerExpr(fieldValue, binds);
1514
+ if (declaredTy?.kind === "optional") {
1515
+ const isUndef = rawVal.kind === "var" && (rawVal.name === "undefined" || rawVal.name === "null");
1516
+ if (rawVal.ty.kind !== "optional" && !isUndef) {
1517
+ value = { kind: "app", fn: "Some", args: [value] };
1518
+ }
1519
+ }
1520
+ else if (declaredTy?.kind === "nullish") {
1521
+ value = wrapNullishBranch(value, rawVal);
1522
+ }
1523
+ return value;
1524
+ };
1525
+ const buildVariantCtor = (variantName, tyName, baseName, variant, resolveArg) => {
1526
+ // Bare-constructor shortcut only when the variant truly has no fields —
1527
+ // a variant with only optional fields still needs its argument list.
1528
+ if (variant.fields.length === 0) {
1529
+ return { kind: "constructor", name: variantName, type: tyName, args: [] };
1530
+ }
1531
+ // Constructor with args: match variant field order. Emit a bare `app`
1532
+ // (Dafny renders `variantName(args)`) tagged with `ctorOf` so Lean
1533
+ // qualifies it as `BaseType.variantName args` (using the base name).
1534
+ return { kind: "app", fn: variantName, args: variant.fields.map(resolveArg), ctorOf: baseName };
1535
+ };
1391
1536
  // Discriminated union: { kind: 'NoOp' } → constructor NoOp
1392
1537
  if (e.ty.kind === "user" && !e.spread) {
1393
1538
  const tyName = e.ty.name;
@@ -1397,23 +1542,11 @@ function lowerExpr(e, binds) {
1397
1542
  if (decl && decl.discriminant) {
1398
1543
  const discField = e.fields.find(f => f.name === decl.discriminant);
1399
1544
  if (discField && (discField.value.kind === "str" || discField.value.kind === "bool")) {
1400
- const variantName = String(discField.value.kind === "str" ? discField.value.value : discField.value.value);
1545
+ const variantName = String(discField.value.value);
1401
1546
  const variant = decl.variants?.find(v => v.name === variantName);
1402
1547
  if (variant) {
1403
1548
  const nonDiscFields = e.fields.filter(f => f.name !== decl.discriminant);
1404
- // Bare-constructor shortcut only when the variant truly has no
1405
- // fields — a variant with only optional fields still needs its
1406
- // None-filled argument list (`int_(None)`, not `int_`).
1407
- if (variant.fields.length === 0) {
1408
- return { kind: "constructor", name: variantName, type: tyName, args: [] };
1409
- }
1410
- // Constructor with args: match variant field order. Emit a bare `app`
1411
- // (Dafny renders `variantName(args)`, a valid unqualified constructor
1412
- // call — unchanged output) tagged with `ctorOf` so the Lean emitter,
1413
- // which CANNOT take a bare constructor name, qualifies it as
1414
- // `BaseType.variantName args`. Use the BASE type name (no generic args):
1415
- // `Result.true_` is valid in Lean; `Result<Model,Err>.true_` is not.
1416
- const args = variant.fields.map(vf => {
1549
+ return buildVariantCtor(variantName, tyName, baseName, variant, vf => {
1417
1550
  const ef = nonDiscFields.find(f => f.name === vf.name);
1418
1551
  if (ef)
1419
1552
  return lowerExpr(ef.value, binds);
@@ -1422,7 +1555,6 @@ function lowerExpr(e, binds) {
1422
1555
  }
1423
1556
  return { kind: "var", name: "None" };
1424
1557
  });
1425
- return { kind: "app", fn: variantName, args, ctorOf: baseName };
1426
1558
  }
1427
1559
  }
1428
1560
  }
@@ -1431,17 +1563,117 @@ function lowerExpr(e, binds) {
1431
1563
  if (e.spread) {
1432
1564
  const spreadTy = e.spread.ty.kind === "optional" ? e.spread.ty.inner : e.spread.ty;
1433
1565
  const structName = spreadTy.kind === "user" ? spreadTy.name : undefined;
1434
- const structDecl = structName ? declOfKind(_typeDecls, structName, "record") : undefined;
1566
+ const baseName = structName ? tyBaseName(structName) : undefined;
1567
+ const structDecl = baseName ? declOfKind(_typeDecls, baseName, "record") : undefined;
1435
1568
  // Also check discriminated-union variants for field types
1436
- const unionDecl = structName ? declOfKind(_typeDecls, structName, "discriminated-union") : undefined;
1569
+ const unionDecl = baseName ? declOfKind(_typeDecls, baseName, "discriminated-union") : undefined;
1570
+ // Tag-overriding spread on a discriminated union (`{ ...sh, kind: "b", ... }`):
1571
+ // once a spread explicitly overrides the discriminant, ordinary field update
1572
+ // is the wrong operation (it can silently write a colliding renamed payload
1573
+ // destructor such as `value_a` and preserve the old constructor). Either
1574
+ // construct the target variant faithfully or reject with a diagnostic.
1575
+ if (unionDecl?.discriminant) {
1576
+ const discField = e.fields.find(f => f.name === unionDecl.discriminant);
1577
+ if (discField) {
1578
+ if (discField.value.kind !== "str" && discField.value.kind !== "bool") {
1579
+ throw new Error(`spread on '${unionDecl.name}' must set '${unionDecl.discriminant}' to a literal tag`);
1580
+ }
1581
+ const variantName = String(discField.value.value);
1582
+ const targetVariant = unionDecl.variants?.find(v => v.name === variantName);
1583
+ if (!targetVariant) {
1584
+ throw new Error(`unknown '${unionDecl.name}' variant '${variantName}' in spread`);
1585
+ }
1586
+ const sourceVariant = e.spreadOfVariant
1587
+ ? unionDecl.variants?.find(v => v.name === e.spreadOfVariant)
1588
+ : undefined;
1589
+ const possibleSources = sourceVariant ? [sourceVariant] : (unionDecl.variants ?? []);
1590
+ const spreadExpr = lowerExpr(e.spread, binds);
1591
+ const overriddenByName = new Map();
1592
+ for (const f of e.fields) {
1593
+ if (f.name === unionDecl.discriminant)
1594
+ continue;
1595
+ const declaredTy = targetVariant.fields.find(vf => vf.name === f.name)?.type;
1596
+ overriddenByName.set(f.name, lowerTypedField(f.value, declaredTy));
1597
+ }
1598
+ return buildVariantCtor(variantName, structName, baseName, targetVariant, vf => {
1599
+ const explicit = overriddenByName.get(vf.name);
1600
+ if (explicit !== undefined)
1601
+ return explicit;
1602
+ for (const sv of possibleSources) {
1603
+ const sf = sv.fields.find(f => f.name === vf.name);
1604
+ if (!sf?.type || !vf.type || !tyEqual(sf.type, vf.type)) {
1605
+ throw new Error(`cannot change '${unionDecl.name}' from '${sv.name}' to '${variantName}' via spread: pass '${vf.name}' explicitly`);
1606
+ }
1607
+ }
1608
+ return {
1609
+ kind: "field",
1610
+ obj: spreadExpr,
1611
+ field: vf.name,
1612
+ fromUnion: baseName,
1613
+ ctor: sourceVariant?.name,
1614
+ datatypeField: true,
1615
+ };
1616
+ });
1617
+ }
1618
+ }
1619
+ const pinnedVariant = unionDecl && e.ofVariant
1620
+ ? unionDecl.variants?.find(v => v.name === e.ofVariant)
1621
+ : undefined;
1622
+ // Un-narrowed union spread where an overridden field has differing types
1623
+ // across variants (e.g. `a.value: number` vs `b.value: number | undefined`):
1624
+ // expand to a per-variant `match` so each constructor receives the right
1625
+ // coercion (`5` vs `Some(5)`) and destructor in both Dafny and Lean.
1626
+ if (unionDecl?.variants && !pinnedVariant) {
1627
+ const hasMixedField = e.fields.some(f => {
1628
+ const tys = unionDecl.variants
1629
+ .map(v => v.fields.find(vf => vf.name === f.name)?.type)
1630
+ .filter((t) => t !== undefined);
1631
+ return tys.length > 1 && tys.some(t => !tyEqual(t, tys[0]));
1632
+ });
1633
+ if (hasMixedField) {
1634
+ const spreadExpr = lowerExpr(e.spread, binds);
1635
+ const baseFieldExprs = new Map(e.fields.map(f => [f.name, lowerExpr(f.value, binds)]));
1636
+ const rawFieldByName = new Map(e.fields.map(f => [f.name, f.value]));
1637
+ const arms = unionDecl.variants.map(v => {
1638
+ const binders = [];
1639
+ const fieldExprs = new Map();
1640
+ v.fields.forEach((vf, idx) => {
1641
+ const rawVal = rawFieldByName.get(vf.name);
1642
+ if (rawVal !== undefined) {
1643
+ binders.push("_");
1644
+ let val = baseFieldExprs.get(vf.name);
1645
+ if (vf.type?.kind === "optional") {
1646
+ const isUndef = rawVal.kind === "var" && (rawVal.name === "undefined" || rawVal.name === "null");
1647
+ if (rawVal.ty.kind !== "optional" && !isUndef) {
1648
+ val = { kind: "app", fn: "Some", args: [val] };
1649
+ }
1650
+ }
1651
+ else if (vf.type?.kind === "nullish") {
1652
+ val = wrapNullishBranch(val, rawVal);
1653
+ }
1654
+ fieldExprs.set(vf.name, val);
1655
+ }
1656
+ else {
1657
+ const bv = freshName(`_sp${idx}`);
1658
+ binders.push(bv);
1659
+ fieldExprs.set(vf.name, { kind: "var", name: bv });
1660
+ }
1661
+ });
1662
+ const body = buildVariantCtor(v.name, structName, baseName, v, vf => fieldExprs.get(vf.name));
1663
+ return { pattern: { kind: "ctor", ctor: v.name, binders }, body };
1664
+ });
1665
+ return { kind: "match", scrutinee: spreadExpr, arms };
1666
+ }
1667
+ }
1437
1668
  const loweredFields = e.fields.map(f => {
1438
- // Propagate declared field type onto value if it has unknown type
1439
- let fieldValue = f.value;
1440
1669
  const fieldDecl = structDecl?.fields?.find(sf => sf.name === f.name);
1441
1670
  let declaredTy;
1442
1671
  if (fieldDecl) {
1443
1672
  declaredTy = fieldDecl.type;
1444
1673
  }
1674
+ else if (pinnedVariant) {
1675
+ declaredTy = pinnedVariant.fields.find(vf => vf.name === f.name)?.type;
1676
+ }
1445
1677
  else if (unionDecl?.variants) {
1446
1678
  for (const v of unionDecl.variants) {
1447
1679
  const vf = v.fields.find(vf => vf.name === f.name);
@@ -1451,23 +1683,14 @@ function lowerExpr(e, binds) {
1451
1683
  }
1452
1684
  }
1453
1685
  }
1454
- if (declaredTy && fieldValue.ty.kind === "unknown") {
1455
- fieldValue = { ...fieldValue, ty: declaredTy };
1456
- }
1457
- let value = lowerExpr(fieldValue, binds);
1458
- // Wrap non-optional/non-nullish values for optional/nullish fields
1459
- if (declaredTy?.kind === "optional") {
1460
- const isUndef = f.value.kind === "var" && (f.value.name === "undefined" || f.value.name === "null");
1461
- if (f.value.ty.kind !== "optional" && !isUndef) {
1462
- value = { kind: "app", fn: "Some", args: [value] };
1463
- }
1464
- }
1465
- else if (declaredTy?.kind === "nullish") {
1466
- value = wrapNullishBranch(value, f.value);
1467
- }
1468
- return { name: f.name, value };
1686
+ return { name: f.name, value: lowerTypedField(f.value, declaredTy) };
1469
1687
  });
1470
- return { kind: "record", spread: lowerExpr(e.spread, binds), fields: loweredFields };
1688
+ return {
1689
+ kind: "record",
1690
+ spread: lowerExpr(e.spread, binds),
1691
+ fields: loweredFields,
1692
+ ...(unionDecl && baseName ? { ctor: e.ofVariant, ctorOf: baseName } : {}),
1693
+ };
1471
1694
  }
1472
1695
  // Empty record with map type → empty map
1473
1696
  if (e.fields.length === 0 && !e.spread && e.ty.kind === "map") {
@@ -1684,30 +1907,43 @@ function lowerExpr(e, binds) {
1684
1907
  const pathHint = varName ?? scrutineeHint(e.scrutinee);
1685
1908
  const wrapOpt = e.ty.kind === "optional";
1686
1909
  const wrapNullish = e.ty.kind === "nullish";
1687
- const arms = e.cases.map(c => {
1910
+ const lowered = e.cases.map(c => lowerExpr(c.body, binds));
1911
+ const loweredFallthrough = e.fallthrough ? lowerExpr(e.fallthrough, binds) : null;
1912
+ // The arms may already read a binder minted for an enclosing narrowing
1913
+ // with the same hint (`u` and `m.u` both give `_u_arr`). Prime this
1914
+ // match's binders past those names so the arm does not capture them.
1915
+ const read = new Set();
1916
+ for (const b of [...lowered, ...(loweredFallthrough ? [loweredFallthrough] : [])])
1917
+ anyExpr(b, x => { if (x.kind === "var")
1918
+ read.add(x.name); return false; });
1919
+ const taken = (n) => read.has(n);
1920
+ const arms = e.cases.map((c, i) => {
1688
1921
  const variant = decl?.variants?.find(v => v.name === c.variant);
1689
1922
  const fields = variant?.fields ?? [];
1690
- let body = lowerExpr(c.body, binds);
1923
+ let body = lowered[i];
1691
1924
  if (varName && fields.length > 0) {
1692
- body = replaceFieldAccess(body, varName, fields, c.variant, tyBaseName(e.typeName));
1925
+ body = replaceFieldAccess(body, varName, fields, c.variant, tyBaseName(e.typeName), taken);
1693
1926
  if (isSynthArrayUnion && fields.length === 1) {
1694
- body = replaceVarInExpr(body, varName, matchBinder(fields[0].name, varName));
1927
+ body = replaceVarInExpr(body, varName, matchBinder(fields[0].name, varName, taken));
1695
1928
  }
1696
1929
  }
1697
1930
  else if (!varName && isSynthArrayUnion && fields.length === 1) {
1698
- // Path scrutinee (e.g. `m.content`): replace structural occurrences
1931
+ // Path scrutinee (e.g. `m.content`): replace both projected
1932
+ // `m.content.arr` (inserted by checked-reads) and bare `m.content`
1699
1933
  // with the binder var ref.
1700
- const binderName = matchBinder(fields[0].name, pathHint);
1934
+ const binderName = matchBinder(fields[0].name, pathHint, taken);
1935
+ const projectedField = { kind: "field", obj: scrutinee, field: fields[0].name };
1936
+ body = replaceExprInExpr(body, projectedField, { kind: "var", name: binderName });
1701
1937
  body = replaceExprInExpr(body, scrutinee, { kind: "var", name: binderName });
1702
1938
  }
1703
1939
  if (wrapOpt)
1704
1940
  body = wrapOptionalBranch(body, c.body);
1705
1941
  else if (wrapNullish)
1706
1942
  body = wrapNullishBranch(body, c.body);
1707
- return { pattern: buildMatchPattern(c.variant, fields, pathHint), body };
1943
+ return { pattern: buildMatchPattern(c.variant, fields, pathHint, taken), body };
1708
1944
  });
1709
- if (e.fallthrough) {
1710
- let body = lowerExpr(e.fallthrough, binds);
1945
+ if (e.fallthrough && loweredFallthrough) {
1946
+ let body = loweredFallthrough;
1711
1947
  if (wrapOpt)
1712
1948
  body = wrapOptionalBranch(body, e.fallthrough);
1713
1949
  else if (wrapNullish)
@@ -1756,14 +1992,49 @@ function ensuresToMatch(e, typeDecls) {
1756
1992
  rhs = replaceFieldAccess(rhs, obj.name, fields);
1757
1993
  return { kind: "match", scrutinee: varE(obj.name), arms: [{ pattern, body: rhs }, { pattern: pWild(), body: { kind: "bool", value: true } }] };
1758
1994
  }
1759
- function replaceFieldAccess(e, varName, fields, ctorName, ctorOf) {
1760
- return mapExpr(e, x => {
1995
+ /** Substitution into a nested `match` that is capture-avoiding. An arm whose
1996
+ * pattern rebinds `oldName` keeps its body. An arm that binds one of the
1997
+ * `introduced` names, while its body still reads `oldName`, has that binder
1998
+ * renamed to a fresh name first. Without the rename, the substituted
1999
+ * reference would resolve to the inner binder instead of the outer one. */
2000
+ function substIntoMatch(x, oldName, introduced, sub) {
2001
+ return { ...x, scrutinee: sub(x.scrutinee), arms: x.arms.map(a => {
2002
+ if (patternBinders(a.pattern).includes(oldName))
2003
+ return a;
2004
+ const readsOld = anyExpr(a.body, y => y.kind === "var" && y.name === oldName);
2005
+ if (!readsOld || a.pattern.kind !== "ctor")
2006
+ return { ...a, body: sub(a.body) };
2007
+ const binders = [...a.pattern.binders];
2008
+ let body = a.body;
2009
+ for (let i = 0; i < binders.length; i++) {
2010
+ const b = binders[i];
2011
+ if (!introduced.includes(b))
2012
+ continue;
2013
+ const fresh = freshNameWhere(b, n => isUserName(n) || introduced.includes(n) || binders.includes(n) ||
2014
+ anyExpr(body, y => y.kind === "var" && y.name === n));
2015
+ binders[i] = fresh;
2016
+ body = renameFreeVar(body, b, fresh);
2017
+ }
2018
+ const pattern = { ...a.pattern, binders };
2019
+ return { ...a, pattern, body: sub(body) };
2020
+ }) };
2021
+ }
2022
+ function replaceFieldAccess(e, varName, fields, ctorName, ctorOf, taken) {
2023
+ const introduced = fields.map(f => matchBinder(f.name, varName, taken));
2024
+ const fn = (x) => {
2025
+ if (x.kind === "lambda")
2026
+ return mapLambdaBody(x, varName, fn);
2027
+ if ((x.kind === "forall" || x.kind === "exists") && x.var === varName)
2028
+ return x;
2029
+ if (x.kind === "match") {
2030
+ return substIntoMatch(x, varName, introduced, y => replaceFieldAccess(y, varName, fields, ctorName, ctorOf, taken));
2031
+ }
1761
2032
  const objMatches = x.kind === "field" && ((x.obj.kind === "var" && x.obj.name === varName) ||
1762
2033
  (x.obj.kind === "checkedUnwrap" && x.obj.expr.kind === "var" && x.obj.expr.name === varName));
1763
2034
  if (objMatches && x.kind === "field") {
1764
2035
  const f = fields.find(f => f.name === x.field);
1765
2036
  if (f)
1766
- return { kind: "var", name: matchBinder(f.name, varName) };
2037
+ return { kind: "var", name: matchBinder(f.name, varName, taken) };
1767
2038
  }
1768
2039
  // Datatype update of the scrutinee (`{ ...vn, f: v }`): the arm knows the
1769
2040
  // variant, so stamp it — emitters need it for per-constructor destructor
@@ -1771,27 +2042,35 @@ function replaceFieldAccess(e, varName, fields, ctorName, ctorOf) {
1771
2042
  if (ctorName && x.kind === "record" && !x.ctor && x.spread &&
1772
2043
  x.spread.kind === "var" && x.spread.name === varName) {
1773
2044
  return { ...x, ctor: ctorName, ctorOf,
1774
- fields: x.fields.map(f => ({ ...f, value: replaceFieldAccess(f.value, varName, fields, ctorName, ctorOf) })) };
2045
+ fields: x.fields.map(f => ({ ...f, value: replaceFieldAccess(f.value, varName, fields, ctorName, ctorOf, taken) })) };
1775
2046
  }
1776
2047
  // If this let shadows the matched variable, stop replacing in the body
1777
2048
  if (x.kind === "let" && x.name === varName)
1778
- return { ...x, value: replaceFieldAccess(x.value, varName, fields, ctorName, ctorOf) };
2049
+ return { ...x, value: replaceFieldAccess(x.value, varName, fields, ctorName, ctorOf, taken) };
1779
2050
  return null;
1780
- });
2051
+ };
2052
+ return mapExpr(e, fn);
1781
2053
  }
1782
2054
  /** Replace bare `var(oldName)` references → `var(newName)` in lowered IR.
1783
2055
  * Used inside synth array-union match arms: the user code refers to the
1784
2056
  * scrutinee by its bare name (`content`), but in the arm body that name
1785
2057
  * must refer to the variant's sole payload binder (`i_content_arr`). */
1786
2058
  function replaceVarInExpr(e, oldName, newName) {
1787
- return mapExpr(e, x => {
2059
+ const fn = (x) => {
1788
2060
  if (x.kind === "var" && x.name === oldName)
1789
2061
  return { kind: "var", name: newName };
2062
+ if (x.kind === "match")
2063
+ return substIntoMatch(x, oldName, [newName], y => replaceVarInExpr(y, oldName, newName));
2064
+ if (x.kind === "lambda")
2065
+ return mapLambdaBody(x, oldName, fn);
1790
2066
  // If a binding shadows the name, stop substituting inside its body.
1791
2067
  if (x.kind === "let" && x.name === oldName)
1792
2068
  return { ...x, value: replaceVarInExpr(x.value, oldName, newName) };
2069
+ if ((x.kind === "forall" || x.kind === "exists") && x.var === oldName)
2070
+ return x;
1793
2071
  return null;
1794
- });
2072
+ };
2073
+ return mapExpr(e, fn);
1795
2074
  }
1796
2075
  /** Structural equality on Expr access-paths (var / field chain). Enough to
1797
2076
  * match the scrutinee `m.content` against later occurrences in a match arm. */
@@ -1804,16 +2083,36 @@ function exprPathEqual(a, b) {
1804
2083
  return a.field === b.field && exprPathEqual(a.obj, b.obj);
1805
2084
  return false;
1806
2085
  }
2086
+ /** Extract the root variable name of an access-path Expr (e.g. `m.u` → `m`). */
2087
+ function exprPathRoot(e) {
2088
+ let cur = e;
2089
+ while (cur.kind === "field")
2090
+ cur = cur.obj;
2091
+ return cur.kind === "var" ? cur.name : null;
2092
+ }
1807
2093
  /** Substitute every occurrence of `target` (an access-path Expr) with `repl`
1808
2094
  * inside `e`. Mirror of `replaceVarInExpr` but keyed on a sub-path rather
1809
2095
  * than a bare name — needed when the narrowing scrutinee is `m.content`
1810
2096
  * (field access) rather than a bare `content` (var). */
1811
2097
  function replaceExprInExpr(e, target, repl) {
1812
- return mapExpr(e, x => {
2098
+ const root = exprPathRoot(target);
2099
+ const introduced = repl.kind === "var" ? [repl.name] : [];
2100
+ const fn = (x) => {
1813
2101
  if (exprPathEqual(x, target))
1814
2102
  return repl;
2103
+ if (root) {
2104
+ if (x.kind === "match")
2105
+ return substIntoMatch(x, root, introduced, y => replaceExprInExpr(y, target, repl));
2106
+ if (x.kind === "lambda")
2107
+ return mapLambdaBody(x, root, fn);
2108
+ if (x.kind === "let" && x.name === root)
2109
+ return { ...x, value: replaceExprInExpr(x.value, target, repl) };
2110
+ if ((x.kind === "forall" || x.kind === "exists") && x.var === root)
2111
+ return x;
2112
+ }
1815
2113
  return null;
1816
- });
2114
+ };
2115
+ return mapExpr(e, fn);
1817
2116
  }
1818
2117
  /** Extract a short reader-friendly hint for a TExpr access-path: the last
1819
2118
  * field name in a field chain, or the var name. Used to derive a stable
@@ -1836,30 +2135,60 @@ function negateExpr(e) {
1836
2135
  return e.expr;
1837
2136
  return { kind: "unop", op: "¬", expr: e };
1838
2137
  }
1839
- /** Build the two pieces of an `arr.pop()` lowering on a named array variable:
1840
- * - `optValue` is `(if |arr|>0 then Some(arr[|arr|-1]) else None)` (the popped element)
1841
- * - `guardedTrunc` is `(if |arr|>0 then arr[..|arr|-1] else arr)` (the array minus its last element)
1842
- * Callers wrap these in let/assign statements appropriate to their context. */
1843
- function buildPopLoweringExpr(arrExpr, arrTy) {
2138
+ /** Lower an array `.pop()` or `.shift()` call on any writable Place receiver
2139
+ * into `{ method, result, writeStmts }`:
2140
+ * - `result` reads the removed element from the original receiver,
2141
+ * - `writeStmts` writes the shortened array
2142
+ * back through the original receiver Place + enclosing `someMatch` frames.
2143
+ * A consumed nonoptional result reads an element directly, already requiring
2144
+ * nonemptiness. Optional or discarded results still need an empty-array guard.
2145
+ * Value callers evaluate `result` before `writeStmts` and only assign to the
2146
+ * destination afterward so `t = t.children.shift()!` mutates the original `t`. */
2147
+ function lowerArrayPopOrShift(e, usage) {
2148
+ if (e.kind !== "call" || e.fn.kind !== "field" || e.fn.obj.ty.kind !== "array")
2149
+ return null;
2150
+ const method = e.fn.field;
2151
+ if (method !== "pop" && method !== "shift")
2152
+ return null;
2153
+ const obj = e.fn.obj;
2154
+ const arrExpr = lowerExpr(obj, null);
1844
2155
  const arrLen = { kind: "field", obj: arrExpr, field: "size" };
1845
- const lastIdx = { kind: "binop", op: "-", left: arrLen, right: { kind: "num", value: 1 } };
1846
- const lastElem = { kind: "index", arr: arrExpr, idx: lastIdx };
1847
2156
  const isNonEmpty = { kind: "binop", op: ">", left: arrLen, right: { kind: "num", value: 0 } };
1848
- const optValue = { kind: "if", cond: isNonEmpty,
1849
- then: { kind: "app", fn: "Some", args: [lastElem] },
1850
- else: { kind: "var", name: "undefined" } };
1851
- const truncated = { kind: "methodCall", obj: arrExpr, objTy: arrTy, method: "slice",
1852
- args: [{ kind: "num", value: 0 }, lastIdx], monadic: false };
1853
- const guardedTrunc = { kind: "if", cond: isNonEmpty, then: truncated, else: arrExpr };
1854
- return { optValue, guardedTrunc };
2157
+ const index = method === "pop"
2158
+ ? { kind: "binop", op: "-", left: arrLen, right: { kind: "num", value: 1 } }
2159
+ : { kind: "num", value: 0 };
2160
+ const elemValue = { kind: "index", arr: arrExpr, idx: index };
2161
+ const isOptResult = e.ty.kind === "optional" || e.ty.kind === "nullish";
2162
+ const result = isOptResult
2163
+ ? { kind: "if", cond: isNonEmpty, then: { kind: "app", fn: "Some", args: [elemValue] }, else: { kind: "var", name: "undefined" } }
2164
+ : elemValue;
2165
+ const truncated = { kind: "methodCall", obj: arrExpr, objTy: obj.ty, method: "slice",
2166
+ args: method === "pop" ? [{ kind: "num", value: 0 }, index] : [{ kind: "num", value: 1 }], monadic: false };
2167
+ const needsEmptyGuard = usage === "discard" || isOptResult;
2168
+ const nextArr = needsEmptyGuard
2169
+ ? { kind: "if", cond: isNonEmpty, then: truncated, else: arrExpr }
2170
+ : truncated;
2171
+ const write = buildPlaceWrite(obj, nextArr);
2172
+ if (!write)
2173
+ return null;
2174
+ return {
2175
+ method,
2176
+ result,
2177
+ writeStmts: [
2178
+ { kind: "assign", target: write.target, value: write.value },
2179
+ ...emitWriteBacksForTarget(write.target, _writeBackFrames),
2180
+ ],
2181
+ };
1855
2182
  }
1856
2183
  /**
1857
- * Velvet (Lean backend) rejects `return` inside a loop. For a function shaped as
1858
- * `…; while (…) { … early returns … }; return fallthrough`, hoist a mutable
1859
- * result variable: each in-loop `return e` becomes `_loopRet := e; break`, then
1860
- * `return _loopRet` after the loop. The trailing fallthrough return seeds
1861
- * `_loopRet`, so a normal loop exit returns it unchanged. Dafny is untouched —
1862
- * it keeps the native early returns.
2184
+ * Velvet (Lean backend) rejects `return` inside a loop. For a loop containing
2185
+ * early `return`s, hoist a mutable `Option T` result variable `_loopRet := none`:
2186
+ * each in-loop `return e` becomes `_loopRet := some e; break`. After the loop,
2187
+ * match on `_loopRet` so an early return returns its saved value, while a normal
2188
+ * exit (or regular `break`) runs the remaining statements with the post-loop
2189
+ * state rather than a stale pre-loop snapshot. Using `Option T` avoids needing
2190
+ * an `Inhabited T` default value whenever fallthrough statements follow the loop.
2191
+ * Dafny is untouched — it keeps the native early returns.
1863
2192
  */
1864
2193
  function stmtsContainReturn(stmts) {
1865
2194
  for (const s of stmts) {
@@ -1875,19 +2204,25 @@ function stmtsContainReturn(stmts) {
1875
2204
  }
1876
2205
  function replaceReturnsWithBreak(stmts, retVar) {
1877
2206
  return stmts.flatMap((s) => {
1878
- if (s.kind === "return")
1879
- return [{ kind: "assign", target: retVar, value: s.value }, { kind: "break" }];
1880
- if (s.kind === "if")
2207
+ if (s.kind === "return") {
2208
+ return [
2209
+ { kind: "assign", target: retVar, value: { kind: "app", fn: "Some", args: [s.value] } },
2210
+ { kind: "break" },
2211
+ ];
2212
+ }
2213
+ if (s.kind === "if") {
1881
2214
  return [{ ...s, then: replaceReturnsWithBreak(s.then, retVar), else: replaceReturnsWithBreak(s.else, retVar) }];
1882
- if (s.kind === "match")
2215
+ }
2216
+ if (s.kind === "match") {
1883
2217
  return [{ ...s, arms: s.arms.map(a => ({ ...a, body: replaceReturnsWithBreak(a.body, retVar) })) }];
2218
+ }
1884
2219
  return [s];
1885
2220
  });
1886
2221
  }
1887
- // Seed value for `_loopRet` when a return-in-loop function has no trailing
1888
- // fallthrough return. Readable literals for the primitives; everything else
1889
- // (user types, arrays, maps, optionals) gets a typed `default : T` rather than a
1890
- // type-incorrect `0` — these types derive `Inhabited`, so the default exists.
2222
+ // Fallback value only when a non-void return-in-loop has no statements after
2223
+ // the loop (e.g. `while (true) { ... return e; }`) so the unreachable `none`
2224
+ // branch still type-checks. Readable literals for primitives; everything else
2225
+ // gets a typed `default : T`.
1891
2226
  function defaultExprForTy(ty) {
1892
2227
  switch (ty.kind) {
1893
2228
  case "bool": return { kind: "bool", value: false };
@@ -1898,25 +2233,53 @@ function defaultExprForTy(ty) {
1898
2233
  default: return { kind: "default", type: ty };
1899
2234
  }
1900
2235
  }
1901
- function eliminateReturnInLoops(stmts, retTy, resultInvariants) {
2236
+ function eliminateReturnInLoops(stmts, retTy, ensuresExprs, counter = { n: 0 }) {
1902
2237
  const out = [];
1903
2238
  for (let i = 0; i < stmts.length; i++) {
1904
2239
  const s = stmts[i];
1905
2240
  if (s.kind === "while" && stmtsContainReturn(s.body)) {
1906
- const retVar = "_loopRet";
1907
- const next = stmts[i + 1];
1908
- const init = next && next.kind === "return" ? next.value : defaultExprForTy(retTy);
1909
- out.push({ kind: "let", name: retVar, type: retTy, mutable: true, value: init });
1910
- // The result variable carries the postcondition (the function's `ensures`
1911
- // with `\result` → `_loopRet`) as a loop invariant: it holds initially (the
1912
- // fallthrough seed) and after each `_loopRet := e; break`, so the
1913
- // postcondition is re-established from the invariant when the loop exits.
1914
- // Where Dafny discharged the postcondition at each `return` site, the
1915
- // break-rewrite discharges it once, after the loop.
1916
- out.push({ ...s, invariants: [...s.invariants, ...resultInvariants], body: replaceReturnsWithBreak(s.body, retVar) });
1917
- out.push({ kind: "return", value: { kind: "var", name: retVar } });
1918
- if (next && next.kind === "return")
1919
- i++; // consume the seeded fallthrough return
2241
+ const suffix = counter.n === 0 ? "" : String(counter.n);
2242
+ counter.n += 1;
2243
+ const retVar = freshName(`_loopRet${suffix}`);
2244
+ const retVal = freshName(`_loopRet${suffix}_val`);
2245
+ const retRef = { kind: "var", name: retVar };
2246
+ const retIsSome = { kind: "field", obj: retRef, field: "isSome" };
2247
+ const retUnwrap = { kind: "checkedUnwrap", expr: retRef };
2248
+ const resultInvariants = ensuresExprs.map(e => ({
2249
+ kind: "implies",
2250
+ premises: [retIsSome],
2251
+ conclusion: replaceVar(e, "\\result", retUnwrap),
2252
+ }));
2253
+ out.push({
2254
+ kind: "let",
2255
+ name: retVar,
2256
+ type: { kind: "optional", inner: retTy },
2257
+ mutable: true,
2258
+ value: { kind: "app", fn: "None", args: [] },
2259
+ });
2260
+ // Guard each postcondition invariant with `_loopRet.isSome → P[_loopRet.get / \result]`:
2261
+ // it holds vacuously while `_loopRet = none`, and Velvet checks `P[e / \result]`
2262
+ // at each `_loopRet := some e; break`.
2263
+ out.push({
2264
+ ...s,
2265
+ invariants: [...s.invariants, ...resultInvariants],
2266
+ body: replaceReturnsWithBreak(s.body, retVar),
2267
+ });
2268
+ const rest = stmts.slice(i + 1);
2269
+ const noneBody = rest.length > 0
2270
+ ? eliminateReturnInLoops(rest, retTy, ensuresExprs, counter)
2271
+ : retTy.kind === "void"
2272
+ ? []
2273
+ : [{ kind: "return", value: defaultExprForTy(retTy) }];
2274
+ out.push({
2275
+ kind: "match",
2276
+ scrutinee: retRef,
2277
+ arms: [
2278
+ { pattern: pCtor("some", retVal), body: [{ kind: "return", value: { kind: "var", name: retVal } }] },
2279
+ { pattern: pCtor("none"), body: noneBody },
2280
+ ],
2281
+ });
2282
+ break;
1920
2283
  }
1921
2284
  else {
1922
2285
  out.push(s);
@@ -1957,10 +2320,12 @@ function matchToIfChains(stmts) {
1957
2320
  if (arms.some(a => a.pattern.kind === "literal"))
1958
2321
  return [{ ...s, arms }];
1959
2322
  const ctorArms = arms.filter(a => a.pattern.kind === "ctor");
1960
- const firstCtor = ctorArms[0] ? patternCtor(ctorArms[0].pattern) : undefined;
1961
- const decl = firstCtor ? declWithVariant(_typeDecls, firstCtor) : undefined;
2323
+ // Only user-union matches carry `unionType` (from `emitMatchStmt` / `emitSwitchStmt`);
2324
+ // leave `Option` matches and other non-union matches alone even if a user union
2325
+ // happens to define `"some"` / `"none"` variants.
2326
+ const decl = s.unionType ? declOf(_typeDecls, tyBaseName(s.unionType)) : undefined;
1962
2327
  if (!decl)
1963
- return [{ ...s, arms }]; // not a user union (e.g. Option) — leave as match
2328
+ return [{ ...s, arms }];
1964
2329
  const scrutExpr = s.scrutinee;
1965
2330
  const defaultArm = arms.find(a => a.pattern.kind === "wild");
1966
2331
  const declaredCtors = decl.kind === "discriminated-union"
@@ -1971,8 +2336,10 @@ function matchToIfChains(stmts) {
1971
2336
  let elseBranch = defaultArm ? defaultArm.body : [];
1972
2337
  for (let k = ctorArms.length - 1; k >= 0; k--) {
1973
2338
  const armBody = ctorArms[k].body;
1974
- if (armBody.length === 0)
1975
- continue; // empty arm (no-op) — let it fall through to `else`
2339
+ // Only skip an empty arm when there is no fallback branch to fall into;
2340
+ // otherwise skipping it would execute `elseBranch` instead of doing nothing.
2341
+ if (armBody.length === 0 && elseBranch.length === 0)
2342
+ continue;
1976
2343
  const ctor = patternCtor(ctorArms[k].pattern) ?? "";
1977
2344
  const binders = patternBinders(ctorArms[k].pattern);
1978
2345
  const variant = decl.variants?.find(v => v.name === ctor);
@@ -2222,25 +2589,44 @@ function transformSpecExpr(e) {
2222
2589
  let _writeBackFrames = [];
2223
2590
  // Declared types of in-scope variables and narrowing binders (for optional-field wrap checks).
2224
2591
  let _varTypes = new Map();
2225
- /** Look up the declared field type reached by walking `fields` from `rootTy`. */
2226
- function lookupFieldTy(rootTy, fields, typeDecls) {
2592
+ /** Look up the declared field type and union-owner tags reached by walking
2593
+ * `fields` from `rootTy`. */
2594
+ function lookupFieldPathInfo(rootTy, fields, typeDecls, ownerVariants) {
2227
2595
  let cur = rootTy;
2228
- for (const field of fields) {
2596
+ const unionsByDepth = [];
2597
+ for (let i = 0; i < fields.length; i++) {
2598
+ const field = fields[i];
2229
2599
  if (!cur)
2230
- return null;
2600
+ return { fieldTy: null, unionsByDepth };
2231
2601
  if (cur.kind === "optional" || cur.kind === "nullish")
2232
2602
  cur = cur.inner;
2233
2603
  if (cur.kind !== "user")
2234
- return null;
2604
+ return { fieldTy: null, unionsByDepth };
2235
2605
  const decl = declOfTy(typeDecls, cur);
2236
- if (!decl || decl.kind !== "record" || !decl.fields)
2237
- return null;
2238
- const f = decl.fields.find(fi => fi.name === field);
2239
- if (!f)
2240
- return null;
2241
- cur = f.type ?? parseTsType(f.tsType);
2606
+ if (!decl)
2607
+ return { fieldTy: null, unionsByDepth };
2608
+ if (decl.kind === "record" && decl.fields) {
2609
+ unionsByDepth.push(undefined);
2610
+ const f = decl.fields.find(fi => fi.name === field);
2611
+ if (!f)
2612
+ return { fieldTy: null, unionsByDepth };
2613
+ cur = f.type ?? parseTsType(f.tsType);
2614
+ }
2615
+ else if (decl.kind === "discriminated-union" && decl.variants) {
2616
+ const ov = ownerVariants?.[i];
2617
+ unionsByDepth.push({ ctor: ov, ctorOf: decl.name });
2618
+ const variant = (ov ? decl.variants.find(v => v.name === ov) : undefined)
2619
+ ?? decl.variants.find(v => v.fields.some(fi => fi.name === field));
2620
+ const f = variant?.fields.find(fi => fi.name === field);
2621
+ if (!f)
2622
+ return { fieldTy: null, unionsByDepth };
2623
+ cur = f.type ?? parseTsType(f.tsType);
2624
+ }
2625
+ else {
2626
+ return { fieldTy: null, unionsByDepth };
2627
+ }
2242
2628
  }
2243
- return cur ?? null;
2629
+ return { fieldTy: cur ?? null, unionsByDepth };
2244
2630
  }
2245
2631
  /** True if `e` contains any subexpression that can carry a backend precondition
2246
2632
  * (calls, indexing, checked unwraps, division/modulo). Used to ensure optional
@@ -2298,41 +2684,15 @@ function transformStmt(s, typeDecls) {
2298
2684
  if (s.init.kind === "havoc") {
2299
2685
  return [{ kind: "let", name: s.name, type: s.ty, mutable: s.mutable, value: { kind: "havoc", type: s.init.ty } }];
2300
2686
  }
2301
- // arr.shift()! → let x = arr[0]; arr = arr[1..] (handles narrowed Option/Nullish via checkedUnwrap)
2687
+ // let x = recv.shift() / recv.pop(): bind removed element from original receiver,
2688
+ // then write shortened array back through the receiver Place.
2302
2689
  const init = s.init.kind === "call" ? s.init : undefined;
2303
- if (init && init.fn.kind === "field" && init.fn.field === "shift" && init.fn.obj.ty.kind === "array") {
2304
- const obj = init.fn.obj;
2305
- const arrName = obj.kind === "var" ? obj.name
2306
- : obj.kind === "checkedUnwrap" && obj.expr.kind === "var" ? obj.expr.name : undefined;
2307
- if (arrName) {
2308
- const arrExpr = obj.kind === "checkedUnwrap"
2309
- ? { kind: "checkedUnwrap", expr: { kind: "var", name: arrName } }
2310
- : { kind: "var", name: arrName };
2311
- const letHead = { kind: "let", name: s.name, type: s.ty, mutable: s.mutable,
2312
- value: { kind: "index", arr: arrExpr, idx: { kind: "num", value: 0 } } };
2313
- const sliced = { kind: "methodCall", obj: arrExpr, objTy: init.fn.obj.ty, method: "slice", args: [{ kind: "num", value: 1 }], monadic: false };
2314
- const tailVal = obj.kind === "checkedUnwrap" ? wrapCheckedUnwrapValue(sliced, obj.expr.ty) : sliced;
2315
- const sliceTail = { kind: "assign", target: arrName, value: tailVal };
2316
- return [letHead, sliceTail, ...emitWriteBacksForTarget(arrName, _writeBackFrames)];
2317
- }
2318
- }
2319
- // let x = arr.pop() → let x: T? = (Option-expr); arr := (truncated-or-self)
2320
- if (init && init.fn.kind === "field" && init.fn.field === "pop" && init.fn.obj.ty.kind === "array") {
2321
- const obj = init.fn.obj;
2322
- const arrName = obj.kind === "var" ? obj.name
2323
- : obj.kind === "checkedUnwrap" && obj.expr.kind === "var" ? obj.expr.name : undefined;
2324
- if (arrName) {
2325
- const arrExpr = obj.kind === "checkedUnwrap"
2326
- ? { kind: "checkedUnwrap", expr: { kind: "var", name: arrName } }
2327
- : { kind: "var", name: arrName };
2328
- const { optValue, guardedTrunc } = buildPopLoweringExpr(arrExpr, init.fn.obj.ty);
2329
- const truncVal = obj.kind === "checkedUnwrap" ? wrapCheckedUnwrapValue(guardedTrunc, obj.expr.ty) : guardedTrunc;
2330
- return [
2331
- { kind: "let", name: s.name, type: s.ty, mutable: s.mutable, value: optValue },
2332
- { kind: "assign", target: arrName, value: truncVal },
2333
- ...emitWriteBacksForTarget(arrName, _writeBackFrames),
2334
- ];
2335
- }
2690
+ const popOrShiftLet = lowerArrayPopOrShift(s.init, "value");
2691
+ if (popOrShiftLet) {
2692
+ return [
2693
+ { kind: "let", name: s.name, type: s.ty, mutable: s.mutable, value: popOrShiftLet.result },
2694
+ ...popOrShiftLet.writeStmts,
2695
+ ];
2336
2696
  }
2337
2697
  // new Map(arr.map(n => [n.field, n])) → let m = map[]; for (n of arr) m[n.field] := n
2338
2698
  if (init && init.fn.kind === "var" && init.fn.name === "__mapFromArray" &&
@@ -2385,24 +2745,19 @@ function transformStmt(s, typeDecls) {
2385
2745
  return [...binds, { kind: "let", name: s.name, type: s.ty, mutable: s.mutable, value: expr }];
2386
2746
  }
2387
2747
  case "assign": {
2388
- // x = arr.pop() → x := (Option-expr); arr := (truncated-or-self) + Place write-back
2389
- if (s.value.kind === "call" && s.value.fn.kind === "field" &&
2390
- s.value.fn.field === "pop" && s.value.fn.obj.ty.kind === "array") {
2391
- const obj = s.value.fn.obj;
2392
- const arrName = obj.kind === "var" ? obj.name
2393
- : obj.kind === "checkedUnwrap" && obj.expr.kind === "var" ? obj.expr.name : undefined;
2394
- if (arrName) {
2395
- const arrExpr = obj.kind === "checkedUnwrap"
2396
- ? { kind: "checkedUnwrap", expr: { kind: "var", name: arrName } }
2397
- : { kind: "var", name: arrName };
2398
- const { optValue, guardedTrunc } = buildPopLoweringExpr(arrExpr, s.value.fn.obj.ty);
2399
- const truncVal = obj.kind === "checkedUnwrap" ? wrapCheckedUnwrapValue(guardedTrunc, obj.expr.ty) : guardedTrunc;
2400
- return [
2401
- { kind: "assign", target: s.target, value: optValue },
2402
- { kind: "assign", target: arrName, value: truncVal },
2403
- ...emitWriteBacksForTarget(arrName, _writeBackFrames),
2404
- ];
2405
- }
2748
+ // target = recv.shift() / recv.pop(): save the removed element first,
2749
+ // write the shortened array back through the original receiver, and only
2750
+ // then assign the saved result to `s.target` (so `t = t.children.shift()!`
2751
+ // mutates the original `t`, not the shifted child).
2752
+ const popOrShiftAssign = lowerArrayPopOrShift(s.value, "value");
2753
+ if (popOrShiftAssign) {
2754
+ const tmp = freshName(`_${popOrShiftAssign.method}${_liftCounter++}`);
2755
+ const assignTmp = { ...s, value: { kind: "var", name: tmp, ty: s.value.ty } };
2756
+ return [
2757
+ { kind: "let", name: tmp, type: s.value.ty, mutable: false, value: popOrShiftAssign.result },
2758
+ ...popOrShiftAssign.writeStmts,
2759
+ ...transformStmt(assignTmp, typeDecls),
2760
+ ];
2406
2761
  }
2407
2762
  // Non-`this.` dotted field assignment on a record, union variant, or narrowed
2408
2763
  // optional/nullish record (e.g. `b.count = 5`, `u.v = 99`, `u.items[0] = 10`, `u.box.count = 42`):
@@ -2432,7 +2787,7 @@ function transformStmt(s, typeDecls) {
2432
2787
  if (frame.fields.length > 0) {
2433
2788
  return [
2434
2789
  ...binds,
2435
- { kind: "assign", target: frame.rootVar, value: buildNestedFieldExpr(frame.rootVar, frame.fields, optExpr) },
2790
+ { kind: "assign", target: frame.rootVar, value: buildNestedFieldExpr({ kind: "var", name: frame.rootVar }, frame.fields, optExpr) },
2436
2791
  ...emitWriteBacksForTarget(frame.rootVar, _writeBackFrames),
2437
2792
  ];
2438
2793
  }
@@ -2442,48 +2797,24 @@ function transformStmt(s, typeDecls) {
2442
2797
  ...emitWriteBacksForTarget(frame.rootVar, _writeBackFrames),
2443
2798
  ];
2444
2799
  }
2445
- if (resolved.leafVariantBinder) {
2446
- const binderTy = _varTypes.get(resolved.leafVariantBinder);
2447
- const rhsExpr = binderTy?.kind === "nullish"
2448
- ? wrapNullishBranch(expr, s.value)
2449
- : binderTy?.kind === "optional"
2450
- ? wrapOptionalBranch(expr, s.value)
2451
- : expr;
2452
- return [
2453
- ...binds,
2454
- { kind: "assign", target: resolved.leafVariantBinder, value: rhsExpr },
2455
- ...emitWriteBacksForTarget(resolved.leafVariantBinder, _writeBackFrames),
2456
- ];
2457
- }
2458
2800
  if (resolved.remainingFields.length > 0) {
2459
2801
  const rootTy = _varTypes.get(resolved.currentRoot);
2460
- const fieldTy = lookupFieldTy(rootTy, resolved.remainingFields, typeDecls);
2802
+ const skippedDepth = fields.length - resolved.remainingFields.length;
2803
+ const remOwnerVariants = s.ownerVariants?.slice(skippedDepth);
2804
+ const { fieldTy, unionsByDepth } = lookupFieldPathInfo(rootTy, resolved.remainingFields, typeDecls, remOwnerVariants);
2461
2805
  const rhsExpr = fieldTy?.kind === "nullish"
2462
2806
  ? wrapNullishBranch(expr, s.value)
2463
2807
  : fieldTy?.kind === "optional"
2464
2808
  ? wrapOptionalBranch(expr, s.value)
2465
2809
  : expr;
2466
- // If the root variable itself has Nullish<Record> or Option<Record> storage
2467
- // (narrowed without a someMatch frame), update `root.value` and re-wrap.
2468
- if (rootTy?.kind === "nullish" || rootTy?.kind === "optional") {
2469
- const unwrappedRoot = { kind: "checkedUnwrap", expr: { kind: "var", name: resolved.currentRoot } };
2470
- const buildNestedFromExpr = (base, fs, val) => {
2471
- if (fs.length === 1)
2472
- return { kind: "record", spread: base, fields: [{ name: fs[0], value: val }] };
2473
- const nextBase = { kind: "field", obj: base, field: fs[0] };
2474
- return { kind: "record", spread: base, fields: [{ name: fs[0], value: buildNestedFromExpr(nextBase, fs.slice(1), val) }] };
2475
- };
2476
- const updatedRecord = buildNestedFromExpr(unwrappedRoot, resolved.remainingFields, rhsExpr);
2477
- const wrappedRoot = wrapCheckedUnwrapValue(updatedRecord, rootTy);
2478
- return [
2479
- ...binds,
2480
- { kind: "assign", target: resolved.currentRoot, value: wrappedRoot },
2481
- ...emitWriteBacksForTarget(resolved.currentRoot, _writeBackFrames),
2482
- ];
2483
- }
2810
+ const rootExpr = { kind: "var", name: resolved.currentRoot };
2811
+ const isOptRoot = rootTy?.kind === "nullish" || rootTy?.kind === "optional";
2812
+ const baseExpr = isOptRoot ? { kind: "checkedUnwrap", expr: rootExpr } : rootExpr;
2813
+ const hasAnyUnion = unionsByDepth.some(u => u !== undefined);
2814
+ const updated = buildNestedFieldExpr(baseExpr, resolved.remainingFields, rhsExpr, hasAnyUnion ? unionsByDepth : undefined);
2484
2815
  return [
2485
2816
  ...binds,
2486
- { kind: "assign", target: resolved.currentRoot, value: buildNestedFieldExpr(resolved.currentRoot, resolved.remainingFields, rhsExpr) },
2817
+ { kind: "assign", target: resolved.currentRoot, value: isOptRoot ? wrapCheckedUnwrapValue(updated, rootTy) : updated },
2487
2818
  ...emitWriteBacksForTarget(resolved.currentRoot, _writeBackFrames),
2488
2819
  ];
2489
2820
  }
@@ -2534,6 +2865,9 @@ function transformStmt(s, typeDecls) {
2534
2865
  // enclosing narrowing frames (`someMatch` unwrap or union variant arm).
2535
2866
  // Non-Place receivers (e.g. `getArr().push(1)`) fail closed instead of
2536
2867
  // silently discarding the updated collection.
2868
+ const popOrShiftExpr = lowerArrayPopOrShift(s.expr, "discard");
2869
+ if (popOrShiftExpr)
2870
+ return popOrShiftExpr.writeStmts;
2537
2871
  if (s.expr.kind === "call" && s.expr.fn.kind === "field") {
2538
2872
  const recv = s.expr.fn.obj;
2539
2873
  const f = s.expr.fn.field;
@@ -2674,10 +3008,9 @@ function transformStmt(s, typeDecls) {
2674
3008
  }
2675
3009
  }
2676
3010
  /** Build match arms from variant cases — shared by imperative and pure paths.
2677
- * Looks up variant fields from typeDecls, builds patterns via buildMatchPattern,
2678
- * and delegates body transformation to the caller-provided function.
2679
- * Returns null if any body transformation returns null (pure path abort). */
2680
- function buildMatchArms(cases, varName, typeName, typeDecls, transformBody) {
3011
+ * Pure paths bind constructor fields via `buildMatchPattern`; imperative paths
3012
+ * pass `wildcard: true` so arms read and update live storage directly (#405). */
3013
+ function buildMatchArms(cases, varName, typeName, typeDecls, transformBody, wildcard = false) {
2681
3014
  const decl = declOf(typeDecls, typeName);
2682
3015
  if (!decl || (decl.kind !== "string-union" && decl.kind !== "discriminated-union")) {
2683
3016
  throw new Error(`match type ${typeName} is not a declared union`);
@@ -2691,7 +3024,9 @@ function buildMatchArms(cases, varName, typeName, typeDecls, transformBody) {
2691
3024
  if (!declared)
2692
3025
  throw new Error(`case ${JSON.stringify(c.name)} is not a variant of ${typeName}`);
2693
3026
  const fields = variant?.fields ?? [];
2694
- const pattern = buildMatchPattern(c.name, fields, varName);
3027
+ const pattern = wildcard
3028
+ ? buildWildcardMatchPattern(c.name, fields)
3029
+ : buildMatchPattern(c.name, fields, varName);
2695
3030
  const body = transformBody(c.body, varName, fields, c.name);
2696
3031
  if (body === null)
2697
3032
  return null;
@@ -2714,109 +3049,22 @@ function buildLiteralMatchArms(cases, transformBody) {
2714
3049
  }
2715
3050
  function emitMatchStmt(scrutinee, typeName, cases, fallthrough, typeDecls) {
2716
3051
  const decl = declOf(typeDecls, typeName);
2717
- // Synth array-unions (discriminant "__isArray__") have single-field variants
2718
- // ArrayBranch(arr) / NonArrayBranch(val). The matched arm refers to the
2719
- // scrutinee by its bare name/path (`content`, `m.content`), not `.arr`, so
2720
- // we substitute that whole reference with the variant's sole field binder.
2721
- const isSynthArrayUnion = decl?.discriminant === "__isArray__";
2722
- // The scrutinee is a bare var (`current`) or a field-access path
2723
- // (`current.content`). `prefix` names the binder scope — the var name, or a
2724
- // safe id derived from the path (`current.content` → `current_content`) —
2725
- // and is used for both pattern binders and arm-body substitution so they
2726
- // always agree. A var scrutinee has empty `fields`, so `prefix` is just its
2727
- // name and the emitted code is unchanged from before this generalization.
2728
- const path = asTAccessPath(scrutinee);
2729
- const isPath = !!path && path.fields.length > 0;
2730
- const prefix = path ? [path.rootVar, ...path.fields].join("_") : "?";
2731
- const baseUnionName = tyBaseName(typeName);
2732
- function transformArmBody(body, fields, ctorName) {
2733
- let stmts;
2734
- if (isPath && path) {
2735
- // Path scrutinee: the matched value is referred to by the bare path, so
2736
- // substitute the whole path (only the synth single-field shape arises
2737
- // here — discriminant chains require a var scrutinee).
2738
- stmts = isSynthArrayUnion && fields.length === 1
2739
- ? replacePathInTStmts(body, path, matchBinder(fields[0].name, prefix), fields[0].type ?? parseTsType(fields[0].tsType))
2740
- : body;
2741
- }
2742
- else {
2743
- stmts = replaceFieldAccessInTStmts(body, prefix, fields);
2744
- if (isSynthArrayUnion && fields.length === 1) {
2745
- const f = fields[0];
2746
- stmts = replaceVarInTStmts(stmts, prefix, matchBinder(f.name, prefix), f.type ?? parseTsType(f.tsType));
2747
- }
2748
- }
2749
- const pushVariant = !isPath && !!ctorName && fields.length > 0;
2750
- if (pushVariant) {
2751
- for (const f of fields) {
2752
- _varTypes.set(matchBinder(f.name, prefix), f.type ?? parseTsType(f.tsType));
2753
- }
2754
- _writeBackFrames.push(makeVariantFrame(prefix, baseUnionName, ctorName, fields.map(f => ({ fieldName: f.name, binder: matchBinder(f.name, prefix) }))));
2755
- }
2756
- let lowered;
2757
- try {
2758
- lowered = transformStmts(stmts, typeDecls);
2759
- }
2760
- finally {
2761
- if (pushVariant)
2762
- _writeBackFrames.pop();
2763
- }
2764
- if (_opts.backend === "lean" && pushVariant) {
2765
- const assigned = collectAssignedIrTargets(lowered);
2766
- const mutShadows = fields
2767
- .filter(f => assigned.has(matchBinder(f.name, prefix)))
2768
- .map(f => {
2769
- const b = matchBinder(f.name, prefix);
2770
- return { kind: "let", name: b, type: f.type ?? parseTsType(f.tsType), mutable: true, value: varE(b) };
2771
- });
2772
- if (mutShadows.length > 0)
2773
- lowered = [...mutShadows, ...lowered];
2774
- }
2775
- return lowered;
2776
- }
2777
3052
  const armCases = cases.map(c => ({ name: c.variant, body: c.body }));
2778
- const arms = buildMatchArms(armCases, prefix, typeName, typeDecls, (body, _vn, fields, ctorName) => transformArmBody(body, fields, ctorName));
2779
- // Add the fallthrough arm whenever the listed cases don't cover every
2780
- // variant — needed for exhaustiveness even when there's no `else`
2781
- // (`fallthrough` empty), e.g. `if (Array.isArray(x)) {...}` with no else
2782
- // becomes `match x { case ArrayBranch(..) => ... case NonArrayBranch(..) => }`.
3053
+ const arms = buildMatchArms(armCases, undefined, typeName, typeDecls, (body) => transformStmts(body, typeDecls), /* wildcard */ true);
2783
3054
  const allCovered = !!decl?.variants && cases.length >= decl.variants.length;
2784
3055
  if (!allCovered) {
2785
- const remaining = remainingVariant(typeName, cases, typeDecls);
3056
+ const remaining = remainingVariant(decl, cases.map(c => c.variant));
2786
3057
  if (remaining) {
2787
- // Exactly one variant left — destructure so the fallthrough body can
2788
- // access variant-specific fields (Lean requires this; Dafny tolerates `_`).
2789
- const pattern = buildMatchPattern(remaining.name, remaining.fields, prefix);
2790
- const body = transformArmBody(fallthrough, remaining.fields, remaining.name);
2791
- arms.push({ pattern, body });
3058
+ arms.push({
3059
+ pattern: buildWildcardMatchPattern(remaining.name, remaining.fields),
3060
+ body: transformStmts(fallthrough, typeDecls),
3061
+ });
2792
3062
  }
2793
3063
  else {
2794
3064
  arms.push({ pattern: pWild(), body: transformStmts(fallthrough, typeDecls) });
2795
3065
  }
2796
3066
  }
2797
- return { kind: "match", scrutinee: (isPath || scrutinee.kind === "checkedUnwrap") ? transformExpr(scrutinee) : varE(prefix), arms };
2798
- }
2799
- /** Replace bare `var(oldName)` references → `var(newName)` with the given type.
2800
- * Used by emitMatchStmt for synth array-unions where the variant has a single
2801
- * payload field and the user code refers to the scrutinee by its bare name. */
2802
- function replaceVarInTStmts(stmts, oldName, newName, newTy) {
2803
- return stmts.map(s => mapTStmt(s, e => {
2804
- if (e.kind === "var" && e.name === oldName) {
2805
- return { kind: "var", name: newName, ty: newTy };
2806
- }
2807
- return null;
2808
- }));
2809
- }
2810
- /** If the chain has matched all variants but one, return that remaining variant. */
2811
- function remainingVariant(typeName, cases, typeDecls) {
2812
- const decl = declOf(typeDecls, typeName);
2813
- if (!decl?.variants)
2814
- return null;
2815
- const matched = new Set(cases.map(c => c.variant));
2816
- const remaining = decl.variants.filter(v => !matched.has(v.name));
2817
- if (remaining.length !== 1)
2818
- return null;
2819
- return remaining[0];
3067
+ return { kind: "match", scrutinee: transformExpr(scrutinee), arms, unionType: typeName };
2820
3068
  }
2821
3069
  /** `switch(obj.field)` is stripped at extraction to scrutinee `obj` + discriminant
2822
3070
  * `field`, assuming `obj` is a discriminated union with `field` as its
@@ -2846,22 +3094,19 @@ function switchCtorDecl(typeDecls, ty) {
2846
3094
  const decl = declOfTy(typeDecls, ty);
2847
3095
  return decl?.kind === "string-union" || decl?.kind === "discriminated-union" ? decl : undefined;
2848
3096
  }
2849
- /** Stamp variant ctor info onto datatype updates of the match scrutinee in
2850
- * lowered arm bodies (`{ ...vn, f: v }`) — the statement-path twin of
2851
- * `replaceFieldAccess`'s stamping. Emitters need the pin to use
2852
- * per-constructor destructor names for collision-renamed fields. */
2853
- function stampScrutineeUpdates(body, varName, ctorName, ctorOf) {
2854
- const stamp = (x) => {
2855
- if (x.kind === "record" && !x.ctor && x.spread &&
2856
- x.spread.kind === "var" && x.spread.name === varName) {
2857
- return { ...x, ctor: ctorName, ctorOf,
2858
- fields: x.fields.map(f => ({ ...f, value: mapExpr(f.value, stamp) })) };
2859
- }
2860
- return null;
2861
- };
2862
- return body.map(st => mapStmt(st, stamp));
3097
+ /** A default covering one union variant needs the same variant pattern as an
3098
+ * explicit case, in both pure and imperative lowering. */
3099
+ function withExplicitVariantDefault(s, typeDecls) {
3100
+ if (s.defaultBody.length === 0)
3101
+ return s;
3102
+ const decl = unionDeclOfTy(typeDecls, s.expr.ty);
3103
+ if (decl?.discriminant !== s.discriminant)
3104
+ return s;
3105
+ const remaining = remainingVariant(decl, s.cases.map(c => c.label));
3106
+ return remaining ? { ...s, cases: [...s.cases, { label: remaining.name, body: s.defaultBody }], defaultBody: [] } : s;
2863
3107
  }
2864
3108
  function emitSwitchStmt(s, typeDecls) {
3109
+ s = withExplicitVariantDefault(s, typeDecls);
2865
3110
  const cases = s.cases.map(c => ({ name: c.label, body: c.body }));
2866
3111
  const ef = enumFieldSwitch(s, typeDecls);
2867
3112
  const matchTy = ef ? ef.fieldTy : s.expr.ty;
@@ -2871,132 +3116,13 @@ function emitSwitchStmt(s, typeDecls) {
2871
3116
  const typeName = !matchTy ? "unknown" : matchTy.kind === "user" ? matchTy.name : matchTy.kind;
2872
3117
  throw new Error(`switch scrutinee must be string-typed or a declared union, got ${typeName}`);
2873
3118
  }
2874
- const baseName = s.expr.ty.kind === "user" ? tyBaseName(s.expr.ty.name) : undefined;
2875
- const switchVarName = s.expr.kind === "var" ? s.expr.name
2876
- : s.expr.kind === "checkedUnwrap" && s.expr.expr.kind === "var" ? s.expr.expr.name : "?";
2877
3119
  const arms = literalCases
2878
3120
  ? buildLiteralMatchArms(cases, (body) => transformStmts(body, typeDecls))
2879
- : ef
2880
- ? buildMatchArms(cases, undefined, ctorDecl.name, typeDecls, (body) => transformStmts(body, typeDecls))
2881
- : buildMatchArms(cases, switchVarName, ctorDecl.name, typeDecls, (body, vn, fields, ctorName) => {
2882
- const pushVariant = !!ctorName && !!vn && vn !== "?" && !!baseName && fields.length > 0 && s.expr.kind !== "checkedUnwrap";
2883
- const variantMeta = ctorName ? ctorDecl?.variants?.find(v => v.name === ctorName) : undefined;
2884
- if (pushVariant) {
2885
- for (const f of fields) {
2886
- const vf = variantMeta?.fields.find(vf => vf.name === f.name);
2887
- _varTypes.set(matchBinder(f.name, vn), vf?.type ?? parseTsType(f.tsType));
2888
- }
2889
- _writeBackFrames.push(makeVariantFrame(vn, baseName, ctorName, fields.map(f => ({ fieldName: f.name, binder: matchBinder(f.name, vn) }))));
2890
- }
2891
- let out;
2892
- try {
2893
- out = transformStmts(replaceFieldAccessInTStmts(body, vn, fields), typeDecls);
2894
- }
2895
- finally {
2896
- if (pushVariant)
2897
- _writeBackFrames.pop();
2898
- }
2899
- if (ctorName && vn && baseName)
2900
- out = stampScrutineeUpdates(out, vn, ctorName, baseName);
2901
- if (_opts.backend === "lean" && pushVariant) {
2902
- const assigned = collectAssignedIrTargets(out);
2903
- const mutShadows = fields
2904
- .filter(f => assigned.has(matchBinder(f.name, vn)))
2905
- .map(f => {
2906
- const b = matchBinder(f.name, vn);
2907
- return { kind: "let", name: b, type: parseTsType(f.tsType), mutable: true, value: varE(b) };
2908
- });
2909
- if (mutShadows.length > 0)
2910
- out = [...mutShadows, ...out];
2911
- }
2912
- return out;
2913
- });
3121
+ : buildMatchArms(cases, undefined, ctorDecl.name, typeDecls, (body) => transformStmts(body, typeDecls), /* wildcard */ true);
2914
3122
  if (s.defaultBody.length > 0)
2915
3123
  arms.push({ pattern: pWild(), body: transformStmts(s.defaultBody, typeDecls) });
2916
- const scrutinee = ef ? ef.scrutinee
2917
- : s.expr.kind === "checkedUnwrap" ? transformExpr(s.expr)
2918
- : varE(switchVarName);
2919
- return { kind: "match", scrutinee, arms };
2920
- }
2921
- /** Replace obj.field → replacement var in typed IR.
2922
- * Uses the TExpr's resolved type when available, falling back to `fallbackTy`. */
2923
- function replaceFieldsInTStmts(stmts, objName, replacements) {
2924
- if (replacements.length === 0)
2925
- return stmts;
2926
- return stmts.map(s => mapTStmt(s, e => {
2927
- const objMatches = e.kind === "field" && ((e.obj.kind === "var" && e.obj.name === objName) ||
2928
- (e.obj.kind === "checkedUnwrap" && e.obj.expr.kind === "var" && e.obj.expr.name === objName));
2929
- if (objMatches && e.kind === "field") {
2930
- const r = replacements.find(r => r.fieldName === e.field);
2931
- if (r) {
2932
- const ty = e.ty.kind !== "unknown" ? e.ty : r.fallbackTy;
2933
- return { kind: "var", name: r.newName, ty };
2934
- }
2935
- }
2936
- return null;
2937
- }));
2938
- }
2939
- /** Replace all variant fields of obj → match binder vars in typed IR.
2940
- * Before replacing field reads, realize TypeScript's structural argument
2941
- * conversion for calls such as `helper(outcome)` inside a narrowed union arm.
2942
- * The source value is still the enclosing union in typed IR, while Dafny and
2943
- * Lean expect the helper's nominal record. Rebuild that record solely from
2944
- * the fields bound by this arm's match pattern. */
2945
- function replaceFieldAccessInTStmts(stmts, varName, fields) {
2946
- const projected = projectStructuralCallArgsInTStmts(stmts, varName, fields);
2947
- return replaceFieldsInTStmts(projected, varName, fields.map(f => ({
2948
- fieldName: f.name,
2949
- newName: matchBinder(f.name, varName),
2950
- fallbackTy: f.type ?? parseTsType(f.tsType),
2951
- })));
2952
- }
2953
- /** Project a narrowed union scrutinee into a named structural record expected
2954
- * by a same-module/extern call. Resolution stamps named calls with paramTys;
2955
- * this pass fires only when every target record field has an identically typed
2956
- * match-bound source field. That deliberately avoids inventing a broad cast:
2957
- * it is the nominal-backend witness for the structural call TS already accepts. */
2958
- function projectStructuralCallArgsInTStmts(stmts, varName, fields) {
2959
- const sourceFields = fields.map(f => ({
2960
- ...f,
2961
- resolvedTy: f.type ?? parseTsType(f.tsType),
2962
- }));
2963
- return stmts.map(s => mapTStmt(s, e => {
2964
- if (e.kind !== "call" || !e.paramTys)
2965
- return null;
2966
- const paramTys = e.paramTys;
2967
- let changed = false;
2968
- const args = e.args.map((arg, i) => {
2969
- if (arg.kind !== "var" || arg.name !== varName || i >= paramTys.length)
2970
- return arg;
2971
- const targetTy = paramTys[i];
2972
- const targetDecl = declOfTy(_typeDecls, targetTy);
2973
- if (targetTy.kind !== "user" || targetDecl?.kind !== "record" || !targetDecl.fields)
2974
- return arg;
2975
- const matched = [];
2976
- for (const targetField of targetDecl.fields) {
2977
- const sourceField = sourceFields.find(f => f.name === targetField.name);
2978
- const targetFieldTy = targetField.type ?? parseTsType(targetField.tsType);
2979
- if (!sourceField || !tyEqual(sourceField.resolvedTy, targetFieldTy))
2980
- return arg;
2981
- matched.push({ targetField, sourceField });
2982
- }
2983
- changed = true;
2984
- return {
2985
- kind: "record",
2986
- spread: null,
2987
- fields: matched.map(m => ({
2988
- name: m.targetField.name,
2989
- value: {
2990
- kind: "var",
2991
- name: matchBinder(m.sourceField.name, varName),
2992
- ty: m.sourceField.resolvedTy,
2993
- },
2994
- })),
2995
- ty: targetTy,
2996
- };
2997
- });
2998
- return changed ? { ...e, args } : null;
2999
- }));
3124
+ const scrutinee = ef ? ef.scrutinee : transformExpr(s.expr);
3125
+ return { kind: "match", scrutinee, arms, ...(ctorDecl ? { unionType: ctorDecl.name } : {}) };
3000
3126
  }
3001
3127
  function asTAccessPath(e) {
3002
3128
  if (e.kind === "var")
@@ -3034,19 +3160,10 @@ function matchesAccessPath(e, path) {
3034
3160
  * leaves no binding that shadows another (see LexicalNames), so the name
3035
3161
  * identifies the variable, also inside a lambda that captures it. */
3036
3162
  function replacePathInTExpr(expr, path, binder, binderTy) {
3037
- return mapTExpr(expr, e => {
3038
- if (matchesAccessPath(e, path))
3039
- return { kind: "var", name: binder, ty: binderTy };
3040
- if (e.kind === "lambda")
3041
- return { ...e,
3042
- params: e.params.map(p => p.defaultValue
3043
- ? { ...p, defaultValue: replacePathInTExpr(p.defaultValue, path, binder, binderTy) } : p),
3044
- body: replacePathInTStmts(e.body, path, binder, binderTy) };
3045
- return null;
3046
- });
3163
+ return mapTExpr(expr, e => matchesAccessPath(e, path) ? { kind: "var", name: binder, ty: binderTy } : null);
3047
3164
  }
3048
3165
  function replacePathInTStmts(stmts, path, binder, binderTy) {
3049
- return stmts.map(s => mapTStmt(s, e => replacePathInTExpr(e, path, binder, binderTy)));
3166
+ return stmts.map(s => mapTStmt(s, e => matchesAccessPath(e, path) ? { kind: "var", name: binder, ty: binderTy } : null));
3050
3167
  }
3051
3168
  // ── Pure function generation ─────────────────────────────────
3052
3169
  function transformPureBody(stmts, typeDecls) {
@@ -3115,6 +3232,7 @@ function transformPureBody(stmts, typeDecls) {
3115
3232
  return null;
3116
3233
  }
3117
3234
  function transformPureSwitch(s, typeDecls) {
3235
+ s = withExplicitVariantDefault(s, typeDecls);
3118
3236
  const ef = enumFieldSwitch(s, typeDecls);
3119
3237
  if (ef) {
3120
3238
  const cases = s.cases.map(c => ({ name: c.label, body: c.body }));
@@ -3143,8 +3261,7 @@ function transformPureSwitch(s, typeDecls) {
3143
3261
  : s.expr.kind === "checkedUnwrap" && s.expr.expr.kind === "var" ? s.expr.expr.name : undefined;
3144
3262
  const cases = s.cases.map(c => ({ name: c.label, body: c.body }));
3145
3263
  const arms = buildMatchArms(cases, varName, typeName, typeDecls, (body, vn, fields, ctorName) => {
3146
- const projected = vn ? projectStructuralCallArgsInTStmts(body, vn, fields) : body;
3147
- let result = transformPureBody(projected, typeDecls);
3264
+ let result = transformPureBody(body, typeDecls);
3148
3265
  if (!result)
3149
3266
  return null;
3150
3267
  if (fields.length > 0 && vn)
@@ -3173,8 +3290,7 @@ function transformPureMatch(chain, typeDecls) {
3173
3290
  // the statement-level counterpart of this substitution.
3174
3291
  const isSynthArrayUnion = decl?.discriminant === "__isArray__";
3175
3292
  const arms = buildMatchArms(cases, chain.varName, chain.typeName, typeDecls, (body, vn, fields, ctorName) => {
3176
- const projected = vn ? projectStructuralCallArgsInTStmts(body, vn, fields) : body;
3177
- let result = transformPureBody(projected, typeDecls);
3293
+ let result = transformPureBody(body, typeDecls);
3178
3294
  if (!result)
3179
3295
  return null;
3180
3296
  if (fields.length > 0 && vn)
@@ -3191,11 +3307,10 @@ function transformPureMatch(chain, typeDecls) {
3191
3307
  // since Lean errors on redundant match arms.
3192
3308
  const allCovered = decl?.variants && chain.cases.length >= decl.variants.length;
3193
3309
  if (chain.fallthrough.length > 0 && !allCovered) {
3194
- const remaining = remainingVariant(chain.typeName, chain.cases, typeDecls);
3310
+ const remaining = remainingVariant(decl, chain.cases.map(c => c.variant));
3195
3311
  if (remaining) {
3196
3312
  // Exactly one variant left — destructure for variant-specific field access.
3197
- const projected = projectStructuralCallArgsInTStmts(chain.fallthrough, chain.varName, remaining.fields);
3198
- let body = transformPureBody(projected, typeDecls);
3313
+ let body = transformPureBody(chain.fallthrough, typeDecls);
3199
3314
  if (!body)
3200
3315
  return null;
3201
3316
  if (remaining.fields.length > 0)
@@ -3256,17 +3371,29 @@ function transformTypeDecl(d) {
3256
3371
  /** Find parameter names that are reassigned anywhere in the body. */
3257
3372
  function findReassignedNames(stmts, names) {
3258
3373
  const found = new Set();
3374
+ const markRoot = (root) => {
3375
+ if (root && names.has(root))
3376
+ found.add(root);
3377
+ };
3259
3378
  function scan(stmts) {
3260
3379
  for (const s of stmts) {
3261
- if (s.kind === "assign" && names.has(s.target))
3262
- found.add(s.target);
3380
+ if (s.kind === "assign") {
3381
+ markRoot(s.target.split(".")[0]);
3382
+ if (s.value.kind === "call" && s.value.fn.kind === "field" &&
3383
+ (s.value.fn.field === "pop" || s.value.fn.field === "shift") && s.value.fn.obj.ty.kind === "array") {
3384
+ markRoot(placeRootVar(s.value.fn.obj));
3385
+ }
3386
+ }
3263
3387
  if (s.kind === "ghostAssign" && names.has(s.target))
3264
3388
  found.add(s.target);
3265
- // Mutating collection calls: s.add(x), m.set(k,v), s.delete(x), arr.push(x)
3389
+ if (s.kind === "let" && s.init.kind === "call" && s.init.fn.kind === "field" &&
3390
+ (s.init.fn.field === "pop" || s.init.fn.field === "shift") && s.init.fn.obj.ty.kind === "array") {
3391
+ markRoot(placeRootVar(s.init.fn.obj));
3392
+ }
3393
+ // Mutating collection calls: s.add(x), m.set(k,v), s.delete(x), arr.push(x), b.items.pop()
3266
3394
  if (s.kind === "expr" && s.expr.kind === "call" && s.expr.fn.kind === "field" &&
3267
- s.expr.fn.obj.kind === "var" && names.has(s.expr.fn.obj.name) &&
3268
- ["add", "set", "delete", "push", "unshift"].includes(s.expr.fn.field)) {
3269
- found.add(s.expr.fn.obj.name);
3395
+ ["add", "set", "delete", "push", "unshift", "sort", "pop", "shift"].includes(s.expr.fn.field)) {
3396
+ markRoot(placeRootVar(s.expr.fn.obj));
3270
3397
  }
3271
3398
  if (s.kind === "if") {
3272
3399
  scan(s.then);
@@ -3281,6 +3408,15 @@ function findReassignedNames(stmts, names) {
3281
3408
  scan(c.body);
3282
3409
  scan(s.defaultBody);
3283
3410
  }
3411
+ if (s.kind === "someMatch") {
3412
+ scan(s.someBody);
3413
+ scan(s.noneBody);
3414
+ }
3415
+ if (s.kind === "tagMatch") {
3416
+ for (const c of s.cases)
3417
+ scan(c.body);
3418
+ scan(s.fallthrough);
3419
+ }
3284
3420
  }
3285
3421
  }
3286
3422
  scan(stmts);
@@ -3488,8 +3624,8 @@ export function transformModule(mod, specImport, moduleBaseOverride) {
3488
3624
  // since loom's default loop-exit fact `¬guard` does not hold across a break.
3489
3625
  if (_opts.backend === "lean" && !pureDefNames.has(fn.name)) {
3490
3626
  body = matchToIfChains(body);
3491
- const resultInvariants = fn.ensures.map(e => replaceVar(transformSpecExpr(e), "\\result", { kind: "var", name: "_loopRet" }));
3492
- body = eliminateReturnInLoops(body, fn.returnTy, resultInvariants);
3627
+ const ensuresExprs = fn.ensures.map(e => transformSpecExpr(e));
3628
+ body = eliminateReturnInLoops(body, fn.returnTy, ensuresExprs);
3493
3629
  requireDoneWithForBreaks(body, fn.name);
3494
3630
  }
3495
3631
  // Shadow reassigned parameters with mutable locals (including parameters