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
  * Uses linked environments (Scheme-style) for lexical scoping.
5
5
  * No mutation — each let extends the chain, lookup walks it.
6
6
  */
7
- import { isBigInt, tyEqual, isTerminatorKind } from "./typedir.js";
7
+ import { isBigInt, optAbsent, tyEqual, isTerminatorKind } from "./typedir.js";
8
8
  import { parseTsType, tyToCanonical } from "./types.js";
9
9
  import { parseExpr } from "./specparser.js";
10
10
  import { freshName } from "./names.js";
@@ -21,8 +21,12 @@ function lookup(env, name) {
21
21
  return undefined;
22
22
  return env.name === name ? env.ty : lookup(env.parent, name);
23
23
  }
24
+ function storageLookup(env, name) {
25
+ const entry = binding(env, name);
26
+ return entry ? (entry.storageTy ?? entry.ty) : undefined;
27
+ }
24
28
  function extend(env, name, ty) {
25
- return { name, ty, parent: env };
29
+ return { name, ty, storageTy: ty, parent: env };
26
30
  }
27
31
  /** A quantified variable that reuses the name of a binding in scope is emitted
28
32
  * under a fresh name, so no later pass confuses it with that binding. */
@@ -48,7 +52,7 @@ function refine(env, name, ty) {
48
52
  break;
49
53
  }
50
54
  }
51
- return { ...entry, name: entry?.name ?? name, ty, parent: env };
55
+ return { ...entry, name: entry?.name ?? name, ty, storageTy: entry?.storageTy ?? entry?.ty ?? ty, parent: env };
52
56
  }
53
57
  function asRawAccessPath(e) {
54
58
  if (e.kind === "var")
@@ -78,32 +82,40 @@ function resolveTsType(tsType, overrides, varName) {
78
82
  return parseTsType(tsType);
79
83
  }
80
84
  /** Infer a conditional's result type after its branches have been resolved or
81
- * contextually coerced. A void branch is the source-level null/undefined arm. */
85
+ * contextually coerced. `void` is `undefined`, `null` is `null`; mixing both
86
+ * sentinels yields `nullish<T>` so `null !== undefined` is preserved (#304). */
82
87
  function conditionalResultTy(thenTy, elseTy) {
83
88
  if ((thenTy.kind === "int" || thenTy.kind === "nat") &&
84
89
  (elseTy.kind === "int" || elseTy.kind === "nat")) {
85
90
  return { ...thenTy, kind: thenTy.kind === "int" || elseTy.kind === "int" ? "int" : "nat" };
86
91
  }
87
- let ty = thenTy.kind !== "unknown" ? thenTy : elseTy;
88
- if (thenTy.kind === "void" && elseTy.kind !== "void" && elseTy.kind !== "unknown") {
89
- ty = { kind: "optional", inner: elseTy };
90
- }
91
- else if (elseTy.kind === "void" && thenTy.kind !== "void" && thenTy.kind !== "unknown") {
92
- ty = { kind: "optional", inner: thenTy };
93
- }
94
- else if (thenTy.kind === "optional" && elseTy.kind !== "optional" && elseTy.kind !== "unknown") {
95
- ty = thenTy;
96
- }
97
- else if (elseTy.kind === "optional" && thenTy.kind !== "optional" && thenTy.kind !== "unknown") {
98
- ty = elseTy;
92
+ const hasNull = (t) => t.kind === "null" || t.kind === "nullish" || (t.kind === "optional" && optAbsent(t) === "null");
93
+ const hasUndef = (t) => t.kind === "void" || t.kind === "nullish" || (t.kind === "optional" && optAbsent(t) === "undefined");
94
+ const payloadOf = (t) => t.kind === "void" || t.kind === "null" || t.kind === "unknown" ? null
95
+ : (t.kind === "optional" || t.kind === "nullish") ? t.inner : t;
96
+ const bothNull = hasNull(thenTy) || hasNull(elseTy);
97
+ const bothUndef = hasUndef(thenTy) || hasUndef(elseTy);
98
+ if (bothNull || bothUndef) {
99
+ const p1 = payloadOf(thenTy);
100
+ const p2 = payloadOf(elseTy);
101
+ const inner = p1 ?? p2;
102
+ if (inner) {
103
+ if (bothNull && bothUndef)
104
+ return { kind: "nullish", inner };
105
+ if (bothNull)
106
+ return { kind: "optional", inner, absent: "null" };
107
+ return { kind: "optional", inner };
108
+ }
109
+ if (bothNull && bothUndef)
110
+ return { kind: "nullish", inner: { kind: "void" } };
99
111
  }
100
- return ty;
112
+ return thenTy.kind !== "unknown" ? thenTy : elseTy;
101
113
  }
102
114
  /** Contextually type string literals as string-union constructors. Ternary branches inherit
103
- * the ternary's target, and an optional target contributes its payload type —
104
- * the caller adds the Some wrapper only after the payload has been coerced. */
115
+ * the ternary's target, and an optional/nullish target contributes its payload type —
116
+ * the caller adds the Some/Value wrapper only after the payload has been coerced. */
105
117
  function coerceStr(expr, targetTy, typeDecls) {
106
- const payloadTy = targetTy.kind === "optional" ? targetTy.inner : targetTy;
118
+ const payloadTy = (targetTy.kind === "optional" || targetTy.kind === "nullish") ? targetTy.inner : targetTy;
107
119
  if (expr.kind === "str" && payloadTy.kind === "user") {
108
120
  const enumTy = expandAlias(payloadTy, typeDecls);
109
121
  // A synthesized string/array union has a string payload, not a constructor
@@ -126,6 +138,13 @@ function wrapSome(value, optionalTy) {
126
138
  args: [value], ty: optionalTy, callKind: "pure",
127
139
  };
128
140
  }
141
+ /** Wrap a resolved non-nullish value in Nullish.Value(...) for Nullish<T> coercion. */
142
+ function wrapNullishValue(value, nullishTy) {
143
+ return {
144
+ kind: "call", fn: { kind: "var", name: "NullishValue", ty: nullishTy },
145
+ args: [value], ty: nullishTy, callKind: "pure",
146
+ };
147
+ }
129
148
  /** Find the synth array-union TypeDecl named `name` (discriminant `__isArray__`). */
130
149
  function findSynthArrayUnion(name, typeDecls) {
131
150
  const decl = declOf(typeDecls, name);
@@ -136,6 +155,8 @@ function findSynthArrayUnion(name, typeDecls) {
136
155
  /** Coerce `value` to `targetTy` at an assignment-position. Contextually types
137
156
  * real literals, then mirrors TS subtyping for the upcast shapes LS synthesizes:
138
157
  * - `T` into `optional<T>` slot → wrap with `Some(...)`
158
+ * - `T` / `Option<T>` / `null` / `undefined` into `nullish<T>` slot → `Nullish<T>`
159
+ * - `fromNullish` into `optional<T>` slot → `__nullishToOption(...)`
139
160
  * - `T[]` into a synth `T[] | U` slot → wrap with `ArrayBranch(...)`
140
161
  * - `U` into a synth `T[] | U` slot → wrap with `NonArrayBranch(...)`
141
162
  * Returns `value` unchanged if no coercion applies (types already match,
@@ -143,8 +164,8 @@ function findSynthArrayUnion(name, typeDecls) {
143
164
  function coerceToTargetTy(value, targetTy, typeDecls) {
144
165
  value = coerceStr(value, targetTy, typeDecls);
145
166
  // Real targets also type integer literals, including negative literals and
146
- // conditional arms. Coerce optional payloads before adding Some wrappers.
147
- const payloadTy = targetTy.kind === "optional" ? targetTy.inner : targetTy;
167
+ // conditional arms. Coerce optional/nullish payloads before adding wrappers.
168
+ const payloadTy = (targetTy.kind === "optional" || targetTy.kind === "nullish") ? targetTy.inner : targetTy;
148
169
  if (payloadTy.kind === "real") {
149
170
  if (value.kind === "num") {
150
171
  value = { ...value, ty: payloadTy };
@@ -158,10 +179,53 @@ function coerceToTargetTy(value, targetTy, typeDecls) {
158
179
  value = { ...value, then: then_, else: else_, ty: conditionalResultTy(then_.ty, else_.ty) };
159
180
  }
160
181
  }
161
- if (value.ty.kind === "unknown" || value.ty.kind === "void")
182
+ if (targetTy.kind === "nullish") {
183
+ if (value.ty.kind === "unknown")
184
+ return value;
185
+ if (value.kind === "var" && (value.name === "undefined" || value.name === "null")) {
186
+ return { ...value, ty: targetTy };
187
+ }
188
+ if (value.ty.kind === "void")
189
+ return { kind: "var", name: "undefined", ty: targetTy };
190
+ if (value.ty.kind === "null")
191
+ return { kind: "var", name: "null", ty: targetTy };
192
+ if (value.ty.kind === "nullish")
193
+ return value;
194
+ if (value.ty.kind === "optional") {
195
+ // Partially narrowed fromNullish already lives in Nullish<T> storage.
196
+ if (value.ty.fromNullish)
197
+ return { ...value, ty: targetTy };
198
+ const helper = optAbsent(value.ty) === "null" ? "__optNullToNullish" : "__optUndefToNullish";
199
+ return {
200
+ kind: "call",
201
+ fn: { kind: "var", name: helper, ty: targetTy },
202
+ args: [value],
203
+ ty: targetTy,
204
+ callKind: "pure",
205
+ };
206
+ }
207
+ if (value.kind === "conditional") {
208
+ const then_ = coerceToTargetTy(value.then, targetTy, typeDecls);
209
+ const else_ = coerceToTargetTy(value.else, targetTy, typeDecls);
210
+ return { ...value, then: then_, else: else_, ty: targetTy };
211
+ }
212
+ return wrapNullishValue(value, targetTy);
213
+ }
214
+ if (value.ty.kind === "unknown" || value.ty.kind === "void" || value.ty.kind === "null")
162
215
  return value;
163
- if (targetTy.kind === "optional" && value.ty.kind !== "optional") {
164
- return wrapSome(value, targetTy);
216
+ if (targetTy.kind === "optional") {
217
+ if (value.ty.kind === "nullish" || (value.ty.kind === "optional" && value.ty.fromNullish)) {
218
+ return {
219
+ kind: "call",
220
+ fn: { kind: "var", name: "__nullishToOption", ty: targetTy },
221
+ args: [value],
222
+ ty: targetTy,
223
+ callKind: "pure",
224
+ };
225
+ }
226
+ if (value.ty.kind !== "optional") {
227
+ return wrapSome(value, targetTy);
228
+ }
165
229
  }
166
230
  if (targetTy.kind === "user") {
167
231
  if (value.ty.kind === "user" && value.ty.name === targetTy.name)
@@ -195,6 +259,60 @@ function negatedVarPresence(cond) {
195
259
  /** Collect all optional narrowings from an early-return condition.
196
260
  * Handles single checks (x === undefined) and compound || chains
197
261
  * (x === undefined || y === undefined). */
262
+ /** Extract field-path or optional-chain narrowings guaranteed after an early
263
+ * return (`if (d.b === undefined) return;` or `if (b?.tag !== 1) return;`, #354). */
264
+ function collectEarlyReturnPathNarrowings(cond) {
265
+ if (cond.kind === "binop" && cond.op === "||") {
266
+ return [
267
+ ...collectEarlyReturnPathNarrowings(cond.left),
268
+ ...collectEarlyReturnPathNarrowings(cond.right),
269
+ ];
270
+ }
271
+ // Negated field-path presence: `d.b === undefined` or `!d.b`
272
+ const f = presentFact(cond);
273
+ if (f && f.negated && f.scrutinee.kind === "field") {
274
+ const path = asTExprAccessPath(f.scrutinee);
275
+ if (path)
276
+ return [{ path, narrowedTy: f.innerTy }];
277
+ }
278
+ // Optional-chain comparison with non-undefined: `b?.tag !== 1` or `1 !== b?.tag`
279
+ // If `b` were undefined, `b?.tag` is undefined !== 1 (true -> returns early),
280
+ // so after the early return `b` is definitely present.
281
+ if (cond.kind === "binop" && cond.op === "!==") {
282
+ const [ocSide, otherSide] = cond.left.kind === "optChain"
283
+ ? [cond.left, cond.right]
284
+ : cond.right.kind === "optChain"
285
+ ? [cond.right, cond.left]
286
+ : [null, null];
287
+ if (ocSide && otherSide && !(otherSide.kind === "var" && otherSide.name === "undefined") &&
288
+ otherSide.ty.kind !== "optional" && otherSide.ty.kind !== "void" &&
289
+ ocSide.obj.ty.kind === "optional") {
290
+ const path = asTExprAccessPath(ocSide.obj);
291
+ if (path)
292
+ return [{ path, narrowedTy: ocSide.obj.ty.inner }];
293
+ }
294
+ }
295
+ // Bare negated optional chain `!b?.flag` or `b?.tag === undefined`
296
+ if (cond.kind === "unop" && cond.op === "!" && cond.expr.kind === "optChain" && cond.expr.obj.ty.kind === "optional") {
297
+ const path = asTExprAccessPath(cond.expr.obj);
298
+ if (path)
299
+ return [{ path, narrowedTy: cond.expr.obj.ty.inner }];
300
+ }
301
+ if (cond.kind === "binop" && cond.op === "===") {
302
+ const [ocSide, otherSide] = cond.left.kind === "optChain"
303
+ ? [cond.left, cond.right]
304
+ : cond.right.kind === "optChain"
305
+ ? [cond.right, cond.left]
306
+ : [null, null];
307
+ if (ocSide && otherSide && otherSide.kind === "var" && otherSide.name === "undefined" &&
308
+ ocSide.obj.ty.kind === "optional") {
309
+ const path = asTExprAccessPath(ocSide.obj);
310
+ if (path)
311
+ return [{ path, narrowedTy: ocSide.obj.ty.inner }];
312
+ }
313
+ }
314
+ return [];
315
+ }
198
316
  function collectEarlyReturnNarrowings(cond) {
199
317
  if (cond.kind === "binop" && cond.op === "||") {
200
318
  return [...collectEarlyReturnNarrowings(cond.left), ...collectEarlyReturnNarrowings(cond.right)];
@@ -303,6 +421,27 @@ function collectAndChainNarrowings(cond, ctx) {
303
421
  }
304
422
  return ctx;
305
423
  }
424
+ /** Walk an `||` chain of negated presence checks (`x === undefined || a.b === undefined || ...`)
425
+ * on the resolved left operand, returning a Ctx where those paths are narrowed
426
+ * for evaluating the right operand of `||` (since the RHS only runs when the
427
+ * LHS was false). Mirrors `collectAndChainNarrowings`. */
428
+ function collectOrChainNarrowings(cond, ctx) {
429
+ if (cond.kind === "binop" && cond.op === "||") {
430
+ const leftCtx = collectOrChainNarrowings(cond.left, ctx);
431
+ return collectOrChainNarrowings(cond.right, leftCtx);
432
+ }
433
+ const f = presentFact(cond);
434
+ if (f && f.negated) {
435
+ if (f.scrutinee.kind === "var") {
436
+ return withEnv(ctx, refine(ctx.env, f.scrutinee.name, f.innerTy));
437
+ }
438
+ const path = asTExprAccessPath(f.scrutinee);
439
+ if (path) {
440
+ return { ...ctx, narrowedPaths: [...ctx.narrowedPaths, { path, narrowedTy: f.innerTy }] };
441
+ }
442
+ }
443
+ return ctx;
444
+ }
306
445
  /** TS reference types that become value types in Dafny/Lean — const bindings need mutable var. */
307
446
  function isRefMutableInTS(ty) {
308
447
  return ty.kind === "array" || ty.kind === "map" || ty.kind === "set";
@@ -331,14 +470,33 @@ function expandAlias(ty, typeDecls, seen = new Set()) {
331
470
  if (decl.constEnumMembers)
332
471
  return { kind: "int" };
333
472
  const target = decl.aliasOfTy;
334
- if (target.kind === "array" || target.kind === "map" || target.kind === "set" || target.kind === "optional" || target.kind === "user") {
473
+ if (target.kind === "array" || target.kind === "map" || target.kind === "set" || target.kind === "optional" || target.kind === "nullish" || target.kind === "user") {
335
474
  return expandAlias(target, typeDecls, new Set([...seen, ty.name]));
336
475
  }
337
476
  }
338
477
  return ty;
339
478
  }
340
- if (ty.kind === "optional")
341
- return { kind: "optional", inner: expandAlias(ty.inner, typeDecls, seen) };
479
+ if (ty.kind === "optional") {
480
+ const expanded = expandAlias(ty.inner, typeDecls, seen);
481
+ if (expanded.kind === "nullish")
482
+ return expanded;
483
+ if (expanded.kind === "optional") {
484
+ const mergedNull = optAbsent(ty) === "null" || optAbsent(expanded) === "null";
485
+ const mergedUndef = optAbsent(ty) === "undefined" || optAbsent(expanded) === "undefined";
486
+ if (mergedNull && mergedUndef)
487
+ return { kind: "nullish", inner: expanded.inner };
488
+ return { ...ty, inner: expanded.inner };
489
+ }
490
+ return { ...ty, inner: expanded };
491
+ }
492
+ if (ty.kind === "nullish") {
493
+ const expanded = expandAlias(ty.inner, typeDecls, seen);
494
+ if (expanded.kind === "nullish")
495
+ return expanded;
496
+ if (expanded.kind === "optional")
497
+ return { kind: "nullish", inner: expanded.inner };
498
+ return { kind: "nullish", inner: expanded };
499
+ }
342
500
  if (ty.kind === "array")
343
501
  return { kind: "array", elem: expandAlias(ty.elem, typeDecls, seen) };
344
502
  if (ty.kind === "tuple")
@@ -350,11 +508,13 @@ function expandAlias(ty, typeDecls, seen = new Set()) {
350
508
  return ty;
351
509
  }
352
510
  /** Numeric aliases keep their names in declarations but use their underlying
353
- * types in expressions. Optional payloads need the same treatment for zero's
354
- * falsiness; collection elements are resolved when read. */
511
+ * types in expressions. Optional/nullish payloads need the same treatment for
512
+ * zero's falsiness; collection elements are resolved when read. */
355
513
  function numericValueType(ty, typeDecls, seen = new Set()) {
356
514
  if (ty.kind === "optional")
357
515
  return { ...ty, inner: numericValueType(ty.inner, typeDecls, seen) };
516
+ if (ty.kind === "nullish")
517
+ return { kind: "nullish", inner: numericValueType(ty.inner, typeDecls, seen) };
358
518
  if (ty.kind !== "user" || seen.has(ty.name))
359
519
  return ty;
360
520
  const decl = declOfDotted(typeDecls, ty.name);
@@ -408,7 +568,7 @@ function warnRefEq(op, l, r) {
408
568
  function isUnmodeledTy(ty, typeDecls) {
409
569
  if (ty.kind === "unknown")
410
570
  return true;
411
- if (ty.kind === "optional")
571
+ if (ty.kind === "optional" || ty.kind === "nullish")
412
572
  return isUnmodeledTy(ty.inner, typeDecls);
413
573
  if (ty.kind === "array")
414
574
  return isUnmodeledTy(ty.elem, typeDecls);
@@ -604,8 +764,14 @@ let callbackCounter = 0;
604
764
  function callbackDefaultState(ty, ctx, seen = new Set()) {
605
765
  if (ty.kind === "void")
606
766
  return "missing";
607
- if (ty.kind === "optional" || ty.kind === "unknown")
608
- return ty.kind;
767
+ if (ty.kind === "null")
768
+ return "defined";
769
+ if (ty.kind === "optional")
770
+ return optAbsent(ty) === "null" ? "defined" : "optional";
771
+ if (ty.kind === "nullish")
772
+ return "optional";
773
+ if (ty.kind === "unknown")
774
+ return "unknown";
609
775
  if (ty.kind !== "user" || ty.name === "null")
610
776
  return "defined";
611
777
  if (seen.has(ty.name))
@@ -648,10 +814,13 @@ function resolveCallback(e, actual, baseArity, ctx) {
648
814
  // binding identities; nested declarations shadow them through ordinary lookup.
649
815
  let env = ctx.env;
650
816
  const frames = e.params.map((p, i) => {
817
+ const paramTy = executesDefault(i)
818
+ ? expandAlias(parseTsType(p.inferredTsType ?? p.tsType ?? "unknown"), ctx.typeDecls)
819
+ : p.rest ? { kind: "unknown" } : slots[i]?.ty ?? { kind: "void" };
651
820
  const frame = {
652
821
  name: p.name, parent: env,
653
- ty: executesDefault(i) ? expandAlias(parseTsType(p.inferredTsType ?? p.tsType ?? "unknown"), ctx.typeDecls)
654
- : p.rest ? { kind: "unknown" } : slots[i]?.ty ?? { kind: "void" },
822
+ ty: paramTy,
823
+ storageTy: paramTy,
655
824
  onRead: () => {
656
825
  captures?.add(i);
657
826
  // A forward reference must never resolve to an outer variable if
@@ -767,20 +936,25 @@ function argumentPack(e, ctx) {
767
936
  entry.onRead?.();
768
937
  return pack;
769
938
  }
770
- /** A defined-check filter predicate: `(x) => x !== undefined` (expression or
771
- * single-return body). Detected on the raw IR before narrowing rewrites it. */
772
- function isDefinedCheckRawLambda(raw) {
939
+ /** A defined-check filter predicate: `(x) => x !== undefined`, `(x) => x !== null`,
940
+ * or loose `(x) => x != null` / `(x) => x != undefined`. Returns which sentinel
941
+ * the filter removes so `filterSome` only fires when it matches the array
942
+ * element's absent sentinel (`#304`). */
943
+ function definedCheckRawLambdaSentinel(raw) {
773
944
  if (raw.kind !== "lambda" || raw.params.length !== 1)
774
- return false;
945
+ return null;
775
946
  const p = raw.params[0].name;
776
947
  const body = Array.isArray(raw.body)
777
948
  ? (raw.body.length === 1 && raw.body[0].kind === "return" ? raw.body[0].value : null)
778
949
  : raw.body;
779
- if (!body || body.kind !== "binop" || body.op !== "!==")
780
- return false;
950
+ if (!body || body.kind !== "binop" || (body.op !== "!==" && body.op !== "!="))
951
+ return null;
781
952
  const isParam = (x) => x.kind === "var" && x.name === p;
782
- const isUndef = (x) => x.kind === "var" && x.name === "undefined";
783
- return (isParam(body.left) && isUndef(body.right)) || (isParam(body.right) && isUndef(body.left));
953
+ const sentinelOf = (x) => x.kind === "var" && (x.name === "undefined" || x.name === "null") ? x.name : null;
954
+ const s = isParam(body.left) ? sentinelOf(body.right) : isParam(body.right) ? sentinelOf(body.left) : null;
955
+ if (!s)
956
+ return null;
957
+ return body.op === "!=" ? "both" : s;
784
958
  }
785
959
  /** Coerce call arguments to their declared parameter slots and pad missing optional args. */
786
960
  function coerceCallArgs(args, fn, ctx) {
@@ -792,9 +966,9 @@ function coerceCallArgs(args, fn, ctx) {
792
966
  return a;
793
967
  return coerceToTargetTy(a, paramTys[i], ctx.typeDecls);
794
968
  });
795
- // Pad missing optional args with None
969
+ // Pad missing optional/nullish args with undefined (None / Nullish.Undefined)
796
970
  for (let i = args.length; i < paramTys.length; i++) {
797
- if (paramTys[i].kind === "optional") {
971
+ if (paramTys[i].kind === "optional" || paramTys[i].kind === "nullish") {
798
972
  args.push({ kind: "var", name: "undefined", ty: paramTys[i] });
799
973
  }
800
974
  }
@@ -914,8 +1088,8 @@ let mergeBinder = 0;
914
1088
  function resolveRecordMerge(base, override, ctx) {
915
1089
  const tbase = resolveExpr(base, ctx);
916
1090
  const tover = resolveExpr(override, ctx);
917
- const overInner = tover.ty.kind === "optional" ? tover.ty.inner : tover.ty;
918
- // Result record type: prefer the override's (an optional override still merges
1091
+ const overInner = (tover.ty.kind === "optional" || tover.ty.kind === "nullish") ? tover.ty.inner : tover.ty;
1092
+ // Result record type: prefer the override's (an optional/nullish override still merges
919
1093
  // into its inner type), else the base's.
920
1094
  const rTy = overInner.kind === "user" ? overInner
921
1095
  : tbase.ty.kind === "user" ? tbase.ty : null;
@@ -924,7 +1098,7 @@ function resolveRecordMerge(base, override, ctx) {
924
1098
  throw new Error(`object spread merge { ...a, ...b } needs a known record type for both operands ` +
925
1099
  `(base: ${tyToCanonical(tbase.ty)}, override: ${tyToCanonical(tover.ty)})`);
926
1100
  }
927
- if (tbase.ty.kind === "optional") {
1101
+ if (tbase.ty.kind === "optional" || tbase.ty.kind === "nullish") {
928
1102
  throw new Error(`object spread merge with an optional base operand is not supported (base: ${tyToCanonical(tbase.ty)})`);
929
1103
  }
930
1104
  const userTy = rTy;
@@ -936,10 +1110,19 @@ function resolveRecordMerge(base, override, ctx) {
936
1110
  const ft = f.type;
937
1111
  const ovf = { kind: "field", obj: ov, field: f.name, ty: ft };
938
1112
  // A required key is always copied, even when its value is null/undefined.
939
- if (ft.kind !== "optional" || !f.optionalKey)
1113
+ if (!f.optionalKey || (ft.kind !== "optional" && ft.kind !== "nullish"))
940
1114
  return { name: f.name, value: ovf };
941
- // `f?:` key: override field wins iff present, else base's field
942
1115
  const bvf = { kind: "field", obj: bv, field: f.name, ty: ft };
1116
+ if (ft.kind === "nullish") {
1117
+ // `f?: T | null`: override wins unless `ov.f === undefined` (null still overrides!).
1118
+ const isUndef = {
1119
+ kind: "binop", op: "===",
1120
+ left: ovf, right: { kind: "var", name: "undefined", ty: { kind: "void" } },
1121
+ ty: { kind: "bool" },
1122
+ };
1123
+ return { name: f.name, value: { kind: "conditional", cond: isUndef, then: bvf, else: ovf, ty: ft } };
1124
+ }
1125
+ // `f?:` optional key: override field wins iff present, else base's field
943
1126
  const binder = freshName(`_m${mergeBinder++}`);
944
1127
  // someBody is the unwrapped present value; transform re-wraps each arm in
945
1128
  // the backend's Some constructor (Dafny `Some`, Lean `Option.some`).
@@ -949,6 +1132,16 @@ function resolveRecordMerge(base, override, ctx) {
949
1132
  } };
950
1133
  }),
951
1134
  });
1135
+ if (tover.ty.kind === "nullish" || (tover.ty.kind === "optional" && tover.ty.fromNullish)) {
1136
+ // Nullish override: undefined/null spreads nothing → base unchanged; Value(v) merges.
1137
+ const isPresent = {
1138
+ kind: "binop", op: "!=",
1139
+ left: tover, right: { kind: "var", name: "null", ty: { kind: "null" } },
1140
+ ty: { kind: "bool" },
1141
+ };
1142
+ const unwrappedOver = { kind: "checkedUnwrap", expr: tover, ty: userTy };
1143
+ return { kind: "conditional", cond: isPresent, then: merged(tbase, unwrappedOver), else: tbase, ty: userTy };
1144
+ }
952
1145
  if (tover.ty.kind === "optional") {
953
1146
  // override may be absent (undefined spreads nothing) → base unchanged
954
1147
  const binder = freshName(`_mo${mergeBinder++}`);
@@ -1019,13 +1212,19 @@ function resolveConstEnumMember(obj, name, ctx) {
1019
1212
  }
1020
1213
  function resolveExpr(e, ctx) {
1021
1214
  const expr = resolveExprInner(e, ctx);
1022
- return { ...expr, ty: numericValueType(expr.ty, ctx.typeDecls) };
1215
+ const out = { ...expr, ty: numericValueType(expr.ty, ctx.typeDecls) };
1216
+ if ("freshClone" in e && e.freshClone && (out.kind === "var" || out.kind === "field" || out.kind === "index" || out.kind === "call")) {
1217
+ return { ...out, freshClone: true };
1218
+ }
1219
+ return out;
1023
1220
  }
1024
1221
  function resolveExprInner(e, ctx) {
1025
1222
  switch (e.kind) {
1026
1223
  case "var": {
1027
1224
  if (e.name === "undefined")
1028
1225
  return { kind: "var", name: "undefined", ty: { kind: "void" } };
1226
+ if (e.name === "null")
1227
+ return { kind: "var", name: "null", ty: { kind: "null" } };
1029
1228
  const entry = binding(ctx.env, e.name);
1030
1229
  if (entry?.argumentPack) {
1031
1230
  throw new Error(`cannot materialize callback rest parameter '${e.name}'; use its length or a constant indexed read`);
@@ -1052,20 +1251,43 @@ function resolveExprInner(e, ctx) {
1052
1251
  expr.fn.obj.ty.kind === "map" && expr.fn.field === "get") {
1053
1252
  return { ...expr, ty: expr.fn.obj.ty.value };
1054
1253
  }
1055
- const ty = expr.ty.kind === "optional" ? expr.ty.inner : expr.ty;
1254
+ const ty = (expr.ty.kind === "optional" || expr.ty.kind === "nullish") ? expr.ty.inner : expr.ty;
1056
1255
  return { ...expr, ty };
1057
1256
  }
1058
1257
  case "binop": {
1059
1258
  let left = resolveExpr(e.left, ctx);
1060
- // && and ==> narrowing: left-side optional checks narrow the right side.
1259
+ // && and ==> narrowing: left-side optional/nullish checks narrow the right side.
1061
1260
  // (For ==>, the premise is assumed in the conclusion — same principle.)
1062
1261
  let rightCtx = ctx;
1063
1262
  let rawRight = e.right;
1064
1263
  if (e.op === "&&" || e.op === "==>") {
1065
1264
  rightCtx = collectAndChainNarrowings(left, ctx);
1066
1265
  }
1266
+ else if (e.op === "||") {
1267
+ // Preserve direct single-optional var comparisons (`opt === null || x < opt`,
1268
+ // `excludeTag === undefined || getTagId(t) !== excludeTag`) for transform's
1269
+ // native mirrored match lowering, as long as the non-optional side doesn't
1270
+ // also depend on a variable narrowed by `left` and neither side is `Nullish<T>`;
1271
+ // narrow all other RHS shapes via checked reads.
1272
+ const orCtx = collectOrChainNarrowings(left, ctx);
1273
+ const narrowedVars = new Set();
1274
+ for (let cur = orCtx.env; cur && cur !== ctx.env; cur = cur.parent) {
1275
+ narrowedVars.add(cur.name);
1276
+ }
1277
+ const leftTy = rawRight.kind === "binop" && rawRight.left.kind === "var" ? lookup(ctx.env, rawRight.left.name) : undefined;
1278
+ const rightTy = rawRight.kind === "binop" && rawRight.right.kind === "var" ? lookup(ctx.env, rawRight.right.name) : undefined;
1279
+ const leftIsOptVar = leftTy?.kind === "optional" && !leftTy.fromNullish;
1280
+ const rightIsOptVar = rightTy?.kind === "optional" && !rightTy.fromNullish;
1281
+ const isDirectSingleOptCmp = rawRight.kind === "binop" &&
1282
+ ["===", "!==", "<", "<=", ">", ">="].includes(rawRight.op) &&
1283
+ (leftIsOptVar !== rightIsOptVar) &&
1284
+ !rawExprMentionsAny(leftIsOptVar ? rawRight.right : rawRight.left, narrowedVars);
1285
+ if (!isDirectSingleOptCmp) {
1286
+ rightCtx = orCtx;
1287
+ }
1288
+ }
1067
1289
  let right = resolveExpr(rawRight, rightCtx);
1068
- if (e.op === "===" || e.op === "!==") {
1290
+ if (e.op === "===" || e.op === "!==" || e.op === "==" || e.op === "!=") {
1069
1291
  left = coerceStr(left, right.ty, ctx.typeDecls);
1070
1292
  right = coerceStr(right, left.ty, ctx.typeDecls);
1071
1293
  // Spec (`//@`) comparisons are proof-only, so they can't diverge at
@@ -1077,13 +1299,27 @@ function resolveExprInner(e, ctx) {
1077
1299
  let ty = { kind: "unknown" };
1078
1300
  // <==> is bool like the comparisons; unlike ==>, neither side narrows
1079
1301
  // the other (no premise to assume).
1080
- if (["===", "!==", ">=", "<=", ">", "<", "in", "<==>"].includes(e.op))
1302
+ if (["===", "!==", "==", "!=", ">=", "<=", ">", "<", "in", "<==>"].includes(e.op))
1081
1303
  ty = { kind: "bool" };
1082
1304
  else if (e.op === "&&")
1083
1305
  ty = right.ty;
1084
- else if (e.op === "||" && left.ty.kind === "optional") {
1085
- // || undefined is identity for optionals — keep the optional type
1086
- ty = (e.right.kind === "var" && e.right.name === "undefined") ? left.ty : left.ty.inner;
1306
+ else if (e.op === "||" && (left.ty.kind === "optional" || left.ty.kind === "nullish")) {
1307
+ // || undefined / || null / || nullable preserves the RHS nullability;
1308
+ // otherwise yields inner type.
1309
+ if (e.right.kind === "var" && e.right.name === "undefined") {
1310
+ ty = left.ty.kind === "optional" && optAbsent(left.ty) === "undefined"
1311
+ ? left.ty
1312
+ : { kind: "optional", inner: left.ty.inner };
1313
+ }
1314
+ else if (e.right.kind === "var" && e.right.name === "null") {
1315
+ ty = { kind: "optional", inner: left.ty.inner, absent: "null" };
1316
+ }
1317
+ else if (right.ty.kind === "optional" || right.ty.kind === "nullish") {
1318
+ ty = right.ty;
1319
+ }
1320
+ else {
1321
+ ty = left.ty.inner;
1322
+ }
1087
1323
  }
1088
1324
  else if (e.op === "||")
1089
1325
  ty = right.ty;
@@ -1180,7 +1416,7 @@ function resolveExprInner(e, ctx) {
1180
1416
  let args = coerceCallArgs(rawArgs.map((a, i) => {
1181
1417
  let aCtx = argCtx;
1182
1418
  if (paramTypes && i < paramTypes.length &&
1183
- (paramTypes[i].kind === "user" || paramTypes[i].kind === "array" || paramTypes[i].kind === "optional")) {
1419
+ (paramTypes[i].kind === "user" || paramTypes[i].kind === "array" || paramTypes[i].kind === "optional" || paramTypes[i].kind === "nullish")) {
1184
1420
  aCtx = { ...aCtx, returnTy: paramTypes[i] };
1185
1421
  }
1186
1422
  if (i === 0 && a.kind === "lambda" && callback)
@@ -1212,9 +1448,11 @@ function resolveExprInner(e, ctx) {
1212
1448
  // seq<T>. Rewrite to a synthetic `filterSome` call lowered to the proven
1213
1449
  // SeqFilterSome preamble (a plain `Map(.value, Filter(.Some?))` wouldn't
1214
1450
  // verify — `.value` is partial).
1215
- if (e.fn.kind === "field" && e.fn.field === "filter" && e.args.length === 1
1216
- && isDefinedCheckRawLambda(e.args[0])
1217
- && fn.kind === "field" && fn.obj.ty.kind === "array" && fn.obj.ty.elem.kind === "optional") {
1451
+ const filterSentinel = e.fn.kind === "field" && e.fn.field === "filter" && e.args.length === 1
1452
+ ? definedCheckRawLambdaSentinel(e.args[0]) : null;
1453
+ if (filterSentinel !== null
1454
+ && fn.kind === "field" && fn.obj.ty.kind === "array" && fn.obj.ty.elem.kind === "optional"
1455
+ && (filterSentinel === "both" || filterSentinel === optAbsent(fn.obj.ty.elem))) {
1218
1456
  return { kind: "call", fn: { ...fn, field: "filterSome" }, args: [], ty: { kind: "array", elem: fn.obj.ty.elem.inner }, callKind: "method" };
1219
1457
  }
1220
1458
  const builtinId = fn.kind === "field" ? recognizeBuiltin(fn.obj.ty, fn.field) : null;
@@ -1285,9 +1523,12 @@ function resolveExprInner(e, ctx) {
1285
1523
  if (ctx.narrowedPaths.length > 0) {
1286
1524
  const myPath = asRawAccessPath(e);
1287
1525
  if (myPath) {
1288
- const np = ctx.narrowedPaths.find(n => accessPathsEqual(n.path, myPath));
1289
- if (np)
1290
- ty = np.narrowedTy;
1526
+ for (let i = ctx.narrowedPaths.length - 1; i >= 0; i--) {
1527
+ if (accessPathsEqual(ctx.narrowedPaths[i].path, myPath)) {
1528
+ ty = ctx.narrowedPaths[i].narrowedTy;
1529
+ break;
1530
+ }
1531
+ }
1291
1532
  }
1292
1533
  }
1293
1534
  // A variant narrowing on the object picks the field's type from that
@@ -1295,7 +1536,16 @@ function resolveExprInner(e, ctx) {
1295
1536
  let ofVariant;
1296
1537
  if (ty.kind === "unknown" && ctx.narrowedPaths.length > 0 && obj.ty.kind === "user") {
1297
1538
  const objPath = asRawAccessPath(e.obj);
1298
- const np = objPath ? ctx.narrowedPaths.find(n => n.variant && accessPathsEqual(n.path, objPath)) : undefined;
1539
+ let np;
1540
+ if (objPath) {
1541
+ for (let i = ctx.narrowedPaths.length - 1; i >= 0; i--) {
1542
+ const cand = ctx.narrowedPaths[i];
1543
+ if (cand.variant && accessPathsEqual(cand.path, objPath)) {
1544
+ np = cand;
1545
+ break;
1546
+ }
1547
+ }
1548
+ }
1299
1549
  if (np?.variant) {
1300
1550
  const decl = findDecl(ctx, tyBaseName(obj.ty.name));
1301
1551
  const f = decl?.variants?.find(v => v.name === np.variant)?.fields.find(f => f.name === e.field);
@@ -1313,27 +1563,45 @@ function resolveExprInner(e, ctx) {
1313
1563
  return { kind: "field", obj, field: e.field, ty, isDiscriminant, ofVariant };
1314
1564
  }
1315
1565
  case "nullish": {
1316
- // left ?? right — result type is left's inner (when left is optional)
1566
+ // left ?? right — result type is left's inner (when left is optional/nullish)
1317
1567
  // or just left's type, unified with right's type.
1318
1568
  const left = resolveExpr(e.left, ctx);
1319
- const inner = left.ty.kind === "optional" ? left.ty.inner : left.ty;
1569
+ const isLeftNullishLit = (left.kind === "var" && (left.name === "undefined" || left.name === "null")) ||
1570
+ left.ty.kind === "void" || left.ty.kind === "null";
1571
+ const isArrayIndex = left.kind === "index" && left.obj.ty.kind === "array";
1572
+ const isLeftNullable = left.ty.kind === "optional" || left.ty.kind === "nullish";
1573
+ const inner = (left.ty.kind === "optional" || left.ty.kind === "nullish") ? left.ty.inner : left.ty;
1320
1574
  // The default shares the result type, so coerce a string literal to a
1321
1575
  // string-union enum (e.g. `availableLevels[0] ?? "off"`).
1322
- const right = coerceToTargetTy(resolveExpr(e.right, ctx), inner, ctx.typeDecls);
1323
- // `??` is only total when its default is: with a nullable right operand
1324
- // (rule-chain style `ruleA(e) ?? ruleB(e) ?? null`), the result stays
1325
- // optional — otherwise the enclosing chain level loses its optionality
1326
- // and narrowing can't rewrite it.
1327
- const ty = right.ty.kind === "optional" ? right.ty : inner;
1576
+ const right = coerceToTargetTy(resolveExpr(e.right, ctx), isLeftNullishLit ? { kind: "unknown" } : inner, ctx.typeDecls);
1577
+ // When `left` is non-nullable and not an unchecked array index (#352):
1578
+ // `undefined ?? right` / `null ?? right` has `right`'s type, and `nonOpt ?? right`
1579
+ // evaluates to `left` directly (narrow.ts strips the dead fallback).
1580
+ if (!isLeftNullable && !isArrayIndex) {
1581
+ return { kind: "nullish", left, right, ty: isLeftNullishLit ? right.ty : left.ty };
1582
+ }
1583
+ // `??` is only total when its default is: with a nullable/null/undefined
1584
+ // right operand (`x ?? undefined`, `ruleA(e) ?? ruleB(e) ?? null`), the
1585
+ // result keeps the right operand's nullability.
1586
+ let ty = inner;
1587
+ if (right.ty.kind === "optional" || right.ty.kind === "nullish")
1588
+ ty = right.ty;
1589
+ else if (right.ty.kind === "void" || (right.kind === "var" && right.name === "undefined"))
1590
+ ty = { kind: "optional", inner };
1591
+ else if (right.ty.kind === "null" || (right.kind === "var" && right.name === "null"))
1592
+ ty = { kind: "optional", inner, absent: "null" };
1328
1593
  return { kind: "nullish", left, right, ty };
1329
1594
  }
1330
1595
  case "optChain": {
1331
- // obj?.<chain> — obj has type Option<T>; we walk the chain stepping
1332
- // through types from T. The final result is Option<finalStepTy>
1333
- // (collapsed: if finalStepTy is already optional, we don't double-wrap).
1334
- // Narrow rewrites this to a someMatch with the chain applied to the binder.
1596
+ // obj?.<chain> — obj has type Option<T> or Nullish<T>; we walk the chain
1597
+ // stepping through types from T. Short-circuiting always yields `undefined`
1598
+ // in JS (so a `T | null` chain step becomes `Nullish<T>`).
1335
1599
  const obj = resolveExpr(e.obj, ctx);
1336
- let stepInTy = obj.ty.kind === "optional" ? obj.ty.inner : obj.ty;
1600
+ const isObjNullishLit = (obj.kind === "var" && (obj.name === "undefined" || obj.name === "null")) ||
1601
+ obj.ty.kind === "void" || obj.ty.kind === "null";
1602
+ const isObjArrayIndex = obj.kind === "index" && obj.obj.ty.kind === "array";
1603
+ const isObjNullable = obj.ty.kind === "optional" || obj.ty.kind === "nullish";
1604
+ let stepInTy = (obj.ty.kind === "optional" || obj.ty.kind === "nullish") ? obj.ty.inner : obj.ty;
1337
1605
  const chain = [];
1338
1606
  for (const step of e.chain) {
1339
1607
  if (step.kind === "field") {
@@ -1363,7 +1631,7 @@ function resolveExprInner(e, ctx) {
1363
1631
  let rawArgs = step.args;
1364
1632
  if (lastField) {
1365
1633
  const priorInTy = chain.length >= 2 ? chain[chain.length - 2].ty
1366
- : (obj.ty.kind === "optional" ? obj.ty.inner : obj.ty);
1634
+ : ((obj.ty.kind === "optional" || obj.ty.kind === "nullish") ? obj.ty.inner : obj.ty);
1367
1635
  const fakeObj = { kind: "var", name: "_chain_recv", ty: priorInTy };
1368
1636
  const fakeFn = { kind: "field", obj: fakeObj, field: lastField.name, ty: lastField.ty };
1369
1637
  rawArgs = inferLambdaParamTypes(fakeFn, rawArgs);
@@ -1386,7 +1654,19 @@ function resolveExprInner(e, ctx) {
1386
1654
  }
1387
1655
  }
1388
1656
  const finalTy = stepInTy;
1389
- const ty = finalTy.kind === "optional" ? finalTy : { kind: "optional", inner: finalTy };
1657
+ // Non-optional receiver (excluding unchecked array index) never produces
1658
+ // None from the `?.` step itself (#352); narrow.ts lowers it directly.
1659
+ // When the receiver IS nullable, short-circuiting adds `| undefined`:
1660
+ // - `T | null` + `| undefined` → `Nullish<T>`
1661
+ // - `Nullish<T>` → `Nullish<T>`
1662
+ // - `T | undefined` → `T | undefined`
1663
+ // - `T` → `T | undefined`
1664
+ const ty = isObjNullishLit ? { kind: "void" }
1665
+ : (!isObjNullable && !isObjArrayIndex) ? finalTy
1666
+ : finalTy.kind === "nullish" ? finalTy
1667
+ : finalTy.kind === "optional"
1668
+ ? (optAbsent(finalTy) === "null" ? { kind: "nullish", inner: finalTy.inner } : finalTy)
1669
+ : { kind: "optional", inner: finalTy };
1390
1670
  return { kind: "optChain", obj, chain, ty };
1391
1671
  }
1392
1672
  case "record": {
@@ -1404,9 +1684,9 @@ function resolveExprInner(e, ctx) {
1404
1684
  return { kind: "record", spread: null, fields, ty: mapTy };
1405
1685
  }
1406
1686
  // Infer record type: from spread, or from return type context. Unwrap
1407
- // an outer Optional when looking at returnTy — `return {...} : null`
1408
- // has ctx.returnTy = Option<T>, but the record literal's natural type is T.
1409
- const returnTyUnwrapped = ctx.returnTy.kind === "optional" ? ctx.returnTy.inner : ctx.returnTy;
1687
+ // an outer Optional/Nullish when looking at returnTy — `return {...} : null`
1688
+ // has ctx.returnTy = Option<T>/Nullish<T>, but the record literal's natural type is T.
1689
+ const returnTyUnwrapped = (ctx.returnTy.kind === "optional" || ctx.returnTy.kind === "nullish") ? ctx.returnTy.inner : ctx.returnTy;
1410
1690
  const recordTy = ty.kind === "user" ? ty : returnTyUnwrapped.kind === "user" ? returnTyUnwrapped : null;
1411
1691
  const decl = recordTy ? declOfKind(ctx.typeDecls, recordTy.name, "record") : undefined;
1412
1692
  // Union-variant literal in union-typed context (a constructed IR node,
@@ -1432,7 +1712,7 @@ function resolveExprInner(e, ctx) {
1432
1712
  // by coerceToTargetTy below); array fields propagate whole, so the
1433
1713
  // arrayLiteral case can thread the element type.
1434
1714
  const fdTy = fieldDecl?.type;
1435
- const fdCtxTy = fdTy?.kind === "optional" ? fdTy.inner : fdTy;
1715
+ const fdCtxTy = (fdTy?.kind === "optional" || fdTy?.kind === "nullish") ? fdTy.inner : fdTy;
1436
1716
  const valueCtx = fdCtxTy && (fdCtxTy.kind === "user" || fdCtxTy.kind === "array")
1437
1717
  ? { ...fieldCtx, returnTy: fdCtxTy }
1438
1718
  : fieldCtx;
@@ -1491,7 +1771,7 @@ function resolveExprInner(e, ctx) {
1491
1771
  // get their type via ctx.returnTy). Only narrow when the context type is an
1492
1772
  // array (unwrapping one optional level — `TStmt[] | null` return positions);
1493
1773
  // otherwise leave ctx untouched.
1494
- const rtUnwrapped = ctx.returnTy.kind === "optional" ? ctx.returnTy.inner : ctx.returnTy;
1774
+ const rtUnwrapped = (ctx.returnTy.kind === "optional" || ctx.returnTy.kind === "nullish") ? ctx.returnTy.inner : ctx.returnTy;
1495
1775
  const expectedElem = rtUnwrapped.kind === "array" ? rtUnwrapped.elem : null;
1496
1776
  const elemCtx = expectedElem ? { ...ctx, returnTy: expectedElem } : ctx;
1497
1777
  const elems = e.elems.map(el => {
@@ -1546,20 +1826,24 @@ function resolveExprInner(e, ctx) {
1546
1826
  // checks are in scope when resolving later ones.
1547
1827
  let thenCtx = collectAndChainNarrowings(cond, ctx);
1548
1828
  let elseCtx = ctx;
1549
- // Truthiness — cond itself is optional (`opt ? a : b`), only for simple vars.
1550
- if (cond.ty.kind === "optional" && cond.kind === "var") {
1829
+ // Truthiness — cond itself is optional/nullish (`opt ? a : b`), only for simple vars.
1830
+ if ((cond.ty.kind === "optional" || cond.ty.kind === "nullish") && cond.kind === "var") {
1551
1831
  thenCtx = withEnv(thenCtx, refine(thenCtx.env, cond.name, cond.ty.inner));
1552
1832
  }
1553
- // Single === undefined check narrows the else-branch.
1833
+ // Negated presence check (single or `||`-chain, var or field path) narrows else-branch.
1554
1834
  const single = negatedVarPresence(cond);
1555
1835
  if (single) {
1556
1836
  elseCtx = withEnv(elseCtx, refine(elseCtx.env, single.varName, single.innerTy));
1557
1837
  }
1558
- if (!single && cond.kind === "binop" && cond.op === "||") {
1838
+ else if (cond.kind === "binop" && cond.op === "||") {
1559
1839
  for (const n of collectEarlyReturnNarrowings(cond)) {
1560
1840
  elseCtx = withEnv(elseCtx, refine(elseCtx.env, n.varName, n.innerTy));
1561
1841
  }
1562
1842
  }
1843
+ const negPaths = collectEarlyReturnPathNarrowings(cond);
1844
+ if (negPaths.length > 0) {
1845
+ elseCtx = { ...elseCtx, narrowedPaths: [...elseCtx.narrowedPaths, ...negPaths] };
1846
+ }
1563
1847
  // Map-index narrowing: `k in m` in the cond narrows the then-branch; `!(k in m)`
1564
1848
  // narrows the else-branch. Parallel to the if-statement hook in resolveStmt.
1565
1849
  thenCtx = withInAtoms(thenCtx, extractInAtoms(cond));
@@ -1599,6 +1883,137 @@ function splitConj(e) {
1599
1883
  return [e];
1600
1884
  }
1601
1885
  // ── Resolve statements ───────────────────────────────────────
1886
+ /** True if `e` references any variable name in `names`. */
1887
+ function rawExprMentionsAny(e, names) {
1888
+ if (names.size === 0)
1889
+ return false;
1890
+ switch (e.kind) {
1891
+ case "var": return names.has(e.name);
1892
+ case "num":
1893
+ case "bigint":
1894
+ case "str":
1895
+ case "bool":
1896
+ case "havoc": return false;
1897
+ case "binop": return rawExprMentionsAny(e.left, names) || rawExprMentionsAny(e.right, names);
1898
+ case "unop":
1899
+ case "nonNull": return rawExprMentionsAny(e.expr, names);
1900
+ case "field": return rawExprMentionsAny(e.obj, names);
1901
+ case "index": return rawExprMentionsAny(e.obj, names) || rawExprMentionsAny(e.idx, names);
1902
+ case "call": return rawExprMentionsAny(e.fn, names) || e.args.some(a => rawExprMentionsAny(a, names));
1903
+ case "record":
1904
+ return (e.spread ? rawExprMentionsAny(e.spread, names) : false) ||
1905
+ e.fields.some(f => rawExprMentionsAny(f.value, names));
1906
+ case "arrayLiteral": return e.elems.some(el => rawExprMentionsAny(el, names));
1907
+ case "conditional":
1908
+ return rawExprMentionsAny(e.cond, names) || rawExprMentionsAny(e.then, names) || rawExprMentionsAny(e.else, names);
1909
+ case "nullish": return rawExprMentionsAny(e.left, names) || rawExprMentionsAny(e.right, names);
1910
+ case "optChain": return rawExprMentionsAny(e.obj, names);
1911
+ case "forall":
1912
+ case "exists": return rawExprMentionsAny(e.body, names);
1913
+ case "lambda": return false;
1914
+ default: return false;
1915
+ }
1916
+ }
1917
+ /** Collect root variable names assigned anywhere in `stmts` (both direct
1918
+ * assignments `x = ...` and dotted field writes `x.f = ...`). */
1919
+ function collectAssignedRootsRaw(stmts, out = new Set()) {
1920
+ for (const s of stmts) {
1921
+ if (s.kind === "assign") {
1922
+ out.add(s.target.split(".")[0]);
1923
+ }
1924
+ else if (s.kind === "if") {
1925
+ collectAssignedRootsRaw(s.then, out);
1926
+ collectAssignedRootsRaw(s.else, out);
1927
+ }
1928
+ else if (s.kind === "while" || s.kind === "forof") {
1929
+ collectAssignedRootsRaw(s.body, out);
1930
+ }
1931
+ else if (s.kind === "switch") {
1932
+ for (const c of s.cases)
1933
+ collectAssignedRootsRaw(c.body, out);
1934
+ collectAssignedRootsRaw(s.defaultBody, out);
1935
+ }
1936
+ }
1937
+ return out;
1938
+ }
1939
+ /** Restore any narrowed optional variable in `roots` back to its declared
1940
+ * `storageTy`, and drop `narrowedPaths` whose root is in `roots`. Used when
1941
+ * entering a loop (`while`/`forof`) or exiting a control-flow statement that
1942
+ * may reassign or clear a previously narrowed variable. */
1943
+ function invalidateNarrowings(env, narrowedPaths, roots) {
1944
+ if (roots.size === 0)
1945
+ return { env, narrowedPaths };
1946
+ let nextEnv = env;
1947
+ for (const root of roots) {
1948
+ const cur = lookup(nextEnv, root);
1949
+ const storage = storageLookup(nextEnv, root);
1950
+ if ((storage?.kind === "optional" || storage?.kind === "nullish") && cur && !tyEqual(cur, storage)) {
1951
+ nextEnv = refine(nextEnv, root, storage);
1952
+ }
1953
+ }
1954
+ const nextPaths = narrowedPaths.filter(np => !roots.has(np.path.rootVar));
1955
+ return { env: nextEnv, narrowedPaths: nextPaths };
1956
+ }
1957
+ /** True if `stmts` definitely assigns a non-optional/non-nullish value
1958
+ * to `varName` (without subsequently clearing or shadowing it) on every
1959
+ * non-terminating exit path. Used for `#340` assignment narrowing:
1960
+ * `if (v === undefined) { v = 6; } return v + 3;`. */
1961
+ function definitelyAssignsNonOptional(stmts, varName, ctx) {
1962
+ let assigned = false;
1963
+ let env = ctx.env;
1964
+ const targetStorage = storageLookup(env, varName);
1965
+ for (const st of stmts) {
1966
+ if (isTerminatorKind(st.kind))
1967
+ return true;
1968
+ if (st.kind === "let") {
1969
+ // Inner `let` shadowing `varName` prevents outer assignment tracking.
1970
+ if (st.name === varName)
1971
+ return assigned;
1972
+ const [, nextEnv] = resolveStmt(st, { ...ctx, env });
1973
+ env = nextEnv;
1974
+ continue;
1975
+ }
1976
+ if (st.kind === "assign" && st.target === varName) {
1977
+ if (st.value.kind === "var" && (st.value.name === "undefined" || st.value.name === "null")) {
1978
+ assigned = false;
1979
+ }
1980
+ else {
1981
+ const rhsCtx = { ...ctx, env, returnTy: targetStorage ?? ctx.returnTy };
1982
+ const rhsTy = resolveExpr(st.value, rhsCtx).ty;
1983
+ assigned = rhsTy.kind !== "optional" && rhsTy.kind !== "nullish" &&
1984
+ rhsTy.kind !== "void" && rhsTy.kind !== "null" && rhsTy.kind !== "unknown";
1985
+ }
1986
+ }
1987
+ else if (st.kind === "if") {
1988
+ const subCtx = { ...ctx, env };
1989
+ if (st.else.length > 0 &&
1990
+ definitelyAssignsNonOptional(st.then, varName, subCtx) &&
1991
+ definitelyAssignsNonOptional(st.else, varName, subCtx)) {
1992
+ assigned = true;
1993
+ }
1994
+ else if (collectAssignedRootsRaw(st.then).has(varName) || collectAssignedRootsRaw(st.else).has(varName)) {
1995
+ assigned = false;
1996
+ }
1997
+ }
1998
+ else if (st.kind === "while" || st.kind === "forof") {
1999
+ if (collectAssignedRootsRaw(st.body).has(varName))
2000
+ assigned = false;
2001
+ }
2002
+ else if (st.kind === "switch") {
2003
+ const swAssigned = sHasRootAssignSwitch(st, varName);
2004
+ if (swAssigned)
2005
+ assigned = false;
2006
+ }
2007
+ }
2008
+ return assigned;
2009
+ }
2010
+ function sHasRootAssignSwitch(s, varName) {
2011
+ for (const c of s.cases) {
2012
+ if (collectAssignedRootsRaw(c.body).has(varName))
2013
+ return true;
2014
+ }
2015
+ return collectAssignedRootsRaw(s.defaultBody).has(varName);
2016
+ }
1602
2017
  function resolveBlock(stmts, ctx) {
1603
2018
  const result = [];
1604
2019
  let env = ctx.env;
@@ -1609,6 +2024,47 @@ function resolveBlock(stmts, ctx) {
1609
2024
  const [typed, nextEnv] = resolveStmt(s, currentCtx);
1610
2025
  result.push(typed);
1611
2026
  env = nextEnv;
2027
+ // Assignment narrowing (#340): assigning a non-optional value to an optional
2028
+ // variable narrows it for subsequent statements; assigning `undefined` or an
2029
+ // optional restores its declared optional storage type. Also drop stale
2030
+ // narrowedPaths rooted at any assigned target (including field writes).
2031
+ if (s.kind === "assign") {
2032
+ const root = s.target.split(".")[0];
2033
+ narrowedPaths = narrowedPaths.filter(np => np.path.rootVar !== root);
2034
+ if (!s.target.includes(".")) {
2035
+ const storage = storageLookup(env, s.target);
2036
+ if (storage?.kind === "optional" || storage?.kind === "nullish") {
2037
+ const isNullLit = s.value.kind === "var" && s.value.name === "null";
2038
+ const isUndefLit = s.value.kind === "var" && s.value.name === "undefined";
2039
+ const rhsCtx = { ...currentCtx, returnTy: storage };
2040
+ const rawTy = isUndefLit ? { kind: "void" } : isNullLit ? { kind: "null" } : resolveExpr(s.value, rhsCtx).ty;
2041
+ if (!isUndefLit && !isNullLit && rawTy.kind !== "optional" && rawTy.kind !== "nullish" &&
2042
+ rawTy.kind !== "void" && rawTy.kind !== "null" && rawTy.kind !== "unknown") {
2043
+ env = refine(env, s.target, storage.inner);
2044
+ }
2045
+ else {
2046
+ env = refine(env, s.target, storage);
2047
+ }
2048
+ }
2049
+ }
2050
+ }
2051
+ // Control-flow invalidation: if an `if`/`while`/`forof`/`switch` may assign
2052
+ // a narrowed variable or path, restore its declared optional storage type
2053
+ // before subsequent statements (definite-assignment guards re-narrow below).
2054
+ if (s.kind === "if" || s.kind === "while" || s.kind === "forof" || s.kind === "switch") {
2055
+ const mutated = collectAssignedRootsRaw([s]);
2056
+ const inv = invalidateNarrowings(env, narrowedPaths, mutated);
2057
+ env = inv.env;
2058
+ narrowedPaths = inv.narrowedPaths;
2059
+ }
2060
+ // Definite-assignment guard (#340): `if (v === undefined) { v = nonOpt; }`
2061
+ // guarantees `v` is present after the `if` on both branches.
2062
+ if (s.kind === "if" && typed.kind === "if" && s.else.length === 0) {
2063
+ const neg = negatedVarPresence(typed.cond);
2064
+ if (neg && definitelyAssignsNonOptional(s.then, neg.varName, currentCtx)) {
2065
+ env = refine(env, neg.varName, neg.innerTy);
2066
+ }
2067
+ }
1612
2068
  // Flow narrowing: if (x === undefined) { return } narrows x for rest of block.
1613
2069
  // Also handles compound: if (x === undefined || y === undefined) { return }
1614
2070
  // Any terminator counts (return/throw/break/continue — same set as narrow's
@@ -1621,6 +2077,14 @@ function resolveBlock(stmts, ctx) {
1621
2077
  for (const n of collectEarlyReturnNarrowings(typed.cond)) {
1622
2078
  env = refine(env, n.varName, n.innerTy);
1623
2079
  }
2080
+ for (const np of collectEarlyReturnPathNarrowings(typed.cond)) {
2081
+ if (np.path.fields.length === 0) {
2082
+ env = refine(env, np.path.rootVar, np.narrowedTy);
2083
+ }
2084
+ else {
2085
+ narrowedPaths = [...narrowedPaths, np];
2086
+ }
2087
+ }
1624
2088
  const nv = negatedVariantCheck(typed.cond);
1625
2089
  if (nv)
1626
2090
  narrowedPaths = [...narrowedPaths, nv];
@@ -1663,7 +2127,7 @@ function resolveStmt(s, ctx) {
1663
2127
  // type into the array literal (see the arrayLiteral case). Optionals too
1664
2128
  // (`const r: TExpr | null = cond ? {…} : null`) — the record case unwraps
1665
2129
  // one optional level when consulting returnTy.
1666
- const initCtx = (declTy.kind === "user" || declTy.kind === "array" || declTy.kind === "optional")
2130
+ const initCtx = (declTy.kind === "user" || declTy.kind === "array" || declTy.kind === "optional" || declTy.kind === "nullish")
1667
2131
  ? { ...ctx, returnTy: declTy } : ctx;
1668
2132
  let init = coerceStr(resolveExpr(s.init, initCtx), declTy, ctx.typeDecls);
1669
2133
  // Under noUncheckedIndexedAccess, TS gives `const e = arr[i]` type T | undefined
@@ -1681,9 +2145,11 @@ function resolveStmt(s, ctx) {
1681
2145
  // by inlining an alias we shadow via declare-type, or any-laden), but
1682
2146
  // LS resolved the initializer to something concrete. Take the structure
1683
2147
  // from `init.ty`, keeping only the optionality ts-morph reported.
1684
- ty = declTy.kind === "optional" && init.ty.kind !== "optional"
1685
- ? { kind: "optional", inner: init.ty }
1686
- : init.ty;
2148
+ ty = declTy.kind === "nullish" && init.ty.kind !== "nullish"
2149
+ ? { kind: "nullish", inner: init.ty.kind === "optional" ? init.ty.inner : init.ty }
2150
+ : declTy.kind === "optional" && init.ty.kind !== "optional"
2151
+ ? { ...declTy, inner: init.ty }
2152
+ : init.ty;
1687
2153
  }
1688
2154
  else if (isWidenedStringUnionTy(declTy, init.ty, ctx.typeDecls) && !ctx.overrides.has(s.name)) {
1689
2155
  // ts-morph widened a string-union to `string`; keep the initializer's
@@ -1698,7 +2164,7 @@ function resolveStmt(s, ctx) {
1698
2164
  }
1699
2165
  else {
1700
2166
  // Map indexing: TS says T, but access can fail → use Optional<T> from init
1701
- ty = (declTy.kind !== "optional" && init.ty.kind === "optional") ? init.ty : declTy;
2167
+ ty = (declTy.kind !== "optional" && declTy.kind !== "nullish" && init.ty.kind === "optional") ? init.ty : declTy;
1702
2168
  }
1703
2169
  // const collections are mutable in value-semantics world (TS mutates in place, Dafny/Lean reassign)
1704
2170
  const mutable = s.mutable || isRefMutableInTS(ty);
@@ -1710,11 +2176,14 @@ function resolveStmt(s, ctx) {
1710
2176
  throw new Error(`assignment to callback binding '${s.target}' requires materializing its argument value`);
1711
2177
  }
1712
2178
  entry?.onRead?.();
1713
- const targetTy = lookup(ctx.env, s.target) ?? { kind: "unknown" };
2179
+ // Coerce RHS against the variable's declared storage type (not a narrowed
2180
+ // flow type) so reassignments like `v = 7` or `v = undefined` stay typed
2181
+ // as `Option<T>`.
2182
+ const targetTy = storageLookup(ctx.env, s.target) ?? { kind: "unknown" };
1714
2183
  // Propagate the target's type as returnTy, mirroring the annotated-let
1715
2184
  // case, so record/union literals and array literals in the RHS resolve
1716
2185
  // to their named datatypes.
1717
- const valueCtx = (targetTy.kind === "user" || targetTy.kind === "array" || targetTy.kind === "optional")
2186
+ const valueCtx = (targetTy.kind === "user" || targetTy.kind === "array" || targetTy.kind === "optional" || targetTy.kind === "nullish")
1718
2187
  ? { ...ctx, returnTy: targetTy } : ctx;
1719
2188
  const value = coerceToTargetTy(resolveExpr(s.value, valueCtx), targetTy, ctx.typeDecls);
1720
2189
  return [{ kind: "assign", target: entry?.emittedName ?? s.target, value }, ctx.env];
@@ -1741,6 +2210,15 @@ function resolveStmt(s, ctx) {
1741
2210
  if (single) {
1742
2211
  elseCtx = withEnv(ctx, refine(ctx.env, single.varName, single.innerTy));
1743
2212
  }
2213
+ else if (resolvedCond.kind === "binop" && resolvedCond.op === "||") {
2214
+ for (const n of collectEarlyReturnNarrowings(resolvedCond)) {
2215
+ elseCtx = withEnv(elseCtx, refine(elseCtx.env, n.varName, n.innerTy));
2216
+ }
2217
+ }
2218
+ const negPaths = collectEarlyReturnPathNarrowings(resolvedCond);
2219
+ if (negPaths.length > 0) {
2220
+ elseCtx = { ...elseCtx, narrowedPaths: [...elseCtx.narrowedPaths, ...negPaths] };
2221
+ }
1744
2222
  // Narrow map index access across `k in m` / `!(k in m)` in the cond:
1745
2223
  // positive atoms (from `k in m` or &&-chains containing it) → then-branch;
1746
2224
  // negated atoms (from `!(k in m)`) → else-branch.
@@ -1749,14 +2227,21 @@ function resolveStmt(s, ctx) {
1749
2227
  return [{ kind: "if", cond: resolvedCond, then: resolveBlock(s.then, thenCtx), else: resolveBlock(s.else, elseCtx) }, ctx.env];
1750
2228
  }
1751
2229
  case "while": {
1752
- const whileSpecCtx = { ...ctx, inSpec: true };
2230
+ // Any variable or path mutated inside the loop body cannot keep a pre-loop
2231
+ // narrowing across iterations (including inside the loop condition and
2232
+ // invariants on back-edges).
2233
+ const loopMutated = collectAssignedRootsRaw(s.body);
2234
+ const loopInv = invalidateNarrowings(ctx.env, ctx.narrowedPaths, loopMutated);
2235
+ const loopCtx = { ...ctx, env: loopInv.env, narrowedPaths: loopInv.narrowedPaths };
2236
+ const whileSpecCtx = { ...loopCtx, inSpec: true };
1753
2237
  const resolvedInvariants = resolveSpecs(s.invariants, whileSpecCtx);
1754
- // Invariants hold at the top of the body, so any `k in m` atoms among them
1755
- // narrow map index access in the body.
1756
- const bodyCtx = withInAtoms(ctx, resolvedInvariants.flatMap(extractInAtoms));
2238
+ const resolvedCond = resolveExpr(s.cond, loopCtx);
2239
+ // Invariants and presence checks in the `while` condition (#339) both hold
2240
+ // at the top of the loop body.
2241
+ const bodyCtx = collectAndChainNarrowings(resolvedCond, withInAtoms(loopCtx, resolvedInvariants.flatMap(extractInAtoms)));
1757
2242
  return [{
1758
2243
  kind: "while",
1759
- cond: resolveExpr(s.cond, ctx),
2244
+ cond: resolvedCond,
1760
2245
  invariants: resolvedInvariants,
1761
2246
  decreases: s.decreases ? resolveSpec(s.decreases, whileSpecCtx) : null,
1762
2247
  doneWith: s.doneWith ? resolveSpec(s.doneWith, whileSpecCtx) : null,
@@ -1796,11 +2281,14 @@ function resolveStmt(s, ctx) {
1796
2281
  const count = ctx.forofCounts.get(s.names[0]) ?? 0;
1797
2282
  ctx.forofCounts.set(s.names[0], count + 1);
1798
2283
  const idxName = freshName(`_${s.names[0]}_idx${count === 0 ? "" : count + 1}`);
2284
+ const loopMutated = collectAssignedRootsRaw(s.body);
2285
+ const loopInv = invalidateNarrowings(ctx.env, ctx.narrowedPaths, loopMutated);
2286
+ env = loopInv.env;
1799
2287
  env = extend(env, idxName, { kind: "nat" });
1800
2288
  for (let j = 0; j < s.names.length; j++) {
1801
2289
  env = extend(env, s.names[j], nameTypes[j] ?? { kind: "unknown" });
1802
2290
  }
1803
- const bodyCtx = withEnv(ctx, env);
2291
+ const bodyCtx = { ...ctx, env, narrowedPaths: loopInv.narrowedPaths };
1804
2292
  return [{
1805
2293
  kind: "forof", names: s.names, nameTypes, iterable, idx: idxName,
1806
2294
  invariants: resolveSpecs(s.invariants, { ...bodyCtx, inSpec: true }),