lemmascript 0.6.12 → 0.6.14

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,7 +4,7 @@
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
10
  import { freshName } from "./names.js";
@@ -12,6 +12,7 @@ import { builtinSpec } from "./builtins.js";
12
12
  import { lowerIndexedCallback } from "./callback-lowering.js";
13
13
  import { isFalsyCapableTy } from "./condition-facts.js";
14
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";
15
16
  // ── Generic IR walkers ──────────────────────────────────────
16
17
  /**
17
18
  * Map over all sub-expressions in an Expr. `f` is called on each node;
@@ -43,6 +44,7 @@ function mapExpr(e, f) {
43
44
  case "toNat": return { ...e, expr: r(e.expr) };
44
45
  case "toInt": return { ...e, expr: r(e.expr) };
45
46
  case "toReal": return { ...e, expr: r(e.expr) };
47
+ case "checkedUnwrap": return { ...e, expr: r(e.expr) };
46
48
  case "index": return { ...e, arr: r(e.arr), idx: r(e.idx) };
47
49
  case "stringIndex": return { ...e, str: r(e.str), idx: r(e.idx) };
48
50
  case "tupleLiteral": return { ...e, elems: e.elems.map(r) };
@@ -113,6 +115,7 @@ function mapTExpr(e, f) {
113
115
  : s) };
114
116
  case "nullish": return { ...e, left: r(e.left), right: r(e.right) };
115
117
  case "someMatch": return { ...e, scrutinee: r(e.scrutinee), someBody: r(e.someBody), noneBody: r(e.noneBody) };
118
+ case "checkedUnwrap": return { ...e, expr: r(e.expr) };
116
119
  case "tagMatch": return { ...e, scrutinee: r(e.scrutinee),
117
120
  cases: e.cases.map(c => ({ ...c, body: r(c.body) })),
118
121
  fallthrough: e.fallthrough ? r(e.fallthrough) : null };
@@ -350,24 +353,75 @@ function asCondition(e) {
350
353
  return { kind: "binop", op: ">",
351
354
  left: { kind: "field", obj: e, field: "length", ty: { kind: "nat" } },
352
355
  right: { kind: "num", value: 0, ty: { kind: "nat" } }, ty: bool };
356
+ if (e.ty.kind === "void" || e.ty.kind === "null")
357
+ return { kind: "bool", value: false, ty: bool };
358
+ // Nullish<T> truthiness in `if (x)` / `while (x)` / `x ? a : b`:
359
+ // lower as `!(!x)` so `lowerExpr`'s nullish truthiness rule handles both
360
+ // falsy-capable inners (0, "", false) and always-truthy inners uniformly.
361
+ if (e.ty.kind === "nullish")
362
+ return { kind: "unop", op: "!", expr: { kind: "unop", op: "!", expr: e, ty: bool }, ty: bool };
353
363
  // Arrays, objects, maps, sets, tuples are always truthy in JS (even `[]`/`{}`).
354
364
  if (["array", "user", "map", "set", "tuple"].includes(e.ty.kind))
355
365
  return { kind: "bool", value: true, ty: bool };
356
366
  return e;
357
367
  }
358
368
  /** Wrap an expression in Some/None for optional-typed conditionals.
359
- * If the raw TExpr is `undefined`, emit `.none`; otherwise wrap in `Some`. */
369
+ * If the raw TExpr is `undefined`/`null`, emit `.none`; otherwise wrap in `Some`. */
360
370
  function wrapOptionalBranch(expr, raw) {
361
371
  // Set type: "Option" so Lean emits `Option.some`/`Option.none` (qualified).
362
372
  // The dotted form `.some`/`.none` would be ambiguous in expression positions
363
373
  // like the scrutinee of an outer match. Dafny treats `Option.Some` and bare
364
374
  // `Some` equivalently — the qualification is harmless there.
365
- if (raw.kind === "var" && raw.name === "undefined")
375
+ if (raw.kind === "var" && (raw.name === "undefined" || raw.name === "null"))
366
376
  return { kind: "constructor", name: "none", type: "Option", args: [] };
377
+ if (raw.ty.kind === "nullish" || (raw.ty.kind === "optional" && raw.ty.fromNullish)) {
378
+ const bound = matchBinder("value");
379
+ return {
380
+ kind: "match", scrutinee: expr,
381
+ arms: [
382
+ { pattern: pCtor("nullishValue", bound), body: { kind: "constructor", name: "some", type: "Option", args: [{ kind: "var", name: bound }] } },
383
+ { pattern: pCtor("nullishNull"), body: { kind: "constructor", name: "none", type: "Option", args: [] } },
384
+ { pattern: pCtor("nullishUndefined"), body: { kind: "constructor", name: "none", type: "Option", args: [] } },
385
+ ],
386
+ };
387
+ }
367
388
  if (raw.ty.kind === "optional")
368
389
  return expr; // already Option<T>, don't double-wrap
369
390
  return { kind: "constructor", name: "some", type: "Option", args: [expr] };
370
391
  }
392
+ /** Wrap an expression in Nullish.Undefined / Nullish.Null / Nullish.Value for
393
+ * nullish-typed conditionals and matches (#304). */
394
+ function wrapNullishBranch(expr, raw) {
395
+ if (raw.kind === "var" && raw.name === "undefined") {
396
+ return { kind: "constructor", name: "nullishUndefined", type: "Nullish", args: [] };
397
+ }
398
+ if (raw.kind === "var" && raw.name === "null") {
399
+ return { kind: "constructor", name: "nullishNull", type: "Nullish", args: [] };
400
+ }
401
+ if (raw.ty.kind === "nullish" || (raw.ty.kind === "optional" && raw.ty.fromNullish))
402
+ return expr;
403
+ if (expr.kind === "if" && raw.kind === "conditional" && raw.ty.kind !== "optional") {
404
+ return { ...expr, then: wrapNullishBranch(expr.then, raw.then), else: wrapNullishBranch(expr.else, raw.else) };
405
+ }
406
+ if (raw.ty.kind === "optional") {
407
+ const bound = matchBinder("value");
408
+ const noneCtor = optAbsent(raw.ty) === "null" ? "nullishNull" : "nullishUndefined";
409
+ return {
410
+ kind: "match", scrutinee: expr,
411
+ arms: [
412
+ { pattern: pCtor("some", bound), body: { kind: "constructor", name: "nullishValue", type: "Nullish", args: [{ kind: "var", name: bound }] } },
413
+ { pattern: pCtor("none"), body: { kind: "constructor", name: noneCtor, type: "Nullish", args: [] } },
414
+ ],
415
+ };
416
+ }
417
+ return { kind: "constructor", name: "nullishValue", type: "Nullish", args: [expr] };
418
+ }
419
+ function wrapCheckedUnwrapValue(expr, storageTy) {
420
+ if (storageTy.kind === "nullish") {
421
+ return { kind: "constructor", name: "nullishValue", type: "Nullish", args: [expr] };
422
+ }
423
+ return { kind: "app", fn: "Some", args: [expr] };
424
+ }
371
425
  /** Lean needs `let mut` for any local that is later reassigned. A const local
372
426
  * whose collection field is mutated (`b.items.push(v)` → `b := b.(items := …)`)
373
427
  * becomes an assign in the lowered body, so scan for assign targets and flip
@@ -406,7 +460,9 @@ function promoteAssignedLets(stmts) {
406
460
  }
407
461
  /** Build a nested record-update assigning `newVal` to a field-path receiver
408
462
  * rooted at a var: `b.a.items` → `b := b.(a := b.a.(items := newVal))`.
409
- * Returns null if the path isn't a chain of field accesses ending at a var. */
463
+ * Handles `checkedUnwrap` hops along the path by wrapping the updated record
464
+ * in `Some(...)`. Returns null if the path isn't a chain of field accesses
465
+ * (with optional checked unwraps) ending at a var. */
410
466
  function buildNestedFieldUpdate(recv, newVal) {
411
467
  if (recv.kind !== "field")
412
468
  return null;
@@ -415,6 +471,13 @@ function buildNestedFieldUpdate(recv, newVal) {
415
471
  return { root: recv.obj.name, value: upd };
416
472
  if (recv.obj.kind === "field")
417
473
  return buildNestedFieldUpdate(recv.obj, upd);
474
+ if (recv.obj.kind === "checkedUnwrap") {
475
+ const wrapped = wrapCheckedUnwrapValue(upd, recv.obj.expr.ty);
476
+ if (recv.obj.expr.kind === "var")
477
+ return { root: recv.obj.expr.name, value: wrapped };
478
+ if (recv.obj.expr.kind === "field")
479
+ return buildNestedFieldUpdate(recv.obj.expr, wrapped);
480
+ }
418
481
  return null;
419
482
  }
420
483
  /** Promote every spread segment before concatenation, preserving evaluation
@@ -467,7 +530,18 @@ function lowerExpr(e, binds) {
467
530
  return { kind: "var", name };
468
531
  }
469
532
  switch (e.kind) {
470
- case "var": return { kind: "var", name: e.name };
533
+ case "var":
534
+ if (e.name === "undefined") {
535
+ if (e.ty.kind === "nullish")
536
+ return { kind: "constructor", name: "nullishUndefined", type: "Nullish", args: [] };
537
+ return { kind: "var", name: "undefined" };
538
+ }
539
+ if (e.name === "null") {
540
+ if (e.ty.kind === "nullish")
541
+ return { kind: "constructor", name: "nullishNull", type: "Nullish", args: [] };
542
+ return { kind: "var", name: "undefined" };
543
+ }
544
+ return { kind: "var", name: e.name };
471
545
  case "num": {
472
546
  const literal = { kind: "num", value: e.value };
473
547
  return e.ty.kind === "real" && Number.isInteger(e.value)
@@ -489,6 +563,43 @@ function lowerExpr(e, binds) {
489
563
  // String truthiness: !str → str == ""
490
564
  if (e.op === "!" && e.expr.ty.kind === "string")
491
565
  return { kind: "binop", op: "=", left: lowerExpr(e.expr, binds), right: { kind: "str", value: "" } };
566
+ // Double negation of Nullish<T> (synthesized by asCondition for `if (x)`):
567
+ // true iff `x` is Value(v) and `v` is truthy.
568
+ if (e.op === "!" && e.expr.kind === "unop" && e.expr.op === "!" && e.expr.expr.ty.kind === "nullish") {
569
+ const inner = e.expr.expr;
570
+ const innerTy = e.expr.expr.ty;
571
+ const innerExpr = lowerExpr(inner, binds);
572
+ const bound = matchBinder("value");
573
+ const truthy = valueTruthyCond({ kind: "var", name: bound }, innerTy.inner);
574
+ if (!truthy) {
575
+ return { kind: "methodCall", obj: innerExpr, objTy: innerTy, method: "isValue", args: [], monadic: false };
576
+ }
577
+ return {
578
+ kind: "match", scrutinee: innerExpr,
579
+ arms: [
580
+ { pattern: pCtor("nullishValue", bound), body: truthy },
581
+ { pattern: pCtor("nullishNull"), body: { kind: "bool", value: false } },
582
+ { pattern: pCtor("nullishUndefined"), body: { kind: "bool", value: false } },
583
+ ],
584
+ };
585
+ }
586
+ // Nullish<T> truthiness: !x → true on Null/Undefined; on Value(v), !(truthy v).
587
+ if (e.op === "!" && e.expr.ty.kind === "nullish") {
588
+ const innerExpr = lowerExpr(e.expr, binds);
589
+ const bound = matchBinder("value");
590
+ const truthy = valueTruthyCond({ kind: "var", name: bound }, e.expr.ty.inner);
591
+ if (!truthy) {
592
+ return { kind: "unop", op: "¬", expr: { kind: "methodCall", obj: innerExpr, objTy: e.expr.ty, method: "isValue", args: [], monadic: false } };
593
+ }
594
+ return {
595
+ kind: "match", scrutinee: innerExpr,
596
+ arms: [
597
+ { pattern: pCtor("nullishValue", bound), body: { kind: "unop", op: "¬", expr: truthy } },
598
+ { pattern: pCtor("nullishNull"), body: { kind: "bool", value: true } },
599
+ { pattern: pCtor("nullishUndefined"), body: { kind: "bool", value: true } },
600
+ ],
601
+ };
602
+ }
492
603
  // Optional truthiness: !opt → None negates to `true`. The Some branch is
493
604
  // `!(value truthy)`: always-truthy inners (array/user) give a plain `false`,
494
605
  // while falsy-capable inners re-test the wrapped value (`!Some(0)` is `true`).
@@ -547,10 +658,21 @@ function lowerExpr(e, binds) {
547
658
  right: { kind: "constructor", name: e.right.value, type: objTy, args: [] },
548
659
  };
549
660
  }
661
+ // Literal null/undefined comparison (e.g. `null === undefined` → false,
662
+ // `null == undefined` → true, `null === null` → true).
663
+ if (["===", "!==", "==", "!="].includes(e.op) &&
664
+ e.left.kind === "var" && (e.left.name === "null" || e.left.name === "undefined") &&
665
+ e.right.kind === "var" && (e.right.name === "null" || e.right.name === "undefined")) {
666
+ const isLoose = e.op === "==" || e.op === "!=";
667
+ const eq = isLoose ? true : e.left.name === e.right.name;
668
+ const res = (e.op === "===" || e.op === "==") ? eq : !eq;
669
+ return { kind: "bool", value: res };
670
+ }
550
671
  // String literal comparison — constructor if user type, string literal if string.
551
- // Skip when the left is optional: fall through to the optional-comparison rule,
552
- // which unwraps and compares the inner value (`Some(v) => v == "")`.
553
- if ((e.op === "===" || e.op === "!==") && e.right.kind === "str" && e.left.ty.kind !== "optional") {
672
+ // Skip when the left is optional/nullish: fall through to the nullable-comparison rules,
673
+ // which unwrap and compare the inner value (`Some(v) => v == ""`).
674
+ if ((e.op === "===" || e.op === "!==") && e.right.kind === "str" &&
675
+ e.left.ty.kind !== "optional" && e.left.ty.kind !== "nullish") {
554
676
  const left = lowerExpr(e.left, binds);
555
677
  const leftTy = e.left.ty.kind === "user" ? e.left.ty.name : undefined;
556
678
  const right = isUser(e.left.ty)
@@ -558,19 +680,161 @@ function lowerExpr(e, binds) {
558
680
  : { kind: "str", value: e.right.value };
559
681
  return { kind: "binop", op: e.op === "===" ? "=" : "≠", left, right };
560
682
  }
683
+ // Two-sided nullable equality/inequality rules (#304):
684
+ // 1. Opposite-sentinel Option<T> (`T | null` vs `T | undefined`) under ===/!==:
685
+ // None vs None is false for === (null !== undefined).
686
+ // 2. Nullish<T> vs Nullish<T> under loose ==/!=:
687
+ // Null vs Undefined is true for == (null == undefined).
688
+ // 3. Nullish<T> vs Option<T> under ===/!==/==/!=:
689
+ // Nested match comparing Value/Some, plus sentinel match on Null/Undefined vs None.
690
+ if (["===", "!==", "==", "!="].includes(e.op)) {
691
+ const isLoose = e.op === "==" || e.op === "!=";
692
+ const isEq = e.op === "===" || e.op === "==";
693
+ const cmpOp = isEq ? "=" : "≠";
694
+ if (!isLoose && e.left.ty.kind === "optional" && e.right.ty.kind === "optional" &&
695
+ optAbsent(e.left.ty) !== optAbsent(e.right.ty)) {
696
+ const lExpr = lowerExpr(e.left, binds);
697
+ const rExpr = lowerExpr(e.right, binds);
698
+ const lv = matchBinder("lv");
699
+ const rv = matchBinder("rv");
700
+ return {
701
+ kind: "match", scrutinee: lExpr,
702
+ arms: [
703
+ { pattern: pCtor("some", lv), body: {
704
+ kind: "match", scrutinee: rExpr,
705
+ arms: [
706
+ { pattern: pCtor("some", rv), body: { kind: "binop", op: cmpOp, left: { kind: "var", name: lv }, right: { kind: "var", name: rv } } },
707
+ { pattern: pCtor("none"), body: { kind: "bool", value: !isEq } },
708
+ ],
709
+ } },
710
+ { pattern: pCtor("none"), body: { kind: "bool", value: !isEq } },
711
+ ],
712
+ };
713
+ }
714
+ if (isLoose && e.left.ty.kind === "nullish" && e.right.ty.kind === "nullish") {
715
+ const lExpr = lowerExpr(e.left, binds);
716
+ const rExpr = lowerExpr(e.right, binds);
717
+ const lv = matchBinder("lv");
718
+ const rv = matchBinder("rv");
719
+ const absentArm = {
720
+ kind: "match", scrutinee: rExpr,
721
+ arms: [
722
+ { pattern: pCtor("nullishValue", "_"), body: { kind: "bool", value: !isEq } },
723
+ { pattern: pCtor("nullishNull"), body: { kind: "bool", value: isEq } },
724
+ { pattern: pCtor("nullishUndefined"), body: { kind: "bool", value: isEq } },
725
+ ],
726
+ };
727
+ return {
728
+ kind: "match", scrutinee: lExpr,
729
+ arms: [
730
+ { pattern: pCtor("nullishValue", lv), body: {
731
+ kind: "match", scrutinee: rExpr,
732
+ arms: [
733
+ { pattern: pCtor("nullishValue", rv), body: { kind: "binop", op: cmpOp, left: { kind: "var", name: lv }, right: { kind: "var", name: rv } } },
734
+ { pattern: pCtor("nullishNull"), body: { kind: "bool", value: !isEq } },
735
+ { pattern: pCtor("nullishUndefined"), body: { kind: "bool", value: !isEq } },
736
+ ],
737
+ } },
738
+ { pattern: pCtor("nullishNull"), body: absentArm },
739
+ { pattern: pCtor("nullishUndefined"), body: absentArm },
740
+ ],
741
+ };
742
+ }
743
+ if ((e.left.ty.kind === "nullish" && e.right.ty.kind === "optional") ||
744
+ (e.left.ty.kind === "optional" && e.right.ty.kind === "nullish")) {
745
+ const [nulSide, optSide] = e.left.ty.kind === "nullish" ? [e.left, e.right] : [e.right, e.left];
746
+ const nulExpr = lowerExpr(nulSide, binds);
747
+ const optExpr = lowerExpr(optSide, binds);
748
+ const optAbs = optAbsent(optSide.ty);
749
+ const nv = matchBinder("nv");
750
+ const ov = matchBinder("ov");
751
+ const nullMatchesNone = isLoose || optAbs === "null";
752
+ const undefMatchesNone = isLoose || optAbs === "undefined";
753
+ const makeAbsentArm = (matchesNone) => ({
754
+ kind: "match", scrutinee: optExpr,
755
+ arms: [
756
+ { pattern: pCtor("some", "_"), body: { kind: "bool", value: !isEq } },
757
+ { pattern: pCtor("none"), body: { kind: "bool", value: isEq ? matchesNone : !matchesNone } },
758
+ ],
759
+ });
760
+ return {
761
+ kind: "match", scrutinee: nulExpr,
762
+ arms: [
763
+ { pattern: pCtor("nullishValue", nv), body: {
764
+ kind: "match", scrutinee: optExpr,
765
+ arms: [
766
+ { pattern: pCtor("some", ov), body: { kind: "binop", op: cmpOp, left: { kind: "var", name: nv }, right: { kind: "var", name: ov } } },
767
+ { pattern: pCtor("none"), body: { kind: "bool", value: !isEq } },
768
+ ],
769
+ } },
770
+ { pattern: pCtor("nullishNull"), body: makeAbsentArm(nullMatchesNone) },
771
+ { pattern: pCtor("nullishUndefined"), body: makeAbsentArm(undefMatchesNone) },
772
+ ],
773
+ };
774
+ }
775
+ }
776
+ // Nullish<T> comparison against null / undefined / non-nullish value (#304).
777
+ if (["===", "!==", "==", "!=", ">=", "<=", ">", "<"].includes(e.op) &&
778
+ (e.left.ty.kind === "nullish") !== (e.right.ty.kind === "nullish")) {
779
+ const [nulSide, valSide] = e.left.ty.kind === "nullish" ? [e.left, e.right] : [e.right, e.left];
780
+ const nulExpr = lowerExpr(nulSide, binds);
781
+ const nulTy = nulSide.ty;
782
+ if (valSide.kind === "var" && (valSide.name === "undefined" || valSide.name === "null")) {
783
+ const isLoose = e.op === "==" || e.op === "!=";
784
+ const isEq = e.op === "===" || e.op === "==";
785
+ if (isLoose) {
786
+ // x == null / x == undefined → !x.isValue; x != null / x != undefined → x.isValue
787
+ const isVal = { kind: "methodCall", obj: nulExpr, objTy: nulTy, method: "isValue", args: [], monadic: false };
788
+ return isEq ? { kind: "unop", op: "¬", expr: isVal } : isVal;
789
+ }
790
+ const pred = {
791
+ kind: "methodCall", obj: nulExpr, objTy: nulTy,
792
+ method: valSide.name === "null" ? "isNull" : "isUndefined", args: [], monadic: false,
793
+ };
794
+ return isEq ? pred : { kind: "unop", op: "¬", expr: pred };
795
+ }
796
+ const innerTy = nulTy.inner;
797
+ const valExpr = valSide.kind === "str" && innerTy.kind === "user"
798
+ ? { kind: "constructor", name: valSide.value, type: innerTy.name, args: [] }
799
+ : lowerExpr(valSide, binds);
800
+ const op = e.left.ty.kind === "nullish" ? e.op : MIRROR_OP[e.op] ?? e.op;
801
+ const cmpOp = BOOL_OP_MAP[op] ?? op;
802
+ const absentVal = (e.op === "!==" || e.op === "!=") ? true : false;
803
+ const bound = matchBinder("value");
804
+ const makeNullishCmpMatch = (rhs) => ({
805
+ kind: "match", scrutinee: nulExpr,
806
+ arms: [
807
+ { pattern: pCtor("nullishValue", bound), body: { kind: "binop", op: cmpOp, left: { kind: "var", name: bound }, right: rhs } },
808
+ { pattern: pCtor("nullishNull"), body: { kind: "bool", value: absentVal } },
809
+ { pattern: pCtor("nullishUndefined"), body: { kind: "bool", value: absentVal } },
810
+ ],
811
+ });
812
+ if (!_inSpec && valExpr.kind !== "var" && hasPreconditionExpr(valSide)) {
813
+ const tmp = freshName(`_cmp${_cmpCounter++}`);
814
+ return { kind: "let", name: tmp, value: valExpr, body: makeNullishCmpMatch({ kind: "var", name: tmp }) };
815
+ }
816
+ return makeNullishCmpMatch(valExpr);
817
+ }
561
818
  // Optional comparison: optExpr op val → match optExpr { Some(v) => v op val, None => false/true }
562
- if (["===", "!==", ">=", "<=", ">", "<"].includes(e.op) &&
819
+ if (["===", "!==", "==", "!=", ">=", "<=", ">", "<"].includes(e.op) &&
563
820
  (e.left.ty.kind === "optional") !== (e.right.ty.kind === "optional")) {
564
821
  const [optSide, valSide] = e.left.ty.kind === "optional" ? [e.left, e.right] : [e.right, e.left];
565
822
  const optExpr = lowerExpr(optSide, binds);
566
- // x === undefined → None?, x !== undefined → Some?
567
- if (valSide.kind === "var" && valSide.name === "undefined") {
568
- const isNone = e.op === "===";
823
+ const optTy = optSide.ty;
824
+ // x === undefined / x === null / loose x == null / x == undefined
825
+ if (valSide.kind === "var" && (valSide.name === "undefined" || valSide.name === "null")) {
826
+ const isLoose = e.op === "==" || e.op === "!=";
827
+ const isEq = e.op === "===" || e.op === "==";
828
+ // Strict comparison against the OTHER sentinel (`x: T | undefined; x === null`
829
+ // or `x: T | null; x === undefined`) is always false (and `!==` is always true).
830
+ if (!isLoose && valSide.name !== optAbsent(optTy)) {
831
+ return { kind: "bool", value: !isEq };
832
+ }
569
833
  return {
570
834
  kind: "match", scrutinee: optExpr,
571
835
  arms: [
572
- { pattern: pCtor("some", "_"), body: { kind: "bool", value: !isNone } },
573
- { pattern: pCtor("none"), body: { kind: "bool", value: isNone } },
836
+ { pattern: pCtor("some", "_"), body: { kind: "bool", value: !isEq } },
837
+ { pattern: pCtor("none"), body: { kind: "bool", value: isEq } },
574
838
  ],
575
839
  };
576
840
  }
@@ -581,12 +845,34 @@ function lowerExpr(e, binds) {
581
845
  const valExpr = valSide.kind === "str" && innerTy.kind === "user"
582
846
  ? { kind: "constructor", name: valSide.value, type: innerTy.name, args: [] }
583
847
  : lowerExpr(valSide, binds);
584
- // The bound value goes on the left, so mirror the operator when the
585
- // optional was on the right: `x < opt` → `Some(v) => v > x`.
848
+ // Precondition preservation (#349): JavaScript evaluates BOTH operands of
849
+ // `===`, `!==`, `<`, `<=`, `>`, `>=` unconditionally. When `valSide` can
850
+ // carry preconditions (calls, indexing, checked reads, div/mod), bind
851
+ // `valExpr` in a `let` BEFORE matching `optExpr` so:
852
+ // 1. Every precondition in `valSide` is checked even when `optExpr` is `None`.
853
+ // 2. Comparing `bound op _cmp` unwrapped inside `Some` preserves Z3's
854
+ // sequence/map extensionality triggers (unlike `opt == Some(val)`).
855
+ // Pure comparisons (e.g. `res.truncatedBy === "bytes"` in pi-lemmascript)
856
+ // skip the `let` binding completely (zero temporary churn).
586
857
  const op = e.left.ty.kind === "optional" ? e.op : MIRROR_OP[e.op] ?? e.op;
587
858
  const cmpOp = BOOL_OP_MAP[op] ?? op;
588
- const noneVal = e.op === "!==" ? true : false;
859
+ const noneVal = (e.op === "!==" || e.op === "!=") ? true : false;
589
860
  const bound = matchBinder("value");
861
+ if (!_inSpec && valExpr.kind !== "var" && hasPreconditionExpr(valSide)) {
862
+ const tmp = freshName(`_cmp${_cmpCounter++}`);
863
+ return {
864
+ kind: "let",
865
+ name: tmp,
866
+ value: valExpr,
867
+ body: {
868
+ kind: "match", scrutinee: optExpr,
869
+ arms: [
870
+ { pattern: pCtor("some", bound), body: { kind: "binop", op: cmpOp, left: { kind: "var", name: bound }, right: { kind: "var", name: tmp } } },
871
+ { pattern: pCtor("none"), body: { kind: "bool", value: noneVal } },
872
+ ],
873
+ },
874
+ };
875
+ }
590
876
  return {
591
877
  kind: "match", scrutinee: optExpr,
592
878
  arms: [
@@ -595,12 +881,27 @@ function lowerExpr(e, binds) {
595
881
  ],
596
882
  };
597
883
  }
598
- // || undefined on optional → identity (no-op: x || undefined = x) when the
884
+ // Definite non-nullable value compared against `null` or `undefined`
885
+ // (e.g. `x === null` inside a `someMatch` body where `x` was already unwrapped
886
+ // to `int`): constant-fold to `false` (for ===/==) or `true` (for !==/!=)
887
+ // while preserving any side-effecting lifts in the non-sentinel operand.
888
+ if (["===", "!==", "==", "!="].includes(e.op)) {
889
+ const isSentinel = (x) => x.kind === "var" && (x.name === "null" || x.name === "undefined");
890
+ if (isSentinel(e.left) !== isSentinel(e.right)) {
891
+ const other = isSentinel(e.left) ? e.right : e.left;
892
+ const k = other.ty.kind;
893
+ if (k !== "optional" && k !== "nullish" && k !== "unknown" && k !== "void" && k !== "null") {
894
+ lowerExpr(other, binds);
895
+ return { kind: "bool", value: e.op === "!==" || e.op === "!=" };
896
+ }
897
+ }
898
+ }
899
+ // || undefined / || null on optional → identity (no-op: x || undefined = x) when the
599
900
  // inner type is always truthy. When it can be falsy, JS still drops the
600
901
  // wrapped value: `Some(0) || undefined === undefined`, so the Some arm
601
902
  // re-tests and falls back to None.
602
903
  if (e.op === "||" && e.left.ty.kind === "optional" &&
603
- e.right.kind === "var" && e.right.name === "undefined") {
904
+ e.right.kind === "var" && (e.right.name === "undefined" || e.right.name === "null")) {
604
905
  const optExpr = lowerExpr(e.left, binds);
605
906
  const bound = matchBinder("value");
606
907
  const truthy = valueTruthyCond({ kind: "var", name: bound }, e.left.ty.inner);
@@ -618,6 +919,29 @@ function lowerExpr(e, binds) {
618
919
  ],
619
920
  };
620
921
  }
922
+ // || on nullish → 3-arm match Value/Null/Undefined with default.
923
+ if (e.op === "||" && e.left.ty.kind === "nullish") {
924
+ const nulExpr = lowerExpr(e.left, binds);
925
+ const defaultExpr = lowerExpr(e.right, binds);
926
+ const bound = matchBinder("value");
927
+ const truthy = valueTruthyCond({ kind: "var", name: bound }, e.left.ty.inner);
928
+ const valPresent = e.ty.kind === "nullish"
929
+ ? { kind: "constructor", name: "nullishValue", type: "Nullish", args: [{ kind: "var", name: bound }] }
930
+ : e.ty.kind === "optional"
931
+ ? { kind: "constructor", name: "some", type: "Option", args: [{ kind: "var", name: bound }] }
932
+ : { kind: "var", name: bound };
933
+ const someBody = truthy
934
+ ? { kind: "if", cond: truthy, then: valPresent, else: defaultExpr }
935
+ : valPresent;
936
+ return {
937
+ kind: "match", scrutinee: nulExpr,
938
+ arms: [
939
+ { pattern: pCtor("nullishValue", bound), body: someBody },
940
+ { pattern: pCtor("nullishNull"), body: defaultExpr },
941
+ { pattern: pCtor("nullishUndefined"), body: defaultExpr },
942
+ ],
943
+ };
944
+ }
621
945
  // || on optional → match Some/None with default. JS `||` tests falsiness of
622
946
  // the *unwrapped* value, so when the inner type can be falsy the Some arm must
623
947
  // re-test (`Some(0) || 1 === 1`); array/user inners are always truthy and
@@ -668,8 +992,8 @@ function lowerExpr(e, binds) {
668
992
  (e.left.ty.kind === "user" && e.right.ty.kind === "string"))) {
669
993
  const left = lowerExpr(e.left, binds);
670
994
  const right = lowerExpr(e.right, binds);
671
- // `s || undefined` produces `Option<string>` — wrap the truthy branch in Some.
672
- const rightIsUndef = e.right.kind === "var" && e.right.name === "undefined";
995
+ // `s || undefined` / `s || null` produces `Option<string>` — wrap the truthy branch in Some.
996
+ const rightIsUndef = e.right.kind === "var" && (e.right.name === "undefined" || e.right.name === "null");
673
997
  return {
674
998
  kind: "if",
675
999
  // strings carry the `length` marker — it renders to `|x|` in Dafny and
@@ -679,12 +1003,12 @@ function lowerExpr(e, binds) {
679
1003
  else: right,
680
1004
  };
681
1005
  }
682
- // `bool || undefined` → `if bool then Some(bool) else None`. Used in
1006
+ // `bool || undefined` / `bool || null` → `if bool then Some(bool) else None`. Used in
683
1007
  // optional-field initialization where the source assigns a truthy/false
684
1008
  // bool to a `T?` field. Without this, emit produces `bool || None`,
685
1009
  // which Dafny rejects (bool || Option<?> is ill-typed).
686
1010
  if (e.op === "||" && e.left.ty.kind === "bool" &&
687
- e.right.kind === "var" && e.right.name === "undefined") {
1011
+ e.right.kind === "var" && (e.right.name === "undefined" || e.right.name === "null")) {
688
1012
  const left = lowerExpr(e.left, binds);
689
1013
  return {
690
1014
  kind: "if",
@@ -1034,6 +1358,32 @@ function lowerExpr(e, binds) {
1034
1358
  }
1035
1359
  if (e.fn.kind !== "var")
1036
1360
  throw new Error(`Unsupported call expression: ${e.fn.kind}`);
1361
+ // Synthetic Nullish<T> constructors and widening/narrowing helpers (#304).
1362
+ if (e.fn.name === "NullishValue" && e.args.length === 1) {
1363
+ return { kind: "constructor", name: "nullishValue", type: "Nullish", args: [lowerExpr(e.args[0], binds)] };
1364
+ }
1365
+ if ((e.fn.name === "__optUndefToNullish" || e.fn.name === "__optNullToNullish") && e.args.length === 1) {
1366
+ const bound = matchBinder("value");
1367
+ const noneCtor = e.fn.name === "__optNullToNullish" ? "nullishNull" : "nullishUndefined";
1368
+ return {
1369
+ kind: "match", scrutinee: lowerExpr(e.args[0], binds),
1370
+ arms: [
1371
+ { pattern: pCtor("some", bound), body: { kind: "constructor", name: "nullishValue", type: "Nullish", args: [{ kind: "var", name: bound }] } },
1372
+ { pattern: pCtor("none"), body: { kind: "constructor", name: noneCtor, type: "Nullish", args: [] } },
1373
+ ],
1374
+ };
1375
+ }
1376
+ if (e.fn.name === "__nullishToOption" && e.args.length === 1) {
1377
+ const bound = matchBinder("value");
1378
+ return {
1379
+ kind: "match", scrutinee: lowerExpr(e.args[0], binds),
1380
+ arms: [
1381
+ { pattern: pCtor("nullishValue", bound), body: { kind: "constructor", name: "some", type: "Option", args: [{ kind: "var", name: bound }] } },
1382
+ { pattern: pCtor("nullishNull"), body: { kind: "constructor", name: "none", type: "Option", args: [] } },
1383
+ { pattern: pCtor("nullishUndefined"), body: { kind: "constructor", name: "none", type: "Option", args: [] } },
1384
+ ],
1385
+ };
1386
+ }
1037
1387
  const prefix = e.callKind === "spec-pure" && _opts.backend === "lean" ? "Pure." : "";
1038
1388
  return { kind: "app", fn: prefix + e.fn.name, args: e.args.map(a => lowerExpr(a, binds)) };
1039
1389
  }
@@ -1065,7 +1415,12 @@ function lowerExpr(e, binds) {
1065
1415
  // `Result.true_` is valid in Lean; `Result<Model,Err>.true_` is not.
1066
1416
  const args = variant.fields.map(vf => {
1067
1417
  const ef = nonDiscFields.find(f => f.name === vf.name);
1068
- return ef ? lowerExpr(ef.value, binds) : { kind: "var", name: "None" };
1418
+ if (ef)
1419
+ return lowerExpr(ef.value, binds);
1420
+ if (vf.type?.kind === "nullish") {
1421
+ return { kind: "constructor", name: "nullishUndefined", type: "Nullish", args: [] };
1422
+ }
1423
+ return { kind: "var", name: "None" };
1069
1424
  });
1070
1425
  return { kind: "app", fn: variantName, args, ctorOf: baseName };
1071
1426
  }
@@ -1100,13 +1455,16 @@ function lowerExpr(e, binds) {
1100
1455
  fieldValue = { ...fieldValue, ty: declaredTy };
1101
1456
  }
1102
1457
  let value = lowerExpr(fieldValue, binds);
1103
- // Wrap non-optional values in Some for optional fields
1458
+ // Wrap non-optional/non-nullish values for optional/nullish fields
1104
1459
  if (declaredTy?.kind === "optional") {
1105
- const isUndef = f.value.kind === "var" && f.value.name === "undefined";
1460
+ const isUndef = f.value.kind === "var" && (f.value.name === "undefined" || f.value.name === "null");
1106
1461
  if (f.value.ty.kind !== "optional" && !isUndef) {
1107
1462
  value = { kind: "app", fn: "Some", args: [value] };
1108
1463
  }
1109
1464
  }
1465
+ else if (declaredTy?.kind === "nullish") {
1466
+ value = wrapNullishBranch(value, f.value);
1467
+ }
1110
1468
  return { name: f.name, value };
1111
1469
  });
1112
1470
  return { kind: "record", spread: lowerExpr(e.spread, binds), fields: loweredFields };
@@ -1183,6 +1541,10 @@ function lowerExpr(e, binds) {
1183
1541
  thenExpr = wrapOptionalBranch(thenExpr, e.then);
1184
1542
  elseExpr = wrapOptionalBranch(elseExpr, e.else);
1185
1543
  }
1544
+ else if (e.ty.kind === "nullish") {
1545
+ thenExpr = wrapNullishBranch(thenExpr, e.then);
1546
+ elseExpr = wrapNullishBranch(elseExpr, e.else);
1547
+ }
1186
1548
  if (binds && (thenBinds?.length || elseBinds?.length)) {
1187
1549
  const name = freshName(`_branch${_branchCounter++}`);
1188
1550
  // Both arms assign before the result is read. This initializer is not
@@ -1196,12 +1558,69 @@ function lowerExpr(e, binds) {
1196
1558
  }
1197
1559
  return { kind: "if", cond, then: thenExpr, else: elseExpr };
1198
1560
  }
1199
- case "optChain":
1200
- // Narrow should have rewritten optChain to someMatch.
1561
+ case "optChain": {
1562
+ if (e.obj.ty.kind === "nullish") {
1563
+ const scrutinee = lowerExpr(e.obj, binds);
1564
+ const binder = freshName(`_oc${_liftCounter++}_val`);
1565
+ let bodyT = { kind: "var", name: binder, ty: e.obj.ty.inner };
1566
+ for (const step of e.chain) {
1567
+ if (step.kind === "field")
1568
+ bodyT = { kind: "field", obj: bodyT, field: step.name, ty: step.ty };
1569
+ else if (step.kind === "index")
1570
+ bodyT = { kind: "index", obj: bodyT, idx: step.idx, ty: step.ty };
1571
+ else
1572
+ bodyT = { kind: "call", fn: bodyT, args: step.args, ty: step.ty, callKind: step.callKind,
1573
+ ...(step.builtinId ? { builtinId: step.builtinId } : {}) };
1574
+ }
1575
+ let valBody = lowerExpr(bodyT, binds);
1576
+ let absentBody;
1577
+ if (e.ty.kind === "nullish") {
1578
+ valBody = wrapNullishBranch(valBody, bodyT);
1579
+ absentBody = { kind: "constructor", name: "nullishUndefined", type: "Nullish", args: [] };
1580
+ }
1581
+ else {
1582
+ valBody = wrapOptionalBranch(valBody, bodyT);
1583
+ absentBody = { kind: "constructor", name: "none", type: "Option", args: [] };
1584
+ }
1585
+ return {
1586
+ kind: "match", scrutinee,
1587
+ arms: [
1588
+ { pattern: pCtor("nullishValue", binder), body: valBody },
1589
+ { pattern: pCtor("nullishNull"), body: absentBody },
1590
+ { pattern: pCtor("nullishUndefined"), body: absentBody },
1591
+ ],
1592
+ };
1593
+ }
1594
+ // Narrow should have rewritten non-nullish optChain to someMatch.
1201
1595
  throw new Error(`optChain reached transform — narrow should have rewritten it: ${JSON.stringify(e).slice(0, 400)}`);
1202
- case "nullish":
1203
- // Narrow should have rewritten nullish to someMatch.
1596
+ }
1597
+ case "nullish": {
1598
+ if (e.left.ty.kind === "nullish") {
1599
+ const scrutinee = lowerExpr(e.left, binds);
1600
+ const binder = freshName(`_oc${_liftCounter++}_val`);
1601
+ const rawBinder = { kind: "var", name: binder, ty: e.left.ty.inner };
1602
+ let valBody = { kind: "var", name: binder };
1603
+ let rightBody = lowerExpr(e.right, binds);
1604
+ if (e.ty.kind === "optional") {
1605
+ valBody = wrapOptionalBranch(valBody, rawBinder);
1606
+ rightBody = wrapOptionalBranch(rightBody, e.right);
1607
+ }
1608
+ else if (e.ty.kind === "nullish") {
1609
+ valBody = wrapNullishBranch(valBody, rawBinder);
1610
+ rightBody = wrapNullishBranch(rightBody, e.right);
1611
+ }
1612
+ return {
1613
+ kind: "match", scrutinee,
1614
+ arms: [
1615
+ { pattern: pCtor("nullishValue", binder), body: valBody },
1616
+ { pattern: pCtor("nullishNull"), body: rightBody },
1617
+ { pattern: pCtor("nullishUndefined"), body: rightBody },
1618
+ ],
1619
+ };
1620
+ }
1621
+ // Narrow should have rewritten non-nullish ?? to someMatch.
1204
1622
  throw new Error(`nullish reached transform — narrow should have rewritten it: ${JSON.stringify(e).slice(0, 300)}`);
1623
+ }
1205
1624
  case "havoc":
1206
1625
  // Dafny's * only works in var/assign positions — lift to own declaration
1207
1626
  if (binds) {
@@ -1210,6 +1629,8 @@ function lowerExpr(e, binds) {
1210
1629
  return { kind: "var", name };
1211
1630
  }
1212
1631
  return { kind: "havoc", type: e.ty };
1632
+ case "checkedUnwrap":
1633
+ return { kind: "checkedUnwrap", expr: lowerExpr(e.expr, binds) };
1213
1634
  case "someMatch": {
1214
1635
  let someBody;
1215
1636
  let scrutinee;
@@ -1236,6 +1657,10 @@ function lowerExpr(e, binds) {
1236
1657
  someBody = wrapOptionalBranch(someBody, e.someBody);
1237
1658
  noneBody = wrapOptionalBranch(noneBody, e.noneBody);
1238
1659
  }
1660
+ else if (e.ty.kind === "nullish") {
1661
+ someBody = wrapNullishBranch(someBody, e.someBody);
1662
+ noneBody = wrapNullishBranch(noneBody, e.noneBody);
1663
+ }
1239
1664
  return {
1240
1665
  kind: "match", scrutinee,
1241
1666
  arms: [
@@ -1258,6 +1683,7 @@ function lowerExpr(e, binds) {
1258
1683
  const varName = e.scrutinee.kind === "var" ? e.scrutinee.name : undefined;
1259
1684
  const pathHint = varName ?? scrutineeHint(e.scrutinee);
1260
1685
  const wrapOpt = e.ty.kind === "optional";
1686
+ const wrapNullish = e.ty.kind === "nullish";
1261
1687
  const arms = e.cases.map(c => {
1262
1688
  const variant = decl?.variants?.find(v => v.name === c.variant);
1263
1689
  const fields = variant?.fields ?? [];
@@ -1276,12 +1702,16 @@ function lowerExpr(e, binds) {
1276
1702
  }
1277
1703
  if (wrapOpt)
1278
1704
  body = wrapOptionalBranch(body, c.body);
1705
+ else if (wrapNullish)
1706
+ body = wrapNullishBranch(body, c.body);
1279
1707
  return { pattern: buildMatchPattern(c.variant, fields, pathHint), body };
1280
1708
  });
1281
1709
  if (e.fallthrough) {
1282
1710
  let body = lowerExpr(e.fallthrough, binds);
1283
1711
  if (wrapOpt)
1284
1712
  body = wrapOptionalBranch(body, e.fallthrough);
1713
+ else if (wrapNullish)
1714
+ body = wrapNullishBranch(body, e.fallthrough);
1285
1715
  arms.push({ pattern: pWild(), body });
1286
1716
  }
1287
1717
  return { kind: "match", scrutinee: varName !== undefined ? varE(varName) : scrutinee, arms };
@@ -1328,7 +1758,9 @@ function ensuresToMatch(e, typeDecls) {
1328
1758
  }
1329
1759
  function replaceFieldAccess(e, varName, fields, ctorName, ctorOf) {
1330
1760
  return mapExpr(e, x => {
1331
- if (x.kind === "field" && x.obj.kind === "var" && x.obj.name === varName) {
1761
+ const objMatches = x.kind === "field" && ((x.obj.kind === "var" && x.obj.name === varName) ||
1762
+ (x.obj.kind === "checkedUnwrap" && x.obj.expr.kind === "var" && x.obj.expr.name === varName));
1763
+ if (objMatches && x.kind === "field") {
1332
1764
  const f = fields.find(f => f.name === x.field);
1333
1765
  if (f)
1334
1766
  return { kind: "var", name: matchBinder(f.name, varName) };
@@ -1408,18 +1840,17 @@ function negateExpr(e) {
1408
1840
  * - `optValue` is `(if |arr|>0 then Some(arr[|arr|-1]) else None)` (the popped element)
1409
1841
  * - `guardedTrunc` is `(if |arr|>0 then arr[..|arr|-1] else arr)` (the array minus its last element)
1410
1842
  * Callers wrap these in let/assign statements appropriate to their context. */
1411
- function buildPopLowering(arrName, arrTy) {
1412
- const arrVar = { kind: "var", name: arrName };
1413
- const arrLen = { kind: "field", obj: arrVar, field: "size" };
1843
+ function buildPopLoweringExpr(arrExpr, arrTy) {
1844
+ const arrLen = { kind: "field", obj: arrExpr, field: "size" };
1414
1845
  const lastIdx = { kind: "binop", op: "-", left: arrLen, right: { kind: "num", value: 1 } };
1415
- const lastElem = { kind: "index", arr: arrVar, idx: lastIdx };
1846
+ const lastElem = { kind: "index", arr: arrExpr, idx: lastIdx };
1416
1847
  const isNonEmpty = { kind: "binop", op: ">", left: arrLen, right: { kind: "num", value: 0 } };
1417
1848
  const optValue = { kind: "if", cond: isNonEmpty,
1418
1849
  then: { kind: "app", fn: "Some", args: [lastElem] },
1419
1850
  else: { kind: "var", name: "undefined" } };
1420
- const truncated = { kind: "methodCall", obj: arrVar, objTy: arrTy, method: "slice",
1851
+ const truncated = { kind: "methodCall", obj: arrExpr, objTy: arrTy, method: "slice",
1421
1852
  args: [{ kind: "num", value: 0 }, lastIdx], monadic: false };
1422
- const guardedTrunc = { kind: "if", cond: isNonEmpty, then: truncated, else: arrVar };
1853
+ const guardedTrunc = { kind: "if", cond: isNonEmpty, then: truncated, else: arrExpr };
1423
1854
  return { optValue, guardedTrunc };
1424
1855
  }
1425
1856
  /**
@@ -1757,7 +2188,7 @@ function transformStmts(stmts, typeDecls) {
1757
2188
  const bodyStmts = insertIncrementBeforeContinue(eliminateTopLevelContinue(transformStmts(s.body, typeDecls)), idxName);
1758
2189
  result.push({
1759
2190
  kind: "forin", idx: idxName, bound: arrSize,
1760
- invariants: [boundInv, ...s.invariants.map(transformExpr)],
2191
+ invariants: [boundInv, ...s.invariants.map(transformSpecExpr)],
1761
2192
  body: [...perIter, ...bodyStmts],
1762
2193
  });
1763
2194
  i++;
@@ -1772,6 +2203,88 @@ let _liftCounter = 0;
1772
2203
  let _callbackCounter = 0;
1773
2204
  // Branch results must not renumber the existing lifted-call temporaries.
1774
2205
  let _branchCounter = 0;
2206
+ let _cmpCounter = 0;
2207
+ // True while lowering proof-only spec clauses (`requires`, `ensures`, `invariants`,
2208
+ // `decreases`, `doneWith`). Prevents executable-only rewrites like `#349` `let _cmp`
2209
+ // from firing inside specifications.
2210
+ let _inSpec = false;
2211
+ function transformSpecExpr(e) {
2212
+ const prev = _inSpec;
2213
+ _inSpec = true;
2214
+ try {
2215
+ return transformExpr(e);
2216
+ }
2217
+ finally {
2218
+ _inSpec = prev;
2219
+ }
2220
+ }
2221
+ // Active narrowing write-back frames (`someMatch` unwraps & union variant arms).
2222
+ let _writeBackFrames = [];
2223
+ // Declared types of in-scope variables and narrowing binders (for optional-field wrap checks).
2224
+ let _varTypes = new Map();
2225
+ /** Look up the declared field type reached by walking `fields` from `rootTy`. */
2226
+ function lookupFieldTy(rootTy, fields, typeDecls) {
2227
+ let cur = rootTy;
2228
+ for (const field of fields) {
2229
+ if (!cur)
2230
+ return null;
2231
+ if (cur.kind === "optional" || cur.kind === "nullish")
2232
+ cur = cur.inner;
2233
+ if (cur.kind !== "user")
2234
+ return null;
2235
+ const decl = declOfTy(typeDecls, cur);
2236
+ if (!decl || decl.kind !== "record" || !decl.fields)
2237
+ return null;
2238
+ const f = decl.fields.find(fi => fi.name === field);
2239
+ if (!f)
2240
+ return null;
2241
+ cur = f.type ?? parseTsType(f.tsType);
2242
+ }
2243
+ return cur ?? null;
2244
+ }
2245
+ /** True if `e` contains any subexpression that can carry a backend precondition
2246
+ * (calls, indexing, checked unwraps, division/modulo). Used to ensure optional
2247
+ * comparisons evaluate `valSide` unconditionally instead of skipping it in a
2248
+ * `None` match arm (#349), while leaving pure literal/variable comparisons
2249
+ * untouched (zero churn on `pi-lemmascript` and existing `examples/`). */
2250
+ const TOTAL_PURE_BUILTINS = new Set([
2251
+ "set.has", "map.has", "array.includes", "string.includes",
2252
+ "string.startsWith", "string.endsWith", "string.indexOf", "string.lastIndexOf",
2253
+ "string.trim", "string.toLowerCase", "string.toUpperCase",
2254
+ ]);
2255
+ function hasPreconditionExpr(e) {
2256
+ switch (e.kind) {
2257
+ case "call":
2258
+ if (e.builtinId && TOTAL_PURE_BUILTINS.has(e.builtinId)) {
2259
+ return hasPreconditionExpr(e.fn) || e.args.some(hasPreconditionExpr);
2260
+ }
2261
+ return true;
2262
+ case "index":
2263
+ return true;
2264
+ case "checkedUnwrap":
2265
+ return true;
2266
+ case "binop":
2267
+ return e.op === "/" || e.op === "%" || hasPreconditionExpr(e.left) || hasPreconditionExpr(e.right);
2268
+ case "unop":
2269
+ return hasPreconditionExpr(e.expr);
2270
+ case "field":
2271
+ return hasPreconditionExpr(e.obj);
2272
+ case "record":
2273
+ return (e.spread !== null && hasPreconditionExpr(e.spread)) || e.fields.some(f => hasPreconditionExpr(f.value));
2274
+ case "arrayLiteral":
2275
+ return e.elems.some(hasPreconditionExpr);
2276
+ case "conditional":
2277
+ return hasPreconditionExpr(e.cond) || hasPreconditionExpr(e.then) || hasPreconditionExpr(e.else);
2278
+ case "nullish":
2279
+ return hasPreconditionExpr(e.left) || hasPreconditionExpr(e.right);
2280
+ case "someMatch":
2281
+ return hasPreconditionExpr(e.scrutinee) || hasPreconditionExpr(e.someBody) || hasPreconditionExpr(e.noneBody);
2282
+ case "tagMatch":
2283
+ return hasPreconditionExpr(e.scrutinee) || e.cases.some(c => hasPreconditionExpr(c.body)) || (e.fallthrough !== null && hasPreconditionExpr(e.fallthrough));
2284
+ default:
2285
+ return false;
2286
+ }
2287
+ }
1775
2288
  function liftMethodCalls(e) {
1776
2289
  const binds = [];
1777
2290
  return { binds, expr: lowerExpr(e, binds) };
@@ -1780,31 +2293,44 @@ function liftMethodCalls(e) {
1780
2293
  function transformStmt(s, typeDecls) {
1781
2294
  switch (s.kind) {
1782
2295
  case "let": {
2296
+ _varTypes.set(s.name, s.ty);
1783
2297
  // Whole-init havoc: emit directly, no lifting
1784
2298
  if (s.init.kind === "havoc") {
1785
2299
  return [{ kind: "let", name: s.name, type: s.ty, mutable: s.mutable, value: { kind: "havoc", type: s.init.ty } }];
1786
2300
  }
1787
- // arr.shift()! → let x = arr[0]; arr = arr[1..]
2301
+ // arr.shift()! → let x = arr[0]; arr = arr[1..] (handles narrowed Option/Nullish via checkedUnwrap)
1788
2302
  const init = s.init.kind === "call" ? s.init : undefined;
1789
2303
  if (init && init.fn.kind === "field" && init.fn.field === "shift" && init.fn.obj.ty.kind === "array") {
1790
- const arrName = init.fn.obj.kind === "var" ? init.fn.obj.name : undefined;
2304
+ const obj = init.fn.obj;
2305
+ const arrName = obj.kind === "var" ? obj.name
2306
+ : obj.kind === "checkedUnwrap" && obj.expr.kind === "var" ? obj.expr.name : undefined;
1791
2307
  if (arrName) {
1792
- const arrVar = { kind: "var", name: arrName };
2308
+ const arrExpr = obj.kind === "checkedUnwrap"
2309
+ ? { kind: "checkedUnwrap", expr: { kind: "var", name: arrName } }
2310
+ : { kind: "var", name: arrName };
1793
2311
  const letHead = { kind: "let", name: s.name, type: s.ty, mutable: s.mutable,
1794
- value: { kind: "index", arr: arrVar, idx: { kind: "num", value: 0 } } };
1795
- const sliceTail = { kind: "assign", target: arrName,
1796
- value: { kind: "methodCall", obj: arrVar, objTy: init.fn.obj.ty, method: "slice", args: [{ kind: "num", value: 1 }], monadic: false } };
1797
- return [letHead, sliceTail];
2312
+ value: { kind: "index", arr: arrExpr, idx: { kind: "num", value: 0 } } };
2313
+ const sliced = { kind: "methodCall", obj: arrExpr, objTy: init.fn.obj.ty, method: "slice", args: [{ kind: "num", value: 1 }], monadic: false };
2314
+ const tailVal = obj.kind === "checkedUnwrap" ? wrapCheckedUnwrapValue(sliced, obj.expr.ty) : sliced;
2315
+ const sliceTail = { kind: "assign", target: arrName, value: tailVal };
2316
+ return [letHead, sliceTail, ...emitWriteBacksForTarget(arrName, _writeBackFrames)];
1798
2317
  }
1799
2318
  }
1800
2319
  // let x = arr.pop() → let x: T? = (Option-expr); arr := (truncated-or-self)
1801
2320
  if (init && init.fn.kind === "field" && init.fn.field === "pop" && init.fn.obj.ty.kind === "array") {
1802
- const arrName = init.fn.obj.kind === "var" ? init.fn.obj.name : undefined;
2321
+ const obj = init.fn.obj;
2322
+ const arrName = obj.kind === "var" ? obj.name
2323
+ : obj.kind === "checkedUnwrap" && obj.expr.kind === "var" ? obj.expr.name : undefined;
1803
2324
  if (arrName) {
1804
- const { optValue, guardedTrunc } = buildPopLowering(arrName, init.fn.obj.ty);
2325
+ const arrExpr = obj.kind === "checkedUnwrap"
2326
+ ? { kind: "checkedUnwrap", expr: { kind: "var", name: arrName } }
2327
+ : { kind: "var", name: arrName };
2328
+ const { optValue, guardedTrunc } = buildPopLoweringExpr(arrExpr, init.fn.obj.ty);
2329
+ const truncVal = obj.kind === "checkedUnwrap" ? wrapCheckedUnwrapValue(guardedTrunc, obj.expr.ty) : guardedTrunc;
1805
2330
  return [
1806
2331
  { kind: "let", name: s.name, type: s.ty, mutable: s.mutable, value: optValue },
1807
- { kind: "assign", target: arrName, value: guardedTrunc },
2332
+ { kind: "assign", target: arrName, value: truncVal },
2333
+ ...emitWriteBacksForTarget(arrName, _writeBackFrames),
1808
2334
  ];
1809
2335
  }
1810
2336
  }
@@ -1859,22 +2385,141 @@ function transformStmt(s, typeDecls) {
1859
2385
  return [...binds, { kind: "let", name: s.name, type: s.ty, mutable: s.mutable, value: expr }];
1860
2386
  }
1861
2387
  case "assign": {
1862
- // x = arr.pop() → x := (Option-expr); arr := (truncated-or-self)
2388
+ // x = arr.pop() → x := (Option-expr); arr := (truncated-or-self) + Place write-back
1863
2389
  if (s.value.kind === "call" && s.value.fn.kind === "field" &&
1864
- s.value.fn.field === "pop" && s.value.fn.obj.ty.kind === "array" &&
1865
- s.value.fn.obj.kind === "var") {
1866
- const arrName = s.value.fn.obj.name;
1867
- const { optValue, guardedTrunc } = buildPopLowering(arrName, s.value.fn.obj.ty);
1868
- return [
1869
- { kind: "assign", target: s.target, value: optValue },
1870
- { kind: "assign", target: arrName, value: guardedTrunc },
1871
- ];
2390
+ s.value.fn.field === "pop" && s.value.fn.obj.ty.kind === "array") {
2391
+ const obj = s.value.fn.obj;
2392
+ const arrName = obj.kind === "var" ? obj.name
2393
+ : obj.kind === "checkedUnwrap" && obj.expr.kind === "var" ? obj.expr.name : undefined;
2394
+ if (arrName) {
2395
+ const arrExpr = obj.kind === "checkedUnwrap"
2396
+ ? { kind: "checkedUnwrap", expr: { kind: "var", name: arrName } }
2397
+ : { kind: "var", name: arrName };
2398
+ const { optValue, guardedTrunc } = buildPopLoweringExpr(arrExpr, s.value.fn.obj.ty);
2399
+ const truncVal = obj.kind === "checkedUnwrap" ? wrapCheckedUnwrapValue(guardedTrunc, obj.expr.ty) : guardedTrunc;
2400
+ return [
2401
+ { kind: "assign", target: s.target, value: optValue },
2402
+ { kind: "assign", target: arrName, value: truncVal },
2403
+ ...emitWriteBacksForTarget(arrName, _writeBackFrames),
2404
+ ];
2405
+ }
2406
+ }
2407
+ // Non-`this.` dotted field assignment on a record, union variant, or narrowed
2408
+ // optional/nullish record (e.g. `b.count = 5`, `u.v = 99`, `u.items[0] = 10`, `u.box.count = 42`):
2409
+ // lower through active `unwrap` & `variant` frames with cascading write-back.
2410
+ if (s.target.includes(".") && !s.target.startsWith("this.")) {
2411
+ const parts = s.target.split(".");
2412
+ const rootVar = parts[0];
2413
+ const fields = parts.slice(1);
2414
+ const { binds, expr } = liftMethodCalls(s.value);
2415
+ const isUndefRhs = s.value.kind === "var" && (s.value.name === "undefined" || s.value.name === "null");
2416
+ const isOptRhs = s.value.ty.kind === "optional" || isUndefRhs;
2417
+ const resolved = resolveWriteTargetThroughFrames(rootVar, fields, _writeBackFrames);
2418
+ if (resolved.leafUnwrapFrame) {
2419
+ const frame = resolved.leafUnwrapFrame;
2420
+ if (!isOptRhs) {
2421
+ return [
2422
+ ...binds,
2423
+ { kind: "assign", target: frame.binder, value: expr },
2424
+ ...emitWriteBacksForTarget(frame.binder, _writeBackFrames),
2425
+ ];
2426
+ }
2427
+ // Assigning `undefined`/`null` or an `Option<T>` value to a narrowed optional field:
2428
+ // write directly to the enclosing record field without double-wrapping in `Some`.
2429
+ const optExpr = isUndefRhs
2430
+ ? { kind: "constructor", name: "none", type: "Option", args: [] }
2431
+ : expr;
2432
+ if (frame.fields.length > 0) {
2433
+ return [
2434
+ ...binds,
2435
+ { kind: "assign", target: frame.rootVar, value: buildNestedFieldExpr(frame.rootVar, frame.fields, optExpr) },
2436
+ ...emitWriteBacksForTarget(frame.rootVar, _writeBackFrames),
2437
+ ];
2438
+ }
2439
+ return [
2440
+ ...binds,
2441
+ { kind: "assign", target: frame.rootVar, value: optExpr },
2442
+ ...emitWriteBacksForTarget(frame.rootVar, _writeBackFrames),
2443
+ ];
2444
+ }
2445
+ if (resolved.leafVariantBinder) {
2446
+ const binderTy = _varTypes.get(resolved.leafVariantBinder);
2447
+ const rhsExpr = binderTy?.kind === "nullish"
2448
+ ? wrapNullishBranch(expr, s.value)
2449
+ : binderTy?.kind === "optional"
2450
+ ? wrapOptionalBranch(expr, s.value)
2451
+ : expr;
2452
+ return [
2453
+ ...binds,
2454
+ { kind: "assign", target: resolved.leafVariantBinder, value: rhsExpr },
2455
+ ...emitWriteBacksForTarget(resolved.leafVariantBinder, _writeBackFrames),
2456
+ ];
2457
+ }
2458
+ if (resolved.remainingFields.length > 0) {
2459
+ const rootTy = _varTypes.get(resolved.currentRoot);
2460
+ const fieldTy = lookupFieldTy(rootTy, resolved.remainingFields, typeDecls);
2461
+ const rhsExpr = fieldTy?.kind === "nullish"
2462
+ ? wrapNullishBranch(expr, s.value)
2463
+ : fieldTy?.kind === "optional"
2464
+ ? wrapOptionalBranch(expr, s.value)
2465
+ : expr;
2466
+ // If the root variable itself has Nullish<Record> or Option<Record> storage
2467
+ // (narrowed without a someMatch frame), update `root.value` and re-wrap.
2468
+ if (rootTy?.kind === "nullish" || rootTy?.kind === "optional") {
2469
+ const unwrappedRoot = { kind: "checkedUnwrap", expr: { kind: "var", name: resolved.currentRoot } };
2470
+ const buildNestedFromExpr = (base, fs, val) => {
2471
+ if (fs.length === 1)
2472
+ return { kind: "record", spread: base, fields: [{ name: fs[0], value: val }] };
2473
+ const nextBase = { kind: "field", obj: base, field: fs[0] };
2474
+ return { kind: "record", spread: base, fields: [{ name: fs[0], value: buildNestedFromExpr(nextBase, fs.slice(1), val) }] };
2475
+ };
2476
+ const updatedRecord = buildNestedFromExpr(unwrappedRoot, resolved.remainingFields, rhsExpr);
2477
+ const wrappedRoot = wrapCheckedUnwrapValue(updatedRecord, rootTy);
2478
+ return [
2479
+ ...binds,
2480
+ { kind: "assign", target: resolved.currentRoot, value: wrappedRoot },
2481
+ ...emitWriteBacksForTarget(resolved.currentRoot, _writeBackFrames),
2482
+ ];
2483
+ }
2484
+ return [
2485
+ ...binds,
2486
+ { kind: "assign", target: resolved.currentRoot, value: buildNestedFieldExpr(resolved.currentRoot, resolved.remainingFields, rhsExpr) },
2487
+ ...emitWriteBacksForTarget(resolved.currentRoot, _writeBackFrames),
2488
+ ];
2489
+ }
2490
+ }
2491
+ // Assignment to a narrowed optional variable (e.g., `arr[0] = v` desugared to
2492
+ // `arr = arr.with(0, v)` or `a = 10` coerced to `Some(10)` by resolve):
2493
+ // update the match binder and write back `arr := Option.Some(binder)` so
2494
+ // storage and binder stay in sync (#342).
2495
+ const activeUnwrap = !s.target.includes(".")
2496
+ ? findActiveUnwrapFrame(s.target, [], _writeBackFrames)
2497
+ : null;
2498
+ if (activeUnwrap) {
2499
+ if (s.value.kind === "call" && s.value.fn.kind === "var" &&
2500
+ s.value.fn.name === "Some" && s.value.args.length === 1) {
2501
+ const { binds, expr } = liftMethodCalls(s.value.args[0]);
2502
+ return [
2503
+ ...binds,
2504
+ { kind: "assign", target: activeUnwrap.binder, value: expr },
2505
+ ...emitWriteBacksForTarget(activeUnwrap.binder, _writeBackFrames),
2506
+ ];
2507
+ }
2508
+ if (s.value.ty.kind !== "optional" &&
2509
+ !(s.value.kind === "var" && s.value.name === "undefined")) {
2510
+ const { binds, expr } = liftMethodCalls(s.value);
2511
+ return [
2512
+ ...binds,
2513
+ { kind: "assign", target: activeUnwrap.binder, value: expr },
2514
+ ...emitWriteBacksForTarget(activeUnwrap.binder, _writeBackFrames),
2515
+ ];
2516
+ }
1872
2517
  }
1873
2518
  // Top-level method call → direct monadic bind, no lifting needed
1874
2519
  if (s.value.kind === "call" && s.value.callKind === "method")
1875
- return [{ kind: "bind", target: s.target, value: transformExpr(s.value) }];
2520
+ return [{ kind: "bind", target: s.target, value: transformExpr(s.value) }, ...emitWriteBacksForTarget(s.target, _writeBackFrames)];
1876
2521
  const { binds, expr } = liftMethodCalls(s.value);
1877
- return [...binds, { kind: "assign", target: s.target, value: expr }];
2522
+ return [...binds, { kind: "assign", target: s.target, value: expr }, ...emitWriteBacksForTarget(s.target, _writeBackFrames)];
1878
2523
  }
1879
2524
  case "return": {
1880
2525
  const { binds, expr } = liftMethodCalls(s.value);
@@ -1884,22 +2529,57 @@ function transformStmt(s, typeDecls) {
1884
2529
  case "continue": return [{ kind: "continue" }];
1885
2530
  case "expr": {
1886
2531
  // Mutating collection call: m.set(k, v) → m := m.set(k, v) (same for set
1887
- // .add/.delete and array .push). The receiver may be a bare var, or a
1888
- // field path rooted at a var (b.items.push(v) → b := b.(items := b.items + [v])).
2532
+ // .add/.delete and array .push/.unshift/.sort). The receiver may be a bare
2533
+ // var or a field path rooted at a var, with Place write-back through any
2534
+ // enclosing narrowing frames (`someMatch` unwrap or union variant arm).
2535
+ // Non-Place receivers (e.g. `getArr().push(1)`) fail closed instead of
2536
+ // silently discarding the updated collection.
1889
2537
  if (s.expr.kind === "call" && s.expr.fn.kind === "field") {
1890
2538
  const recv = s.expr.fn.obj;
1891
2539
  const f = s.expr.fn.field;
1892
- const isMutating = ((recv.ty.kind === "map" || recv.ty.kind === "set") && (f === "set" || f === "add" || f === "delete")) ||
1893
- (recv.ty.kind === "array" && (f === "push" || f === "unshift" || f === "sort"));
1894
- if (isMutating && recv.kind === "var") {
1895
- const { binds, expr } = liftMethodCalls(s.expr);
1896
- return [...binds, { kind: "assign", target: recv.name, value: expr }];
1897
- }
1898
- if (isMutating && recv.kind === "field") {
1899
- const { binds, expr } = liftMethodCalls(s.expr);
1900
- const upd = buildNestedFieldUpdate(recv, expr);
1901
- if (upd)
1902
- return [...binds, { kind: "assign", target: upd.root, value: upd.value }];
2540
+ if (isMutatingCollectionMethod(recv.ty, f)) {
2541
+ if (recv.kind === "var") {
2542
+ const { binds, expr } = liftMethodCalls(s.expr);
2543
+ return [
2544
+ ...binds,
2545
+ { kind: "assign", target: recv.name, value: expr },
2546
+ ...emitWriteBacksForTarget(recv.name, _writeBackFrames),
2547
+ ];
2548
+ }
2549
+ if (recv.kind === "field") {
2550
+ const { binds, expr } = liftMethodCalls(s.expr);
2551
+ const upd = buildNestedFieldUpdate(recv, expr);
2552
+ if (upd) {
2553
+ return [
2554
+ ...binds,
2555
+ { kind: "assign", target: upd.root, value: upd.value },
2556
+ ...emitWriteBacksForTarget(upd.root, _writeBackFrames),
2557
+ ];
2558
+ }
2559
+ }
2560
+ if (recv.kind === "checkedUnwrap") {
2561
+ const { binds, expr } = liftMethodCalls(s.expr);
2562
+ const wrapped = wrapCheckedUnwrapValue(expr, recv.expr.ty);
2563
+ if (recv.expr.kind === "var") {
2564
+ return [
2565
+ ...binds,
2566
+ { kind: "assign", target: recv.expr.name, value: wrapped },
2567
+ ...emitWriteBacksForTarget(recv.expr.name, _writeBackFrames),
2568
+ ];
2569
+ }
2570
+ if (recv.expr.kind === "field") {
2571
+ const upd = buildNestedFieldUpdate(recv.expr, wrapped);
2572
+ if (upd) {
2573
+ return [
2574
+ ...binds,
2575
+ { kind: "assign", target: upd.root, value: upd.value },
2576
+ ...emitWriteBacksForTarget(upd.root, _writeBackFrames),
2577
+ ];
2578
+ }
2579
+ }
2580
+ }
2581
+ throw new Error(`Unsupported in-place mutation \`${describeReceiver(recv)}.${f}(...)\`: ` +
2582
+ `receiver is not a writable Place rooted at a variable (bind it to a variable or mutate through a field path).`);
1903
2583
  }
1904
2584
  }
1905
2585
  // Optional chaining on map.get at statement level: m.get(k)?.push(v)
@@ -1921,7 +2601,12 @@ function transformStmt(s, typeDecls) {
1921
2601
  const pushed = { kind: "methodCall", obj: directGet, objTy: mapExpr.ty.value, method: "push", args: [pushArg], monadic: false };
1922
2602
  const updated = { kind: "methodCall", obj: mapVar, objTy: mapExpr.ty, method: "set", args: [keyExpr, pushed], monadic: false };
1923
2603
  const hasCond = { kind: "methodCall", obj: mapVar, objTy: mapExpr.ty, method: "has", args: [keyExpr], monadic: false };
1924
- return [{ kind: "if", cond: hasCond, then: [{ kind: "assign", target: mapName, value: updated }], else: [] }];
2604
+ return [{
2605
+ kind: "if",
2606
+ cond: hasCond,
2607
+ then: [{ kind: "assign", target: mapName, value: updated }, ...emitWriteBacksForTarget(mapName, _writeBackFrames)],
2608
+ else: [],
2609
+ }];
1925
2610
  }
1926
2611
  }
1927
2612
  const { binds, expr } = liftMethodCalls(s.expr);
@@ -1936,9 +2621,9 @@ function transformStmt(s, typeDecls) {
1936
2621
  return [{
1937
2622
  kind: "while",
1938
2623
  cond: transformExpr(asCondition(s.cond)),
1939
- invariants: s.invariants.map(transformExpr),
1940
- decreasing: s.decreases ? transformExpr(s.decreases) : null,
1941
- doneWith: s.doneWith ? transformExpr(s.doneWith) : null,
2624
+ invariants: s.invariants.map(transformSpecExpr),
2625
+ decreasing: s.decreases ? transformSpecExpr(s.decreases) : null,
2626
+ doneWith: s.doneWith ? transformSpecExpr(s.doneWith) : null,
1942
2627
  body: eliminateTopLevelContinue(transformStmts(s.body, typeDecls)),
1943
2628
  }];
1944
2629
  case "throw":
@@ -1957,7 +2642,21 @@ function transformStmt(s, typeDecls) {
1957
2642
  const path = asTAccessPath(s.scrutinee);
1958
2643
  if (path) {
1959
2644
  const replaced = replacePathInTStmts(s.someBody, path, s.binder, s.binderTy);
1960
- const someBody = transformStmts(replaced, typeDecls);
2645
+ _varTypes.set(s.binder, s.binderTy);
2646
+ _writeBackFrames.push(makeUnwrapFrame(s.binder, path.rootVar, path.fields));
2647
+ let someBody;
2648
+ try {
2649
+ someBody = transformStmts(replaced, typeDecls);
2650
+ }
2651
+ finally {
2652
+ _writeBackFrames.pop();
2653
+ }
2654
+ if (_opts.backend === "lean" && collectAssignedIrTargets(someBody).has(s.binder)) {
2655
+ someBody = [
2656
+ { kind: "let", name: s.binder, type: s.binderTy, mutable: true, value: varE(s.binder) },
2657
+ ...someBody,
2658
+ ];
2659
+ }
1961
2660
  const noneBody = transformStmts(s.noneBody, typeDecls);
1962
2661
  const scrutinee = path.fields.length === 0 ? varE(path.rootVar) : transformExpr(s.scrutinee);
1963
2662
  return [{
@@ -2029,7 +2728,8 @@ function emitMatchStmt(scrutinee, typeName, cases, fallthrough, typeDecls) {
2029
2728
  const path = asTAccessPath(scrutinee);
2030
2729
  const isPath = !!path && path.fields.length > 0;
2031
2730
  const prefix = path ? [path.rootVar, ...path.fields].join("_") : "?";
2032
- function transformArmBody(body, fields) {
2731
+ const baseUnionName = tyBaseName(typeName);
2732
+ function transformArmBody(body, fields, ctorName) {
2033
2733
  let stmts;
2034
2734
  if (isPath && path) {
2035
2735
  // Path scrutinee: the matched value is referred to by the bare path, so
@@ -2046,10 +2746,36 @@ function emitMatchStmt(scrutinee, typeName, cases, fallthrough, typeDecls) {
2046
2746
  stmts = replaceVarInTStmts(stmts, prefix, matchBinder(f.name, prefix), f.type ?? parseTsType(f.tsType));
2047
2747
  }
2048
2748
  }
2049
- return transformStmts(stmts, typeDecls);
2749
+ const pushVariant = !isPath && !!ctorName && fields.length > 0;
2750
+ if (pushVariant) {
2751
+ for (const f of fields) {
2752
+ _varTypes.set(matchBinder(f.name, prefix), f.type ?? parseTsType(f.tsType));
2753
+ }
2754
+ _writeBackFrames.push(makeVariantFrame(prefix, baseUnionName, ctorName, fields.map(f => ({ fieldName: f.name, binder: matchBinder(f.name, prefix) }))));
2755
+ }
2756
+ let lowered;
2757
+ try {
2758
+ lowered = transformStmts(stmts, typeDecls);
2759
+ }
2760
+ finally {
2761
+ if (pushVariant)
2762
+ _writeBackFrames.pop();
2763
+ }
2764
+ if (_opts.backend === "lean" && pushVariant) {
2765
+ const assigned = collectAssignedIrTargets(lowered);
2766
+ const mutShadows = fields
2767
+ .filter(f => assigned.has(matchBinder(f.name, prefix)))
2768
+ .map(f => {
2769
+ const b = matchBinder(f.name, prefix);
2770
+ return { kind: "let", name: b, type: f.type ?? parseTsType(f.tsType), mutable: true, value: varE(b) };
2771
+ });
2772
+ if (mutShadows.length > 0)
2773
+ lowered = [...mutShadows, ...lowered];
2774
+ }
2775
+ return lowered;
2050
2776
  }
2051
2777
  const armCases = cases.map(c => ({ name: c.variant, body: c.body }));
2052
- const arms = buildMatchArms(armCases, prefix, typeName, typeDecls, (body, _vn, fields) => transformArmBody(body, fields));
2778
+ const arms = buildMatchArms(armCases, prefix, typeName, typeDecls, (body, _vn, fields, ctorName) => transformArmBody(body, fields, ctorName));
2053
2779
  // Add the fallthrough arm whenever the listed cases don't cover every
2054
2780
  // variant — needed for exhaustiveness even when there's no `else`
2055
2781
  // (`fallthrough` empty), e.g. `if (Array.isArray(x)) {...}` with no else
@@ -2061,14 +2787,14 @@ function emitMatchStmt(scrutinee, typeName, cases, fallthrough, typeDecls) {
2061
2787
  // Exactly one variant left — destructure so the fallthrough body can
2062
2788
  // access variant-specific fields (Lean requires this; Dafny tolerates `_`).
2063
2789
  const pattern = buildMatchPattern(remaining.name, remaining.fields, prefix);
2064
- const body = transformArmBody(fallthrough, remaining.fields);
2790
+ const body = transformArmBody(fallthrough, remaining.fields, remaining.name);
2065
2791
  arms.push({ pattern, body });
2066
2792
  }
2067
2793
  else {
2068
2794
  arms.push({ pattern: pWild(), body: transformStmts(fallthrough, typeDecls) });
2069
2795
  }
2070
2796
  }
2071
- return { kind: "match", scrutinee: isPath ? transformExpr(scrutinee) : varE(prefix), arms };
2797
+ return { kind: "match", scrutinee: (isPath || scrutinee.kind === "checkedUnwrap") ? transformExpr(scrutinee) : varE(prefix), arms };
2072
2798
  }
2073
2799
  /** Replace bare `var(oldName)` references → `var(newName)` with the given type.
2074
2800
  * Used by emitMatchStmt for synth array-unions where the variant has a single
@@ -2146,19 +2872,51 @@ function emitSwitchStmt(s, typeDecls) {
2146
2872
  throw new Error(`switch scrutinee must be string-typed or a declared union, got ${typeName}`);
2147
2873
  }
2148
2874
  const baseName = s.expr.ty.kind === "user" ? tyBaseName(s.expr.ty.name) : undefined;
2875
+ const switchVarName = s.expr.kind === "var" ? s.expr.name
2876
+ : s.expr.kind === "checkedUnwrap" && s.expr.expr.kind === "var" ? s.expr.expr.name : "?";
2149
2877
  const arms = literalCases
2150
2878
  ? buildLiteralMatchArms(cases, (body) => transformStmts(body, typeDecls))
2151
2879
  : ef
2152
2880
  ? buildMatchArms(cases, undefined, ctorDecl.name, typeDecls, (body) => transformStmts(body, typeDecls))
2153
- : buildMatchArms(cases, s.expr.kind === "var" ? s.expr.name : "?", ctorDecl.name, typeDecls, (body, vn, fields, ctorName) => {
2154
- let out = transformStmts(replaceFieldAccessInTStmts(body, vn, fields), typeDecls);
2881
+ : buildMatchArms(cases, switchVarName, ctorDecl.name, typeDecls, (body, vn, fields, ctorName) => {
2882
+ const pushVariant = !!ctorName && !!vn && vn !== "?" && !!baseName && fields.length > 0 && s.expr.kind !== "checkedUnwrap";
2883
+ const variantMeta = ctorName ? ctorDecl?.variants?.find(v => v.name === ctorName) : undefined;
2884
+ if (pushVariant) {
2885
+ for (const f of fields) {
2886
+ const vf = variantMeta?.fields.find(vf => vf.name === f.name);
2887
+ _varTypes.set(matchBinder(f.name, vn), vf?.type ?? parseTsType(f.tsType));
2888
+ }
2889
+ _writeBackFrames.push(makeVariantFrame(vn, baseName, ctorName, fields.map(f => ({ fieldName: f.name, binder: matchBinder(f.name, vn) }))));
2890
+ }
2891
+ let out;
2892
+ try {
2893
+ out = transformStmts(replaceFieldAccessInTStmts(body, vn, fields), typeDecls);
2894
+ }
2895
+ finally {
2896
+ if (pushVariant)
2897
+ _writeBackFrames.pop();
2898
+ }
2155
2899
  if (ctorName && vn && baseName)
2156
2900
  out = stampScrutineeUpdates(out, vn, ctorName, baseName);
2901
+ if (_opts.backend === "lean" && pushVariant) {
2902
+ const assigned = collectAssignedIrTargets(out);
2903
+ const mutShadows = fields
2904
+ .filter(f => assigned.has(matchBinder(f.name, vn)))
2905
+ .map(f => {
2906
+ const b = matchBinder(f.name, vn);
2907
+ return { kind: "let", name: b, type: parseTsType(f.tsType), mutable: true, value: varE(b) };
2908
+ });
2909
+ if (mutShadows.length > 0)
2910
+ out = [...mutShadows, ...out];
2911
+ }
2157
2912
  return out;
2158
2913
  });
2159
2914
  if (s.defaultBody.length > 0)
2160
2915
  arms.push({ pattern: pWild(), body: transformStmts(s.defaultBody, typeDecls) });
2161
- return { kind: "match", scrutinee: ef ? ef.scrutinee : varE(s.expr.kind === "var" ? s.expr.name : "?"), arms };
2916
+ const scrutinee = ef ? ef.scrutinee
2917
+ : s.expr.kind === "checkedUnwrap" ? transformExpr(s.expr)
2918
+ : varE(switchVarName);
2919
+ return { kind: "match", scrutinee, arms };
2162
2920
  }
2163
2921
  /** Replace obj.field → replacement var in typed IR.
2164
2922
  * Uses the TExpr's resolved type when available, falling back to `fallbackTy`. */
@@ -2166,7 +2924,9 @@ function replaceFieldsInTStmts(stmts, objName, replacements) {
2166
2924
  if (replacements.length === 0)
2167
2925
  return stmts;
2168
2926
  return stmts.map(s => mapTStmt(s, e => {
2169
- if (e.kind === "field" && e.obj.kind === "var" && e.obj.name === objName) {
2927
+ const objMatches = e.kind === "field" && ((e.obj.kind === "var" && e.obj.name === objName) ||
2928
+ (e.obj.kind === "checkedUnwrap" && e.obj.expr.kind === "var" && e.obj.expr.name === objName));
2929
+ if (objMatches && e.kind === "field") {
2170
2930
  const r = replacements.find(r => r.fieldName === e.field);
2171
2931
  if (r) {
2172
2932
  const ty = e.ty.kind !== "unknown" ? e.ty : r.fallbackTy;
@@ -2241,6 +3001,8 @@ function projectStructuralCallArgsInTStmts(stmts, varName, fields) {
2241
3001
  function asTAccessPath(e) {
2242
3002
  if (e.kind === "var")
2243
3003
  return { rootVar: e.name, fields: [] };
3004
+ if (e.kind === "checkedUnwrap")
3005
+ return asTAccessPath(e.expr);
2244
3006
  if (e.kind === "field") {
2245
3007
  const inner = asTAccessPath(e.obj);
2246
3008
  if (!inner)
@@ -2253,9 +3015,14 @@ function asTAccessPath(e) {
2253
3015
  function matchesAccessPath(e, path) {
2254
3016
  const collected = [];
2255
3017
  let cur = e;
2256
- while (cur.kind === "field") {
2257
- collected.unshift(cur.field);
2258
- cur = cur.obj;
3018
+ while (cur.kind === "field" || cur.kind === "checkedUnwrap") {
3019
+ if (cur.kind === "field") {
3020
+ collected.unshift(cur.field);
3021
+ cur = cur.obj;
3022
+ }
3023
+ else {
3024
+ cur = cur.expr;
3025
+ }
2259
3026
  }
2260
3027
  if (cur.kind !== "var" || cur.name !== path.rootVar)
2261
3028
  return false;
@@ -2296,6 +3063,13 @@ function transformPureBody(stmts, typeDecls) {
2296
3063
  switch (s.kind) {
2297
3064
  case "return": return transformExpr(s.value);
2298
3065
  case "let": {
3066
+ // Mutating array methods (`pop`, `shift`) update the receiver in place
3067
+ // and cannot be lowered as a pure expression.
3068
+ if (s.init.kind === "call" && s.init.fn.kind === "field" &&
3069
+ (s.init.fn.field === "pop" || s.init.fn.field === "shift") &&
3070
+ s.init.fn.obj.ty.kind === "array") {
3071
+ return null;
3072
+ }
2299
3073
  const restExpr = transformPureBody(rest, typeDecls);
2300
3074
  if (!restExpr)
2301
3075
  return null;
@@ -2365,7 +3139,8 @@ function transformPureSwitch(s, typeDecls) {
2365
3139
  if (!ctorDecl)
2366
3140
  return null;
2367
3141
  const typeName = ctorDecl.name;
2368
- const varName = s.expr.kind === "var" ? s.expr.name : undefined;
3142
+ const varName = s.expr.kind === "var" ? s.expr.name
3143
+ : s.expr.kind === "checkedUnwrap" && s.expr.expr.kind === "var" ? s.expr.expr.name : undefined;
2369
3144
  const cases = s.cases.map(c => ({ name: c.label, body: c.body }));
2370
3145
  const arms = buildMatchArms(cases, varName, typeName, typeDecls, (body, vn, fields, ctorName) => {
2371
3146
  const projected = vn ? projectStructuralCallArgsInTStmts(body, vn, fields) : body;
@@ -2384,6 +3159,8 @@ function transformPureSwitch(s, typeDecls) {
2384
3159
  return null;
2385
3160
  arms.push({ pattern: pWild(), body });
2386
3161
  }
3162
+ if (s.expr.kind === "checkedUnwrap")
3163
+ return { kind: "match", scrutinee: transformExpr(s.expr), arms };
2387
3164
  if (s.expr.kind !== "var")
2388
3165
  return null;
2389
3166
  return { kind: "match", scrutinee: varE(s.expr.name), arms };
@@ -2573,6 +3350,9 @@ export function transformModule(mod, specImport, moduleBaseOverride) {
2573
3350
  _liftCounter = 0;
2574
3351
  _callbackCounter = 0;
2575
3352
  _branchCounter = 0;
3353
+ _cmpCounter = 0;
3354
+ _inSpec = false;
3355
+ _writeBackFrames = [];
2576
3356
  _typeDecls = mod.typeDecls;
2577
3357
  _neededKindHelpers = new Map();
2578
3358
  _pureDefNames = new Set(mod.functions.filter(f => f.isPure).map(f => f.name));
@@ -2594,22 +3374,23 @@ export function transformModule(mod, specImport, moduleBaseOverride) {
2594
3374
  if (body) {
2595
3375
  // For pure-function lemmas, replace \result with the function call.
2596
3376
  const fnCall = { kind: "app", fn: fn.name, args: fn.params.map(p => ({ kind: "var", name: p.name })) };
2597
- const ensures = fn.ensures.map(e => replaceVar(transformExpr(e), "\\result", fnCall));
3377
+ const ensures = fn.ensures.map(e => replaceVar(transformSpecExpr(e), "\\result", fnCall));
2598
3378
  pureDefs.push({
2599
3379
  kind: "def",
2600
3380
  name: fn.name,
2601
3381
  typeParams: fn.typeParams,
2602
3382
  params: fn.params.map(p => ({ name: p.name, type: p.ty })),
2603
3383
  returnType: fn.returnTy,
2604
- requires: fn.requires.map(transformExpr),
3384
+ requires: fn.requires.map(transformSpecExpr),
2605
3385
  ensures,
2606
- decreases: fn.decreases ? transformExpr(fn.decreases) : null,
3386
+ decreases: fn.decreases ? transformSpecExpr(fn.decreases) : null,
2607
3387
  body,
2608
3388
  });
2609
3389
  }
2610
3390
  else if (fn.forcePure) {
2611
3391
  // //@ pure but body can't be auto-converted — emit function by method
2612
3392
  _forofCounters.clear();
3393
+ _writeBackFrames = [];
2613
3394
  const methodBody = promoteAssignedLets(transformStmts(fn.body, mod.typeDecls));
2614
3395
  defByMethods.push({
2615
3396
  kind: "def-by-method",
@@ -2617,9 +3398,9 @@ export function transformModule(mod, specImport, moduleBaseOverride) {
2617
3398
  typeParams: fn.typeParams,
2618
3399
  params: fn.params.map(p => ({ name: p.name, type: p.ty })),
2619
3400
  returnType: fn.returnTy,
2620
- requires: fn.requires.map(transformExpr),
2621
- ensures: fn.ensures.map(transformExpr),
2622
- decreases: fn.decreases ? transformExpr(fn.decreases) : null,
3401
+ requires: fn.requires.map(transformSpecExpr),
3402
+ ensures: fn.ensures.map(transformSpecExpr),
3403
+ decreases: fn.decreases ? transformSpecExpr(fn.decreases) : null,
2623
3404
  methodBody,
2624
3405
  });
2625
3406
  }
@@ -2664,10 +3445,10 @@ export function transformModule(mod, specImport, moduleBaseOverride) {
2664
3445
  typeParams: ext.typeParams,
2665
3446
  params: ext.params.map(p => ({ name: p.name, type: p.ty })),
2666
3447
  returnType: ext.returnTy,
2667
- requires: ext.requires.map(transformExpr),
3448
+ requires: ext.requires.map(transformSpecExpr),
2668
3449
  ensures: ext.ensures.map(e => ext.impure
2669
- ? transformExpr(e)
2670
- : replaceVar(transformExpr(e), "\\result", fnCall)),
3450
+ ? transformSpecExpr(e)
3451
+ : replaceVar(transformSpecExpr(e), "\\result", fnCall)),
2671
3452
  impure: ext.impure,
2672
3453
  };
2673
3454
  });
@@ -2678,14 +3459,23 @@ export function transformModule(mod, specImport, moduleBaseOverride) {
2678
3459
  const pureDefNames = new Set([...pureDefs.map(d => d.name), ...defByMethods.map(d => d.name)]);
2679
3460
  const methods = mod.functions.map(fn => {
2680
3461
  const ensures = [];
2681
- for (const e of fn.ensures) {
2682
- const m = ensuresToMatch(e, mod.typeDecls);
2683
- if (m)
2684
- ensures.push(m);
2685
- else
2686
- ensures.push(transformExpr(e));
3462
+ const prevInSpec = _inSpec;
3463
+ _inSpec = true;
3464
+ try {
3465
+ for (const e of fn.ensures) {
3466
+ const m = ensuresToMatch(e, mod.typeDecls);
3467
+ if (m)
3468
+ ensures.push(m);
3469
+ else
3470
+ ensures.push(transformExpr(e));
3471
+ }
3472
+ }
3473
+ finally {
3474
+ _inSpec = prevInSpec;
2687
3475
  }
2688
3476
  _forofCounters.clear();
3477
+ _writeBackFrames = [];
3478
+ _varTypes = new Map(fn.params.map(p => [p.name, p.ty]));
2689
3479
  let body = pureDefNames.has(fn.name)
2690
3480
  ? [{ kind: "return", value: { kind: "app", fn: _opts.backend === "lean" ? `Pure.${fn.name}` : fn.name, args: fn.params.map(p => ({ kind: "var", name: p.name })) } }]
2691
3481
  : promoteAssignedLets(transformStmts(fn.body, mod.typeDecls));
@@ -2698,13 +3488,18 @@ export function transformModule(mod, specImport, moduleBaseOverride) {
2698
3488
  // since loom's default loop-exit fact `¬guard` does not hold across a break.
2699
3489
  if (_opts.backend === "lean" && !pureDefNames.has(fn.name)) {
2700
3490
  body = matchToIfChains(body);
2701
- const resultInvariants = fn.ensures.map(e => replaceVar(transformExpr(e), "\\result", { kind: "var", name: "_loopRet" }));
3491
+ const resultInvariants = fn.ensures.map(e => replaceVar(transformSpecExpr(e), "\\result", { kind: "var", name: "_loopRet" }));
2702
3492
  body = eliminateReturnInLoops(body, fn.returnTy, resultInvariants);
2703
3493
  requireDoneWithForBreaks(body, fn.name);
2704
3494
  }
2705
- // Shadow reassigned parameters with mutable locals
3495
+ // Shadow reassigned parameters with mutable locals (including parameters
3496
+ // written back via Place lowering inside `someMatch`, `tagMatch`, or `switch`).
2706
3497
  const paramNames = new Set(fn.params.map(p => p.name));
2707
3498
  const reassigned = findReassignedNames(fn.body, paramNames);
3499
+ for (const target of collectAssignedIrTargets(body)) {
3500
+ if (paramNames.has(target))
3501
+ reassigned.add(target);
3502
+ }
2708
3503
  if (reassigned.size > 0) {
2709
3504
  const shadows = fn.params
2710
3505
  .filter(p => reassigned.has(p.name))
@@ -2717,27 +3512,41 @@ export function transformModule(mod, specImport, moduleBaseOverride) {
2717
3512
  typeParams: fn.typeParams,
2718
3513
  params: fn.params.map(p => ({ name: p.name, type: p.ty })),
2719
3514
  returnType: fn.returnTy,
2720
- requires: fn.requires.map(transformExpr),
3515
+ requires: fn.requires.map(transformSpecExpr),
2721
3516
  ensures,
2722
- decreases: fn.decreases ? transformExpr(fn.decreases) : null,
3517
+ decreases: fn.decreases ? transformSpecExpr(fn.decreases) : null,
2723
3518
  body,
2724
3519
  };
2725
3520
  });
2726
3521
  // Class declarations
2727
3522
  const classDecls = (mod.classes ?? []).map(cls => {
2728
3523
  const classMethods = cls.methods.map(fn => {
2729
- const ensures = fn.ensures.map(transformExpr);
3524
+ const ensures = fn.ensures.map(transformSpecExpr);
2730
3525
  _forofCounters.clear();
2731
- const body = promoteAssignedLets(transformStmts(fn.body, mod.typeDecls));
3526
+ _writeBackFrames = [];
3527
+ _varTypes = new Map(fn.params.map(p => [p.name, p.ty]));
3528
+ let body = promoteAssignedLets(transformStmts(fn.body, mod.typeDecls));
3529
+ const paramNames = new Set(fn.params.map(p => p.name));
3530
+ const reassigned = findReassignedNames(fn.body, paramNames);
3531
+ for (const target of collectAssignedIrTargets(body)) {
3532
+ if (paramNames.has(target))
3533
+ reassigned.add(target);
3534
+ }
3535
+ if (reassigned.size > 0) {
3536
+ const shadows = fn.params
3537
+ .filter(p => reassigned.has(p.name))
3538
+ .map(p => ({ kind: "let", name: p.name, type: p.ty, mutable: true, value: { kind: "var", name: p.name } }));
3539
+ body = [...shadows, ...body];
3540
+ }
2732
3541
  return {
2733
3542
  kind: "method",
2734
3543
  name: fn.name,
2735
3544
  typeParams: fn.typeParams,
2736
3545
  params: fn.params.map(p => ({ name: p.name, type: p.ty })),
2737
3546
  returnType: fn.returnTy,
2738
- requires: fn.requires.map(transformExpr),
3547
+ requires: fn.requires.map(transformSpecExpr),
2739
3548
  ensures,
2740
- decreases: fn.decreases ? transformExpr(fn.decreases) : null,
3549
+ decreases: fn.decreases ? transformSpecExpr(fn.decreases) : null,
2741
3550
  body,
2742
3551
  };
2743
3552
  });