lemmascript 0.6.13 → 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";
@@ -353,24 +353,75 @@ function asCondition(e) {
353
353
  return { kind: "binop", op: ">",
354
354
  left: { kind: "field", obj: e, field: "length", ty: { kind: "nat" } },
355
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 };
356
363
  // Arrays, objects, maps, sets, tuples are always truthy in JS (even `[]`/`{}`).
357
364
  if (["array", "user", "map", "set", "tuple"].includes(e.ty.kind))
358
365
  return { kind: "bool", value: true, ty: bool };
359
366
  return e;
360
367
  }
361
368
  /** Wrap an expression in Some/None for optional-typed conditionals.
362
- * 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`. */
363
370
  function wrapOptionalBranch(expr, raw) {
364
371
  // Set type: "Option" so Lean emits `Option.some`/`Option.none` (qualified).
365
372
  // The dotted form `.some`/`.none` would be ambiguous in expression positions
366
373
  // like the scrutinee of an outer match. Dafny treats `Option.Some` and bare
367
374
  // `Some` equivalently — the qualification is harmless there.
368
- if (raw.kind === "var" && raw.name === "undefined")
375
+ if (raw.kind === "var" && (raw.name === "undefined" || raw.name === "null"))
369
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
+ }
370
388
  if (raw.ty.kind === "optional")
371
389
  return expr; // already Option<T>, don't double-wrap
372
390
  return { kind: "constructor", name: "some", type: "Option", args: [expr] };
373
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
+ }
374
425
  /** Lean needs `let mut` for any local that is later reassigned. A const local
375
426
  * whose collection field is mutated (`b.items.push(v)` → `b := b.(items := …)`)
376
427
  * becomes an assign in the lowered body, so scan for assign targets and flip
@@ -421,7 +472,7 @@ function buildNestedFieldUpdate(recv, newVal) {
421
472
  if (recv.obj.kind === "field")
422
473
  return buildNestedFieldUpdate(recv.obj, upd);
423
474
  if (recv.obj.kind === "checkedUnwrap") {
424
- const wrapped = { kind: "app", fn: "Some", args: [upd] };
475
+ const wrapped = wrapCheckedUnwrapValue(upd, recv.obj.expr.ty);
425
476
  if (recv.obj.expr.kind === "var")
426
477
  return { root: recv.obj.expr.name, value: wrapped };
427
478
  if (recv.obj.expr.kind === "field")
@@ -479,7 +530,18 @@ function lowerExpr(e, binds) {
479
530
  return { kind: "var", name };
480
531
  }
481
532
  switch (e.kind) {
482
- 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 };
483
545
  case "num": {
484
546
  const literal = { kind: "num", value: e.value };
485
547
  return e.ty.kind === "real" && Number.isInteger(e.value)
@@ -501,6 +563,43 @@ function lowerExpr(e, binds) {
501
563
  // String truthiness: !str → str == ""
502
564
  if (e.op === "!" && e.expr.ty.kind === "string")
503
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
+ }
504
603
  // Optional truthiness: !opt → None negates to `true`. The Some branch is
505
604
  // `!(value truthy)`: always-truthy inners (array/user) give a plain `false`,
506
605
  // while falsy-capable inners re-test the wrapped value (`!Some(0)` is `true`).
@@ -559,10 +658,21 @@ function lowerExpr(e, binds) {
559
658
  right: { kind: "constructor", name: e.right.value, type: objTy, args: [] },
560
659
  };
561
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
+ }
562
671
  // 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") {
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") {
566
676
  const left = lowerExpr(e.left, binds);
567
677
  const leftTy = e.left.ty.kind === "user" ? e.left.ty.name : undefined;
568
678
  const right = isUser(e.left.ty)
@@ -570,19 +680,161 @@ function lowerExpr(e, binds) {
570
680
  : { kind: "str", value: e.right.value };
571
681
  return { kind: "binop", op: e.op === "===" ? "=" : "≠", left, right };
572
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
+ }
573
818
  // Optional comparison: optExpr op val → match optExpr { Some(v) => v op val, None => false/true }
574
- if (["===", "!==", ">=", "<=", ">", "<"].includes(e.op) &&
819
+ if (["===", "!==", "==", "!=", ">=", "<=", ">", "<"].includes(e.op) &&
575
820
  (e.left.ty.kind === "optional") !== (e.right.ty.kind === "optional")) {
576
821
  const [optSide, valSide] = e.left.ty.kind === "optional" ? [e.left, e.right] : [e.right, e.left];
577
822
  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 === "===";
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
+ }
581
833
  return {
582
834
  kind: "match", scrutinee: optExpr,
583
835
  arms: [
584
- { pattern: pCtor("some", "_"), body: { kind: "bool", value: !isNone } },
585
- { 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 } },
586
838
  ],
587
839
  };
588
840
  }
@@ -604,7 +856,7 @@ function lowerExpr(e, binds) {
604
856
  // skip the `let` binding completely (zero temporary churn).
605
857
  const op = e.left.ty.kind === "optional" ? e.op : MIRROR_OP[e.op] ?? e.op;
606
858
  const cmpOp = BOOL_OP_MAP[op] ?? op;
607
- const noneVal = e.op === "!==" ? true : false;
859
+ const noneVal = (e.op === "!==" || e.op === "!=") ? true : false;
608
860
  const bound = matchBinder("value");
609
861
  if (!_inSpec && valExpr.kind !== "var" && hasPreconditionExpr(valSide)) {
610
862
  const tmp = freshName(`_cmp${_cmpCounter++}`);
@@ -629,12 +881,27 @@ function lowerExpr(e, binds) {
629
881
  ],
630
882
  };
631
883
  }
632
- // || 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
633
900
  // inner type is always truthy. When it can be falsy, JS still drops the
634
901
  // wrapped value: `Some(0) || undefined === undefined`, so the Some arm
635
902
  // re-tests and falls back to None.
636
903
  if (e.op === "||" && e.left.ty.kind === "optional" &&
637
- e.right.kind === "var" && e.right.name === "undefined") {
904
+ e.right.kind === "var" && (e.right.name === "undefined" || e.right.name === "null")) {
638
905
  const optExpr = lowerExpr(e.left, binds);
639
906
  const bound = matchBinder("value");
640
907
  const truthy = valueTruthyCond({ kind: "var", name: bound }, e.left.ty.inner);
@@ -652,6 +919,29 @@ function lowerExpr(e, binds) {
652
919
  ],
653
920
  };
654
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
+ }
655
945
  // || on optional → match Some/None with default. JS `||` tests falsiness of
656
946
  // the *unwrapped* value, so when the inner type can be falsy the Some arm must
657
947
  // re-test (`Some(0) || 1 === 1`); array/user inners are always truthy and
@@ -702,8 +992,8 @@ function lowerExpr(e, binds) {
702
992
  (e.left.ty.kind === "user" && e.right.ty.kind === "string"))) {
703
993
  const left = lowerExpr(e.left, binds);
704
994
  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";
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");
707
997
  return {
708
998
  kind: "if",
709
999
  // strings carry the `length` marker — it renders to `|x|` in Dafny and
@@ -713,12 +1003,12 @@ function lowerExpr(e, binds) {
713
1003
  else: right,
714
1004
  };
715
1005
  }
716
- // `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
717
1007
  // optional-field initialization where the source assigns a truthy/false
718
1008
  // bool to a `T?` field. Without this, emit produces `bool || None`,
719
1009
  // which Dafny rejects (bool || Option<?> is ill-typed).
720
1010
  if (e.op === "||" && e.left.ty.kind === "bool" &&
721
- e.right.kind === "var" && e.right.name === "undefined") {
1011
+ e.right.kind === "var" && (e.right.name === "undefined" || e.right.name === "null")) {
722
1012
  const left = lowerExpr(e.left, binds);
723
1013
  return {
724
1014
  kind: "if",
@@ -1068,6 +1358,32 @@ function lowerExpr(e, binds) {
1068
1358
  }
1069
1359
  if (e.fn.kind !== "var")
1070
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
+ }
1071
1387
  const prefix = e.callKind === "spec-pure" && _opts.backend === "lean" ? "Pure." : "";
1072
1388
  return { kind: "app", fn: prefix + e.fn.name, args: e.args.map(a => lowerExpr(a, binds)) };
1073
1389
  }
@@ -1099,7 +1415,12 @@ function lowerExpr(e, binds) {
1099
1415
  // `Result.true_` is valid in Lean; `Result<Model,Err>.true_` is not.
1100
1416
  const args = variant.fields.map(vf => {
1101
1417
  const ef = nonDiscFields.find(f => f.name === vf.name);
1102
- 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" };
1103
1424
  });
1104
1425
  return { kind: "app", fn: variantName, args, ctorOf: baseName };
1105
1426
  }
@@ -1134,13 +1455,16 @@ function lowerExpr(e, binds) {
1134
1455
  fieldValue = { ...fieldValue, ty: declaredTy };
1135
1456
  }
1136
1457
  let value = lowerExpr(fieldValue, binds);
1137
- // Wrap non-optional values in Some for optional fields
1458
+ // Wrap non-optional/non-nullish values for optional/nullish fields
1138
1459
  if (declaredTy?.kind === "optional") {
1139
- 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");
1140
1461
  if (f.value.ty.kind !== "optional" && !isUndef) {
1141
1462
  value = { kind: "app", fn: "Some", args: [value] };
1142
1463
  }
1143
1464
  }
1465
+ else if (declaredTy?.kind === "nullish") {
1466
+ value = wrapNullishBranch(value, f.value);
1467
+ }
1144
1468
  return { name: f.name, value };
1145
1469
  });
1146
1470
  return { kind: "record", spread: lowerExpr(e.spread, binds), fields: loweredFields };
@@ -1217,6 +1541,10 @@ function lowerExpr(e, binds) {
1217
1541
  thenExpr = wrapOptionalBranch(thenExpr, e.then);
1218
1542
  elseExpr = wrapOptionalBranch(elseExpr, e.else);
1219
1543
  }
1544
+ else if (e.ty.kind === "nullish") {
1545
+ thenExpr = wrapNullishBranch(thenExpr, e.then);
1546
+ elseExpr = wrapNullishBranch(elseExpr, e.else);
1547
+ }
1220
1548
  if (binds && (thenBinds?.length || elseBinds?.length)) {
1221
1549
  const name = freshName(`_branch${_branchCounter++}`);
1222
1550
  // Both arms assign before the result is read. This initializer is not
@@ -1230,12 +1558,69 @@ function lowerExpr(e, binds) {
1230
1558
  }
1231
1559
  return { kind: "if", cond, then: thenExpr, else: elseExpr };
1232
1560
  }
1233
- case "optChain":
1234
- // 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.
1235
1595
  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.
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.
1238
1622
  throw new Error(`nullish reached transform — narrow should have rewritten it: ${JSON.stringify(e).slice(0, 300)}`);
1623
+ }
1239
1624
  case "havoc":
1240
1625
  // Dafny's * only works in var/assign positions — lift to own declaration
1241
1626
  if (binds) {
@@ -1272,6 +1657,10 @@ function lowerExpr(e, binds) {
1272
1657
  someBody = wrapOptionalBranch(someBody, e.someBody);
1273
1658
  noneBody = wrapOptionalBranch(noneBody, e.noneBody);
1274
1659
  }
1660
+ else if (e.ty.kind === "nullish") {
1661
+ someBody = wrapNullishBranch(someBody, e.someBody);
1662
+ noneBody = wrapNullishBranch(noneBody, e.noneBody);
1663
+ }
1275
1664
  return {
1276
1665
  kind: "match", scrutinee,
1277
1666
  arms: [
@@ -1294,6 +1683,7 @@ function lowerExpr(e, binds) {
1294
1683
  const varName = e.scrutinee.kind === "var" ? e.scrutinee.name : undefined;
1295
1684
  const pathHint = varName ?? scrutineeHint(e.scrutinee);
1296
1685
  const wrapOpt = e.ty.kind === "optional";
1686
+ const wrapNullish = e.ty.kind === "nullish";
1297
1687
  const arms = e.cases.map(c => {
1298
1688
  const variant = decl?.variants?.find(v => v.name === c.variant);
1299
1689
  const fields = variant?.fields ?? [];
@@ -1312,12 +1702,16 @@ function lowerExpr(e, binds) {
1312
1702
  }
1313
1703
  if (wrapOpt)
1314
1704
  body = wrapOptionalBranch(body, c.body);
1705
+ else if (wrapNullish)
1706
+ body = wrapNullishBranch(body, c.body);
1315
1707
  return { pattern: buildMatchPattern(c.variant, fields, pathHint), body };
1316
1708
  });
1317
1709
  if (e.fallthrough) {
1318
1710
  let body = lowerExpr(e.fallthrough, binds);
1319
1711
  if (wrapOpt)
1320
1712
  body = wrapOptionalBranch(body, e.fallthrough);
1713
+ else if (wrapNullish)
1714
+ body = wrapNullishBranch(body, e.fallthrough);
1321
1715
  arms.push({ pattern: pWild(), body });
1322
1716
  }
1323
1717
  return { kind: "match", scrutinee: varName !== undefined ? varE(varName) : scrutinee, arms };
@@ -1364,7 +1758,9 @@ function ensuresToMatch(e, typeDecls) {
1364
1758
  }
1365
1759
  function replaceFieldAccess(e, varName, fields, ctorName, ctorOf) {
1366
1760
  return mapExpr(e, x => {
1367
- 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") {
1368
1764
  const f = fields.find(f => f.name === x.field);
1369
1765
  if (f)
1370
1766
  return { kind: "var", name: matchBinder(f.name, varName) };
@@ -1444,18 +1840,17 @@ function negateExpr(e) {
1444
1840
  * - `optValue` is `(if |arr|>0 then Some(arr[|arr|-1]) else None)` (the popped element)
1445
1841
  * - `guardedTrunc` is `(if |arr|>0 then arr[..|arr|-1] else arr)` (the array minus its last element)
1446
1842
  * 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" };
1843
+ function buildPopLoweringExpr(arrExpr, arrTy) {
1844
+ const arrLen = { kind: "field", obj: arrExpr, field: "size" };
1450
1845
  const lastIdx = { kind: "binop", op: "-", left: arrLen, right: { kind: "num", value: 1 } };
1451
- const lastElem = { kind: "index", arr: arrVar, idx: lastIdx };
1846
+ const lastElem = { kind: "index", arr: arrExpr, idx: lastIdx };
1452
1847
  const isNonEmpty = { kind: "binop", op: ">", left: arrLen, right: { kind: "num", value: 0 } };
1453
1848
  const optValue = { kind: "if", cond: isNonEmpty,
1454
1849
  then: { kind: "app", fn: "Some", args: [lastElem] },
1455
1850
  else: { kind: "var", name: "undefined" } };
1456
- const truncated = { kind: "methodCall", obj: arrVar, objTy: arrTy, method: "slice",
1851
+ const truncated = { kind: "methodCall", obj: arrExpr, objTy: arrTy, method: "slice",
1457
1852
  args: [{ kind: "num", value: 0 }, lastIdx], monadic: false };
1458
- const guardedTrunc = { kind: "if", cond: isNonEmpty, then: truncated, else: arrVar };
1853
+ const guardedTrunc = { kind: "if", cond: isNonEmpty, then: truncated, else: arrExpr };
1459
1854
  return { optValue, guardedTrunc };
1460
1855
  }
1461
1856
  /**
@@ -1833,7 +2228,7 @@ function lookupFieldTy(rootTy, fields, typeDecls) {
1833
2228
  for (const field of fields) {
1834
2229
  if (!cur)
1835
2230
  return null;
1836
- if (cur.kind === "optional")
2231
+ if (cur.kind === "optional" || cur.kind === "nullish")
1837
2232
  cur = cur.inner;
1838
2233
  if (cur.kind !== "user")
1839
2234
  return null;
@@ -1903,27 +2298,38 @@ function transformStmt(s, typeDecls) {
1903
2298
  if (s.init.kind === "havoc") {
1904
2299
  return [{ kind: "let", name: s.name, type: s.ty, mutable: s.mutable, value: { kind: "havoc", type: s.init.ty } }];
1905
2300
  }
1906
- // 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)
1907
2302
  const init = s.init.kind === "call" ? s.init : undefined;
1908
2303
  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;
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;
1910
2307
  if (arrName) {
1911
- 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 };
1912
2311
  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 } };
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 };
1916
2316
  return [letHead, sliceTail, ...emitWriteBacksForTarget(arrName, _writeBackFrames)];
1917
2317
  }
1918
2318
  }
1919
2319
  // let x = arr.pop() → let x: T? = (Option-expr); arr := (truncated-or-self)
1920
2320
  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;
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;
1922
2324
  if (arrName) {
1923
- 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;
1924
2330
  return [
1925
2331
  { kind: "let", name: s.name, type: s.ty, mutable: s.mutable, value: optValue },
1926
- { kind: "assign", target: arrName, value: guardedTrunc },
2332
+ { kind: "assign", target: arrName, value: truncVal },
1927
2333
  ...emitWriteBacksForTarget(arrName, _writeBackFrames),
1928
2334
  ];
1929
2335
  }
@@ -1981,25 +2387,32 @@ function transformStmt(s, typeDecls) {
1981
2387
  case "assign": {
1982
2388
  // x = arr.pop() → x := (Option-expr); arr := (truncated-or-self) + Place write-back
1983
2389
  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);
1988
- return [
1989
- { kind: "assign", target: s.target, value: optValue },
1990
- { kind: "assign", target: arrName, value: guardedTrunc },
1991
- ...emitWriteBacksForTarget(arrName, _writeBackFrames),
1992
- ];
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
+ }
1993
2406
  }
1994
2407
  // 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`):
2408
+ // optional/nullish record (e.g. `b.count = 5`, `u.v = 99`, `u.items[0] = 10`, `u.box.count = 42`):
1996
2409
  // lower through active `unwrap` & `variant` frames with cascading write-back.
1997
2410
  if (s.target.includes(".") && !s.target.startsWith("this.")) {
1998
2411
  const parts = s.target.split(".");
1999
2412
  const rootVar = parts[0];
2000
2413
  const fields = parts.slice(1);
2001
2414
  const { binds, expr } = liftMethodCalls(s.value);
2002
- const isUndefRhs = s.value.kind === "var" && s.value.name === "undefined";
2415
+ const isUndefRhs = s.value.kind === "var" && (s.value.name === "undefined" || s.value.name === "null");
2003
2416
  const isOptRhs = s.value.ty.kind === "optional" || isUndefRhs;
2004
2417
  const resolved = resolveWriteTargetThroughFrames(rootVar, fields, _writeBackFrames);
2005
2418
  if (resolved.leafUnwrapFrame) {
@@ -2011,7 +2424,7 @@ function transformStmt(s, typeDecls) {
2011
2424
  ...emitWriteBacksForTarget(frame.binder, _writeBackFrames),
2012
2425
  ];
2013
2426
  }
2014
- // Assigning `undefined` or an `Option<T>` value to a narrowed optional field:
2427
+ // Assigning `undefined`/`null` or an `Option<T>` value to a narrowed optional field:
2015
2428
  // write directly to the enclosing record field without double-wrapping in `Some`.
2016
2429
  const optExpr = isUndefRhs
2017
2430
  ? { kind: "constructor", name: "none", type: "Option", args: [] }
@@ -2031,10 +2444,10 @@ function transformStmt(s, typeDecls) {
2031
2444
  }
2032
2445
  if (resolved.leafVariantBinder) {
2033
2446
  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: [] }
2447
+ const rhsExpr = binderTy?.kind === "nullish"
2448
+ ? wrapNullishBranch(expr, s.value)
2449
+ : binderTy?.kind === "optional"
2450
+ ? wrapOptionalBranch(expr, s.value)
2038
2451
  : expr;
2039
2452
  return [
2040
2453
  ...binds,
@@ -2043,14 +2456,31 @@ function transformStmt(s, typeDecls) {
2043
2456
  ];
2044
2457
  }
2045
2458
  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;
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
+ }
2054
2484
  return [
2055
2485
  ...binds,
2056
2486
  { kind: "assign", target: resolved.currentRoot, value: buildNestedFieldExpr(resolved.currentRoot, resolved.remainingFields, rhsExpr) },
@@ -2129,7 +2559,7 @@ function transformStmt(s, typeDecls) {
2129
2559
  }
2130
2560
  if (recv.kind === "checkedUnwrap") {
2131
2561
  const { binds, expr } = liftMethodCalls(s.expr);
2132
- const wrapped = { kind: "app", fn: "Some", args: [expr] };
2562
+ const wrapped = wrapCheckedUnwrapValue(expr, recv.expr.ty);
2133
2563
  if (recv.expr.kind === "var") {
2134
2564
  return [
2135
2565
  ...binds,
@@ -2442,12 +2872,14 @@ function emitSwitchStmt(s, typeDecls) {
2442
2872
  throw new Error(`switch scrutinee must be string-typed or a declared union, got ${typeName}`);
2443
2873
  }
2444
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 : "?";
2445
2877
  const arms = literalCases
2446
2878
  ? buildLiteralMatchArms(cases, (body) => transformStmts(body, typeDecls))
2447
2879
  : ef
2448
2880
  ? 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;
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";
2451
2883
  const variantMeta = ctorName ? ctorDecl?.variants?.find(v => v.name === ctorName) : undefined;
2452
2884
  if (pushVariant) {
2453
2885
  for (const f of fields) {
@@ -2481,7 +2913,10 @@ function emitSwitchStmt(s, typeDecls) {
2481
2913
  });
2482
2914
  if (s.defaultBody.length > 0)
2483
2915
  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 };
2916
+ const scrutinee = ef ? ef.scrutinee
2917
+ : s.expr.kind === "checkedUnwrap" ? transformExpr(s.expr)
2918
+ : varE(switchVarName);
2919
+ return { kind: "match", scrutinee, arms };
2485
2920
  }
2486
2921
  /** Replace obj.field → replacement var in typed IR.
2487
2922
  * Uses the TExpr's resolved type when available, falling back to `fallbackTy`. */
@@ -2628,6 +3063,13 @@ function transformPureBody(stmts, typeDecls) {
2628
3063
  switch (s.kind) {
2629
3064
  case "return": return transformExpr(s.value);
2630
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
+ }
2631
3073
  const restExpr = transformPureBody(rest, typeDecls);
2632
3074
  if (!restExpr)
2633
3075
  return null;
@@ -2697,7 +3139,8 @@ function transformPureSwitch(s, typeDecls) {
2697
3139
  if (!ctorDecl)
2698
3140
  return null;
2699
3141
  const typeName = ctorDecl.name;
2700
- 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;
2701
3144
  const cases = s.cases.map(c => ({ name: c.label, body: c.body }));
2702
3145
  const arms = buildMatchArms(cases, varName, typeName, typeDecls, (body, vn, fields, ctorName) => {
2703
3146
  const projected = vn ? projectStructuralCallArgsInTStmts(body, vn, fields) : body;
@@ -2716,6 +3159,8 @@ function transformPureSwitch(s, typeDecls) {
2716
3159
  return null;
2717
3160
  arms.push({ pattern: pWild(), body });
2718
3161
  }
3162
+ if (s.expr.kind === "checkedUnwrap")
3163
+ return { kind: "match", scrutinee: transformExpr(s.expr), arms };
2719
3164
  if (s.expr.kind !== "var")
2720
3165
  return null;
2721
3166
  return { kind: "match", scrutinee: varE(s.expr.name), arms };