lemmascript 0.6.13 → 0.6.15

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.
@@ -4,15 +4,15 @@
4
4
  * Consumes resolved types and classifications.
5
5
  * No type lookups, no string parsing, no re-inference.
6
6
  */
7
- import { isBigInt, tyEqual } from "./typedir.js";
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, declWithVariant, 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"; }
@@ -353,24 +417,75 @@ function asCondition(e) {
353
417
  return { kind: "binop", op: ">",
354
418
  left: { kind: "field", obj: e, field: "length", ty: { kind: "nat" } },
355
419
  right: { kind: "num", value: 0, ty: { kind: "nat" } }, ty: bool };
420
+ if (e.ty.kind === "void" || e.ty.kind === "null")
421
+ return { kind: "bool", value: false, ty: bool };
422
+ // Nullish<T> truthiness in `if (x)` / `while (x)` / `x ? a : b`:
423
+ // lower as `!(!x)` so `lowerExpr`'s nullish truthiness rule handles both
424
+ // falsy-capable inners (0, "", false) and always-truthy inners uniformly.
425
+ if (e.ty.kind === "nullish")
426
+ return { kind: "unop", op: "!", expr: { kind: "unop", op: "!", expr: e, ty: bool }, ty: bool };
356
427
  // Arrays, objects, maps, sets, tuples are always truthy in JS (even `[]`/`{}`).
357
428
  if (["array", "user", "map", "set", "tuple"].includes(e.ty.kind))
358
429
  return { kind: "bool", value: true, ty: bool };
359
430
  return e;
360
431
  }
361
432
  /** Wrap an expression in Some/None for optional-typed conditionals.
362
- * If the raw TExpr is `undefined`, emit `.none`; otherwise wrap in `Some`. */
433
+ * If the raw TExpr is `undefined`/`null`, emit `.none`; otherwise wrap in `Some`. */
363
434
  function wrapOptionalBranch(expr, raw) {
364
435
  // Set type: "Option" so Lean emits `Option.some`/`Option.none` (qualified).
365
436
  // The dotted form `.some`/`.none` would be ambiguous in expression positions
366
437
  // like the scrutinee of an outer match. Dafny treats `Option.Some` and bare
367
438
  // `Some` equivalently — the qualification is harmless there.
368
- if (raw.kind === "var" && raw.name === "undefined")
439
+ if (raw.kind === "var" && (raw.name === "undefined" || raw.name === "null"))
369
440
  return { kind: "constructor", name: "none", type: "Option", args: [] };
441
+ if (raw.ty.kind === "nullish" || (raw.ty.kind === "optional" && raw.ty.fromNullish)) {
442
+ const bound = matchBinder("value");
443
+ return {
444
+ kind: "match", scrutinee: expr,
445
+ arms: [
446
+ { pattern: pCtor("nullishValue", bound), body: { kind: "constructor", name: "some", type: "Option", args: [{ kind: "var", name: bound }] } },
447
+ { pattern: pCtor("nullishNull"), body: { kind: "constructor", name: "none", type: "Option", args: [] } },
448
+ { pattern: pCtor("nullishUndefined"), body: { kind: "constructor", name: "none", type: "Option", args: [] } },
449
+ ],
450
+ };
451
+ }
370
452
  if (raw.ty.kind === "optional")
371
453
  return expr; // already Option<T>, don't double-wrap
372
454
  return { kind: "constructor", name: "some", type: "Option", args: [expr] };
373
455
  }
456
+ /** Wrap an expression in Nullish.Undefined / Nullish.Null / Nullish.Value for
457
+ * nullish-typed conditionals and matches (#304). */
458
+ function wrapNullishBranch(expr, raw) {
459
+ if (raw.kind === "var" && raw.name === "undefined") {
460
+ return { kind: "constructor", name: "nullishUndefined", type: "Nullish", args: [] };
461
+ }
462
+ if (raw.kind === "var" && raw.name === "null") {
463
+ return { kind: "constructor", name: "nullishNull", type: "Nullish", args: [] };
464
+ }
465
+ if (raw.ty.kind === "nullish" || (raw.ty.kind === "optional" && raw.ty.fromNullish))
466
+ return expr;
467
+ if (expr.kind === "if" && raw.kind === "conditional" && raw.ty.kind !== "optional") {
468
+ return { ...expr, then: wrapNullishBranch(expr.then, raw.then), else: wrapNullishBranch(expr.else, raw.else) };
469
+ }
470
+ if (raw.ty.kind === "optional") {
471
+ const bound = matchBinder("value");
472
+ const noneCtor = optAbsent(raw.ty) === "null" ? "nullishNull" : "nullishUndefined";
473
+ return {
474
+ kind: "match", scrutinee: expr,
475
+ arms: [
476
+ { pattern: pCtor("some", bound), body: { kind: "constructor", name: "nullishValue", type: "Nullish", args: [{ kind: "var", name: bound }] } },
477
+ { pattern: pCtor("none"), body: { kind: "constructor", name: noneCtor, type: "Nullish", args: [] } },
478
+ ],
479
+ };
480
+ }
481
+ return { kind: "constructor", name: "nullishValue", type: "Nullish", args: [expr] };
482
+ }
483
+ function wrapCheckedUnwrapValue(expr, storageTy) {
484
+ if (storageTy.kind === "nullish") {
485
+ return { kind: "constructor", name: "nullishValue", type: "Nullish", args: [expr] };
486
+ }
487
+ return { kind: "app", fn: "Some", args: [expr] };
488
+ }
374
489
  /** Lean needs `let mut` for any local that is later reassigned. A const local
375
490
  * whose collection field is mutated (`b.items.push(v)` → `b := b.(items := …)`)
376
491
  * becomes an assign in the lowered body, so scan for assign targets and flip
@@ -407,6 +522,31 @@ function promoteAssignedLets(stmts) {
407
522
  });
408
523
  return fix(stmts);
409
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
+ }
410
550
  /** Build a nested record-update assigning `newVal` to a field-path receiver
411
551
  * rooted at a var: `b.a.items` → `b := b.(a := b.a.(items := newVal))`.
412
552
  * Handles `checkedUnwrap` hops along the path by wrapping the updated record
@@ -415,13 +555,22 @@ function promoteAssignedLets(stmts) {
415
555
  function buildNestedFieldUpdate(recv, newVal) {
416
556
  if (recv.kind !== "field")
417
557
  return null;
418
- 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
+ };
419
568
  if (recv.obj.kind === "var")
420
569
  return { root: recv.obj.name, value: upd };
421
570
  if (recv.obj.kind === "field")
422
571
  return buildNestedFieldUpdate(recv.obj, upd);
423
572
  if (recv.obj.kind === "checkedUnwrap") {
424
- const wrapped = { kind: "app", fn: "Some", args: [upd] };
573
+ const wrapped = wrapCheckedUnwrapValue(upd, recv.obj.expr.ty);
425
574
  if (recv.obj.expr.kind === "var")
426
575
  return { root: recv.obj.expr.name, value: wrapped };
427
576
  if (recv.obj.expr.kind === "field")
@@ -479,7 +628,18 @@ function lowerExpr(e, binds) {
479
628
  return { kind: "var", name };
480
629
  }
481
630
  switch (e.kind) {
482
- case "var": return { kind: "var", name: e.name };
631
+ case "var":
632
+ if (e.name === "undefined") {
633
+ if (e.ty.kind === "nullish")
634
+ return { kind: "constructor", name: "nullishUndefined", type: "Nullish", args: [] };
635
+ return { kind: "var", name: "undefined" };
636
+ }
637
+ if (e.name === "null") {
638
+ if (e.ty.kind === "nullish")
639
+ return { kind: "constructor", name: "nullishNull", type: "Nullish", args: [] };
640
+ return { kind: "var", name: "undefined" };
641
+ }
642
+ return { kind: "var", name: e.name };
483
643
  case "num": {
484
644
  const literal = { kind: "num", value: e.value };
485
645
  return e.ty.kind === "real" && Number.isInteger(e.value)
@@ -501,6 +661,43 @@ function lowerExpr(e, binds) {
501
661
  // String truthiness: !str → str == ""
502
662
  if (e.op === "!" && e.expr.ty.kind === "string")
503
663
  return { kind: "binop", op: "=", left: lowerExpr(e.expr, binds), right: { kind: "str", value: "" } };
664
+ // Double negation of Nullish<T> (synthesized by asCondition for `if (x)`):
665
+ // true iff `x` is Value(v) and `v` is truthy.
666
+ if (e.op === "!" && e.expr.kind === "unop" && e.expr.op === "!" && e.expr.expr.ty.kind === "nullish") {
667
+ const inner = e.expr.expr;
668
+ const innerTy = e.expr.expr.ty;
669
+ const innerExpr = lowerExpr(inner, binds);
670
+ const bound = matchBinder("value");
671
+ const truthy = valueTruthyCond({ kind: "var", name: bound }, innerTy.inner);
672
+ if (!truthy) {
673
+ return { kind: "methodCall", obj: innerExpr, objTy: innerTy, method: "isValue", args: [], monadic: false };
674
+ }
675
+ return {
676
+ kind: "match", scrutinee: innerExpr,
677
+ arms: [
678
+ { pattern: pCtor("nullishValue", bound), body: truthy },
679
+ { pattern: pCtor("nullishNull"), body: { kind: "bool", value: false } },
680
+ { pattern: pCtor("nullishUndefined"), body: { kind: "bool", value: false } },
681
+ ],
682
+ };
683
+ }
684
+ // Nullish<T> truthiness: !x → true on Null/Undefined; on Value(v), !(truthy v).
685
+ if (e.op === "!" && e.expr.ty.kind === "nullish") {
686
+ const innerExpr = lowerExpr(e.expr, binds);
687
+ const bound = matchBinder("value");
688
+ const truthy = valueTruthyCond({ kind: "var", name: bound }, e.expr.ty.inner);
689
+ if (!truthy) {
690
+ return { kind: "unop", op: "¬", expr: { kind: "methodCall", obj: innerExpr, objTy: e.expr.ty, method: "isValue", args: [], monadic: false } };
691
+ }
692
+ return {
693
+ kind: "match", scrutinee: innerExpr,
694
+ arms: [
695
+ { pattern: pCtor("nullishValue", bound), body: { kind: "unop", op: "¬", expr: truthy } },
696
+ { pattern: pCtor("nullishNull"), body: { kind: "bool", value: true } },
697
+ { pattern: pCtor("nullishUndefined"), body: { kind: "bool", value: true } },
698
+ ],
699
+ };
700
+ }
504
701
  // Optional truthiness: !opt → None negates to `true`. The Some branch is
505
702
  // `!(value truthy)`: always-truthy inners (array/user) give a plain `false`,
506
703
  // while falsy-capable inners re-test the wrapped value (`!Some(0)` is `true`).
@@ -559,10 +756,21 @@ function lowerExpr(e, binds) {
559
756
  right: { kind: "constructor", name: e.right.value, type: objTy, args: [] },
560
757
  };
561
758
  }
759
+ // Literal null/undefined comparison (e.g. `null === undefined` → false,
760
+ // `null == undefined` → true, `null === null` → true).
761
+ if (["===", "!==", "==", "!="].includes(e.op) &&
762
+ e.left.kind === "var" && (e.left.name === "null" || e.left.name === "undefined") &&
763
+ e.right.kind === "var" && (e.right.name === "null" || e.right.name === "undefined")) {
764
+ const isLoose = e.op === "==" || e.op === "!=";
765
+ const eq = isLoose ? true : e.left.name === e.right.name;
766
+ const res = (e.op === "===" || e.op === "==") ? eq : !eq;
767
+ return { kind: "bool", value: res };
768
+ }
562
769
  // String literal comparison — constructor if user type, string literal if string.
563
- // Skip when the left is optional: fall through to the optional-comparison rule,
564
- // which unwraps and compares the inner value (`Some(v) => v == "")`.
565
- if ((e.op === "===" || e.op === "!==") && e.right.kind === "str" && e.left.ty.kind !== "optional") {
770
+ // Skip when the left is optional/nullish: fall through to the nullable-comparison rules,
771
+ // which unwrap and compare the inner value (`Some(v) => v == ""`).
772
+ if ((e.op === "===" || e.op === "!==") && e.right.kind === "str" &&
773
+ e.left.ty.kind !== "optional" && e.left.ty.kind !== "nullish") {
566
774
  const left = lowerExpr(e.left, binds);
567
775
  const leftTy = e.left.ty.kind === "user" ? e.left.ty.name : undefined;
568
776
  const right = isUser(e.left.ty)
@@ -570,19 +778,161 @@ function lowerExpr(e, binds) {
570
778
  : { kind: "str", value: e.right.value };
571
779
  return { kind: "binop", op: e.op === "===" ? "=" : "≠", left, right };
572
780
  }
781
+ // Two-sided nullable equality/inequality rules (#304):
782
+ // 1. Opposite-sentinel Option<T> (`T | null` vs `T | undefined`) under ===/!==:
783
+ // None vs None is false for === (null !== undefined).
784
+ // 2. Nullish<T> vs Nullish<T> under loose ==/!=:
785
+ // Null vs Undefined is true for == (null == undefined).
786
+ // 3. Nullish<T> vs Option<T> under ===/!==/==/!=:
787
+ // Nested match comparing Value/Some, plus sentinel match on Null/Undefined vs None.
788
+ if (["===", "!==", "==", "!="].includes(e.op)) {
789
+ const isLoose = e.op === "==" || e.op === "!=";
790
+ const isEq = e.op === "===" || e.op === "==";
791
+ const cmpOp = isEq ? "=" : "≠";
792
+ if (!isLoose && e.left.ty.kind === "optional" && e.right.ty.kind === "optional" &&
793
+ optAbsent(e.left.ty) !== optAbsent(e.right.ty)) {
794
+ const lExpr = lowerExpr(e.left, binds);
795
+ const rExpr = lowerExpr(e.right, binds);
796
+ const lv = matchBinder("lv");
797
+ const rv = matchBinder("rv");
798
+ return {
799
+ kind: "match", scrutinee: lExpr,
800
+ arms: [
801
+ { pattern: pCtor("some", lv), body: {
802
+ kind: "match", scrutinee: rExpr,
803
+ arms: [
804
+ { pattern: pCtor("some", rv), body: { kind: "binop", op: cmpOp, left: { kind: "var", name: lv }, right: { kind: "var", name: rv } } },
805
+ { pattern: pCtor("none"), body: { kind: "bool", value: !isEq } },
806
+ ],
807
+ } },
808
+ { pattern: pCtor("none"), body: { kind: "bool", value: !isEq } },
809
+ ],
810
+ };
811
+ }
812
+ if (isLoose && e.left.ty.kind === "nullish" && e.right.ty.kind === "nullish") {
813
+ const lExpr = lowerExpr(e.left, binds);
814
+ const rExpr = lowerExpr(e.right, binds);
815
+ const lv = matchBinder("lv");
816
+ const rv = matchBinder("rv");
817
+ const absentArm = {
818
+ kind: "match", scrutinee: rExpr,
819
+ arms: [
820
+ { pattern: pCtor("nullishValue", "_"), body: { kind: "bool", value: !isEq } },
821
+ { pattern: pCtor("nullishNull"), body: { kind: "bool", value: isEq } },
822
+ { pattern: pCtor("nullishUndefined"), body: { kind: "bool", value: isEq } },
823
+ ],
824
+ };
825
+ return {
826
+ kind: "match", scrutinee: lExpr,
827
+ arms: [
828
+ { pattern: pCtor("nullishValue", lv), body: {
829
+ kind: "match", scrutinee: rExpr,
830
+ arms: [
831
+ { pattern: pCtor("nullishValue", rv), body: { kind: "binop", op: cmpOp, left: { kind: "var", name: lv }, right: { kind: "var", name: rv } } },
832
+ { pattern: pCtor("nullishNull"), body: { kind: "bool", value: !isEq } },
833
+ { pattern: pCtor("nullishUndefined"), body: { kind: "bool", value: !isEq } },
834
+ ],
835
+ } },
836
+ { pattern: pCtor("nullishNull"), body: absentArm },
837
+ { pattern: pCtor("nullishUndefined"), body: absentArm },
838
+ ],
839
+ };
840
+ }
841
+ if ((e.left.ty.kind === "nullish" && e.right.ty.kind === "optional") ||
842
+ (e.left.ty.kind === "optional" && e.right.ty.kind === "nullish")) {
843
+ const [nulSide, optSide] = e.left.ty.kind === "nullish" ? [e.left, e.right] : [e.right, e.left];
844
+ const nulExpr = lowerExpr(nulSide, binds);
845
+ const optExpr = lowerExpr(optSide, binds);
846
+ const optAbs = optAbsent(optSide.ty);
847
+ const nv = matchBinder("nv");
848
+ const ov = matchBinder("ov");
849
+ const nullMatchesNone = isLoose || optAbs === "null";
850
+ const undefMatchesNone = isLoose || optAbs === "undefined";
851
+ const makeAbsentArm = (matchesNone) => ({
852
+ kind: "match", scrutinee: optExpr,
853
+ arms: [
854
+ { pattern: pCtor("some", "_"), body: { kind: "bool", value: !isEq } },
855
+ { pattern: pCtor("none"), body: { kind: "bool", value: isEq ? matchesNone : !matchesNone } },
856
+ ],
857
+ });
858
+ return {
859
+ kind: "match", scrutinee: nulExpr,
860
+ arms: [
861
+ { pattern: pCtor("nullishValue", nv), body: {
862
+ kind: "match", scrutinee: optExpr,
863
+ arms: [
864
+ { pattern: pCtor("some", ov), body: { kind: "binop", op: cmpOp, left: { kind: "var", name: nv }, right: { kind: "var", name: ov } } },
865
+ { pattern: pCtor("none"), body: { kind: "bool", value: !isEq } },
866
+ ],
867
+ } },
868
+ { pattern: pCtor("nullishNull"), body: makeAbsentArm(nullMatchesNone) },
869
+ { pattern: pCtor("nullishUndefined"), body: makeAbsentArm(undefMatchesNone) },
870
+ ],
871
+ };
872
+ }
873
+ }
874
+ // Nullish<T> comparison against null / undefined / non-nullish value (#304).
875
+ if (["===", "!==", "==", "!=", ">=", "<=", ">", "<"].includes(e.op) &&
876
+ (e.left.ty.kind === "nullish") !== (e.right.ty.kind === "nullish")) {
877
+ const [nulSide, valSide] = e.left.ty.kind === "nullish" ? [e.left, e.right] : [e.right, e.left];
878
+ const nulExpr = lowerExpr(nulSide, binds);
879
+ const nulTy = nulSide.ty;
880
+ if (valSide.kind === "var" && (valSide.name === "undefined" || valSide.name === "null")) {
881
+ const isLoose = e.op === "==" || e.op === "!=";
882
+ const isEq = e.op === "===" || e.op === "==";
883
+ if (isLoose) {
884
+ // x == null / x == undefined → !x.isValue; x != null / x != undefined → x.isValue
885
+ const isVal = { kind: "methodCall", obj: nulExpr, objTy: nulTy, method: "isValue", args: [], monadic: false };
886
+ return isEq ? { kind: "unop", op: "¬", expr: isVal } : isVal;
887
+ }
888
+ const pred = {
889
+ kind: "methodCall", obj: nulExpr, objTy: nulTy,
890
+ method: valSide.name === "null" ? "isNull" : "isUndefined", args: [], monadic: false,
891
+ };
892
+ return isEq ? pred : { kind: "unop", op: "¬", expr: pred };
893
+ }
894
+ const innerTy = nulTy.inner;
895
+ const valExpr = valSide.kind === "str" && innerTy.kind === "user"
896
+ ? { kind: "constructor", name: valSide.value, type: innerTy.name, args: [] }
897
+ : lowerExpr(valSide, binds);
898
+ const op = e.left.ty.kind === "nullish" ? e.op : MIRROR_OP[e.op] ?? e.op;
899
+ const cmpOp = BOOL_OP_MAP[op] ?? op;
900
+ const absentVal = (e.op === "!==" || e.op === "!=") ? true : false;
901
+ const bound = matchBinder("value");
902
+ const makeNullishCmpMatch = (rhs) => ({
903
+ kind: "match", scrutinee: nulExpr,
904
+ arms: [
905
+ { pattern: pCtor("nullishValue", bound), body: { kind: "binop", op: cmpOp, left: { kind: "var", name: bound }, right: rhs } },
906
+ { pattern: pCtor("nullishNull"), body: { kind: "bool", value: absentVal } },
907
+ { pattern: pCtor("nullishUndefined"), body: { kind: "bool", value: absentVal } },
908
+ ],
909
+ });
910
+ if (!_inSpec && valExpr.kind !== "var" && hasPreconditionExpr(valSide)) {
911
+ const tmp = freshName(`_cmp${_cmpCounter++}`);
912
+ return { kind: "let", name: tmp, value: valExpr, body: makeNullishCmpMatch({ kind: "var", name: tmp }) };
913
+ }
914
+ return makeNullishCmpMatch(valExpr);
915
+ }
573
916
  // Optional comparison: optExpr op val → match optExpr { Some(v) => v op val, None => false/true }
574
- if (["===", "!==", ">=", "<=", ">", "<"].includes(e.op) &&
917
+ if (["===", "!==", "==", "!=", ">=", "<=", ">", "<"].includes(e.op) &&
575
918
  (e.left.ty.kind === "optional") !== (e.right.ty.kind === "optional")) {
576
919
  const [optSide, valSide] = e.left.ty.kind === "optional" ? [e.left, e.right] : [e.right, e.left];
577
920
  const optExpr = lowerExpr(optSide, binds);
578
- // x === undefined → None?, x !== undefined → Some?
579
- if (valSide.kind === "var" && valSide.name === "undefined") {
580
- const isNone = e.op === "===";
921
+ const optTy = optSide.ty;
922
+ // x === undefined / x === null / loose x == null / x == undefined
923
+ if (valSide.kind === "var" && (valSide.name === "undefined" || valSide.name === "null")) {
924
+ const isLoose = e.op === "==" || e.op === "!=";
925
+ const isEq = e.op === "===" || e.op === "==";
926
+ // Strict comparison against the OTHER sentinel (`x: T | undefined; x === null`
927
+ // or `x: T | null; x === undefined`) is always false (and `!==` is always true).
928
+ if (!isLoose && valSide.name !== optAbsent(optTy)) {
929
+ return { kind: "bool", value: !isEq };
930
+ }
581
931
  return {
582
932
  kind: "match", scrutinee: optExpr,
583
933
  arms: [
584
- { pattern: pCtor("some", "_"), body: { kind: "bool", value: !isNone } },
585
- { pattern: pCtor("none"), body: { kind: "bool", value: isNone } },
934
+ { pattern: pCtor("some", "_"), body: { kind: "bool", value: !isEq } },
935
+ { pattern: pCtor("none"), body: { kind: "bool", value: isEq } },
586
936
  ],
587
937
  };
588
938
  }
@@ -604,7 +954,7 @@ function lowerExpr(e, binds) {
604
954
  // skip the `let` binding completely (zero temporary churn).
605
955
  const op = e.left.ty.kind === "optional" ? e.op : MIRROR_OP[e.op] ?? e.op;
606
956
  const cmpOp = BOOL_OP_MAP[op] ?? op;
607
- const noneVal = e.op === "!==" ? true : false;
957
+ const noneVal = (e.op === "!==" || e.op === "!=") ? true : false;
608
958
  const bound = matchBinder("value");
609
959
  if (!_inSpec && valExpr.kind !== "var" && hasPreconditionExpr(valSide)) {
610
960
  const tmp = freshName(`_cmp${_cmpCounter++}`);
@@ -629,12 +979,27 @@ function lowerExpr(e, binds) {
629
979
  ],
630
980
  };
631
981
  }
632
- // || undefined on optional → identity (no-op: x || undefined = x) when the
982
+ // Definite non-nullable value compared against `null` or `undefined`
983
+ // (e.g. `x === null` inside a `someMatch` body where `x` was already unwrapped
984
+ // to `int`): constant-fold to `false` (for ===/==) or `true` (for !==/!=)
985
+ // while preserving any side-effecting lifts in the non-sentinel operand.
986
+ if (["===", "!==", "==", "!="].includes(e.op)) {
987
+ const isSentinel = (x) => x.kind === "var" && (x.name === "null" || x.name === "undefined");
988
+ if (isSentinel(e.left) !== isSentinel(e.right)) {
989
+ const other = isSentinel(e.left) ? e.right : e.left;
990
+ const k = other.ty.kind;
991
+ if (k !== "optional" && k !== "nullish" && k !== "unknown" && k !== "void" && k !== "null") {
992
+ lowerExpr(other, binds);
993
+ return { kind: "bool", value: e.op === "!==" || e.op === "!=" };
994
+ }
995
+ }
996
+ }
997
+ // || undefined / || null on optional → identity (no-op: x || undefined = x) when the
633
998
  // inner type is always truthy. When it can be falsy, JS still drops the
634
999
  // wrapped value: `Some(0) || undefined === undefined`, so the Some arm
635
1000
  // re-tests and falls back to None.
636
1001
  if (e.op === "||" && e.left.ty.kind === "optional" &&
637
- e.right.kind === "var" && e.right.name === "undefined") {
1002
+ e.right.kind === "var" && (e.right.name === "undefined" || e.right.name === "null")) {
638
1003
  const optExpr = lowerExpr(e.left, binds);
639
1004
  const bound = matchBinder("value");
640
1005
  const truthy = valueTruthyCond({ kind: "var", name: bound }, e.left.ty.inner);
@@ -652,6 +1017,29 @@ function lowerExpr(e, binds) {
652
1017
  ],
653
1018
  };
654
1019
  }
1020
+ // || on nullish → 3-arm match Value/Null/Undefined with default.
1021
+ if (e.op === "||" && e.left.ty.kind === "nullish") {
1022
+ const nulExpr = lowerExpr(e.left, binds);
1023
+ const defaultExpr = lowerExpr(e.right, binds);
1024
+ const bound = matchBinder("value");
1025
+ const truthy = valueTruthyCond({ kind: "var", name: bound }, e.left.ty.inner);
1026
+ const valPresent = e.ty.kind === "nullish"
1027
+ ? { kind: "constructor", name: "nullishValue", type: "Nullish", args: [{ kind: "var", name: bound }] }
1028
+ : e.ty.kind === "optional"
1029
+ ? { kind: "constructor", name: "some", type: "Option", args: [{ kind: "var", name: bound }] }
1030
+ : { kind: "var", name: bound };
1031
+ const someBody = truthy
1032
+ ? { kind: "if", cond: truthy, then: valPresent, else: defaultExpr }
1033
+ : valPresent;
1034
+ return {
1035
+ kind: "match", scrutinee: nulExpr,
1036
+ arms: [
1037
+ { pattern: pCtor("nullishValue", bound), body: someBody },
1038
+ { pattern: pCtor("nullishNull"), body: defaultExpr },
1039
+ { pattern: pCtor("nullishUndefined"), body: defaultExpr },
1040
+ ],
1041
+ };
1042
+ }
655
1043
  // || on optional → match Some/None with default. JS `||` tests falsiness of
656
1044
  // the *unwrapped* value, so when the inner type can be falsy the Some arm must
657
1045
  // re-test (`Some(0) || 1 === 1`); array/user inners are always truthy and
@@ -702,8 +1090,8 @@ function lowerExpr(e, binds) {
702
1090
  (e.left.ty.kind === "user" && e.right.ty.kind === "string"))) {
703
1091
  const left = lowerExpr(e.left, binds);
704
1092
  const right = lowerExpr(e.right, binds);
705
- // `s || undefined` produces `Option<string>` — wrap the truthy branch in Some.
706
- const rightIsUndef = e.right.kind === "var" && e.right.name === "undefined";
1093
+ // `s || undefined` / `s || null` produces `Option<string>` — wrap the truthy branch in Some.
1094
+ const rightIsUndef = e.right.kind === "var" && (e.right.name === "undefined" || e.right.name === "null");
707
1095
  return {
708
1096
  kind: "if",
709
1097
  // strings carry the `length` marker — it renders to `|x|` in Dafny and
@@ -713,12 +1101,12 @@ function lowerExpr(e, binds) {
713
1101
  else: right,
714
1102
  };
715
1103
  }
716
- // `bool || undefined` → `if bool then Some(bool) else None`. Used in
1104
+ // `bool || undefined` / `bool || null` → `if bool then Some(bool) else None`. Used in
717
1105
  // optional-field initialization where the source assigns a truthy/false
718
1106
  // bool to a `T?` field. Without this, emit produces `bool || None`,
719
1107
  // which Dafny rejects (bool || Option<?> is ill-typed).
720
1108
  if (e.op === "||" && e.left.ty.kind === "bool" &&
721
- e.right.kind === "var" && e.right.name === "undefined") {
1109
+ e.right.kind === "var" && (e.right.name === "undefined" || e.right.name === "null")) {
722
1110
  const left = lowerExpr(e.left, binds);
723
1111
  return {
724
1112
  kind: "if",
@@ -830,16 +1218,19 @@ function lowerExpr(e, binds) {
830
1218
  const owners = decl?.variants?.filter(v => v.fields.some(f => f.name === e.field)) ?? [];
831
1219
  if (owners.length > 0) {
832
1220
  // Shared field name with differing declared types: those destructors
833
- // are renamed per-constructor, and the read's own resolved type
834
- // identifies the owning variant (the types differ exactly when the
835
- // 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.
836
1225
  const ownerTy = (v) => v.fields.find(f => f.name === e.field)?.type;
837
1226
  const differ = owners.some(v => {
838
1227
  const a = ownerTy(v), b = ownerTy(owners[0]);
839
1228
  return a && b && !tyEqual(a, b);
840
1229
  });
841
- const matching = differ ? owners.filter(v => { const t = ownerTy(v); return t && tyEqual(t, e.ty); }) : [];
842
- 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;
843
1234
  return { kind: "field", obj: transformExpr(e.obj), field: e.field, fromUnion: baseName, ctor, datatypeField: true };
844
1235
  }
845
1236
  }
@@ -1068,10 +1459,70 @@ function lowerExpr(e, binds) {
1068
1459
  }
1069
1460
  if (e.fn.kind !== "var")
1070
1461
  throw new Error(`Unsupported call expression: ${e.fn.kind}`);
1462
+ // Synthetic Nullish<T> constructors and widening/narrowing helpers (#304).
1463
+ if (e.fn.name === "NullishValue" && e.args.length === 1) {
1464
+ return { kind: "constructor", name: "nullishValue", type: "Nullish", args: [lowerExpr(e.args[0], binds)] };
1465
+ }
1466
+ if ((e.fn.name === "__optUndefToNullish" || e.fn.name === "__optNullToNullish") && e.args.length === 1) {
1467
+ const bound = matchBinder("value");
1468
+ const noneCtor = e.fn.name === "__optNullToNullish" ? "nullishNull" : "nullishUndefined";
1469
+ return {
1470
+ kind: "match", scrutinee: lowerExpr(e.args[0], binds),
1471
+ arms: [
1472
+ { pattern: pCtor("some", bound), body: { kind: "constructor", name: "nullishValue", type: "Nullish", args: [{ kind: "var", name: bound }] } },
1473
+ { pattern: pCtor("none"), body: { kind: "constructor", name: noneCtor, type: "Nullish", args: [] } },
1474
+ ],
1475
+ };
1476
+ }
1477
+ if (e.fn.name === "__nullishToOption" && e.args.length === 1) {
1478
+ const bound = matchBinder("value");
1479
+ return {
1480
+ kind: "match", scrutinee: lowerExpr(e.args[0], binds),
1481
+ arms: [
1482
+ { pattern: pCtor("nullishValue", bound), body: { kind: "constructor", name: "some", type: "Option", args: [{ kind: "var", name: bound }] } },
1483
+ { pattern: pCtor("nullishNull"), body: { kind: "constructor", name: "none", type: "Option", args: [] } },
1484
+ { pattern: pCtor("nullishUndefined"), body: { kind: "constructor", name: "none", type: "Option", args: [] } },
1485
+ ],
1486
+ };
1487
+ }
1071
1488
  const prefix = e.callKind === "spec-pure" && _opts.backend === "lean" ? "Pure." : "";
1072
- return { kind: "app", fn: prefix + e.fn.name, args: e.args.map(a => lowerExpr(a, binds)) };
1489
+ const callArgs = e.args.map(a => lowerExpr(a, binds));
1490
+ // Zero-parameter closures are emitted as `fun () => ...` in Lean (`Unit → T`),
1491
+ // so calling one must supply `()`. Top-level 0-arg defs/methods do not carry
1492
+ // a `fn` variable type and stay bare names.
1493
+ if (_opts.backend === "lean" && callArgs.length === 0 && e.fn.ty.kind === "fn" && e.fn.ty.params.length === 0) {
1494
+ callArgs.push({ kind: "var", name: "()" });
1495
+ }
1496
+ return { kind: "app", fn: prefix + e.fn.name, args: callArgs };
1073
1497
  }
1074
1498
  case "record": {
1499
+ const lowerTypedField = (rawVal, declaredTy) => {
1500
+ const fieldValue = declaredTy && rawVal.ty.kind === "unknown"
1501
+ ? { ...rawVal, ty: declaredTy }
1502
+ : rawVal;
1503
+ let value = lowerExpr(fieldValue, binds);
1504
+ if (declaredTy?.kind === "optional") {
1505
+ const isUndef = rawVal.kind === "var" && (rawVal.name === "undefined" || rawVal.name === "null");
1506
+ if (rawVal.ty.kind !== "optional" && !isUndef) {
1507
+ value = { kind: "app", fn: "Some", args: [value] };
1508
+ }
1509
+ }
1510
+ else if (declaredTy?.kind === "nullish") {
1511
+ value = wrapNullishBranch(value, rawVal);
1512
+ }
1513
+ return value;
1514
+ };
1515
+ const buildVariantCtor = (variantName, tyName, baseName, variant, resolveArg) => {
1516
+ // Bare-constructor shortcut only when the variant truly has no fields —
1517
+ // a variant with only optional fields still needs its argument list.
1518
+ if (variant.fields.length === 0) {
1519
+ return { kind: "constructor", name: variantName, type: tyName, args: [] };
1520
+ }
1521
+ // Constructor with args: match variant field order. Emit a bare `app`
1522
+ // (Dafny renders `variantName(args)`) tagged with `ctorOf` so Lean
1523
+ // qualifies it as `BaseType.variantName args` (using the base name).
1524
+ return { kind: "app", fn: variantName, args: variant.fields.map(resolveArg), ctorOf: baseName };
1525
+ };
1075
1526
  // Discriminated union: { kind: 'NoOp' } → constructor NoOp
1076
1527
  if (e.ty.kind === "user" && !e.spread) {
1077
1528
  const tyName = e.ty.name;
@@ -1081,27 +1532,19 @@ function lowerExpr(e, binds) {
1081
1532
  if (decl && decl.discriminant) {
1082
1533
  const discField = e.fields.find(f => f.name === decl.discriminant);
1083
1534
  if (discField && (discField.value.kind === "str" || discField.value.kind === "bool")) {
1084
- const variantName = String(discField.value.kind === "str" ? discField.value.value : discField.value.value);
1535
+ const variantName = String(discField.value.value);
1085
1536
  const variant = decl.variants?.find(v => v.name === variantName);
1086
1537
  if (variant) {
1087
1538
  const nonDiscFields = e.fields.filter(f => f.name !== decl.discriminant);
1088
- // Bare-constructor shortcut only when the variant truly has no
1089
- // fields — a variant with only optional fields still needs its
1090
- // None-filled argument list (`int_(None)`, not `int_`).
1091
- if (variant.fields.length === 0) {
1092
- return { kind: "constructor", name: variantName, type: tyName, args: [] };
1093
- }
1094
- // Constructor with args: match variant field order. Emit a bare `app`
1095
- // (Dafny renders `variantName(args)`, a valid unqualified constructor
1096
- // call — unchanged output) tagged with `ctorOf` so the Lean emitter,
1097
- // which CANNOT take a bare constructor name, qualifies it as
1098
- // `BaseType.variantName args`. Use the BASE type name (no generic args):
1099
- // `Result.true_` is valid in Lean; `Result<Model,Err>.true_` is not.
1100
- const args = variant.fields.map(vf => {
1539
+ return buildVariantCtor(variantName, tyName, baseName, variant, vf => {
1101
1540
  const ef = nonDiscFields.find(f => f.name === vf.name);
1102
- return ef ? lowerExpr(ef.value, binds) : { kind: "var", name: "None" };
1541
+ if (ef)
1542
+ return lowerExpr(ef.value, binds);
1543
+ if (vf.type?.kind === "nullish") {
1544
+ return { kind: "constructor", name: "nullishUndefined", type: "Nullish", args: [] };
1545
+ }
1546
+ return { kind: "var", name: "None" };
1103
1547
  });
1104
- return { kind: "app", fn: variantName, args, ctorOf: baseName };
1105
1548
  }
1106
1549
  }
1107
1550
  }
@@ -1110,17 +1553,117 @@ function lowerExpr(e, binds) {
1110
1553
  if (e.spread) {
1111
1554
  const spreadTy = e.spread.ty.kind === "optional" ? e.spread.ty.inner : e.spread.ty;
1112
1555
  const structName = spreadTy.kind === "user" ? spreadTy.name : undefined;
1113
- const structDecl = structName ? declOfKind(_typeDecls, structName, "record") : undefined;
1556
+ const baseName = structName ? tyBaseName(structName) : undefined;
1557
+ const structDecl = baseName ? declOfKind(_typeDecls, baseName, "record") : undefined;
1114
1558
  // Also check discriminated-union variants for field types
1115
- const unionDecl = structName ? declOfKind(_typeDecls, structName, "discriminated-union") : undefined;
1559
+ const unionDecl = baseName ? declOfKind(_typeDecls, baseName, "discriminated-union") : undefined;
1560
+ // Tag-overriding spread on a discriminated union (`{ ...sh, kind: "b", ... }`):
1561
+ // once a spread explicitly overrides the discriminant, ordinary field update
1562
+ // is the wrong operation (it can silently write a colliding renamed payload
1563
+ // destructor such as `value_a` and preserve the old constructor). Either
1564
+ // construct the target variant faithfully or reject with a diagnostic.
1565
+ if (unionDecl?.discriminant) {
1566
+ const discField = e.fields.find(f => f.name === unionDecl.discriminant);
1567
+ if (discField) {
1568
+ if (discField.value.kind !== "str" && discField.value.kind !== "bool") {
1569
+ throw new Error(`spread on '${unionDecl.name}' must set '${unionDecl.discriminant}' to a literal tag`);
1570
+ }
1571
+ const variantName = String(discField.value.value);
1572
+ const targetVariant = unionDecl.variants?.find(v => v.name === variantName);
1573
+ if (!targetVariant) {
1574
+ throw new Error(`unknown '${unionDecl.name}' variant '${variantName}' in spread`);
1575
+ }
1576
+ const sourceVariant = e.spreadOfVariant
1577
+ ? unionDecl.variants?.find(v => v.name === e.spreadOfVariant)
1578
+ : undefined;
1579
+ const possibleSources = sourceVariant ? [sourceVariant] : (unionDecl.variants ?? []);
1580
+ const spreadExpr = lowerExpr(e.spread, binds);
1581
+ const overriddenByName = new Map();
1582
+ for (const f of e.fields) {
1583
+ if (f.name === unionDecl.discriminant)
1584
+ continue;
1585
+ const declaredTy = targetVariant.fields.find(vf => vf.name === f.name)?.type;
1586
+ overriddenByName.set(f.name, lowerTypedField(f.value, declaredTy));
1587
+ }
1588
+ return buildVariantCtor(variantName, structName, baseName, targetVariant, vf => {
1589
+ const explicit = overriddenByName.get(vf.name);
1590
+ if (explicit !== undefined)
1591
+ return explicit;
1592
+ for (const sv of possibleSources) {
1593
+ const sf = sv.fields.find(f => f.name === vf.name);
1594
+ if (!sf?.type || !vf.type || !tyEqual(sf.type, vf.type)) {
1595
+ throw new Error(`cannot change '${unionDecl.name}' from '${sv.name}' to '${variantName}' via spread: pass '${vf.name}' explicitly`);
1596
+ }
1597
+ }
1598
+ return {
1599
+ kind: "field",
1600
+ obj: spreadExpr,
1601
+ field: vf.name,
1602
+ fromUnion: baseName,
1603
+ ctor: sourceVariant?.name,
1604
+ datatypeField: true,
1605
+ };
1606
+ });
1607
+ }
1608
+ }
1609
+ const pinnedVariant = unionDecl && e.ofVariant
1610
+ ? unionDecl.variants?.find(v => v.name === e.ofVariant)
1611
+ : undefined;
1612
+ // Un-narrowed union spread where an overridden field has differing types
1613
+ // across variants (e.g. `a.value: number` vs `b.value: number | undefined`):
1614
+ // expand to a per-variant `match` so each constructor receives the right
1615
+ // coercion (`5` vs `Some(5)`) and destructor in both Dafny and Lean.
1616
+ if (unionDecl?.variants && !pinnedVariant) {
1617
+ const hasMixedField = e.fields.some(f => {
1618
+ const tys = unionDecl.variants
1619
+ .map(v => v.fields.find(vf => vf.name === f.name)?.type)
1620
+ .filter((t) => t !== undefined);
1621
+ return tys.length > 1 && tys.some(t => !tyEqual(t, tys[0]));
1622
+ });
1623
+ if (hasMixedField) {
1624
+ const spreadExpr = lowerExpr(e.spread, binds);
1625
+ const baseFieldExprs = new Map(e.fields.map(f => [f.name, lowerExpr(f.value, binds)]));
1626
+ const rawFieldByName = new Map(e.fields.map(f => [f.name, f.value]));
1627
+ const arms = unionDecl.variants.map(v => {
1628
+ const binders = [];
1629
+ const fieldExprs = new Map();
1630
+ v.fields.forEach((vf, idx) => {
1631
+ const rawVal = rawFieldByName.get(vf.name);
1632
+ if (rawVal !== undefined) {
1633
+ binders.push("_");
1634
+ let val = baseFieldExprs.get(vf.name);
1635
+ if (vf.type?.kind === "optional") {
1636
+ const isUndef = rawVal.kind === "var" && (rawVal.name === "undefined" || rawVal.name === "null");
1637
+ if (rawVal.ty.kind !== "optional" && !isUndef) {
1638
+ val = { kind: "app", fn: "Some", args: [val] };
1639
+ }
1640
+ }
1641
+ else if (vf.type?.kind === "nullish") {
1642
+ val = wrapNullishBranch(val, rawVal);
1643
+ }
1644
+ fieldExprs.set(vf.name, val);
1645
+ }
1646
+ else {
1647
+ const bv = freshName(`_sp${idx}`);
1648
+ binders.push(bv);
1649
+ fieldExprs.set(vf.name, { kind: "var", name: bv });
1650
+ }
1651
+ });
1652
+ const body = buildVariantCtor(v.name, structName, baseName, v, vf => fieldExprs.get(vf.name));
1653
+ return { pattern: { kind: "ctor", ctor: v.name, binders }, body };
1654
+ });
1655
+ return { kind: "match", scrutinee: spreadExpr, arms };
1656
+ }
1657
+ }
1116
1658
  const loweredFields = e.fields.map(f => {
1117
- // Propagate declared field type onto value if it has unknown type
1118
- let fieldValue = f.value;
1119
1659
  const fieldDecl = structDecl?.fields?.find(sf => sf.name === f.name);
1120
1660
  let declaredTy;
1121
1661
  if (fieldDecl) {
1122
1662
  declaredTy = fieldDecl.type;
1123
1663
  }
1664
+ else if (pinnedVariant) {
1665
+ declaredTy = pinnedVariant.fields.find(vf => vf.name === f.name)?.type;
1666
+ }
1124
1667
  else if (unionDecl?.variants) {
1125
1668
  for (const v of unionDecl.variants) {
1126
1669
  const vf = v.fields.find(vf => vf.name === f.name);
@@ -1130,20 +1673,14 @@ function lowerExpr(e, binds) {
1130
1673
  }
1131
1674
  }
1132
1675
  }
1133
- if (declaredTy && fieldValue.ty.kind === "unknown") {
1134
- fieldValue = { ...fieldValue, ty: declaredTy };
1135
- }
1136
- let value = lowerExpr(fieldValue, binds);
1137
- // Wrap non-optional values in Some for optional fields
1138
- if (declaredTy?.kind === "optional") {
1139
- const isUndef = f.value.kind === "var" && f.value.name === "undefined";
1140
- if (f.value.ty.kind !== "optional" && !isUndef) {
1141
- value = { kind: "app", fn: "Some", args: [value] };
1142
- }
1143
- }
1144
- return { name: f.name, value };
1676
+ return { name: f.name, value: lowerTypedField(f.value, declaredTy) };
1145
1677
  });
1146
- return { kind: "record", spread: lowerExpr(e.spread, binds), fields: loweredFields };
1678
+ return {
1679
+ kind: "record",
1680
+ spread: lowerExpr(e.spread, binds),
1681
+ fields: loweredFields,
1682
+ ...(unionDecl && baseName ? { ctor: e.ofVariant, ctorOf: baseName } : {}),
1683
+ };
1147
1684
  }
1148
1685
  // Empty record with map type → empty map
1149
1686
  if (e.fields.length === 0 && !e.spread && e.ty.kind === "map") {
@@ -1217,6 +1754,10 @@ function lowerExpr(e, binds) {
1217
1754
  thenExpr = wrapOptionalBranch(thenExpr, e.then);
1218
1755
  elseExpr = wrapOptionalBranch(elseExpr, e.else);
1219
1756
  }
1757
+ else if (e.ty.kind === "nullish") {
1758
+ thenExpr = wrapNullishBranch(thenExpr, e.then);
1759
+ elseExpr = wrapNullishBranch(elseExpr, e.else);
1760
+ }
1220
1761
  if (binds && (thenBinds?.length || elseBinds?.length)) {
1221
1762
  const name = freshName(`_branch${_branchCounter++}`);
1222
1763
  // Both arms assign before the result is read. This initializer is not
@@ -1230,12 +1771,69 @@ function lowerExpr(e, binds) {
1230
1771
  }
1231
1772
  return { kind: "if", cond, then: thenExpr, else: elseExpr };
1232
1773
  }
1233
- case "optChain":
1234
- // Narrow should have rewritten optChain to someMatch.
1774
+ case "optChain": {
1775
+ if (e.obj.ty.kind === "nullish") {
1776
+ const scrutinee = lowerExpr(e.obj, binds);
1777
+ const binder = freshName(`_oc${_liftCounter++}_val`);
1778
+ let bodyT = { kind: "var", name: binder, ty: e.obj.ty.inner };
1779
+ for (const step of e.chain) {
1780
+ if (step.kind === "field")
1781
+ bodyT = { kind: "field", obj: bodyT, field: step.name, ty: step.ty };
1782
+ else if (step.kind === "index")
1783
+ bodyT = { kind: "index", obj: bodyT, idx: step.idx, ty: step.ty };
1784
+ else
1785
+ bodyT = { kind: "call", fn: bodyT, args: step.args, ty: step.ty, callKind: step.callKind,
1786
+ ...(step.builtinId ? { builtinId: step.builtinId } : {}) };
1787
+ }
1788
+ let valBody = lowerExpr(bodyT, binds);
1789
+ let absentBody;
1790
+ if (e.ty.kind === "nullish") {
1791
+ valBody = wrapNullishBranch(valBody, bodyT);
1792
+ absentBody = { kind: "constructor", name: "nullishUndefined", type: "Nullish", args: [] };
1793
+ }
1794
+ else {
1795
+ valBody = wrapOptionalBranch(valBody, bodyT);
1796
+ absentBody = { kind: "constructor", name: "none", type: "Option", args: [] };
1797
+ }
1798
+ return {
1799
+ kind: "match", scrutinee,
1800
+ arms: [
1801
+ { pattern: pCtor("nullishValue", binder), body: valBody },
1802
+ { pattern: pCtor("nullishNull"), body: absentBody },
1803
+ { pattern: pCtor("nullishUndefined"), body: absentBody },
1804
+ ],
1805
+ };
1806
+ }
1807
+ // Narrow should have rewritten non-nullish optChain to someMatch.
1235
1808
  throw new Error(`optChain reached transform — narrow should have rewritten it: ${JSON.stringify(e).slice(0, 400)}`);
1236
- case "nullish":
1237
- // Narrow should have rewritten nullish to someMatch.
1809
+ }
1810
+ case "nullish": {
1811
+ if (e.left.ty.kind === "nullish") {
1812
+ const scrutinee = lowerExpr(e.left, binds);
1813
+ const binder = freshName(`_oc${_liftCounter++}_val`);
1814
+ const rawBinder = { kind: "var", name: binder, ty: e.left.ty.inner };
1815
+ let valBody = { kind: "var", name: binder };
1816
+ let rightBody = lowerExpr(e.right, binds);
1817
+ if (e.ty.kind === "optional") {
1818
+ valBody = wrapOptionalBranch(valBody, rawBinder);
1819
+ rightBody = wrapOptionalBranch(rightBody, e.right);
1820
+ }
1821
+ else if (e.ty.kind === "nullish") {
1822
+ valBody = wrapNullishBranch(valBody, rawBinder);
1823
+ rightBody = wrapNullishBranch(rightBody, e.right);
1824
+ }
1825
+ return {
1826
+ kind: "match", scrutinee,
1827
+ arms: [
1828
+ { pattern: pCtor("nullishValue", binder), body: valBody },
1829
+ { pattern: pCtor("nullishNull"), body: rightBody },
1830
+ { pattern: pCtor("nullishUndefined"), body: rightBody },
1831
+ ],
1832
+ };
1833
+ }
1834
+ // Narrow should have rewritten non-nullish ?? to someMatch.
1238
1835
  throw new Error(`nullish reached transform — narrow should have rewritten it: ${JSON.stringify(e).slice(0, 300)}`);
1836
+ }
1239
1837
  case "havoc":
1240
1838
  // Dafny's * only works in var/assign positions — lift to own declaration
1241
1839
  if (binds) {
@@ -1272,6 +1870,10 @@ function lowerExpr(e, binds) {
1272
1870
  someBody = wrapOptionalBranch(someBody, e.someBody);
1273
1871
  noneBody = wrapOptionalBranch(noneBody, e.noneBody);
1274
1872
  }
1873
+ else if (e.ty.kind === "nullish") {
1874
+ someBody = wrapNullishBranch(someBody, e.someBody);
1875
+ noneBody = wrapNullishBranch(noneBody, e.noneBody);
1876
+ }
1275
1877
  return {
1276
1878
  kind: "match", scrutinee,
1277
1879
  arms: [
@@ -1294,30 +1896,48 @@ function lowerExpr(e, binds) {
1294
1896
  const varName = e.scrutinee.kind === "var" ? e.scrutinee.name : undefined;
1295
1897
  const pathHint = varName ?? scrutineeHint(e.scrutinee);
1296
1898
  const wrapOpt = e.ty.kind === "optional";
1297
- const arms = e.cases.map(c => {
1899
+ const wrapNullish = e.ty.kind === "nullish";
1900
+ const lowered = e.cases.map(c => lowerExpr(c.body, binds));
1901
+ const loweredFallthrough = e.fallthrough ? lowerExpr(e.fallthrough, binds) : null;
1902
+ // The arms may already read a binder minted for an enclosing narrowing
1903
+ // with the same hint (`u` and `m.u` both give `_u_arr`). Prime this
1904
+ // match's binders past those names so the arm does not capture them.
1905
+ const read = new Set();
1906
+ for (const b of [...lowered, ...(loweredFallthrough ? [loweredFallthrough] : [])])
1907
+ anyExpr(b, x => { if (x.kind === "var")
1908
+ read.add(x.name); return false; });
1909
+ const taken = (n) => read.has(n);
1910
+ const arms = e.cases.map((c, i) => {
1298
1911
  const variant = decl?.variants?.find(v => v.name === c.variant);
1299
1912
  const fields = variant?.fields ?? [];
1300
- let body = lowerExpr(c.body, binds);
1913
+ let body = lowered[i];
1301
1914
  if (varName && fields.length > 0) {
1302
- body = replaceFieldAccess(body, varName, fields, c.variant, tyBaseName(e.typeName));
1915
+ body = replaceFieldAccess(body, varName, fields, c.variant, tyBaseName(e.typeName), taken);
1303
1916
  if (isSynthArrayUnion && fields.length === 1) {
1304
- body = replaceVarInExpr(body, varName, matchBinder(fields[0].name, varName));
1917
+ body = replaceVarInExpr(body, varName, matchBinder(fields[0].name, varName, taken));
1305
1918
  }
1306
1919
  }
1307
1920
  else if (!varName && isSynthArrayUnion && fields.length === 1) {
1308
- // Path scrutinee (e.g. `m.content`): replace structural occurrences
1921
+ // Path scrutinee (e.g. `m.content`): replace both projected
1922
+ // `m.content.arr` (inserted by checked-reads) and bare `m.content`
1309
1923
  // with the binder var ref.
1310
- const binderName = matchBinder(fields[0].name, pathHint);
1924
+ const binderName = matchBinder(fields[0].name, pathHint, taken);
1925
+ const projectedField = { kind: "field", obj: scrutinee, field: fields[0].name };
1926
+ body = replaceExprInExpr(body, projectedField, { kind: "var", name: binderName });
1311
1927
  body = replaceExprInExpr(body, scrutinee, { kind: "var", name: binderName });
1312
1928
  }
1313
1929
  if (wrapOpt)
1314
1930
  body = wrapOptionalBranch(body, c.body);
1315
- return { pattern: buildMatchPattern(c.variant, fields, pathHint), body };
1931
+ else if (wrapNullish)
1932
+ body = wrapNullishBranch(body, c.body);
1933
+ return { pattern: buildMatchPattern(c.variant, fields, pathHint, taken), body };
1316
1934
  });
1317
- if (e.fallthrough) {
1318
- let body = lowerExpr(e.fallthrough, binds);
1935
+ if (e.fallthrough && loweredFallthrough) {
1936
+ let body = loweredFallthrough;
1319
1937
  if (wrapOpt)
1320
1938
  body = wrapOptionalBranch(body, e.fallthrough);
1939
+ else if (wrapNullish)
1940
+ body = wrapNullishBranch(body, e.fallthrough);
1321
1941
  arms.push({ pattern: pWild(), body });
1322
1942
  }
1323
1943
  return { kind: "match", scrutinee: varName !== undefined ? varE(varName) : scrutinee, arms };
@@ -1362,12 +1982,49 @@ function ensuresToMatch(e, typeDecls) {
1362
1982
  rhs = replaceFieldAccess(rhs, obj.name, fields);
1363
1983
  return { kind: "match", scrutinee: varE(obj.name), arms: [{ pattern, body: rhs }, { pattern: pWild(), body: { kind: "bool", value: true } }] };
1364
1984
  }
1365
- function replaceFieldAccess(e, varName, fields, ctorName, ctorOf) {
1366
- return mapExpr(e, x => {
1367
- if (x.kind === "field" && x.obj.kind === "var" && x.obj.name === varName) {
1985
+ /** Substitution into a nested `match` that is capture-avoiding. An arm whose
1986
+ * pattern rebinds `oldName` keeps its body. An arm that binds one of the
1987
+ * `introduced` names, while its body still reads `oldName`, has that binder
1988
+ * renamed to a fresh name first. Without the rename, the substituted
1989
+ * reference would resolve to the inner binder instead of the outer one. */
1990
+ function substIntoMatch(x, oldName, introduced, sub) {
1991
+ return { ...x, scrutinee: sub(x.scrutinee), arms: x.arms.map(a => {
1992
+ if (patternBinders(a.pattern).includes(oldName))
1993
+ return a;
1994
+ const readsOld = anyExpr(a.body, y => y.kind === "var" && y.name === oldName);
1995
+ if (!readsOld || a.pattern.kind !== "ctor")
1996
+ return { ...a, body: sub(a.body) };
1997
+ const binders = [...a.pattern.binders];
1998
+ let body = a.body;
1999
+ for (let i = 0; i < binders.length; i++) {
2000
+ const b = binders[i];
2001
+ if (!introduced.includes(b))
2002
+ continue;
2003
+ const fresh = freshNameWhere(b, n => isUserName(n) || introduced.includes(n) || binders.includes(n) ||
2004
+ anyExpr(body, y => y.kind === "var" && y.name === n));
2005
+ binders[i] = fresh;
2006
+ body = renameFreeVar(body, b, fresh);
2007
+ }
2008
+ const pattern = { ...a.pattern, binders };
2009
+ return { ...a, pattern, body: sub(body) };
2010
+ }) };
2011
+ }
2012
+ function replaceFieldAccess(e, varName, fields, ctorName, ctorOf, taken) {
2013
+ const introduced = fields.map(f => matchBinder(f.name, varName, taken));
2014
+ const fn = (x) => {
2015
+ if (x.kind === "lambda")
2016
+ return mapLambdaBody(x, varName, fn);
2017
+ if ((x.kind === "forall" || x.kind === "exists") && x.var === varName)
2018
+ return x;
2019
+ if (x.kind === "match") {
2020
+ return substIntoMatch(x, varName, introduced, y => replaceFieldAccess(y, varName, fields, ctorName, ctorOf, taken));
2021
+ }
2022
+ const objMatches = x.kind === "field" && ((x.obj.kind === "var" && x.obj.name === varName) ||
2023
+ (x.obj.kind === "checkedUnwrap" && x.obj.expr.kind === "var" && x.obj.expr.name === varName));
2024
+ if (objMatches && x.kind === "field") {
1368
2025
  const f = fields.find(f => f.name === x.field);
1369
2026
  if (f)
1370
- return { kind: "var", name: matchBinder(f.name, varName) };
2027
+ return { kind: "var", name: matchBinder(f.name, varName, taken) };
1371
2028
  }
1372
2029
  // Datatype update of the scrutinee (`{ ...vn, f: v }`): the arm knows the
1373
2030
  // variant, so stamp it — emitters need it for per-constructor destructor
@@ -1375,27 +2032,35 @@ function replaceFieldAccess(e, varName, fields, ctorName, ctorOf) {
1375
2032
  if (ctorName && x.kind === "record" && !x.ctor && x.spread &&
1376
2033
  x.spread.kind === "var" && x.spread.name === varName) {
1377
2034
  return { ...x, ctor: ctorName, ctorOf,
1378
- fields: x.fields.map(f => ({ ...f, value: replaceFieldAccess(f.value, varName, fields, ctorName, ctorOf) })) };
2035
+ fields: x.fields.map(f => ({ ...f, value: replaceFieldAccess(f.value, varName, fields, ctorName, ctorOf, taken) })) };
1379
2036
  }
1380
2037
  // If this let shadows the matched variable, stop replacing in the body
1381
2038
  if (x.kind === "let" && x.name === varName)
1382
- return { ...x, value: replaceFieldAccess(x.value, varName, fields, ctorName, ctorOf) };
2039
+ return { ...x, value: replaceFieldAccess(x.value, varName, fields, ctorName, ctorOf, taken) };
1383
2040
  return null;
1384
- });
2041
+ };
2042
+ return mapExpr(e, fn);
1385
2043
  }
1386
2044
  /** Replace bare `var(oldName)` references → `var(newName)` in lowered IR.
1387
2045
  * Used inside synth array-union match arms: the user code refers to the
1388
2046
  * scrutinee by its bare name (`content`), but in the arm body that name
1389
2047
  * must refer to the variant's sole payload binder (`i_content_arr`). */
1390
2048
  function replaceVarInExpr(e, oldName, newName) {
1391
- return mapExpr(e, x => {
2049
+ const fn = (x) => {
1392
2050
  if (x.kind === "var" && x.name === oldName)
1393
2051
  return { kind: "var", name: newName };
2052
+ if (x.kind === "match")
2053
+ return substIntoMatch(x, oldName, [newName], y => replaceVarInExpr(y, oldName, newName));
2054
+ if (x.kind === "lambda")
2055
+ return mapLambdaBody(x, oldName, fn);
1394
2056
  // If a binding shadows the name, stop substituting inside its body.
1395
2057
  if (x.kind === "let" && x.name === oldName)
1396
2058
  return { ...x, value: replaceVarInExpr(x.value, oldName, newName) };
2059
+ if ((x.kind === "forall" || x.kind === "exists") && x.var === oldName)
2060
+ return x;
1397
2061
  return null;
1398
- });
2062
+ };
2063
+ return mapExpr(e, fn);
1399
2064
  }
1400
2065
  /** Structural equality on Expr access-paths (var / field chain). Enough to
1401
2066
  * match the scrutinee `m.content` against later occurrences in a match arm. */
@@ -1408,16 +2073,36 @@ function exprPathEqual(a, b) {
1408
2073
  return a.field === b.field && exprPathEqual(a.obj, b.obj);
1409
2074
  return false;
1410
2075
  }
2076
+ /** Extract the root variable name of an access-path Expr (e.g. `m.u` → `m`). */
2077
+ function exprPathRoot(e) {
2078
+ let cur = e;
2079
+ while (cur.kind === "field")
2080
+ cur = cur.obj;
2081
+ return cur.kind === "var" ? cur.name : null;
2082
+ }
1411
2083
  /** Substitute every occurrence of `target` (an access-path Expr) with `repl`
1412
2084
  * inside `e`. Mirror of `replaceVarInExpr` but keyed on a sub-path rather
1413
2085
  * than a bare name — needed when the narrowing scrutinee is `m.content`
1414
2086
  * (field access) rather than a bare `content` (var). */
1415
2087
  function replaceExprInExpr(e, target, repl) {
1416
- return mapExpr(e, x => {
2088
+ const root = exprPathRoot(target);
2089
+ const introduced = repl.kind === "var" ? [repl.name] : [];
2090
+ const fn = (x) => {
1417
2091
  if (exprPathEqual(x, target))
1418
2092
  return repl;
2093
+ if (root) {
2094
+ if (x.kind === "match")
2095
+ return substIntoMatch(x, root, introduced, y => replaceExprInExpr(y, target, repl));
2096
+ if (x.kind === "lambda")
2097
+ return mapLambdaBody(x, root, fn);
2098
+ if (x.kind === "let" && x.name === root)
2099
+ return { ...x, value: replaceExprInExpr(x.value, target, repl) };
2100
+ if ((x.kind === "forall" || x.kind === "exists") && x.var === root)
2101
+ return x;
2102
+ }
1419
2103
  return null;
1420
- });
2104
+ };
2105
+ return mapExpr(e, fn);
1421
2106
  }
1422
2107
  /** Extract a short reader-friendly hint for a TExpr access-path: the last
1423
2108
  * field name in a field chain, or the var name. Used to derive a stable
@@ -1440,23 +2125,50 @@ function negateExpr(e) {
1440
2125
  return e.expr;
1441
2126
  return { kind: "unop", op: "¬", expr: e };
1442
2127
  }
1443
- /** Build the two pieces of an `arr.pop()` lowering on a named array variable:
1444
- * - `optValue` is `(if |arr|>0 then Some(arr[|arr|-1]) else None)` (the popped element)
1445
- * - `guardedTrunc` is `(if |arr|>0 then arr[..|arr|-1] else arr)` (the array minus its last element)
1446
- * Callers wrap these in let/assign statements appropriate to their context. */
1447
- function buildPopLowering(arrName, arrTy) {
1448
- const arrVar = { kind: "var", name: arrName };
1449
- const arrLen = { kind: "field", obj: arrVar, field: "size" };
1450
- const lastIdx = { kind: "binop", op: "-", left: arrLen, right: { kind: "num", value: 1 } };
1451
- const lastElem = { kind: "index", arr: arrVar, idx: lastIdx };
2128
+ /** Lower an array `.pop()` or `.shift()` call on any writable Place receiver
2129
+ * into `{ method, result, writeStmts }`:
2130
+ * - `result` reads the removed element from the original receiver,
2131
+ * - `writeStmts` writes the shortened array
2132
+ * back through the original receiver Place + enclosing `someMatch` frames.
2133
+ * A consumed nonoptional result reads an element directly, already requiring
2134
+ * nonemptiness. Optional or discarded results still need an empty-array guard.
2135
+ * Value callers evaluate `result` before `writeStmts` and only assign to the
2136
+ * destination afterward so `t = t.children.shift()!` mutates the original `t`. */
2137
+ function lowerArrayPopOrShift(e, usage) {
2138
+ if (e.kind !== "call" || e.fn.kind !== "field" || e.fn.obj.ty.kind !== "array")
2139
+ return null;
2140
+ const method = e.fn.field;
2141
+ if (method !== "pop" && method !== "shift")
2142
+ return null;
2143
+ const obj = e.fn.obj;
2144
+ const arrExpr = lowerExpr(obj, null);
2145
+ const arrLen = { kind: "field", obj: arrExpr, field: "size" };
1452
2146
  const isNonEmpty = { kind: "binop", op: ">", left: arrLen, right: { kind: "num", value: 0 } };
1453
- const optValue = { kind: "if", cond: isNonEmpty,
1454
- then: { kind: "app", fn: "Some", args: [lastElem] },
1455
- else: { kind: "var", name: "undefined" } };
1456
- const truncated = { kind: "methodCall", obj: arrVar, objTy: arrTy, method: "slice",
1457
- args: [{ kind: "num", value: 0 }, lastIdx], monadic: false };
1458
- const guardedTrunc = { kind: "if", cond: isNonEmpty, then: truncated, else: arrVar };
1459
- return { optValue, guardedTrunc };
2147
+ const index = method === "pop"
2148
+ ? { kind: "binop", op: "-", left: arrLen, right: { kind: "num", value: 1 } }
2149
+ : { kind: "num", value: 0 };
2150
+ const elemValue = { kind: "index", arr: arrExpr, idx: index };
2151
+ const isOptResult = e.ty.kind === "optional" || e.ty.kind === "nullish";
2152
+ const result = isOptResult
2153
+ ? { kind: "if", cond: isNonEmpty, then: { kind: "app", fn: "Some", args: [elemValue] }, else: { kind: "var", name: "undefined" } }
2154
+ : elemValue;
2155
+ const truncated = { kind: "methodCall", obj: arrExpr, objTy: obj.ty, method: "slice",
2156
+ args: method === "pop" ? [{ kind: "num", value: 0 }, index] : [{ kind: "num", value: 1 }], monadic: false };
2157
+ const needsEmptyGuard = usage === "discard" || isOptResult;
2158
+ const nextArr = needsEmptyGuard
2159
+ ? { kind: "if", cond: isNonEmpty, then: truncated, else: arrExpr }
2160
+ : truncated;
2161
+ const write = buildPlaceWrite(obj, nextArr);
2162
+ if (!write)
2163
+ return null;
2164
+ return {
2165
+ method,
2166
+ result,
2167
+ writeStmts: [
2168
+ { kind: "assign", target: write.target, value: write.value },
2169
+ ...emitWriteBacksForTarget(write.target, _writeBackFrames),
2170
+ ],
2171
+ };
1460
2172
  }
1461
2173
  /**
1462
2174
  * Velvet (Lean backend) rejects `return` inside a loop. For a function shaped as
@@ -1827,25 +2539,44 @@ function transformSpecExpr(e) {
1827
2539
  let _writeBackFrames = [];
1828
2540
  // Declared types of in-scope variables and narrowing binders (for optional-field wrap checks).
1829
2541
  let _varTypes = new Map();
1830
- /** Look up the declared field type reached by walking `fields` from `rootTy`. */
1831
- function lookupFieldTy(rootTy, fields, typeDecls) {
2542
+ /** Look up the declared field type and union-owner tags reached by walking
2543
+ * `fields` from `rootTy`. */
2544
+ function lookupFieldPathInfo(rootTy, fields, typeDecls, ownerVariants) {
1832
2545
  let cur = rootTy;
1833
- for (const field of fields) {
2546
+ const unionsByDepth = [];
2547
+ for (let i = 0; i < fields.length; i++) {
2548
+ const field = fields[i];
1834
2549
  if (!cur)
1835
- return null;
1836
- if (cur.kind === "optional")
2550
+ return { fieldTy: null, unionsByDepth };
2551
+ if (cur.kind === "optional" || cur.kind === "nullish")
1837
2552
  cur = cur.inner;
1838
2553
  if (cur.kind !== "user")
1839
- return null;
2554
+ return { fieldTy: null, unionsByDepth };
1840
2555
  const decl = declOfTy(typeDecls, cur);
1841
- if (!decl || decl.kind !== "record" || !decl.fields)
1842
- return null;
1843
- const f = decl.fields.find(fi => fi.name === field);
1844
- if (!f)
1845
- return null;
1846
- cur = f.type ?? parseTsType(f.tsType);
2556
+ if (!decl)
2557
+ return { fieldTy: null, unionsByDepth };
2558
+ if (decl.kind === "record" && decl.fields) {
2559
+ unionsByDepth.push(undefined);
2560
+ const f = decl.fields.find(fi => fi.name === field);
2561
+ if (!f)
2562
+ return { fieldTy: null, unionsByDepth };
2563
+ cur = f.type ?? parseTsType(f.tsType);
2564
+ }
2565
+ else if (decl.kind === "discriminated-union" && decl.variants) {
2566
+ const ov = ownerVariants?.[i];
2567
+ unionsByDepth.push({ ctor: ov, ctorOf: decl.name });
2568
+ const variant = (ov ? decl.variants.find(v => v.name === ov) : undefined)
2569
+ ?? decl.variants.find(v => v.fields.some(fi => fi.name === field));
2570
+ const f = variant?.fields.find(fi => fi.name === field);
2571
+ if (!f)
2572
+ return { fieldTy: null, unionsByDepth };
2573
+ cur = f.type ?? parseTsType(f.tsType);
2574
+ }
2575
+ else {
2576
+ return { fieldTy: null, unionsByDepth };
2577
+ }
1847
2578
  }
1848
- return cur ?? null;
2579
+ return { fieldTy: cur ?? null, unionsByDepth };
1849
2580
  }
1850
2581
  /** True if `e` contains any subexpression that can carry a backend precondition
1851
2582
  * (calls, indexing, checked unwraps, division/modulo). Used to ensure optional
@@ -1903,30 +2634,15 @@ function transformStmt(s, typeDecls) {
1903
2634
  if (s.init.kind === "havoc") {
1904
2635
  return [{ kind: "let", name: s.name, type: s.ty, mutable: s.mutable, value: { kind: "havoc", type: s.init.ty } }];
1905
2636
  }
1906
- // arr.shift()! → let x = arr[0]; arr = arr[1..]
2637
+ // let x = recv.shift() / recv.pop(): bind removed element from original receiver,
2638
+ // then write shortened array back through the receiver Place.
1907
2639
  const init = s.init.kind === "call" ? s.init : undefined;
1908
- if (init && init.fn.kind === "field" && init.fn.field === "shift" && init.fn.obj.ty.kind === "array") {
1909
- const arrName = init.fn.obj.kind === "var" ? init.fn.obj.name : undefined;
1910
- if (arrName) {
1911
- const arrVar = { kind: "var", name: arrName };
1912
- const letHead = { kind: "let", name: s.name, type: s.ty, mutable: s.mutable,
1913
- value: { kind: "index", arr: arrVar, idx: { kind: "num", value: 0 } } };
1914
- const sliceTail = { kind: "assign", target: arrName,
1915
- value: { kind: "methodCall", obj: arrVar, objTy: init.fn.obj.ty, method: "slice", args: [{ kind: "num", value: 1 }], monadic: false } };
1916
- return [letHead, sliceTail, ...emitWriteBacksForTarget(arrName, _writeBackFrames)];
1917
- }
1918
- }
1919
- // let x = arr.pop() → let x: T? = (Option-expr); arr := (truncated-or-self)
1920
- if (init && init.fn.kind === "field" && init.fn.field === "pop" && init.fn.obj.ty.kind === "array") {
1921
- const arrName = init.fn.obj.kind === "var" ? init.fn.obj.name : undefined;
1922
- if (arrName) {
1923
- const { optValue, guardedTrunc } = buildPopLowering(arrName, init.fn.obj.ty);
1924
- return [
1925
- { kind: "let", name: s.name, type: s.ty, mutable: s.mutable, value: optValue },
1926
- { kind: "assign", target: arrName, value: guardedTrunc },
1927
- ...emitWriteBacksForTarget(arrName, _writeBackFrames),
1928
- ];
1929
- }
2640
+ const popOrShiftLet = lowerArrayPopOrShift(s.init, "value");
2641
+ if (popOrShiftLet) {
2642
+ return [
2643
+ { kind: "let", name: s.name, type: s.ty, mutable: s.mutable, value: popOrShiftLet.result },
2644
+ ...popOrShiftLet.writeStmts,
2645
+ ];
1930
2646
  }
1931
2647
  // new Map(arr.map(n => [n.field, n])) → let m = map[]; for (n of arr) m[n.field] := n
1932
2648
  if (init && init.fn.kind === "var" && init.fn.name === "__mapFromArray" &&
@@ -1979,27 +2695,29 @@ function transformStmt(s, typeDecls) {
1979
2695
  return [...binds, { kind: "let", name: s.name, type: s.ty, mutable: s.mutable, value: expr }];
1980
2696
  }
1981
2697
  case "assign": {
1982
- // x = arr.pop() → x := (Option-expr); arr := (truncated-or-self) + Place write-back
1983
- if (s.value.kind === "call" && s.value.fn.kind === "field" &&
1984
- s.value.fn.field === "pop" && s.value.fn.obj.ty.kind === "array" &&
1985
- s.value.fn.obj.kind === "var") {
1986
- const arrName = s.value.fn.obj.name;
1987
- const { optValue, guardedTrunc } = buildPopLowering(arrName, s.value.fn.obj.ty);
2698
+ // target = recv.shift() / recv.pop(): save the removed element first,
2699
+ // write the shortened array back through the original receiver, and only
2700
+ // then assign the saved result to `s.target` (so `t = t.children.shift()!`
2701
+ // mutates the original `t`, not the shifted child).
2702
+ const popOrShiftAssign = lowerArrayPopOrShift(s.value, "value");
2703
+ if (popOrShiftAssign) {
2704
+ const tmp = freshName(`_${popOrShiftAssign.method}${_liftCounter++}`);
2705
+ const assignTmp = { ...s, value: { kind: "var", name: tmp, ty: s.value.ty } };
1988
2706
  return [
1989
- { kind: "assign", target: s.target, value: optValue },
1990
- { kind: "assign", target: arrName, value: guardedTrunc },
1991
- ...emitWriteBacksForTarget(arrName, _writeBackFrames),
2707
+ { kind: "let", name: tmp, type: s.value.ty, mutable: false, value: popOrShiftAssign.result },
2708
+ ...popOrShiftAssign.writeStmts,
2709
+ ...transformStmt(assignTmp, typeDecls),
1992
2710
  ];
1993
2711
  }
1994
2712
  // Non-`this.` dotted field assignment on a record, union variant, or narrowed
1995
- // optional record (e.g. `b.count = 5`, `u.v = 99`, `u.items[0] = 10`, `u.box.count = 42`):
2713
+ // optional/nullish record (e.g. `b.count = 5`, `u.v = 99`, `u.items[0] = 10`, `u.box.count = 42`):
1996
2714
  // lower through active `unwrap` & `variant` frames with cascading write-back.
1997
2715
  if (s.target.includes(".") && !s.target.startsWith("this.")) {
1998
2716
  const parts = s.target.split(".");
1999
2717
  const rootVar = parts[0];
2000
2718
  const fields = parts.slice(1);
2001
2719
  const { binds, expr } = liftMethodCalls(s.value);
2002
- const isUndefRhs = s.value.kind === "var" && s.value.name === "undefined";
2720
+ const isUndefRhs = s.value.kind === "var" && (s.value.name === "undefined" || s.value.name === "null");
2003
2721
  const isOptRhs = s.value.ty.kind === "optional" || isUndefRhs;
2004
2722
  const resolved = resolveWriteTargetThroughFrames(rootVar, fields, _writeBackFrames);
2005
2723
  if (resolved.leafUnwrapFrame) {
@@ -2011,7 +2729,7 @@ function transformStmt(s, typeDecls) {
2011
2729
  ...emitWriteBacksForTarget(frame.binder, _writeBackFrames),
2012
2730
  ];
2013
2731
  }
2014
- // Assigning `undefined` or an `Option<T>` value to a narrowed optional field:
2732
+ // Assigning `undefined`/`null` or an `Option<T>` value to a narrowed optional field:
2015
2733
  // write directly to the enclosing record field without double-wrapping in `Some`.
2016
2734
  const optExpr = isUndefRhs
2017
2735
  ? { kind: "constructor", name: "none", type: "Option", args: [] }
@@ -2019,7 +2737,7 @@ function transformStmt(s, typeDecls) {
2019
2737
  if (frame.fields.length > 0) {
2020
2738
  return [
2021
2739
  ...binds,
2022
- { kind: "assign", target: frame.rootVar, value: buildNestedFieldExpr(frame.rootVar, frame.fields, optExpr) },
2740
+ { kind: "assign", target: frame.rootVar, value: buildNestedFieldExpr({ kind: "var", name: frame.rootVar }, frame.fields, optExpr) },
2023
2741
  ...emitWriteBacksForTarget(frame.rootVar, _writeBackFrames),
2024
2742
  ];
2025
2743
  }
@@ -2029,31 +2747,24 @@ function transformStmt(s, typeDecls) {
2029
2747
  ...emitWriteBacksForTarget(frame.rootVar, _writeBackFrames),
2030
2748
  ];
2031
2749
  }
2032
- if (resolved.leafVariantBinder) {
2033
- const binderTy = _varTypes.get(resolved.leafVariantBinder);
2034
- const rhsExpr = binderTy?.kind === "optional" && !isOptRhs
2035
- ? { kind: "constructor", name: "some", type: "Option", args: [expr] }
2036
- : isUndefRhs && binderTy?.kind === "optional"
2037
- ? { kind: "constructor", name: "none", type: "Option", args: [] }
2038
- : expr;
2039
- return [
2040
- ...binds,
2041
- { kind: "assign", target: resolved.leafVariantBinder, value: rhsExpr },
2042
- ...emitWriteBacksForTarget(resolved.leafVariantBinder, _writeBackFrames),
2043
- ];
2044
- }
2045
2750
  if (resolved.remainingFields.length > 0) {
2046
- const fieldTy = lookupFieldTy(_varTypes.get(resolved.currentRoot), resolved.remainingFields, typeDecls);
2047
- const rhsExpr = fieldTy?.kind === "optional"
2048
- ? (isUndefRhs
2049
- ? { kind: "constructor", name: "none", type: "Option", args: [] }
2050
- : s.value.ty.kind === "optional"
2051
- ? expr
2052
- : { kind: "constructor", name: "some", type: "Option", args: [expr] })
2053
- : expr;
2751
+ const rootTy = _varTypes.get(resolved.currentRoot);
2752
+ const skippedDepth = fields.length - resolved.remainingFields.length;
2753
+ const remOwnerVariants = s.ownerVariants?.slice(skippedDepth);
2754
+ const { fieldTy, unionsByDepth } = lookupFieldPathInfo(rootTy, resolved.remainingFields, typeDecls, remOwnerVariants);
2755
+ const rhsExpr = fieldTy?.kind === "nullish"
2756
+ ? wrapNullishBranch(expr, s.value)
2757
+ : fieldTy?.kind === "optional"
2758
+ ? wrapOptionalBranch(expr, s.value)
2759
+ : expr;
2760
+ const rootExpr = { kind: "var", name: resolved.currentRoot };
2761
+ const isOptRoot = rootTy?.kind === "nullish" || rootTy?.kind === "optional";
2762
+ const baseExpr = isOptRoot ? { kind: "checkedUnwrap", expr: rootExpr } : rootExpr;
2763
+ const hasAnyUnion = unionsByDepth.some(u => u !== undefined);
2764
+ const updated = buildNestedFieldExpr(baseExpr, resolved.remainingFields, rhsExpr, hasAnyUnion ? unionsByDepth : undefined);
2054
2765
  return [
2055
2766
  ...binds,
2056
- { kind: "assign", target: resolved.currentRoot, value: buildNestedFieldExpr(resolved.currentRoot, resolved.remainingFields, rhsExpr) },
2767
+ { kind: "assign", target: resolved.currentRoot, value: isOptRoot ? wrapCheckedUnwrapValue(updated, rootTy) : updated },
2057
2768
  ...emitWriteBacksForTarget(resolved.currentRoot, _writeBackFrames),
2058
2769
  ];
2059
2770
  }
@@ -2104,6 +2815,9 @@ function transformStmt(s, typeDecls) {
2104
2815
  // enclosing narrowing frames (`someMatch` unwrap or union variant arm).
2105
2816
  // Non-Place receivers (e.g. `getArr().push(1)`) fail closed instead of
2106
2817
  // silently discarding the updated collection.
2818
+ const popOrShiftExpr = lowerArrayPopOrShift(s.expr, "discard");
2819
+ if (popOrShiftExpr)
2820
+ return popOrShiftExpr.writeStmts;
2107
2821
  if (s.expr.kind === "call" && s.expr.fn.kind === "field") {
2108
2822
  const recv = s.expr.fn.obj;
2109
2823
  const f = s.expr.fn.field;
@@ -2129,7 +2843,7 @@ function transformStmt(s, typeDecls) {
2129
2843
  }
2130
2844
  if (recv.kind === "checkedUnwrap") {
2131
2845
  const { binds, expr } = liftMethodCalls(s.expr);
2132
- const wrapped = { kind: "app", fn: "Some", args: [expr] };
2846
+ const wrapped = wrapCheckedUnwrapValue(expr, recv.expr.ty);
2133
2847
  if (recv.expr.kind === "var") {
2134
2848
  return [
2135
2849
  ...binds,
@@ -2244,10 +2958,9 @@ function transformStmt(s, typeDecls) {
2244
2958
  }
2245
2959
  }
2246
2960
  /** Build match arms from variant cases — shared by imperative and pure paths.
2247
- * Looks up variant fields from typeDecls, builds patterns via buildMatchPattern,
2248
- * and delegates body transformation to the caller-provided function.
2249
- * Returns null if any body transformation returns null (pure path abort). */
2250
- function buildMatchArms(cases, varName, typeName, typeDecls, transformBody) {
2961
+ * Pure paths bind constructor fields via `buildMatchPattern`; imperative paths
2962
+ * pass `wildcard: true` so arms read and update live storage directly (#405). */
2963
+ function buildMatchArms(cases, varName, typeName, typeDecls, transformBody, wildcard = false) {
2251
2964
  const decl = declOf(typeDecls, typeName);
2252
2965
  if (!decl || (decl.kind !== "string-union" && decl.kind !== "discriminated-union")) {
2253
2966
  throw new Error(`match type ${typeName} is not a declared union`);
@@ -2261,7 +2974,9 @@ function buildMatchArms(cases, varName, typeName, typeDecls, transformBody) {
2261
2974
  if (!declared)
2262
2975
  throw new Error(`case ${JSON.stringify(c.name)} is not a variant of ${typeName}`);
2263
2976
  const fields = variant?.fields ?? [];
2264
- const pattern = buildMatchPattern(c.name, fields, varName);
2977
+ const pattern = wildcard
2978
+ ? buildWildcardMatchPattern(c.name, fields)
2979
+ : buildMatchPattern(c.name, fields, varName);
2265
2980
  const body = transformBody(c.body, varName, fields, c.name);
2266
2981
  if (body === null)
2267
2982
  return null;
@@ -2284,109 +2999,22 @@ function buildLiteralMatchArms(cases, transformBody) {
2284
2999
  }
2285
3000
  function emitMatchStmt(scrutinee, typeName, cases, fallthrough, typeDecls) {
2286
3001
  const decl = declOf(typeDecls, typeName);
2287
- // Synth array-unions (discriminant "__isArray__") have single-field variants
2288
- // ArrayBranch(arr) / NonArrayBranch(val). The matched arm refers to the
2289
- // scrutinee by its bare name/path (`content`, `m.content`), not `.arr`, so
2290
- // we substitute that whole reference with the variant's sole field binder.
2291
- const isSynthArrayUnion = decl?.discriminant === "__isArray__";
2292
- // The scrutinee is a bare var (`current`) or a field-access path
2293
- // (`current.content`). `prefix` names the binder scope — the var name, or a
2294
- // safe id derived from the path (`current.content` → `current_content`) —
2295
- // and is used for both pattern binders and arm-body substitution so they
2296
- // always agree. A var scrutinee has empty `fields`, so `prefix` is just its
2297
- // name and the emitted code is unchanged from before this generalization.
2298
- const path = asTAccessPath(scrutinee);
2299
- const isPath = !!path && path.fields.length > 0;
2300
- const prefix = path ? [path.rootVar, ...path.fields].join("_") : "?";
2301
- const baseUnionName = tyBaseName(typeName);
2302
- function transformArmBody(body, fields, ctorName) {
2303
- let stmts;
2304
- if (isPath && path) {
2305
- // Path scrutinee: the matched value is referred to by the bare path, so
2306
- // substitute the whole path (only the synth single-field shape arises
2307
- // here — discriminant chains require a var scrutinee).
2308
- stmts = isSynthArrayUnion && fields.length === 1
2309
- ? replacePathInTStmts(body, path, matchBinder(fields[0].name, prefix), fields[0].type ?? parseTsType(fields[0].tsType))
2310
- : body;
2311
- }
2312
- else {
2313
- stmts = replaceFieldAccessInTStmts(body, prefix, fields);
2314
- if (isSynthArrayUnion && fields.length === 1) {
2315
- const f = fields[0];
2316
- stmts = replaceVarInTStmts(stmts, prefix, matchBinder(f.name, prefix), f.type ?? parseTsType(f.tsType));
2317
- }
2318
- }
2319
- const pushVariant = !isPath && !!ctorName && fields.length > 0;
2320
- if (pushVariant) {
2321
- for (const f of fields) {
2322
- _varTypes.set(matchBinder(f.name, prefix), f.type ?? parseTsType(f.tsType));
2323
- }
2324
- _writeBackFrames.push(makeVariantFrame(prefix, baseUnionName, ctorName, fields.map(f => ({ fieldName: f.name, binder: matchBinder(f.name, prefix) }))));
2325
- }
2326
- let lowered;
2327
- try {
2328
- lowered = transformStmts(stmts, typeDecls);
2329
- }
2330
- finally {
2331
- if (pushVariant)
2332
- _writeBackFrames.pop();
2333
- }
2334
- if (_opts.backend === "lean" && pushVariant) {
2335
- const assigned = collectAssignedIrTargets(lowered);
2336
- const mutShadows = fields
2337
- .filter(f => assigned.has(matchBinder(f.name, prefix)))
2338
- .map(f => {
2339
- const b = matchBinder(f.name, prefix);
2340
- return { kind: "let", name: b, type: f.type ?? parseTsType(f.tsType), mutable: true, value: varE(b) };
2341
- });
2342
- if (mutShadows.length > 0)
2343
- lowered = [...mutShadows, ...lowered];
2344
- }
2345
- return lowered;
2346
- }
2347
3002
  const armCases = cases.map(c => ({ name: c.variant, body: c.body }));
2348
- const arms = buildMatchArms(armCases, prefix, typeName, typeDecls, (body, _vn, fields, ctorName) => transformArmBody(body, fields, ctorName));
2349
- // Add the fallthrough arm whenever the listed cases don't cover every
2350
- // variant — needed for exhaustiveness even when there's no `else`
2351
- // (`fallthrough` empty), e.g. `if (Array.isArray(x)) {...}` with no else
2352
- // becomes `match x { case ArrayBranch(..) => ... case NonArrayBranch(..) => }`.
3003
+ const arms = buildMatchArms(armCases, undefined, typeName, typeDecls, (body) => transformStmts(body, typeDecls), /* wildcard */ true);
2353
3004
  const allCovered = !!decl?.variants && cases.length >= decl.variants.length;
2354
3005
  if (!allCovered) {
2355
- const remaining = remainingVariant(typeName, cases, typeDecls);
3006
+ const remaining = remainingVariant(decl, cases.map(c => c.variant));
2356
3007
  if (remaining) {
2357
- // Exactly one variant left — destructure so the fallthrough body can
2358
- // access variant-specific fields (Lean requires this; Dafny tolerates `_`).
2359
- const pattern = buildMatchPattern(remaining.name, remaining.fields, prefix);
2360
- const body = transformArmBody(fallthrough, remaining.fields, remaining.name);
2361
- arms.push({ pattern, body });
3008
+ arms.push({
3009
+ pattern: buildWildcardMatchPattern(remaining.name, remaining.fields),
3010
+ body: transformStmts(fallthrough, typeDecls),
3011
+ });
2362
3012
  }
2363
3013
  else {
2364
3014
  arms.push({ pattern: pWild(), body: transformStmts(fallthrough, typeDecls) });
2365
3015
  }
2366
3016
  }
2367
- return { kind: "match", scrutinee: (isPath || scrutinee.kind === "checkedUnwrap") ? transformExpr(scrutinee) : varE(prefix), arms };
2368
- }
2369
- /** Replace bare `var(oldName)` references → `var(newName)` with the given type.
2370
- * Used by emitMatchStmt for synth array-unions where the variant has a single
2371
- * payload field and the user code refers to the scrutinee by its bare name. */
2372
- function replaceVarInTStmts(stmts, oldName, newName, newTy) {
2373
- return stmts.map(s => mapTStmt(s, e => {
2374
- if (e.kind === "var" && e.name === oldName) {
2375
- return { kind: "var", name: newName, ty: newTy };
2376
- }
2377
- return null;
2378
- }));
2379
- }
2380
- /** If the chain has matched all variants but one, return that remaining variant. */
2381
- function remainingVariant(typeName, cases, typeDecls) {
2382
- const decl = declOf(typeDecls, typeName);
2383
- if (!decl?.variants)
2384
- return null;
2385
- const matched = new Set(cases.map(c => c.variant));
2386
- const remaining = decl.variants.filter(v => !matched.has(v.name));
2387
- if (remaining.length !== 1)
2388
- return null;
2389
- return remaining[0];
3017
+ return { kind: "match", scrutinee: transformExpr(scrutinee), arms };
2390
3018
  }
2391
3019
  /** `switch(obj.field)` is stripped at extraction to scrutinee `obj` + discriminant
2392
3020
  * `field`, assuming `obj` is a discriminated union with `field` as its
@@ -2416,22 +3044,19 @@ function switchCtorDecl(typeDecls, ty) {
2416
3044
  const decl = declOfTy(typeDecls, ty);
2417
3045
  return decl?.kind === "string-union" || decl?.kind === "discriminated-union" ? decl : undefined;
2418
3046
  }
2419
- /** Stamp variant ctor info onto datatype updates of the match scrutinee in
2420
- * lowered arm bodies (`{ ...vn, f: v }`) — the statement-path twin of
2421
- * `replaceFieldAccess`'s stamping. Emitters need the pin to use
2422
- * per-constructor destructor names for collision-renamed fields. */
2423
- function stampScrutineeUpdates(body, varName, ctorName, ctorOf) {
2424
- const stamp = (x) => {
2425
- if (x.kind === "record" && !x.ctor && x.spread &&
2426
- x.spread.kind === "var" && x.spread.name === varName) {
2427
- return { ...x, ctor: ctorName, ctorOf,
2428
- fields: x.fields.map(f => ({ ...f, value: mapExpr(f.value, stamp) })) };
2429
- }
2430
- return null;
2431
- };
2432
- return body.map(st => mapStmt(st, stamp));
3047
+ /** A default covering one union variant needs the same variant pattern as an
3048
+ * explicit case, in both pure and imperative lowering. */
3049
+ function withExplicitVariantDefault(s, typeDecls) {
3050
+ if (s.defaultBody.length === 0)
3051
+ return s;
3052
+ const decl = unionDeclOfTy(typeDecls, s.expr.ty);
3053
+ if (decl?.discriminant !== s.discriminant)
3054
+ return s;
3055
+ const remaining = remainingVariant(decl, s.cases.map(c => c.label));
3056
+ return remaining ? { ...s, cases: [...s.cases, { label: remaining.name, body: s.defaultBody }], defaultBody: [] } : s;
2433
3057
  }
2434
3058
  function emitSwitchStmt(s, typeDecls) {
3059
+ s = withExplicitVariantDefault(s, typeDecls);
2435
3060
  const cases = s.cases.map(c => ({ name: c.label, body: c.body }));
2436
3061
  const ef = enumFieldSwitch(s, typeDecls);
2437
3062
  const matchTy = ef ? ef.fieldTy : s.expr.ty;
@@ -2441,127 +3066,13 @@ function emitSwitchStmt(s, typeDecls) {
2441
3066
  const typeName = !matchTy ? "unknown" : matchTy.kind === "user" ? matchTy.name : matchTy.kind;
2442
3067
  throw new Error(`switch scrutinee must be string-typed or a declared union, got ${typeName}`);
2443
3068
  }
2444
- const baseName = s.expr.ty.kind === "user" ? tyBaseName(s.expr.ty.name) : undefined;
2445
3069
  const arms = literalCases
2446
3070
  ? buildLiteralMatchArms(cases, (body) => transformStmts(body, typeDecls))
2447
- : ef
2448
- ? buildMatchArms(cases, undefined, ctorDecl.name, typeDecls, (body) => transformStmts(body, typeDecls))
2449
- : buildMatchArms(cases, s.expr.kind === "var" ? s.expr.name : "?", ctorDecl.name, typeDecls, (body, vn, fields, ctorName) => {
2450
- const pushVariant = !!ctorName && !!vn && vn !== "?" && !!baseName && fields.length > 0;
2451
- const variantMeta = ctorName ? ctorDecl?.variants?.find(v => v.name === ctorName) : undefined;
2452
- if (pushVariant) {
2453
- for (const f of fields) {
2454
- const vf = variantMeta?.fields.find(vf => vf.name === f.name);
2455
- _varTypes.set(matchBinder(f.name, vn), vf?.type ?? parseTsType(f.tsType));
2456
- }
2457
- _writeBackFrames.push(makeVariantFrame(vn, baseName, ctorName, fields.map(f => ({ fieldName: f.name, binder: matchBinder(f.name, vn) }))));
2458
- }
2459
- let out;
2460
- try {
2461
- out = transformStmts(replaceFieldAccessInTStmts(body, vn, fields), typeDecls);
2462
- }
2463
- finally {
2464
- if (pushVariant)
2465
- _writeBackFrames.pop();
2466
- }
2467
- if (ctorName && vn && baseName)
2468
- out = stampScrutineeUpdates(out, vn, ctorName, baseName);
2469
- if (_opts.backend === "lean" && pushVariant) {
2470
- const assigned = collectAssignedIrTargets(out);
2471
- const mutShadows = fields
2472
- .filter(f => assigned.has(matchBinder(f.name, vn)))
2473
- .map(f => {
2474
- const b = matchBinder(f.name, vn);
2475
- return { kind: "let", name: b, type: parseTsType(f.tsType), mutable: true, value: varE(b) };
2476
- });
2477
- if (mutShadows.length > 0)
2478
- out = [...mutShadows, ...out];
2479
- }
2480
- return out;
2481
- });
3071
+ : buildMatchArms(cases, undefined, ctorDecl.name, typeDecls, (body) => transformStmts(body, typeDecls), /* wildcard */ true);
2482
3072
  if (s.defaultBody.length > 0)
2483
3073
  arms.push({ pattern: pWild(), body: transformStmts(s.defaultBody, typeDecls) });
2484
- return { kind: "match", scrutinee: ef ? ef.scrutinee : varE(s.expr.kind === "var" ? s.expr.name : "?"), arms };
2485
- }
2486
- /** Replace obj.field → replacement var in typed IR.
2487
- * Uses the TExpr's resolved type when available, falling back to `fallbackTy`. */
2488
- function replaceFieldsInTStmts(stmts, objName, replacements) {
2489
- if (replacements.length === 0)
2490
- return stmts;
2491
- return stmts.map(s => mapTStmt(s, e => {
2492
- const objMatches = e.kind === "field" && ((e.obj.kind === "var" && e.obj.name === objName) ||
2493
- (e.obj.kind === "checkedUnwrap" && e.obj.expr.kind === "var" && e.obj.expr.name === objName));
2494
- if (objMatches && e.kind === "field") {
2495
- const r = replacements.find(r => r.fieldName === e.field);
2496
- if (r) {
2497
- const ty = e.ty.kind !== "unknown" ? e.ty : r.fallbackTy;
2498
- return { kind: "var", name: r.newName, ty };
2499
- }
2500
- }
2501
- return null;
2502
- }));
2503
- }
2504
- /** Replace all variant fields of obj → match binder vars in typed IR.
2505
- * Before replacing field reads, realize TypeScript's structural argument
2506
- * conversion for calls such as `helper(outcome)` inside a narrowed union arm.
2507
- * The source value is still the enclosing union in typed IR, while Dafny and
2508
- * Lean expect the helper's nominal record. Rebuild that record solely from
2509
- * the fields bound by this arm's match pattern. */
2510
- function replaceFieldAccessInTStmts(stmts, varName, fields) {
2511
- const projected = projectStructuralCallArgsInTStmts(stmts, varName, fields);
2512
- return replaceFieldsInTStmts(projected, varName, fields.map(f => ({
2513
- fieldName: f.name,
2514
- newName: matchBinder(f.name, varName),
2515
- fallbackTy: f.type ?? parseTsType(f.tsType),
2516
- })));
2517
- }
2518
- /** Project a narrowed union scrutinee into a named structural record expected
2519
- * by a same-module/extern call. Resolution stamps named calls with paramTys;
2520
- * this pass fires only when every target record field has an identically typed
2521
- * match-bound source field. That deliberately avoids inventing a broad cast:
2522
- * it is the nominal-backend witness for the structural call TS already accepts. */
2523
- function projectStructuralCallArgsInTStmts(stmts, varName, fields) {
2524
- const sourceFields = fields.map(f => ({
2525
- ...f,
2526
- resolvedTy: f.type ?? parseTsType(f.tsType),
2527
- }));
2528
- return stmts.map(s => mapTStmt(s, e => {
2529
- if (e.kind !== "call" || !e.paramTys)
2530
- return null;
2531
- const paramTys = e.paramTys;
2532
- let changed = false;
2533
- const args = e.args.map((arg, i) => {
2534
- if (arg.kind !== "var" || arg.name !== varName || i >= paramTys.length)
2535
- return arg;
2536
- const targetTy = paramTys[i];
2537
- const targetDecl = declOfTy(_typeDecls, targetTy);
2538
- if (targetTy.kind !== "user" || targetDecl?.kind !== "record" || !targetDecl.fields)
2539
- return arg;
2540
- const matched = [];
2541
- for (const targetField of targetDecl.fields) {
2542
- const sourceField = sourceFields.find(f => f.name === targetField.name);
2543
- const targetFieldTy = targetField.type ?? parseTsType(targetField.tsType);
2544
- if (!sourceField || !tyEqual(sourceField.resolvedTy, targetFieldTy))
2545
- return arg;
2546
- matched.push({ targetField, sourceField });
2547
- }
2548
- changed = true;
2549
- return {
2550
- kind: "record",
2551
- spread: null,
2552
- fields: matched.map(m => ({
2553
- name: m.targetField.name,
2554
- value: {
2555
- kind: "var",
2556
- name: matchBinder(m.sourceField.name, varName),
2557
- ty: m.sourceField.resolvedTy,
2558
- },
2559
- })),
2560
- ty: targetTy,
2561
- };
2562
- });
2563
- return changed ? { ...e, args } : null;
2564
- }));
3074
+ const scrutinee = ef ? ef.scrutinee : transformExpr(s.expr);
3075
+ return { kind: "match", scrutinee, arms };
2565
3076
  }
2566
3077
  function asTAccessPath(e) {
2567
3078
  if (e.kind === "var")
@@ -2599,19 +3110,10 @@ function matchesAccessPath(e, path) {
2599
3110
  * leaves no binding that shadows another (see LexicalNames), so the name
2600
3111
  * identifies the variable, also inside a lambda that captures it. */
2601
3112
  function replacePathInTExpr(expr, path, binder, binderTy) {
2602
- return mapTExpr(expr, e => {
2603
- if (matchesAccessPath(e, path))
2604
- return { kind: "var", name: binder, ty: binderTy };
2605
- if (e.kind === "lambda")
2606
- return { ...e,
2607
- params: e.params.map(p => p.defaultValue
2608
- ? { ...p, defaultValue: replacePathInTExpr(p.defaultValue, path, binder, binderTy) } : p),
2609
- body: replacePathInTStmts(e.body, path, binder, binderTy) };
2610
- return null;
2611
- });
3113
+ return mapTExpr(expr, e => matchesAccessPath(e, path) ? { kind: "var", name: binder, ty: binderTy } : null);
2612
3114
  }
2613
3115
  function replacePathInTStmts(stmts, path, binder, binderTy) {
2614
- return stmts.map(s => mapTStmt(s, e => replacePathInTExpr(e, path, binder, binderTy)));
3116
+ return stmts.map(s => mapTStmt(s, e => matchesAccessPath(e, path) ? { kind: "var", name: binder, ty: binderTy } : null));
2615
3117
  }
2616
3118
  // ── Pure function generation ─────────────────────────────────
2617
3119
  function transformPureBody(stmts, typeDecls) {
@@ -2628,6 +3130,13 @@ function transformPureBody(stmts, typeDecls) {
2628
3130
  switch (s.kind) {
2629
3131
  case "return": return transformExpr(s.value);
2630
3132
  case "let": {
3133
+ // Mutating array methods (`pop`, `shift`) update the receiver in place
3134
+ // and cannot be lowered as a pure expression.
3135
+ if (s.init.kind === "call" && s.init.fn.kind === "field" &&
3136
+ (s.init.fn.field === "pop" || s.init.fn.field === "shift") &&
3137
+ s.init.fn.obj.ty.kind === "array") {
3138
+ return null;
3139
+ }
2631
3140
  const restExpr = transformPureBody(rest, typeDecls);
2632
3141
  if (!restExpr)
2633
3142
  return null;
@@ -2673,6 +3182,7 @@ function transformPureBody(stmts, typeDecls) {
2673
3182
  return null;
2674
3183
  }
2675
3184
  function transformPureSwitch(s, typeDecls) {
3185
+ s = withExplicitVariantDefault(s, typeDecls);
2676
3186
  const ef = enumFieldSwitch(s, typeDecls);
2677
3187
  if (ef) {
2678
3188
  const cases = s.cases.map(c => ({ name: c.label, body: c.body }));
@@ -2697,11 +3207,11 @@ function transformPureSwitch(s, typeDecls) {
2697
3207
  if (!ctorDecl)
2698
3208
  return null;
2699
3209
  const typeName = ctorDecl.name;
2700
- const varName = s.expr.kind === "var" ? s.expr.name : undefined;
3210
+ const varName = s.expr.kind === "var" ? s.expr.name
3211
+ : s.expr.kind === "checkedUnwrap" && s.expr.expr.kind === "var" ? s.expr.expr.name : undefined;
2701
3212
  const cases = s.cases.map(c => ({ name: c.label, body: c.body }));
2702
3213
  const arms = buildMatchArms(cases, varName, typeName, typeDecls, (body, vn, fields, ctorName) => {
2703
- const projected = vn ? projectStructuralCallArgsInTStmts(body, vn, fields) : body;
2704
- let result = transformPureBody(projected, typeDecls);
3214
+ let result = transformPureBody(body, typeDecls);
2705
3215
  if (!result)
2706
3216
  return null;
2707
3217
  if (fields.length > 0 && vn)
@@ -2716,6 +3226,8 @@ function transformPureSwitch(s, typeDecls) {
2716
3226
  return null;
2717
3227
  arms.push({ pattern: pWild(), body });
2718
3228
  }
3229
+ if (s.expr.kind === "checkedUnwrap")
3230
+ return { kind: "match", scrutinee: transformExpr(s.expr), arms };
2719
3231
  if (s.expr.kind !== "var")
2720
3232
  return null;
2721
3233
  return { kind: "match", scrutinee: varE(s.expr.name), arms };
@@ -2728,8 +3240,7 @@ function transformPureMatch(chain, typeDecls) {
2728
3240
  // the statement-level counterpart of this substitution.
2729
3241
  const isSynthArrayUnion = decl?.discriminant === "__isArray__";
2730
3242
  const arms = buildMatchArms(cases, chain.varName, chain.typeName, typeDecls, (body, vn, fields, ctorName) => {
2731
- const projected = vn ? projectStructuralCallArgsInTStmts(body, vn, fields) : body;
2732
- let result = transformPureBody(projected, typeDecls);
3243
+ let result = transformPureBody(body, typeDecls);
2733
3244
  if (!result)
2734
3245
  return null;
2735
3246
  if (fields.length > 0 && vn)
@@ -2746,11 +3257,10 @@ function transformPureMatch(chain, typeDecls) {
2746
3257
  // since Lean errors on redundant match arms.
2747
3258
  const allCovered = decl?.variants && chain.cases.length >= decl.variants.length;
2748
3259
  if (chain.fallthrough.length > 0 && !allCovered) {
2749
- const remaining = remainingVariant(chain.typeName, chain.cases, typeDecls);
3260
+ const remaining = remainingVariant(decl, chain.cases.map(c => c.variant));
2750
3261
  if (remaining) {
2751
3262
  // Exactly one variant left — destructure for variant-specific field access.
2752
- const projected = projectStructuralCallArgsInTStmts(chain.fallthrough, chain.varName, remaining.fields);
2753
- let body = transformPureBody(projected, typeDecls);
3263
+ let body = transformPureBody(chain.fallthrough, typeDecls);
2754
3264
  if (!body)
2755
3265
  return null;
2756
3266
  if (remaining.fields.length > 0)
@@ -2811,17 +3321,29 @@ function transformTypeDecl(d) {
2811
3321
  /** Find parameter names that are reassigned anywhere in the body. */
2812
3322
  function findReassignedNames(stmts, names) {
2813
3323
  const found = new Set();
3324
+ const markRoot = (root) => {
3325
+ if (root && names.has(root))
3326
+ found.add(root);
3327
+ };
2814
3328
  function scan(stmts) {
2815
3329
  for (const s of stmts) {
2816
- if (s.kind === "assign" && names.has(s.target))
2817
- found.add(s.target);
3330
+ if (s.kind === "assign") {
3331
+ markRoot(s.target.split(".")[0]);
3332
+ if (s.value.kind === "call" && s.value.fn.kind === "field" &&
3333
+ (s.value.fn.field === "pop" || s.value.fn.field === "shift") && s.value.fn.obj.ty.kind === "array") {
3334
+ markRoot(placeRootVar(s.value.fn.obj));
3335
+ }
3336
+ }
2818
3337
  if (s.kind === "ghostAssign" && names.has(s.target))
2819
3338
  found.add(s.target);
2820
- // Mutating collection calls: s.add(x), m.set(k,v), s.delete(x), arr.push(x)
3339
+ if (s.kind === "let" && s.init.kind === "call" && s.init.fn.kind === "field" &&
3340
+ (s.init.fn.field === "pop" || s.init.fn.field === "shift") && s.init.fn.obj.ty.kind === "array") {
3341
+ markRoot(placeRootVar(s.init.fn.obj));
3342
+ }
3343
+ // Mutating collection calls: s.add(x), m.set(k,v), s.delete(x), arr.push(x), b.items.pop()
2821
3344
  if (s.kind === "expr" && s.expr.kind === "call" && s.expr.fn.kind === "field" &&
2822
- s.expr.fn.obj.kind === "var" && names.has(s.expr.fn.obj.name) &&
2823
- ["add", "set", "delete", "push", "unshift"].includes(s.expr.fn.field)) {
2824
- found.add(s.expr.fn.obj.name);
3345
+ ["add", "set", "delete", "push", "unshift", "sort", "pop", "shift"].includes(s.expr.fn.field)) {
3346
+ markRoot(placeRootVar(s.expr.fn.obj));
2825
3347
  }
2826
3348
  if (s.kind === "if") {
2827
3349
  scan(s.then);
@@ -2836,6 +3358,15 @@ function findReassignedNames(stmts, names) {
2836
3358
  scan(c.body);
2837
3359
  scan(s.defaultBody);
2838
3360
  }
3361
+ if (s.kind === "someMatch") {
3362
+ scan(s.someBody);
3363
+ scan(s.noneBody);
3364
+ }
3365
+ if (s.kind === "tagMatch") {
3366
+ for (const c of s.cases)
3367
+ scan(c.body);
3368
+ scan(s.fallthrough);
3369
+ }
2839
3370
  }
2840
3371
  }
2841
3372
  scan(stmts);