lemmascript 0.6.13 → 0.6.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,13 +4,13 @@
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";
11
11
  import { recognizeBuiltin, builtinSpec, callbackArgumentTypes, callbackBaseArity } from "./builtins.js";
12
- import { declOf, declOfKind, declOfDotted, declOfTy, tyBaseName } from "./typedecls.js";
13
- import { presentFact, variantFact } from "./condition-facts.js";
12
+ import { declOf, declOfKind, declOfDotted, declOfTy, tyBaseName, remainingVariant } from "./typedecls.js";
13
+ import { presentFact, variantFact, isArrayFact, typeofStringFact, excludesUndefined } from "./condition-facts.js";
14
14
  function binding(env, name) {
15
15
  if (!env)
16
16
  return undefined;
@@ -57,6 +57,8 @@ function refine(env, name, ty) {
57
57
  function asRawAccessPath(e) {
58
58
  if (e.kind === "var")
59
59
  return { rootVar: e.name, fields: [] };
60
+ if (e.kind === "result")
61
+ return { rootVar: "\\result", fields: [] };
60
62
  if (e.kind === "field") {
61
63
  const inner = asRawAccessPath(e.obj);
62
64
  if (!inner)
@@ -82,32 +84,40 @@ function resolveTsType(tsType, overrides, varName) {
82
84
  return parseTsType(tsType);
83
85
  }
84
86
  /** Infer a conditional's result type after its branches have been resolved or
85
- * contextually coerced. A void branch is the source-level null/undefined arm. */
87
+ * contextually coerced. `void` is `undefined`, `null` is `null`; mixing both
88
+ * sentinels yields `nullish<T>` so `null !== undefined` is preserved (#304). */
86
89
  function conditionalResultTy(thenTy, elseTy) {
87
90
  if ((thenTy.kind === "int" || thenTy.kind === "nat") &&
88
91
  (elseTy.kind === "int" || elseTy.kind === "nat")) {
89
92
  return { ...thenTy, kind: thenTy.kind === "int" || elseTy.kind === "int" ? "int" : "nat" };
90
93
  }
91
- let ty = thenTy.kind !== "unknown" ? thenTy : elseTy;
92
- if (thenTy.kind === "void" && elseTy.kind !== "void" && elseTy.kind !== "unknown") {
93
- ty = { kind: "optional", inner: elseTy };
94
- }
95
- else if (elseTy.kind === "void" && thenTy.kind !== "void" && thenTy.kind !== "unknown") {
96
- ty = { kind: "optional", inner: thenTy };
97
- }
98
- else if (thenTy.kind === "optional" && elseTy.kind !== "optional" && elseTy.kind !== "unknown") {
99
- ty = thenTy;
100
- }
101
- else if (elseTy.kind === "optional" && thenTy.kind !== "optional" && thenTy.kind !== "unknown") {
102
- ty = elseTy;
103
- }
104
- return ty;
94
+ const hasNull = (t) => t.kind === "null" || t.kind === "nullish" || (t.kind === "optional" && optAbsent(t) === "null");
95
+ const hasUndef = (t) => t.kind === "void" || t.kind === "nullish" || (t.kind === "optional" && optAbsent(t) === "undefined");
96
+ const payloadOf = (t) => t.kind === "void" || t.kind === "null" || t.kind === "unknown" ? null
97
+ : (t.kind === "optional" || t.kind === "nullish") ? t.inner : t;
98
+ const bothNull = hasNull(thenTy) || hasNull(elseTy);
99
+ const bothUndef = hasUndef(thenTy) || hasUndef(elseTy);
100
+ if (bothNull || bothUndef) {
101
+ const p1 = payloadOf(thenTy);
102
+ const p2 = payloadOf(elseTy);
103
+ const inner = p1 ?? p2;
104
+ if (inner) {
105
+ if (bothNull && bothUndef)
106
+ return { kind: "nullish", inner };
107
+ if (bothNull)
108
+ return { kind: "optional", inner, absent: "null" };
109
+ return { kind: "optional", inner };
110
+ }
111
+ if (bothNull && bothUndef)
112
+ return { kind: "nullish", inner: { kind: "void" } };
113
+ }
114
+ return thenTy.kind !== "unknown" ? thenTy : elseTy;
105
115
  }
106
116
  /** Contextually type string literals as string-union constructors. Ternary branches inherit
107
- * the ternary's target, and an optional target contributes its payload type —
108
- * the caller adds the Some wrapper only after the payload has been coerced. */
117
+ * the ternary's target, and an optional/nullish target contributes its payload type —
118
+ * the caller adds the Some/Value wrapper only after the payload has been coerced. */
109
119
  function coerceStr(expr, targetTy, typeDecls) {
110
- const payloadTy = targetTy.kind === "optional" ? targetTy.inner : targetTy;
120
+ const payloadTy = (targetTy.kind === "optional" || targetTy.kind === "nullish") ? targetTy.inner : targetTy;
111
121
  if (expr.kind === "str" && payloadTy.kind === "user") {
112
122
  const enumTy = expandAlias(payloadTy, typeDecls);
113
123
  // A synthesized string/array union has a string payload, not a constructor
@@ -130,6 +140,13 @@ function wrapSome(value, optionalTy) {
130
140
  args: [value], ty: optionalTy, callKind: "pure",
131
141
  };
132
142
  }
143
+ /** Wrap a resolved non-nullish value in Nullish.Value(...) for Nullish<T> coercion. */
144
+ function wrapNullishValue(value, nullishTy) {
145
+ return {
146
+ kind: "call", fn: { kind: "var", name: "NullishValue", ty: nullishTy },
147
+ args: [value], ty: nullishTy, callKind: "pure",
148
+ };
149
+ }
133
150
  /** Find the synth array-union TypeDecl named `name` (discriminant `__isArray__`). */
134
151
  function findSynthArrayUnion(name, typeDecls) {
135
152
  const decl = declOf(typeDecls, name);
@@ -140,6 +157,8 @@ function findSynthArrayUnion(name, typeDecls) {
140
157
  /** Coerce `value` to `targetTy` at an assignment-position. Contextually types
141
158
  * real literals, then mirrors TS subtyping for the upcast shapes LS synthesizes:
142
159
  * - `T` into `optional<T>` slot → wrap with `Some(...)`
160
+ * - `T` / `Option<T>` / `null` / `undefined` into `nullish<T>` slot → `Nullish<T>`
161
+ * - `fromNullish` into `optional<T>` slot → `__nullishToOption(...)`
143
162
  * - `T[]` into a synth `T[] | U` slot → wrap with `ArrayBranch(...)`
144
163
  * - `U` into a synth `T[] | U` slot → wrap with `NonArrayBranch(...)`
145
164
  * Returns `value` unchanged if no coercion applies (types already match,
@@ -147,8 +166,8 @@ function findSynthArrayUnion(name, typeDecls) {
147
166
  function coerceToTargetTy(value, targetTy, typeDecls) {
148
167
  value = coerceStr(value, targetTy, typeDecls);
149
168
  // Real targets also type integer literals, including negative literals and
150
- // conditional arms. Coerce optional payloads before adding Some wrappers.
151
- const payloadTy = targetTy.kind === "optional" ? targetTy.inner : targetTy;
169
+ // conditional arms. Coerce optional/nullish payloads before adding wrappers.
170
+ const payloadTy = (targetTy.kind === "optional" || targetTy.kind === "nullish") ? targetTy.inner : targetTy;
152
171
  if (payloadTy.kind === "real") {
153
172
  if (value.kind === "num") {
154
173
  value = { ...value, ty: payloadTy };
@@ -162,10 +181,53 @@ function coerceToTargetTy(value, targetTy, typeDecls) {
162
181
  value = { ...value, then: then_, else: else_, ty: conditionalResultTy(then_.ty, else_.ty) };
163
182
  }
164
183
  }
165
- if (value.ty.kind === "unknown" || value.ty.kind === "void")
184
+ if (targetTy.kind === "nullish") {
185
+ if (value.ty.kind === "unknown")
186
+ return value;
187
+ if (value.kind === "var" && (value.name === "undefined" || value.name === "null")) {
188
+ return { ...value, ty: targetTy };
189
+ }
190
+ if (value.ty.kind === "void")
191
+ return { kind: "var", name: "undefined", ty: targetTy };
192
+ if (value.ty.kind === "null")
193
+ return { kind: "var", name: "null", ty: targetTy };
194
+ if (value.ty.kind === "nullish")
195
+ return value;
196
+ if (value.ty.kind === "optional") {
197
+ // Partially narrowed fromNullish already lives in Nullish<T> storage.
198
+ if (value.ty.fromNullish)
199
+ return { ...value, ty: targetTy };
200
+ const helper = optAbsent(value.ty) === "null" ? "__optNullToNullish" : "__optUndefToNullish";
201
+ return {
202
+ kind: "call",
203
+ fn: { kind: "var", name: helper, ty: targetTy },
204
+ args: [value],
205
+ ty: targetTy,
206
+ callKind: "pure",
207
+ };
208
+ }
209
+ if (value.kind === "conditional") {
210
+ const then_ = coerceToTargetTy(value.then, targetTy, typeDecls);
211
+ const else_ = coerceToTargetTy(value.else, targetTy, typeDecls);
212
+ return { ...value, then: then_, else: else_, ty: targetTy };
213
+ }
214
+ return wrapNullishValue(value, targetTy);
215
+ }
216
+ if (value.ty.kind === "unknown" || value.ty.kind === "void" || value.ty.kind === "null")
166
217
  return value;
167
- if (targetTy.kind === "optional" && value.ty.kind !== "optional") {
168
- return wrapSome(value, targetTy);
218
+ if (targetTy.kind === "optional") {
219
+ if (value.ty.kind === "nullish" || (value.ty.kind === "optional" && value.ty.fromNullish)) {
220
+ return {
221
+ kind: "call",
222
+ fn: { kind: "var", name: "__nullishToOption", ty: targetTy },
223
+ args: [value],
224
+ ty: targetTy,
225
+ callKind: "pure",
226
+ };
227
+ }
228
+ if (value.ty.kind !== "optional") {
229
+ return wrapSome(value, targetTy);
230
+ }
169
231
  }
170
232
  if (targetTy.kind === "user") {
171
233
  if (value.ty.kind === "user" && value.ty.name === targetTy.name)
@@ -201,11 +263,11 @@ function negatedVarPresence(cond) {
201
263
  * (x === undefined || y === undefined). */
202
264
  /** Extract field-path or optional-chain narrowings guaranteed after an early
203
265
  * return (`if (d.b === undefined) return;` or `if (b?.tag !== 1) return;`, #354). */
204
- function collectEarlyReturnPathNarrowings(cond) {
266
+ function collectEarlyReturnPathNarrowings(cond, ctx) {
205
267
  if (cond.kind === "binop" && cond.op === "||") {
206
268
  return [
207
- ...collectEarlyReturnPathNarrowings(cond.left),
208
- ...collectEarlyReturnPathNarrowings(cond.right),
269
+ ...collectEarlyReturnPathNarrowings(cond.left, ctx),
270
+ ...collectEarlyReturnPathNarrowings(cond.right, ctx),
209
271
  ];
210
272
  }
211
273
  // Negated field-path presence: `d.b === undefined` or `!d.b`
@@ -224,8 +286,7 @@ function collectEarlyReturnPathNarrowings(cond) {
224
286
  : cond.right.kind === "optChain"
225
287
  ? [cond.right, cond.left]
226
288
  : [null, null];
227
- if (ocSide && otherSide && !(otherSide.kind === "var" && otherSide.name === "undefined") &&
228
- otherSide.ty.kind !== "optional" && otherSide.ty.kind !== "void" &&
289
+ if (ocSide && otherSide && excludesUndefined(otherSide, ctx.typeDecls, ctx.typeParams) &&
229
290
  ocSide.obj.ty.kind === "optional") {
230
291
  const path = asTExprAccessPath(ocSide.obj);
231
292
  if (path)
@@ -260,18 +321,125 @@ function collectEarlyReturnNarrowings(cond) {
260
321
  const n = negatedVarPresence(cond);
261
322
  return n ? [n] : [];
262
323
  }
263
- /** Negated discriminant check (`path.kind !== "lit"`) on a var or field path.
264
- * After `if (path.kind !== "lit") return`, the rest of the block knows the
265
- * path is that variant. */
266
- function negatedVariantCheck(cond) {
267
- if (cond.kind === "binop" && cond.op === "!==" && cond.right.kind === "str" &&
268
- cond.left.kind === "field" && cond.left.isDiscriminant && cond.left.obj.ty.kind === "user") {
269
- const path = asTExprAccessPath(cond.left.obj);
270
- if (path)
271
- return { path, narrowedTy: cond.left.obj.ty, variant: cond.right.value };
324
+ /** Return the payload type of `variant` on a synth array-union (`__isArray__`),
325
+ * or null for non-synth types. */
326
+ function synthVariantPayloadTy(ty, variant, ctx) {
327
+ if (ty.kind !== "user")
328
+ return null;
329
+ const decl = findSynthArrayUnion(ty.name, ctx.typeDecls);
330
+ const f = decl?.variants?.find(v => v.name === variant)?.fields[0];
331
+ return f ? (f.type ?? parseTsType(f.tsType)) : null;
332
+ }
333
+ /** Narrow a pure access path to a union variant in `ctx`. For synth array-unions
334
+ * (`__isArray__`), also narrows the path's flow type to the branch's payload
335
+ * type so array/string methods and checked projections fire uniformly. */
336
+ function applyVariantNarrowing(ctx, path, unionTy, variant) {
337
+ const payload = synthVariantPayloadTy(unionTy, variant, ctx);
338
+ if (payload) {
339
+ const nextPaths = [...ctx.narrowedPaths, { path, narrowedTy: payload, variant }];
340
+ if (path.fields.length === 0) {
341
+ return { ...withEnv(ctx, refine(ctx.env, path.rootVar, payload)), narrowedPaths: nextPaths };
342
+ }
343
+ return { ...ctx, narrowedPaths: nextPaths };
344
+ }
345
+ return { ...ctx, narrowedPaths: [...ctx.narrowedPaths, { path, narrowedTy: unionTy, variant }] };
346
+ }
347
+ /** Synth array-union branch guaranteed by `Array.isArray(path)`, `!Array.isArray(path)`,
348
+ * or `typeof path === "string"` when `cond` evaluates to `truth`. */
349
+ function synthVariantWhen(cond, truth, ctx) {
350
+ if (cond.kind === "unop" && cond.op === "!")
351
+ return synthVariantWhen(cond.expr, !truth, ctx);
352
+ const condCtx = { decls: ctx.typeDecls, oc: { n: 0 } };
353
+ const arr = isArrayFact(cond, condCtx);
354
+ if (arr) {
355
+ const path = asTExprAccessPath(arr.scrutinee);
356
+ if (!path)
357
+ return null;
358
+ return { path, unionTy: arr.scrutinee.ty, variant: truth ? "ArrayBranch" : "NonArrayBranch" };
359
+ }
360
+ const tof = typeofStringFact(cond, condCtx);
361
+ if (tof) {
362
+ const path = asTExprAccessPath(tof.scrutinee);
363
+ if (!path)
364
+ return null;
365
+ return { path, unionTy: tof.scrutinee.ty, variant: truth ? "NonArrayBranch" : "ArrayBranch" };
272
366
  }
273
367
  return null;
274
368
  }
369
+ /** Innermost narrowed union variant recorded for `path` in `ctx.narrowedPaths`. */
370
+ function lookupNarrowedVariant(path, ctx) {
371
+ for (let i = ctx.narrowedPaths.length - 1; i >= 0; i--) {
372
+ const cand = ctx.narrowedPaths[i];
373
+ if (cand.variant && accessPathsEqual(cand.path, path))
374
+ return cand.variant;
375
+ }
376
+ return undefined;
377
+ }
378
+ /** Project narrowed union arguments to nominal records expected by a callee
379
+ * (`helper(sh)` → `helper({ n: sh.n })`), using `ctx.narrowedPaths` so it works
380
+ * uniformly on live storage and after reassignment. */
381
+ function projectStructuralCallArgs(args, paramTypes, ctx) {
382
+ return args.map((arg, i) => {
383
+ if (i >= paramTypes.length || arg.ty.kind !== "user")
384
+ return arg;
385
+ const targetTy = paramTypes[i];
386
+ if (targetTy.kind !== "user")
387
+ return arg;
388
+ const targetDecl = declOfKind(ctx.typeDecls, targetTy.name, "record");
389
+ if (!targetDecl?.fields)
390
+ return arg;
391
+ const argPath = asTExprAccessPath(arg);
392
+ if (!argPath)
393
+ return arg;
394
+ const variantName = lookupNarrowedVariant(argPath, ctx);
395
+ if (!variantName)
396
+ return arg;
397
+ const unionDecl = declOfKind(ctx.typeDecls, tyBaseName(arg.ty.name), "discriminated-union");
398
+ const variant = unionDecl?.variants?.find(v => v.name === variantName);
399
+ if (!variant)
400
+ return arg;
401
+ const matched = [];
402
+ for (const tf of targetDecl.fields) {
403
+ const sf = variant.fields.find(f => f.name === tf.name);
404
+ const tfTy = tf.type ?? parseTsType(tf.tsType);
405
+ const sfTy = sf ? (sf.type ?? parseTsType(sf.tsType)) : undefined;
406
+ if (!sf || !sfTy || !tyEqual(sfTy, tfTy))
407
+ return arg;
408
+ matched.push({ targetName: tf.name, sourceName: sf.name, ty: sfTy });
409
+ }
410
+ return {
411
+ kind: "record",
412
+ spread: null,
413
+ fields: matched.map(m => ({
414
+ name: m.targetName,
415
+ value: { kind: "field", obj: arg, field: m.sourceName, ty: m.ty, ofVariant: variantName },
416
+ })),
417
+ ty: targetTy,
418
+ };
419
+ });
420
+ }
421
+ /** Variant guaranteed by a discriminant comparison (`path.kind === "lit"` or
422
+ * `!== "lit"`, either operand order, with optional `!`) when `cond` evaluates
423
+ * to `truth`. Exclusions narrow only when exactly one union variant remains. */
424
+ function discriminantVariantWhen(cond, truth, ctx) {
425
+ if (cond.kind === "unop" && cond.op === "!")
426
+ return discriminantVariantWhen(cond.expr, !truth, ctx);
427
+ if (cond.kind !== "binop" || (cond.op !== "===" && cond.op !== "!=="))
428
+ return null;
429
+ const field = cond.left.kind === "field" ? cond.left : cond.right.kind === "field" ? cond.right : null;
430
+ const label = cond.left.kind === "str" ? cond.left : cond.right.kind === "str" ? cond.right : null;
431
+ if (!field?.isDiscriminant || !label || field.obj.ty.kind !== "user")
432
+ return null;
433
+ const path = asTExprAccessPath(field.obj);
434
+ if (!path)
435
+ return null;
436
+ const matches = truth === (cond.op === "===");
437
+ if (matches)
438
+ return { path, narrowedTy: field.obj.ty, variant: label.value };
439
+ const decl = findDecl(ctx, tyBaseName(field.obj.ty.name));
440
+ const rem = decl?.discriminant === field.field ? remainingVariant(decl, [label.value]) : undefined;
441
+ return rem ? { path, narrowedTy: field.obj.ty, variant: rem.name } : null;
442
+ }
275
443
  /** TExpr → AccessPath. Counterpart to `asRawAccessPath` for resolved trees.
276
444
  * Used by `extractInAtoms` when pulling atoms out of typed spec expressions. */
277
445
  function asTExprAccessPath(e) {
@@ -350,13 +518,22 @@ function collectAndChainNarrowings(cond, ctx) {
350
518
  }
351
519
  return ctx;
352
520
  }
353
- // Positive discriminant check (`x.kind === "bool"`): record the variant so
354
- // field reads on the path resolve against that variant's field types.
521
+ // Positive discriminant check (`x.kind === "bool"`, `"bool" === x.kind`, or
522
+ // `x.kind !== "other"` on a 2-variant union): record the variant so field
523
+ // reads on the path resolve against that variant's field types.
524
+ const dv = discriminantVariantWhen(cond, true, ctx);
525
+ if (dv) {
526
+ return { ...ctx, narrowedPaths: [...ctx.narrowedPaths, dv] };
527
+ }
528
+ const sv = synthVariantWhen(cond, true, ctx);
529
+ if (sv) {
530
+ return applyVariantNarrowing(ctx, sv.path, sv.unionTy, sv.variant);
531
+ }
355
532
  const vf = variantFact(cond, { decls: ctx.typeDecls, oc: { n: 0 } });
356
533
  if (vf) {
357
534
  const path = asTExprAccessPath(vf.scrutinee);
358
535
  if (path) {
359
- return { ...ctx, narrowedPaths: [...ctx.narrowedPaths, { path, narrowedTy: vf.scrutinee.ty, variant: vf.variant }] };
536
+ return applyVariantNarrowing(ctx, path, vf.scrutinee.ty, vf.variant);
360
537
  }
361
538
  }
362
539
  return ctx;
@@ -380,6 +557,14 @@ function collectOrChainNarrowings(cond, ctx) {
380
557
  return { ...ctx, narrowedPaths: [...ctx.narrowedPaths, { path, narrowedTy: f.innerTy }] };
381
558
  }
382
559
  }
560
+ const dv = discriminantVariantWhen(cond, false, ctx);
561
+ if (dv) {
562
+ return { ...ctx, narrowedPaths: [...ctx.narrowedPaths, dv] };
563
+ }
564
+ const sv = synthVariantWhen(cond, false, ctx);
565
+ if (sv) {
566
+ return applyVariantNarrowing(ctx, sv.path, sv.unionTy, sv.variant);
567
+ }
383
568
  return ctx;
384
569
  }
385
570
  /** TS reference types that become value types in Dafny/Lean — const bindings need mutable var. */
@@ -410,14 +595,33 @@ function expandAlias(ty, typeDecls, seen = new Set()) {
410
595
  if (decl.constEnumMembers)
411
596
  return { kind: "int" };
412
597
  const target = decl.aliasOfTy;
413
- if (target.kind === "array" || target.kind === "map" || target.kind === "set" || target.kind === "optional" || target.kind === "user") {
598
+ if (target.kind === "array" || target.kind === "map" || target.kind === "set" || target.kind === "optional" || target.kind === "nullish" || target.kind === "user") {
414
599
  return expandAlias(target, typeDecls, new Set([...seen, ty.name]));
415
600
  }
416
601
  }
417
602
  return ty;
418
603
  }
419
- if (ty.kind === "optional")
420
- return { kind: "optional", inner: expandAlias(ty.inner, typeDecls, seen) };
604
+ if (ty.kind === "optional") {
605
+ const expanded = expandAlias(ty.inner, typeDecls, seen);
606
+ if (expanded.kind === "nullish")
607
+ return expanded;
608
+ if (expanded.kind === "optional") {
609
+ const mergedNull = optAbsent(ty) === "null" || optAbsent(expanded) === "null";
610
+ const mergedUndef = optAbsent(ty) === "undefined" || optAbsent(expanded) === "undefined";
611
+ if (mergedNull && mergedUndef)
612
+ return { kind: "nullish", inner: expanded.inner };
613
+ return { ...ty, inner: expanded.inner };
614
+ }
615
+ return { ...ty, inner: expanded };
616
+ }
617
+ if (ty.kind === "nullish") {
618
+ const expanded = expandAlias(ty.inner, typeDecls, seen);
619
+ if (expanded.kind === "nullish")
620
+ return expanded;
621
+ if (expanded.kind === "optional")
622
+ return { kind: "nullish", inner: expanded.inner };
623
+ return { kind: "nullish", inner: expanded };
624
+ }
421
625
  if (ty.kind === "array")
422
626
  return { kind: "array", elem: expandAlias(ty.elem, typeDecls, seen) };
423
627
  if (ty.kind === "tuple")
@@ -429,11 +633,13 @@ function expandAlias(ty, typeDecls, seen = new Set()) {
429
633
  return ty;
430
634
  }
431
635
  /** Numeric aliases keep their names in declarations but use their underlying
432
- * types in expressions. Optional payloads need the same treatment for zero's
433
- * falsiness; collection elements are resolved when read. */
636
+ * types in expressions. Optional/nullish payloads need the same treatment for
637
+ * zero's falsiness; collection elements are resolved when read. */
434
638
  function numericValueType(ty, typeDecls, seen = new Set()) {
435
639
  if (ty.kind === "optional")
436
640
  return { ...ty, inner: numericValueType(ty.inner, typeDecls, seen) };
641
+ if (ty.kind === "nullish")
642
+ return { kind: "nullish", inner: numericValueType(ty.inner, typeDecls, seen) };
437
643
  if (ty.kind !== "user" || seen.has(ty.name))
438
644
  return ty;
439
645
  const decl = declOfDotted(typeDecls, ty.name);
@@ -487,7 +693,7 @@ function warnRefEq(op, l, r) {
487
693
  function isUnmodeledTy(ty, typeDecls) {
488
694
  if (ty.kind === "unknown")
489
695
  return true;
490
- if (ty.kind === "optional")
696
+ if (ty.kind === "optional" || ty.kind === "nullish")
491
697
  return isUnmodeledTy(ty.inner, typeDecls);
492
698
  if (ty.kind === "array")
493
699
  return isUnmodeledTy(ty.elem, typeDecls);
@@ -683,8 +889,14 @@ let callbackCounter = 0;
683
889
  function callbackDefaultState(ty, ctx, seen = new Set()) {
684
890
  if (ty.kind === "void")
685
891
  return "missing";
686
- if (ty.kind === "optional" || ty.kind === "unknown")
687
- return ty.kind;
892
+ if (ty.kind === "null")
893
+ return "defined";
894
+ if (ty.kind === "optional")
895
+ return optAbsent(ty) === "null" ? "defined" : "optional";
896
+ if (ty.kind === "nullish")
897
+ return "optional";
898
+ if (ty.kind === "unknown")
899
+ return "unknown";
688
900
  if (ty.kind !== "user" || ty.name === "null")
689
901
  return "defined";
690
902
  if (seen.has(ty.name))
@@ -849,20 +1061,25 @@ function argumentPack(e, ctx) {
849
1061
  entry.onRead?.();
850
1062
  return pack;
851
1063
  }
852
- /** A defined-check filter predicate: `(x) => x !== undefined` (expression or
853
- * single-return body). Detected on the raw IR before narrowing rewrites it. */
854
- function isDefinedCheckRawLambda(raw) {
1064
+ /** A defined-check filter predicate: `(x) => x !== undefined`, `(x) => x !== null`,
1065
+ * or loose `(x) => x != null` / `(x) => x != undefined`. Returns which sentinel
1066
+ * the filter removes so `filterSome` only fires when it matches the array
1067
+ * element's absent sentinel (`#304`). */
1068
+ function definedCheckRawLambdaSentinel(raw) {
855
1069
  if (raw.kind !== "lambda" || raw.params.length !== 1)
856
- return false;
1070
+ return null;
857
1071
  const p = raw.params[0].name;
858
1072
  const body = Array.isArray(raw.body)
859
1073
  ? (raw.body.length === 1 && raw.body[0].kind === "return" ? raw.body[0].value : null)
860
1074
  : raw.body;
861
- if (!body || body.kind !== "binop" || body.op !== "!==")
862
- return false;
1075
+ if (!body || body.kind !== "binop" || (body.op !== "!==" && body.op !== "!="))
1076
+ return null;
863
1077
  const isParam = (x) => x.kind === "var" && x.name === p;
864
- const isUndef = (x) => x.kind === "var" && x.name === "undefined";
865
- return (isParam(body.left) && isUndef(body.right)) || (isParam(body.right) && isUndef(body.left));
1078
+ const sentinelOf = (x) => x.kind === "var" && (x.name === "undefined" || x.name === "null") ? x.name : null;
1079
+ const s = isParam(body.left) ? sentinelOf(body.right) : isParam(body.right) ? sentinelOf(body.left) : null;
1080
+ if (!s)
1081
+ return null;
1082
+ return body.op === "!=" ? "both" : s;
866
1083
  }
867
1084
  /** Coerce call arguments to their declared parameter slots and pad missing optional args. */
868
1085
  function coerceCallArgs(args, fn, ctx) {
@@ -874,9 +1091,9 @@ function coerceCallArgs(args, fn, ctx) {
874
1091
  return a;
875
1092
  return coerceToTargetTy(a, paramTys[i], ctx.typeDecls);
876
1093
  });
877
- // Pad missing optional args with None
1094
+ // Pad missing optional/nullish args with undefined (None / Nullish.Undefined)
878
1095
  for (let i = args.length; i < paramTys.length; i++) {
879
- if (paramTys[i].kind === "optional") {
1096
+ if (paramTys[i].kind === "optional" || paramTys[i].kind === "nullish") {
880
1097
  args.push({ kind: "var", name: "undefined", ty: paramTys[i] });
881
1098
  }
882
1099
  }
@@ -975,11 +1192,13 @@ function lookupFieldTy(objTy, field, ctx) {
975
1192
  return { ty: f.type, isDiscriminant };
976
1193
  }
977
1194
  if (decl?.kind === "discriminated-union" && decl.variants) {
978
- for (const variant of decl.variants) {
979
- const f = variant.fields.find(f => f.name === field);
980
- if (f)
981
- return { ty: f.type, isDiscriminant };
1195
+ const matches = decl.variants
1196
+ .map(v => v.fields.find(f => f.name === field)?.type)
1197
+ .filter((t) => t !== undefined);
1198
+ if (matches.length > 0 && matches.every(t => tyEqual(t, matches[0]))) {
1199
+ return { ty: matches[0], isDiscriminant };
982
1200
  }
1201
+ return { ty: { kind: "unknown" }, isDiscriminant };
983
1202
  }
984
1203
  return { ty: { kind: "unknown" }, isDiscriminant };
985
1204
  }
@@ -996,8 +1215,8 @@ let mergeBinder = 0;
996
1215
  function resolveRecordMerge(base, override, ctx) {
997
1216
  const tbase = resolveExpr(base, ctx);
998
1217
  const tover = resolveExpr(override, ctx);
999
- const overInner = tover.ty.kind === "optional" ? tover.ty.inner : tover.ty;
1000
- // Result record type: prefer the override's (an optional override still merges
1218
+ const overInner = (tover.ty.kind === "optional" || tover.ty.kind === "nullish") ? tover.ty.inner : tover.ty;
1219
+ // Result record type: prefer the override's (an optional/nullish override still merges
1001
1220
  // into its inner type), else the base's.
1002
1221
  const rTy = overInner.kind === "user" ? overInner
1003
1222
  : tbase.ty.kind === "user" ? tbase.ty : null;
@@ -1006,7 +1225,7 @@ function resolveRecordMerge(base, override, ctx) {
1006
1225
  throw new Error(`object spread merge { ...a, ...b } needs a known record type for both operands ` +
1007
1226
  `(base: ${tyToCanonical(tbase.ty)}, override: ${tyToCanonical(tover.ty)})`);
1008
1227
  }
1009
- if (tbase.ty.kind === "optional") {
1228
+ if (tbase.ty.kind === "optional" || tbase.ty.kind === "nullish") {
1010
1229
  throw new Error(`object spread merge with an optional base operand is not supported (base: ${tyToCanonical(tbase.ty)})`);
1011
1230
  }
1012
1231
  const userTy = rTy;
@@ -1018,10 +1237,19 @@ function resolveRecordMerge(base, override, ctx) {
1018
1237
  const ft = f.type;
1019
1238
  const ovf = { kind: "field", obj: ov, field: f.name, ty: ft };
1020
1239
  // A required key is always copied, even when its value is null/undefined.
1021
- if (ft.kind !== "optional" || !f.optionalKey)
1240
+ if (!f.optionalKey || (ft.kind !== "optional" && ft.kind !== "nullish"))
1022
1241
  return { name: f.name, value: ovf };
1023
- // `f?:` key: override field wins iff present, else base's field
1024
1242
  const bvf = { kind: "field", obj: bv, field: f.name, ty: ft };
1243
+ if (ft.kind === "nullish") {
1244
+ // `f?: T | null`: override wins unless `ov.f === undefined` (null still overrides!).
1245
+ const isUndef = {
1246
+ kind: "binop", op: "===",
1247
+ left: ovf, right: { kind: "var", name: "undefined", ty: { kind: "void" } },
1248
+ ty: { kind: "bool" },
1249
+ };
1250
+ return { name: f.name, value: { kind: "conditional", cond: isUndef, then: bvf, else: ovf, ty: ft } };
1251
+ }
1252
+ // `f?:` optional key: override field wins iff present, else base's field
1025
1253
  const binder = freshName(`_m${mergeBinder++}`);
1026
1254
  // someBody is the unwrapped present value; transform re-wraps each arm in
1027
1255
  // the backend's Some constructor (Dafny `Some`, Lean `Option.some`).
@@ -1031,6 +1259,16 @@ function resolveRecordMerge(base, override, ctx) {
1031
1259
  } };
1032
1260
  }),
1033
1261
  });
1262
+ if (tover.ty.kind === "nullish" || (tover.ty.kind === "optional" && tover.ty.fromNullish)) {
1263
+ // Nullish override: undefined/null spreads nothing → base unchanged; Value(v) merges.
1264
+ const isPresent = {
1265
+ kind: "binop", op: "!=",
1266
+ left: tover, right: { kind: "var", name: "null", ty: { kind: "null" } },
1267
+ ty: { kind: "bool" },
1268
+ };
1269
+ const unwrappedOver = { kind: "checkedUnwrap", expr: tover, ty: userTy };
1270
+ return { kind: "conditional", cond: isPresent, then: merged(tbase, unwrappedOver), else: tbase, ty: userTy };
1271
+ }
1034
1272
  if (tover.ty.kind === "optional") {
1035
1273
  // override may be absent (undefined spreads nothing) → base unchanged
1036
1274
  const binder = freshName(`_mo${mergeBinder++}`);
@@ -1112,6 +1350,8 @@ function resolveExprInner(e, ctx) {
1112
1350
  case "var": {
1113
1351
  if (e.name === "undefined")
1114
1352
  return { kind: "var", name: "undefined", ty: { kind: "void" } };
1353
+ if (e.name === "null")
1354
+ return { kind: "var", name: "null", ty: { kind: "null" } };
1115
1355
  const entry = binding(ctx.env, e.name);
1116
1356
  if (entry?.argumentPack) {
1117
1357
  throw new Error(`cannot materialize callback rest parameter '${e.name}'; use its length or a constant indexed read`);
@@ -1138,12 +1378,12 @@ function resolveExprInner(e, ctx) {
1138
1378
  expr.fn.obj.ty.kind === "map" && expr.fn.field === "get") {
1139
1379
  return { ...expr, ty: expr.fn.obj.ty.value };
1140
1380
  }
1141
- const ty = expr.ty.kind === "optional" ? expr.ty.inner : expr.ty;
1381
+ const ty = (expr.ty.kind === "optional" || expr.ty.kind === "nullish") ? expr.ty.inner : expr.ty;
1142
1382
  return { ...expr, ty };
1143
1383
  }
1144
1384
  case "binop": {
1145
1385
  let left = resolveExpr(e.left, ctx);
1146
- // && and ==> narrowing: left-side optional checks narrow the right side.
1386
+ // && and ==> narrowing: left-side optional/nullish checks narrow the right side.
1147
1387
  // (For ==>, the premise is assumed in the conclusion — same principle.)
1148
1388
  let rightCtx = ctx;
1149
1389
  let rawRight = e.right;
@@ -1154,18 +1394,17 @@ function resolveExprInner(e, ctx) {
1154
1394
  // Preserve direct single-optional var comparisons (`opt === null || x < opt`,
1155
1395
  // `excludeTag === undefined || getTagId(t) !== excludeTag`) for transform's
1156
1396
  // native mirrored match lowering, as long as the non-optional side doesn't
1157
- // also depend on a variable narrowed by `left`; narrow all other RHS shapes
1158
- // (arithmetic, calls using the narrowed var, nested paths, two-optional
1159
- // comparisons) via checked reads.
1397
+ // also depend on a variable narrowed by `left` and neither side is `Nullish<T>`;
1398
+ // narrow all other RHS shapes via checked reads.
1160
1399
  const orCtx = collectOrChainNarrowings(left, ctx);
1161
1400
  const narrowedVars = new Set();
1162
1401
  for (let cur = orCtx.env; cur && cur !== ctx.env; cur = cur.parent) {
1163
1402
  narrowedVars.add(cur.name);
1164
1403
  }
1165
- const leftIsOptVar = rawRight.kind === "binop" && rawRight.left.kind === "var" &&
1166
- lookup(ctx.env, rawRight.left.name)?.kind === "optional";
1167
- const rightIsOptVar = rawRight.kind === "binop" && rawRight.right.kind === "var" &&
1168
- lookup(ctx.env, rawRight.right.name)?.kind === "optional";
1404
+ const leftTy = rawRight.kind === "binop" && rawRight.left.kind === "var" ? lookup(ctx.env, rawRight.left.name) : undefined;
1405
+ const rightTy = rawRight.kind === "binop" && rawRight.right.kind === "var" ? lookup(ctx.env, rawRight.right.name) : undefined;
1406
+ const leftIsOptVar = leftTy?.kind === "optional" && !leftTy.fromNullish;
1407
+ const rightIsOptVar = rightTy?.kind === "optional" && !rightTy.fromNullish;
1169
1408
  const isDirectSingleOptCmp = rawRight.kind === "binop" &&
1170
1409
  ["===", "!==", "<", "<=", ">", ">="].includes(rawRight.op) &&
1171
1410
  (leftIsOptVar !== rightIsOptVar) &&
@@ -1175,7 +1414,7 @@ function resolveExprInner(e, ctx) {
1175
1414
  }
1176
1415
  }
1177
1416
  let right = resolveExpr(rawRight, rightCtx);
1178
- if (e.op === "===" || e.op === "!==") {
1417
+ if (e.op === "===" || e.op === "!==" || e.op === "==" || e.op === "!=") {
1179
1418
  left = coerceStr(left, right.ty, ctx.typeDecls);
1180
1419
  right = coerceStr(right, left.ty, ctx.typeDecls);
1181
1420
  // Spec (`//@`) comparisons are proof-only, so they can't diverge at
@@ -1184,16 +1423,36 @@ function resolveExprInner(e, ctx) {
1184
1423
  warnRefEq(e.op, left.ty, right.ty);
1185
1424
  }
1186
1425
  }
1426
+ else if (e.op === "in") {
1427
+ const keySlot = right.ty.kind === "map" ? right.ty.key
1428
+ : (right.ty.kind === "set" || right.ty.kind === "array") ? right.ty.elem : null;
1429
+ if (keySlot)
1430
+ left = coerceToTargetTy(left, keySlot, ctx.typeDecls);
1431
+ }
1187
1432
  let ty = { kind: "unknown" };
1188
1433
  // <==> is bool like the comparisons; unlike ==>, neither side narrows
1189
1434
  // the other (no premise to assume).
1190
- if (["===", "!==", ">=", "<=", ">", "<", "in", "<==>"].includes(e.op))
1435
+ if (["===", "!==", "==", "!=", ">=", "<=", ">", "<", "in", "<==>"].includes(e.op))
1191
1436
  ty = { kind: "bool" };
1192
1437
  else if (e.op === "&&")
1193
1438
  ty = right.ty;
1194
- else if (e.op === "||" && left.ty.kind === "optional") {
1195
- // || undefined is identity for optionals — keep the optional type
1196
- ty = (e.right.kind === "var" && e.right.name === "undefined") ? left.ty : left.ty.inner;
1439
+ else if (e.op === "||" && (left.ty.kind === "optional" || left.ty.kind === "nullish")) {
1440
+ // || undefined / || null / || nullable preserves the RHS nullability;
1441
+ // otherwise yields inner type.
1442
+ if (e.right.kind === "var" && e.right.name === "undefined") {
1443
+ ty = left.ty.kind === "optional" && optAbsent(left.ty) === "undefined"
1444
+ ? left.ty
1445
+ : { kind: "optional", inner: left.ty.inner };
1446
+ }
1447
+ else if (e.right.kind === "var" && e.right.name === "null") {
1448
+ ty = { kind: "optional", inner: left.ty.inner, absent: "null" };
1449
+ }
1450
+ else if (right.ty.kind === "optional" || right.ty.kind === "nullish") {
1451
+ ty = right.ty;
1452
+ }
1453
+ else {
1454
+ ty = left.ty.inner;
1455
+ }
1197
1456
  }
1198
1457
  else if (e.op === "||")
1199
1458
  ty = right.ty;
@@ -1210,7 +1469,13 @@ function resolveExprInner(e, ctx) {
1210
1469
  return { kind: "binop", op: e.op, left, right, ty };
1211
1470
  }
1212
1471
  case "unop": {
1213
- const expr = resolveExpr(e.expr, ctx);
1472
+ let expr = resolveExpr(e.expr, ctx);
1473
+ if (e.op === "typeof" && expr.kind === "var") {
1474
+ const storage = storageLookup(ctx.env, expr.name);
1475
+ if (storage?.kind === "user" && findSynthArrayUnion(storage.name, ctx.typeDecls)) {
1476
+ expr = { ...expr, ty: storage };
1477
+ }
1478
+ }
1214
1479
  const ty = e.op === "!" ? { kind: "bool" } : e.op === "typeof" ? { kind: "string" }
1215
1480
  : e.op === "-" && expr.ty.kind === "nat" ? { ...expr.ty, kind: "int" } : expr.ty;
1216
1481
  return { kind: "unop", op: e.op, expr, ty };
@@ -1264,7 +1529,7 @@ function resolveExprInner(e, ctx) {
1264
1529
  throw new Error(`impure extern ${qualified} cannot be called from a specification`);
1265
1530
  if (ext.impure && ctx.inLambda)
1266
1531
  throw new Error(`impure extern ${qualified} cannot be called from a lambda`);
1267
- const args = e.args.map(a => resolveExpr(a, ctx));
1532
+ const args = projectStructuralCallArgs(e.args.map(a => resolveExpr(a, ctx)), ext.params, ctx);
1268
1533
  const fn = { kind: "var", name: ext.flat, ty: { kind: "unknown" } };
1269
1534
  return {
1270
1535
  kind: "call", fn, args, ty: ext.returnTy,
@@ -1274,35 +1539,44 @@ function resolveExprInner(e, ctx) {
1274
1539
  }
1275
1540
  }
1276
1541
  const fn = resolveExpr(e.fn, ctx);
1542
+ const builtinId = fn.kind === "field" ? recognizeBuiltin(fn.obj.ty, fn.field) : null;
1543
+ const bSpec = builtinId ? builtinSpec(builtinId) : null;
1277
1544
  const rawArgs = inferLambdaParamTypes(fn, e.args, ctx);
1278
- // For .push() on a typed array, resolve args with element type context
1279
- let argCtx = ctx;
1280
- if (fn.kind === "field" && fn.obj.ty.kind === "array" && fn.field === "push" &&
1281
- fn.obj.ty.elem.kind === "user") {
1282
- argCtx = { ...ctx, returnTy: fn.obj.ty.elem };
1283
- }
1284
- // Propagate parameter types to arguments for record literal resolution
1285
- // (enables inline discriminated union construction in function arguments)
1545
+ // Propagate parameter / builtin-slot types to arguments for record literal
1546
+ // resolution and collection element/key/value coercion (e.g., narrowed `T`
1547
+ // or literals passed into `Set<T | null>.has`, `Map<K | null, V>.set`, etc.).
1286
1548
  const paramTypes = fn.kind === "var" && !binding(ctx.env, fn.name) ? ctx.fnParams.get(fn.name) ?? null : null;
1287
1549
  const initial = fn.kind === "field" && fn.field === "reduce" && rawArgs.length >= 2
1288
- ? resolveExpr(rawArgs[1], argCtx) : undefined;
1550
+ ? resolveExpr(rawArgs[1], ctx) : undefined;
1289
1551
  const callback = callbackContext(fn, initial);
1290
1552
  let args = coerceCallArgs(rawArgs.map((a, i) => {
1291
- let aCtx = argCtx;
1292
- if (paramTypes && i < paramTypes.length &&
1293
- (paramTypes[i].kind === "user" || paramTypes[i].kind === "array" || paramTypes[i].kind === "optional")) {
1294
- aCtx = { ...aCtx, returnTy: paramTypes[i] };
1553
+ const slotTy = (paramTypes && i < paramTypes.length ? paramTypes[i] : null)
1554
+ ?? (bSpec?.argSlot && fn.kind === "field" ? bSpec.argSlot(fn.obj.ty, i) : null);
1555
+ let aCtx = ctx;
1556
+ if (slotTy &&
1557
+ (slotTy.kind === "user" || slotTy.kind === "array" || slotTy.kind === "optional" || slotTy.kind === "nullish")) {
1558
+ aCtx = { ...aCtx, returnTy: slotTy };
1295
1559
  }
1296
1560
  if (i === 0 && a.kind === "lambda" && callback)
1297
1561
  return resolveCallback(a, callback.actual, callback.baseArity, aCtx);
1298
- return i === 1 && initial ? initial : resolveExpr(a, aCtx);
1562
+ const resolved = i === 1 && initial ? initial : resolveExpr(a, aCtx);
1563
+ if (bSpec?.argSlot && fn.kind === "field") {
1564
+ const bSlot = bSpec.argSlot(fn.obj.ty, i);
1565
+ if (bSlot)
1566
+ return coerceToTargetTy(resolved, bSlot, ctx.typeDecls);
1567
+ }
1568
+ return resolved;
1299
1569
  }), fn, ctx);
1300
- // Array method `.with(i, v)`: coerce the value arg to the element type
1301
- // so `arr[i] = v` on `(T|null)[]` wraps `T` → `Some(T)` (and similarly
1302
- // for synth array-unions). Same shape as the record-field coercion
1303
- // below: assigning a narrower value into a wider slot.
1304
- if (fn.kind === "field" && fn.field === "with" && fn.obj.ty.kind === "array" && args.length === 2) {
1305
- args = [args[0], coerceToTargetTy(args[1], fn.obj.ty.elem, ctx.typeDecls)];
1570
+ if (paramTypes)
1571
+ args = projectStructuralCallArgs(args, paramTypes, ctx);
1572
+ // Keep the underlying synth array-union storage type on `Array.isArray(x)`
1573
+ // arguments even when `x` was already narrowed in flow typing.
1574
+ if (fn.kind === "field" && fn.field === "isArray" &&
1575
+ fn.obj.kind === "var" && fn.obj.name === "Array" && args.length === 1 && args[0].kind === "var") {
1576
+ const storage = storageLookup(ctx.env, args[0].name);
1577
+ if (storage?.kind === "user" && findSynthArrayUnion(storage.name, ctx.typeDecls)) {
1578
+ args = [{ ...args[0], ty: storage }];
1579
+ }
1306
1580
  }
1307
1581
  let ty = inferMethodReturnTy(fn, args, ctx);
1308
1582
  // For same-file function calls, use the known return type
@@ -1322,12 +1596,13 @@ function resolveExprInner(e, ctx) {
1322
1596
  // seq<T>. Rewrite to a synthetic `filterSome` call lowered to the proven
1323
1597
  // SeqFilterSome preamble (a plain `Map(.value, Filter(.Some?))` wouldn't
1324
1598
  // verify — `.value` is partial).
1325
- if (e.fn.kind === "field" && e.fn.field === "filter" && e.args.length === 1
1326
- && isDefinedCheckRawLambda(e.args[0])
1327
- && fn.kind === "field" && fn.obj.ty.kind === "array" && fn.obj.ty.elem.kind === "optional") {
1599
+ const filterSentinel = e.fn.kind === "field" && e.fn.field === "filter" && e.args.length === 1
1600
+ ? definedCheckRawLambdaSentinel(e.args[0]) : null;
1601
+ if (filterSentinel !== null
1602
+ && fn.kind === "field" && fn.obj.ty.kind === "array" && fn.obj.ty.elem.kind === "optional"
1603
+ && (filterSentinel === "both" || filterSentinel === optAbsent(fn.obj.ty.elem))) {
1328
1604
  return { kind: "call", fn: { ...fn, field: "filterSome" }, args: [], ty: { kind: "array", elem: fn.obj.ty.elem.inner }, callKind: "method" };
1329
1605
  }
1330
- const builtinId = fn.kind === "field" ? recognizeBuiltin(fn.obj.ty, fn.field) : null;
1331
1606
  return { kind: "call", fn, args, ty, callKind: classifyCall(e.fn, ctx),
1332
1607
  ...(builtinId ? { builtinId } : {}),
1333
1608
  ...(paramTypes ? { paramTys: paramTypes } : {}) };
@@ -1343,7 +1618,7 @@ function resolveExprInner(e, ctx) {
1343
1618
  return member;
1344
1619
  }
1345
1620
  const obj = resolveExpr(e.obj, ctx);
1346
- const idx = resolveExpr(e.idx, ctx);
1621
+ let idx = resolveExpr(e.idx, ctx);
1347
1622
  // Map bracket access: default to Option<V>. But if the enclosing scope has a
1348
1623
  // known `k in m` atom matching (obj, idx) — from requires, assert, an enclosing
1349
1624
  // `if (k in m)`, or a loop invariant — narrow to V. Parallels how `narrowedPaths`
@@ -1366,6 +1641,7 @@ function resolveExprInner(e, ctx) {
1366
1641
  idxTy = elems[idx.value];
1367
1642
  }
1368
1643
  else if (obj.ty.kind === "map") {
1644
+ idx = coerceToTargetTy(idx, obj.ty.key, ctx.typeDecls);
1369
1645
  const objPath = asTExprAccessPath(obj);
1370
1646
  const idxPath = asTExprAccessPath(idx);
1371
1647
  const narrowed = objPath && idxPath && ctx.narrowedIndices.some(n => accessPathsEqual(n.obj, objPath) && accessPathsEqual(n.idx, idxPath));
@@ -1395,23 +1671,37 @@ function resolveExprInner(e, ctx) {
1395
1671
  if (ctx.narrowedPaths.length > 0) {
1396
1672
  const myPath = asRawAccessPath(e);
1397
1673
  if (myPath) {
1398
- const np = ctx.narrowedPaths.find(n => accessPathsEqual(n.path, myPath));
1399
- if (np)
1400
- ty = np.narrowedTy;
1674
+ for (let i = ctx.narrowedPaths.length - 1; i >= 0; i--) {
1675
+ if (accessPathsEqual(ctx.narrowedPaths[i].path, myPath)) {
1676
+ ty = ctx.narrowedPaths[i].narrowedTy;
1677
+ break;
1678
+ }
1679
+ }
1401
1680
  }
1402
1681
  }
1403
- // A variant narrowing on the object picks the field's type from that
1404
- // variant (a shared field name can have a different type per variant).
1682
+ // A variant narrowing on the object pins `ofVariant` (even when `myPath`
1683
+ // itself was also narrowed in `narrowedPaths`, e.g. a nested union) and
1684
+ // supplies the field's type when not already narrowed.
1405
1685
  let ofVariant;
1406
- if (ty.kind === "unknown" && ctx.narrowedPaths.length > 0 && obj.ty.kind === "user") {
1686
+ if (ctx.narrowedPaths.length > 0 && obj.ty.kind === "user") {
1407
1687
  const objPath = asRawAccessPath(e.obj);
1408
- const np = objPath ? ctx.narrowedPaths.find(n => n.variant && accessPathsEqual(n.path, objPath)) : undefined;
1688
+ let np;
1689
+ if (objPath) {
1690
+ for (let i = ctx.narrowedPaths.length - 1; i >= 0; i--) {
1691
+ const cand = ctx.narrowedPaths[i];
1692
+ if (cand.variant && accessPathsEqual(cand.path, objPath)) {
1693
+ np = cand;
1694
+ break;
1695
+ }
1696
+ }
1697
+ }
1409
1698
  if (np?.variant) {
1410
1699
  const decl = findDecl(ctx, tyBaseName(obj.ty.name));
1411
1700
  const f = decl?.variants?.find(v => v.name === np.variant)?.fields.find(f => f.name === e.field);
1412
1701
  if (f?.type) {
1413
- ty = f.type;
1414
1702
  ofVariant = np.variant;
1703
+ if (ty.kind === "unknown")
1704
+ ty = f.type;
1415
1705
  }
1416
1706
  }
1417
1707
  }
@@ -1423,37 +1713,45 @@ function resolveExprInner(e, ctx) {
1423
1713
  return { kind: "field", obj, field: e.field, ty, isDiscriminant, ofVariant };
1424
1714
  }
1425
1715
  case "nullish": {
1426
- // left ?? right — result type is left's inner (when left is optional)
1716
+ // left ?? right — result type is left's inner (when left is optional/nullish)
1427
1717
  // or just left's type, unified with right's type.
1428
1718
  const left = resolveExpr(e.left, ctx);
1429
- const isLeftUndef = (left.kind === "var" && left.name === "undefined") || left.ty.kind === "void";
1719
+ const isLeftNullishLit = (left.kind === "var" && (left.name === "undefined" || left.name === "null")) ||
1720
+ left.ty.kind === "void" || left.ty.kind === "null";
1430
1721
  const isArrayIndex = left.kind === "index" && left.obj.ty.kind === "array";
1431
- const inner = left.ty.kind === "optional" ? left.ty.inner : left.ty;
1722
+ const isLeftNullable = left.ty.kind === "optional" || left.ty.kind === "nullish";
1723
+ const inner = (left.ty.kind === "optional" || left.ty.kind === "nullish") ? left.ty.inner : left.ty;
1432
1724
  // The default shares the result type, so coerce a string literal to a
1433
1725
  // string-union enum (e.g. `availableLevels[0] ?? "off"`).
1434
- const right = coerceToTargetTy(resolveExpr(e.right, ctx), isLeftUndef ? { kind: "unknown" } : inner, ctx.typeDecls);
1435
- // When `left` is non-optional and not an unchecked array index (#352):
1436
- // `undefined ?? right` has `right`'s type, and `nonOpt ?? right` evaluates
1437
- // to `left` directly (narrow.ts strips the dead fallback).
1438
- if (left.ty.kind !== "optional" && !isArrayIndex) {
1439
- return { kind: "nullish", left, right, ty: isLeftUndef ? right.ty : left.ty };
1440
- }
1441
- // `??` is only total when its default is: with a nullable right operand
1442
- // (rule-chain style `ruleA(e) ?? ruleB(e) ?? null`), the result stays
1443
- // optional — otherwise the enclosing chain level loses its optionality
1444
- // and narrowing can't rewrite it.
1445
- const ty = right.ty.kind === "optional" ? right.ty : inner;
1726
+ const right = coerceToTargetTy(resolveExpr(e.right, ctx), isLeftNullishLit ? { kind: "unknown" } : inner, ctx.typeDecls);
1727
+ // When `left` is non-nullable and not an unchecked array index (#352):
1728
+ // `undefined ?? right` / `null ?? right` has `right`'s type, and `nonOpt ?? right`
1729
+ // evaluates to `left` directly (narrow.ts strips the dead fallback).
1730
+ if (!isLeftNullable && !isArrayIndex) {
1731
+ return { kind: "nullish", left, right, ty: isLeftNullishLit ? right.ty : left.ty };
1732
+ }
1733
+ // `??` is only total when its default is: with a nullable/null/undefined
1734
+ // right operand (`x ?? undefined`, `ruleA(e) ?? ruleB(e) ?? null`), the
1735
+ // result keeps the right operand's nullability.
1736
+ let ty = inner;
1737
+ if (right.ty.kind === "optional" || right.ty.kind === "nullish")
1738
+ ty = right.ty;
1739
+ else if (right.ty.kind === "void" || (right.kind === "var" && right.name === "undefined"))
1740
+ ty = { kind: "optional", inner };
1741
+ else if (right.ty.kind === "null" || (right.kind === "var" && right.name === "null"))
1742
+ ty = { kind: "optional", inner, absent: "null" };
1446
1743
  return { kind: "nullish", left, right, ty };
1447
1744
  }
1448
1745
  case "optChain": {
1449
- // obj?.<chain> — obj has type Option<T>; we walk the chain stepping
1450
- // through types from T. The final result is Option<finalStepTy>
1451
- // (collapsed: if finalStepTy is already optional, we don't double-wrap).
1452
- // Narrow rewrites this to a someMatch with the chain applied to the binder.
1746
+ // obj?.<chain> — obj has type Option<T> or Nullish<T>; we walk the chain
1747
+ // stepping through types from T. Short-circuiting always yields `undefined`
1748
+ // in JS (so a `T | null` chain step becomes `Nullish<T>`).
1453
1749
  const obj = resolveExpr(e.obj, ctx);
1454
- const isObjUndef = (obj.kind === "var" && obj.name === "undefined") || obj.ty.kind === "void";
1750
+ const isObjNullishLit = (obj.kind === "var" && (obj.name === "undefined" || obj.name === "null")) ||
1751
+ obj.ty.kind === "void" || obj.ty.kind === "null";
1455
1752
  const isObjArrayIndex = obj.kind === "index" && obj.obj.ty.kind === "array";
1456
- let stepInTy = obj.ty.kind === "optional" ? obj.ty.inner : obj.ty;
1753
+ const isObjNullable = obj.ty.kind === "optional" || obj.ty.kind === "nullish";
1754
+ let stepInTy = (obj.ty.kind === "optional" || obj.ty.kind === "nullish") ? obj.ty.inner : obj.ty;
1457
1755
  const chain = [];
1458
1756
  for (const step of e.chain) {
1459
1757
  if (step.kind === "field") {
@@ -1462,7 +1760,9 @@ function resolveExprInner(e, ctx) {
1462
1760
  stepInTy = fieldTy;
1463
1761
  }
1464
1762
  else if (step.kind === "index") {
1465
- const idx = resolveExpr(step.idx, ctx);
1763
+ let idx = resolveExpr(step.idx, ctx);
1764
+ if (stepInTy.kind === "map")
1765
+ idx = coerceToTargetTy(idx, stepInTy.key, ctx.typeDecls);
1466
1766
  const idxTy = stepInTy.kind === "array" ? stepInTy.elem
1467
1767
  : stepInTy.kind === "string" ? { kind: "string" }
1468
1768
  : stepInTy.kind === "map" ? { kind: "optional", inner: stepInTy.value }
@@ -1483,18 +1783,25 @@ function resolveExprInner(e, ctx) {
1483
1783
  let rawArgs = step.args;
1484
1784
  if (lastField) {
1485
1785
  const priorInTy = chain.length >= 2 ? chain[chain.length - 2].ty
1486
- : (obj.ty.kind === "optional" ? obj.ty.inner : obj.ty);
1786
+ : ((obj.ty.kind === "optional" || obj.ty.kind === "nullish") ? obj.ty.inner : obj.ty);
1487
1787
  const fakeObj = { kind: "var", name: "_chain_recv", ty: priorInTy };
1488
1788
  const fakeFn = { kind: "field", obj: fakeObj, field: lastField.name, ty: lastField.ty };
1789
+ const builtinId = recognizeBuiltin(priorInTy, lastField.name);
1790
+ const bSpec = builtinId ? builtinSpec(builtinId) : null;
1489
1791
  rawArgs = inferLambdaParamTypes(fakeFn, rawArgs);
1490
1792
  const initial = lastField.name === "reduce" && rawArgs.length >= 2 ? resolveExpr(rawArgs[1], ctx) : undefined;
1491
1793
  const callback = callbackContext(fakeFn, initial);
1492
- const args = rawArgs.map((a, i) => i === 0 && a.kind === "lambda" && callback
1493
- ? resolveCallback(a, callback.actual, callback.baseArity, ctx)
1494
- : i === 1 && initial ? initial : resolveExpr(a, ctx));
1794
+ const args = rawArgs.map((a, i) => {
1795
+ const slotTy = bSpec?.argSlot ? bSpec.argSlot(priorInTy, i) : null;
1796
+ const aCtx = slotTy && (slotTy.kind === "user" || slotTy.kind === "array" || slotTy.kind === "optional" || slotTy.kind === "nullish")
1797
+ ? { ...ctx, returnTy: slotTy } : ctx;
1798
+ const resolved = i === 0 && a.kind === "lambda" && callback
1799
+ ? resolveCallback(a, callback.actual, callback.baseArity, aCtx)
1800
+ : i === 1 && initial ? initial : resolveExpr(a, aCtx);
1801
+ return slotTy ? coerceToTargetTy(resolved, slotTy, ctx.typeDecls) : resolved;
1802
+ });
1495
1803
  callTy = inferMethodReturnTy(fakeFn, args, ctx);
1496
1804
  callKind = "method";
1497
- const builtinId = recognizeBuiltin(priorInTy, lastField.name);
1498
1805
  chain.push({ kind: "call", args, ty: callTy, callKind,
1499
1806
  ...(builtinId ? { builtinId } : {}) });
1500
1807
  stepInTy = callTy;
@@ -1508,9 +1815,17 @@ function resolveExprInner(e, ctx) {
1508
1815
  const finalTy = stepInTy;
1509
1816
  // Non-optional receiver (excluding unchecked array index) never produces
1510
1817
  // None from the `?.` step itself (#352); narrow.ts lowers it directly.
1511
- const ty = isObjUndef ? { kind: "void" }
1512
- : (obj.ty.kind !== "optional" && !isObjArrayIndex) ? finalTy
1513
- : finalTy.kind === "optional" ? finalTy : { kind: "optional", inner: finalTy };
1818
+ // When the receiver IS nullable, short-circuiting adds `| undefined`:
1819
+ // - `T | null` + `| undefined` → `Nullish<T>`
1820
+ // - `Nullish<T>` → `Nullish<T>`
1821
+ // - `T | undefined` → `T | undefined`
1822
+ // - `T` → `T | undefined`
1823
+ const ty = isObjNullishLit ? { kind: "void" }
1824
+ : (!isObjNullable && !isObjArrayIndex) ? finalTy
1825
+ : finalTy.kind === "nullish" ? finalTy
1826
+ : finalTy.kind === "optional"
1827
+ ? (optAbsent(finalTy) === "null" ? { kind: "nullish", inner: finalTy.inner } : finalTy)
1828
+ : { kind: "optional", inner: finalTy };
1514
1829
  return { kind: "optChain", obj, chain, ty };
1515
1830
  }
1516
1831
  case "record": {
@@ -1528,21 +1843,32 @@ function resolveExprInner(e, ctx) {
1528
1843
  return { kind: "record", spread: null, fields, ty: mapTy };
1529
1844
  }
1530
1845
  // Infer record type: from spread, or from return type context. Unwrap
1531
- // an outer Optional when looking at returnTy — `return {...} : null`
1532
- // has ctx.returnTy = Option<T>, but the record literal's natural type is T.
1533
- const returnTyUnwrapped = ctx.returnTy.kind === "optional" ? ctx.returnTy.inner : ctx.returnTy;
1846
+ // an outer Optional/Nullish when looking at returnTy — `return {...} : null`
1847
+ // has ctx.returnTy = Option<T>/Nullish<T>, but the record literal's natural type is T.
1848
+ const returnTyUnwrapped = (ctx.returnTy.kind === "optional" || ctx.returnTy.kind === "nullish") ? ctx.returnTy.inner : ctx.returnTy;
1534
1849
  const recordTy = ty.kind === "user" ? ty : returnTyUnwrapped.kind === "user" ? returnTyUnwrapped : null;
1535
1850
  const decl = recordTy ? declOfKind(ctx.typeDecls, recordTy.name, "record") : undefined;
1536
- // Union-variant literal in union-typed context (a constructed IR node,
1537
- // `{ kind: "if", … }: TStmt`): contextual field types come from the
1538
- // variant the literal's discriminant field selects.
1851
+ // Union-variant literal or spread in union-typed context: contextual field
1852
+ // types come from the variant selected by the literal's discriminant field,
1853
+ // or from the narrowed variant of the spread path.
1539
1854
  let declFields = decl?.fields;
1855
+ let ofVariant;
1856
+ let spreadOfVariant;
1540
1857
  if (!declFields && recordTy) {
1541
- const udecl = declOfKind(ctx.typeDecls, recordTy.name, "discriminated-union");
1858
+ const udecl = declOfKind(ctx.typeDecls, tyBaseName(recordTy.name), "discriminated-union");
1542
1859
  if (udecl?.discriminant && udecl.variants) {
1860
+ if (spread) {
1861
+ const spPath = asTExprAccessPath(spread);
1862
+ spreadOfVariant = spPath ? lookupNarrowedVariant(spPath, ctx) : undefined;
1863
+ }
1543
1864
  const tagRaw = e.fields.find(f => f.name === udecl.discriminant)?.value;
1544
- if (tagRaw?.kind === "str") {
1545
- declFields = udecl.variants.find(v => v.name === tagRaw.value)?.fields;
1865
+ if (tagRaw?.kind === "str" || tagRaw?.kind === "bool") {
1866
+ ofVariant = String(tagRaw.value);
1867
+ declFields = udecl.variants.find(v => v.name === ofVariant)?.fields;
1868
+ }
1869
+ else if (spread && !tagRaw && spreadOfVariant) {
1870
+ ofVariant = spreadOfVariant;
1871
+ declFields = udecl.variants.find(v => v.name === spreadOfVariant)?.fields;
1546
1872
  }
1547
1873
  }
1548
1874
  }
@@ -1556,7 +1882,7 @@ function resolveExprInner(e, ctx) {
1556
1882
  // by coerceToTargetTy below); array fields propagate whole, so the
1557
1883
  // arrayLiteral case can thread the element type.
1558
1884
  const fdTy = fieldDecl?.type;
1559
- const fdCtxTy = fdTy?.kind === "optional" ? fdTy.inner : fdTy;
1885
+ const fdCtxTy = (fdTy?.kind === "optional" || fdTy?.kind === "nullish") ? fdTy.inner : fdTy;
1560
1886
  const valueCtx = fdCtxTy && (fdCtxTy.kind === "user" || fdCtxTy.kind === "array")
1561
1887
  ? { ...fieldCtx, returnTy: fdCtxTy }
1562
1888
  : fieldCtx;
@@ -1574,7 +1900,14 @@ function resolveExprInner(e, ctx) {
1574
1900
  }
1575
1901
  return { name: f.name, value };
1576
1902
  });
1577
- return { kind: "record", spread, fields, ty: recordTy ?? ty };
1903
+ return {
1904
+ kind: "record",
1905
+ spread,
1906
+ fields,
1907
+ ty: recordTy ?? ty,
1908
+ ...(ofVariant ? { ofVariant } : {}),
1909
+ ...(spreadOfVariant ? { spreadOfVariant } : {}),
1910
+ };
1578
1911
  }
1579
1912
  case "recordMerge":
1580
1913
  return resolveRecordMerge(e.base, e.override, ctx);
@@ -1615,7 +1948,7 @@ function resolveExprInner(e, ctx) {
1615
1948
  // get their type via ctx.returnTy). Only narrow when the context type is an
1616
1949
  // array (unwrapping one optional level — `TStmt[] | null` return positions);
1617
1950
  // otherwise leave ctx untouched.
1618
- const rtUnwrapped = ctx.returnTy.kind === "optional" ? ctx.returnTy.inner : ctx.returnTy;
1951
+ const rtUnwrapped = (ctx.returnTy.kind === "optional" || ctx.returnTy.kind === "nullish") ? ctx.returnTy.inner : ctx.returnTy;
1619
1952
  const expectedElem = rtUnwrapped.kind === "array" ? rtUnwrapped.elem : null;
1620
1953
  const elemCtx = expectedElem ? { ...ctx, returnTy: expectedElem } : ctx;
1621
1954
  const elems = e.elems.map(el => {
@@ -1654,9 +1987,9 @@ function resolveExprInner(e, ctx) {
1654
1987
  const body = Array.isArray(e.body)
1655
1988
  ? resolveBlock(e.body, lambdaCtx)
1656
1989
  : [{ kind: "return", value: resolveExpr(e.body, lambdaCtx) }];
1657
- // Carry the lambda's type as a fn type when its return is known, so chained
1658
- // array methods (`.map(...).filter(...)`) can infer downstream element types.
1659
- const lamTy = e.returnTsType
1990
+ // Carry the lambda's type as a fn type when its return is known (or when
1991
+ // zero-parameter, so Lean emits `Unit → T` and applies `()` at call sites).
1992
+ const lamTy = e.returnTsType || params.length === 0
1660
1993
  ? { kind: "fn", params: params.map(p => p.ty), result: lambdaReturnTy }
1661
1994
  : { kind: "unknown" };
1662
1995
  return { kind: "lambda", params, body, ty: lamTy };
@@ -1670,20 +2003,32 @@ function resolveExprInner(e, ctx) {
1670
2003
  // checks are in scope when resolving later ones.
1671
2004
  let thenCtx = collectAndChainNarrowings(cond, ctx);
1672
2005
  let elseCtx = ctx;
1673
- // Truthiness — cond itself is optional (`opt ? a : b`), only for simple vars.
1674
- if (cond.ty.kind === "optional" && cond.kind === "var") {
2006
+ // Truthiness — cond itself is optional/nullish (`opt ? a : b`), only for simple vars.
2007
+ if ((cond.ty.kind === "optional" || cond.ty.kind === "nullish") && cond.kind === "var") {
1675
2008
  thenCtx = withEnv(thenCtx, refine(thenCtx.env, cond.name, cond.ty.inner));
1676
2009
  }
1677
- // Single === undefined check narrows the else-branch.
2010
+ // Negated presence check (single or `||`-chain, var or field path) narrows else-branch.
1678
2011
  const single = negatedVarPresence(cond);
1679
2012
  if (single) {
1680
2013
  elseCtx = withEnv(elseCtx, refine(elseCtx.env, single.varName, single.innerTy));
1681
2014
  }
1682
- if (!single && cond.kind === "binop" && cond.op === "||") {
2015
+ else if (cond.kind === "binop" && cond.op === "||") {
1683
2016
  for (const n of collectEarlyReturnNarrowings(cond)) {
1684
2017
  elseCtx = withEnv(elseCtx, refine(elseCtx.env, n.varName, n.innerTy));
1685
2018
  }
1686
2019
  }
2020
+ const negPaths = collectEarlyReturnPathNarrowings(cond, ctx);
2021
+ if (negPaths.length > 0) {
2022
+ elseCtx = { ...elseCtx, narrowedPaths: [...elseCtx.narrowedPaths, ...negPaths] };
2023
+ }
2024
+ const elseVariant = discriminantVariantWhen(cond, false, ctx);
2025
+ if (elseVariant) {
2026
+ elseCtx = { ...elseCtx, narrowedPaths: [...elseCtx.narrowedPaths, elseVariant] };
2027
+ }
2028
+ const elseSynth = synthVariantWhen(cond, false, ctx);
2029
+ if (elseSynth) {
2030
+ elseCtx = applyVariantNarrowing(elseCtx, elseSynth.path, elseSynth.unionTy, elseSynth.variant);
2031
+ }
1687
2032
  // Map-index narrowing: `k in m` in the cond narrows the then-branch; `!(k in m)`
1688
2033
  // narrows the else-branch. Parallel to the if-statement hook in resolveStmt.
1689
2034
  thenCtx = withInAtoms(thenCtx, extractInAtoms(cond));
@@ -1708,12 +2053,18 @@ function resolveExprInner(e, ctx) {
1708
2053
  function resolveSpec(spec, ctx) {
1709
2054
  return resolveExpr(parseExpr(spec), ctx);
1710
2055
  }
1711
- function resolveSpecs(specs, ctx) {
2056
+ function resolveSpecs(specs, ctx, threadAcrossSpecs = false) {
1712
2057
  const result = [];
2058
+ let specCtx = ctx;
1713
2059
  for (const spec of specs) {
2060
+ let clauseCtx = specCtx;
1714
2061
  for (const clause of splitConj(parseExpr(spec))) {
1715
- result.push(resolveExpr(clause, ctx));
2062
+ const resolved = resolveExpr(clause, clauseCtx);
2063
+ result.push(resolved);
2064
+ clauseCtx = collectAndChainNarrowings(resolved, clauseCtx);
1716
2065
  }
2066
+ if (threadAcrossSpecs)
2067
+ specCtx = clauseCtx;
1717
2068
  }
1718
2069
  return result;
1719
2070
  }
@@ -1776,25 +2127,72 @@ function collectAssignedRootsRaw(stmts, out = new Set()) {
1776
2127
  }
1777
2128
  return out;
1778
2129
  }
1779
- /** Restore any narrowed optional variable in `roots` back to its declared
1780
- * `storageTy`, and drop `narrowedPaths` whose root is in `roots`. Used when
1781
- * entering a loop (`while`/`forof`) or exiting a control-flow statement that
1782
- * may reassign or clear a previously narrowed variable. */
1783
- function invalidateNarrowings(env, narrowedPaths, roots) {
1784
- if (roots.size === 0)
2130
+ /** True when `npPath` is at or below dotted `target` (e.g. target `"b.count"`
2131
+ * invalidates `b.count` and `b.count.x`, but preserves `b` itself). */
2132
+ function pathAtOrBelowTarget(npPath, target) {
2133
+ const parts = target.split(".");
2134
+ if (npPath.rootVar !== parts[0])
2135
+ return false;
2136
+ const targetFields = parts.slice(1);
2137
+ if (npPath.fields.length < targetFields.length)
2138
+ return false;
2139
+ return targetFields.every((f, i) => npPath.fields[i] === f);
2140
+ }
2141
+ /** Collect whole-variable assignment roots and dotted field-write targets
2142
+ * separately, so sub-field writes (`sh.y = 10`) do not drop the parent's
2143
+ * discriminated-union variant narrowing while whole-var writes (`sh = ...`) do. */
2144
+ function collectAssignedTargetsRaw(stmts, wholeRoots = new Set(), dottedTargets = new Set()) {
2145
+ for (const s of stmts) {
2146
+ if (s.kind === "assign") {
2147
+ if (s.target.includes("."))
2148
+ dottedTargets.add(s.target);
2149
+ else
2150
+ wholeRoots.add(s.target);
2151
+ }
2152
+ else if (s.kind === "if") {
2153
+ collectAssignedTargetsRaw(s.then, wholeRoots, dottedTargets);
2154
+ collectAssignedTargetsRaw(s.else, wholeRoots, dottedTargets);
2155
+ }
2156
+ else if (s.kind === "while" || s.kind === "forof") {
2157
+ collectAssignedTargetsRaw(s.body, wholeRoots, dottedTargets);
2158
+ }
2159
+ else if (s.kind === "switch") {
2160
+ for (const c of s.cases)
2161
+ collectAssignedTargetsRaw(c.body, wholeRoots, dottedTargets);
2162
+ collectAssignedTargetsRaw(s.defaultBody, wholeRoots, dottedTargets);
2163
+ }
2164
+ }
2165
+ return { wholeRoots, dottedTargets };
2166
+ }
2167
+ /** Restore any narrowed optional/nullish/synth-union variable in `wholeRoots`
2168
+ * back to its declared `storageTy`, drop `narrowedPaths` rooted at `wholeRoots`,
2169
+ * and drop `narrowedPaths` at or below any `dottedTargets` (preserving parent
2170
+ * discriminated-union variants on sub-field writes). */
2171
+ function invalidateNarrowings(env, narrowedPaths, wholeRoots, dottedTargets, typeDecls) {
2172
+ if (wholeRoots.size === 0 && dottedTargets.size === 0)
1785
2173
  return { env, narrowedPaths };
1786
2174
  let nextEnv = env;
1787
- for (const root of roots) {
2175
+ for (const root of wholeRoots) {
1788
2176
  const cur = lookup(nextEnv, root);
1789
2177
  const storage = storageLookup(nextEnv, root);
1790
- if (storage?.kind === "optional" && cur && cur.kind !== "optional") {
2178
+ const isNarrowableStorage = storage?.kind === "optional" || storage?.kind === "nullish" ||
2179
+ (storage?.kind === "user" && !!findSynthArrayUnion(storage.name, typeDecls));
2180
+ if (isNarrowableStorage && cur && !tyEqual(cur, storage)) {
1791
2181
  nextEnv = refine(nextEnv, root, storage);
1792
2182
  }
1793
2183
  }
1794
- const nextPaths = narrowedPaths.filter(np => !roots.has(np.path.rootVar));
2184
+ const nextPaths = narrowedPaths.filter(np => {
2185
+ if (wholeRoots.has(np.path.rootVar))
2186
+ return false;
2187
+ for (const dt of dottedTargets) {
2188
+ if (pathAtOrBelowTarget(np.path, dt))
2189
+ return false;
2190
+ }
2191
+ return true;
2192
+ });
1795
2193
  return { env: nextEnv, narrowedPaths: nextPaths };
1796
2194
  }
1797
- /** True if `stmts` definitely assigns a non-optional, non-`undefined` value
2195
+ /** True if `stmts` definitely assigns a non-optional/non-nullish value
1798
2196
  * to `varName` (without subsequently clearing or shadowing it) on every
1799
2197
  * non-terminating exit path. Used for `#340` assignment narrowing:
1800
2198
  * `if (v === undefined) { v = 6; } return v + 3;`. */
@@ -1814,13 +2212,14 @@ function definitelyAssignsNonOptional(stmts, varName, ctx) {
1814
2212
  continue;
1815
2213
  }
1816
2214
  if (st.kind === "assign" && st.target === varName) {
1817
- if (st.value.kind === "var" && st.value.name === "undefined") {
2215
+ if (st.value.kind === "var" && (st.value.name === "undefined" || st.value.name === "null")) {
1818
2216
  assigned = false;
1819
2217
  }
1820
2218
  else {
1821
2219
  const rhsCtx = { ...ctx, env, returnTy: targetStorage ?? ctx.returnTy };
1822
2220
  const rhsTy = resolveExpr(st.value, rhsCtx).ty;
1823
- assigned = rhsTy.kind !== "optional" && rhsTy.kind !== "void" && rhsTy.kind !== "unknown";
2221
+ assigned = rhsTy.kind !== "optional" && rhsTy.kind !== "nullish" &&
2222
+ rhsTy.kind !== "void" && rhsTy.kind !== "null" && rhsTy.kind !== "unknown";
1824
2223
  }
1825
2224
  }
1826
2225
  else if (st.kind === "if") {
@@ -1863,34 +2262,91 @@ function resolveBlock(stmts, ctx) {
1863
2262
  const [typed, nextEnv] = resolveStmt(s, currentCtx);
1864
2263
  result.push(typed);
1865
2264
  env = nextEnv;
1866
- // Assignment narrowing (#340): assigning a non-optional value to an optional
1867
- // variable narrows it for subsequent statements; assigning `undefined` or an
1868
- // optional restores its declared optional storage type. Also drop stale
1869
- // narrowedPaths rooted at any assigned target (including field writes).
2265
+ // Assignment narrowing (#340) & union reassignment tracking (#405):
2266
+ // assigning a non-optional value to an optional variable or field narrows it;
2267
+ // assigning a variant literal / same-variant spread / synth array-union
2268
+ // updates its narrowed variant; dotted field writes only drop narrowings
2269
+ // at or below the written path (keeping the parent's union variant intact).
1870
2270
  if (s.kind === "assign") {
1871
- const root = s.target.split(".")[0];
1872
- narrowedPaths = narrowedPaths.filter(np => np.path.rootVar !== root);
1873
- if (!s.target.includes(".")) {
2271
+ const parts = s.target.split(".");
2272
+ const root = parts[0];
2273
+ const isNullLit = s.value.kind === "var" && s.value.name === "null";
2274
+ const isUndefLit = s.value.kind === "var" && s.value.name === "undefined";
2275
+ const isDefinitelyPresent = (targetStorage) => {
2276
+ if (isUndefLit || isNullLit)
2277
+ return false;
2278
+ const rhsCtx = { ...currentCtx, returnTy: targetStorage };
2279
+ const rawTy = resolveExpr(s.value, rhsCtx).ty;
2280
+ return rawTy.kind !== "optional" && rawTy.kind !== "nullish" &&
2281
+ rawTy.kind !== "void" && rawTy.kind !== "null" && rawTy.kind !== "unknown";
2282
+ };
2283
+ if (parts.length > 1) {
2284
+ const rootStorage = storageLookup(env, root);
2285
+ const udecl = rootStorage?.kind === "user"
2286
+ ? declOfKind(ctx.typeDecls, tyBaseName(rootStorage.name), "discriminated-union")
2287
+ : undefined;
2288
+ const writesDiscriminant = parts.length === 2 && udecl?.discriminant === parts[1];
2289
+ narrowedPaths = narrowedPaths.filter(np => writesDiscriminant ? np.path.rootVar !== root : !pathAtOrBelowTarget(np.path, s.target));
2290
+ // Dotted assignment to an optional/nullish field (`box.val = 5`):
2291
+ // re-narrow that path when the RHS is definitely present.
2292
+ let fieldTy = rootStorage;
2293
+ for (let i = 1; i < parts.length && fieldTy; i++) {
2294
+ const cur = (fieldTy.kind === "optional" || fieldTy.kind === "nullish") ? fieldTy.inner : fieldTy;
2295
+ fieldTy = lookupFieldTy(cur, parts[i], currentCtx).ty;
2296
+ }
2297
+ if ((fieldTy?.kind === "optional" || fieldTy?.kind === "nullish") && isDefinitelyPresent(fieldTy)) {
2298
+ narrowedPaths = [...narrowedPaths, { path: { rootVar: root, fields: parts.slice(1) }, narrowedTy: fieldTy.inner }];
2299
+ }
2300
+ }
2301
+ else {
2302
+ narrowedPaths = narrowedPaths.filter(np => np.path.rootVar !== s.target);
1874
2303
  const storage = storageLookup(env, s.target);
1875
- if (storage?.kind === "optional") {
1876
- const isUndef = s.value.kind === "var" && s.value.name === "undefined";
1877
- const rhsCtx = { ...currentCtx, returnTy: storage };
1878
- const rawTy = isUndef ? { kind: "void" } : resolveExpr(s.value, rhsCtx).ty;
1879
- if (!isUndef && rawTy.kind !== "optional" && rawTy.kind !== "void" && rawTy.kind !== "unknown") {
1880
- env = refine(env, s.target, storage.inner);
2304
+ if (storage?.kind === "optional" || storage?.kind === "nullish") {
2305
+ env = refine(env, s.target, isDefinitelyPresent(storage) ? storage.inner : storage);
2306
+ }
2307
+ else if (storage?.kind === "user") {
2308
+ const synth = findSynthArrayUnion(storage.name, ctx.typeDecls);
2309
+ if (synth && typed.kind === "assign") {
2310
+ if (typed.value.kind === "call" && typed.value.fn.kind === "var" &&
2311
+ (typed.value.fn.name === "ArrayBranch" || typed.value.fn.name === "NonArrayBranch")) {
2312
+ const payload = synthVariantPayloadTy(storage, typed.value.fn.name, currentCtx);
2313
+ if (payload) {
2314
+ env = refine(env, s.target, payload);
2315
+ narrowedPaths = [...narrowedPaths, { path: { rootVar: s.target, fields: [] }, narrowedTy: payload, variant: typed.value.fn.name }];
2316
+ }
2317
+ else {
2318
+ env = refine(env, s.target, storage);
2319
+ }
2320
+ }
2321
+ else {
2322
+ env = refine(env, s.target, storage);
2323
+ }
1881
2324
  }
1882
2325
  else {
1883
- env = refine(env, s.target, storage);
2326
+ const udecl = declOfKind(ctx.typeDecls, tyBaseName(storage.name), "discriminated-union");
2327
+ if (udecl?.discriminant && typed.kind === "assign" && typed.value.kind === "record") {
2328
+ let nextVariant;
2329
+ const tagF = typed.value.fields.find(f => f.name === udecl.discriminant);
2330
+ if (tagF?.value.kind === "str" || tagF?.value.kind === "bool") {
2331
+ nextVariant = String(tagF.value.value);
2332
+ }
2333
+ else if (typed.value.spread && typed.value.ofVariant && !tagF) {
2334
+ nextVariant = typed.value.ofVariant;
2335
+ }
2336
+ if (nextVariant) {
2337
+ narrowedPaths = [...narrowedPaths, { path: { rootVar: s.target, fields: [] }, narrowedTy: storage, variant: nextVariant }];
2338
+ }
2339
+ }
1884
2340
  }
1885
2341
  }
1886
2342
  }
1887
2343
  }
1888
2344
  // Control-flow invalidation: if an `if`/`while`/`forof`/`switch` may assign
1889
- // a narrowed variable or path, restore its declared optional storage type
1890
- // before subsequent statements (definite-assignment guards re-narrow below).
2345
+ // a narrowed variable or path, restore its declared storage type before
2346
+ // subsequent statements (definite-assignment guards re-narrow below).
1891
2347
  if (s.kind === "if" || s.kind === "while" || s.kind === "forof" || s.kind === "switch") {
1892
- const mutated = collectAssignedRootsRaw([s]);
1893
- const inv = invalidateNarrowings(env, narrowedPaths, mutated);
2348
+ const { wholeRoots, dottedTargets } = collectAssignedTargetsRaw([s]);
2349
+ const inv = invalidateNarrowings(env, narrowedPaths, wholeRoots, dottedTargets, ctx.typeDecls);
1894
2350
  env = inv.env;
1895
2351
  narrowedPaths = inv.narrowedPaths;
1896
2352
  }
@@ -1914,7 +2370,7 @@ function resolveBlock(stmts, ctx) {
1914
2370
  for (const n of collectEarlyReturnNarrowings(typed.cond)) {
1915
2371
  env = refine(env, n.varName, n.innerTy);
1916
2372
  }
1917
- for (const np of collectEarlyReturnPathNarrowings(typed.cond)) {
2373
+ for (const np of collectEarlyReturnPathNarrowings(typed.cond, currentCtx)) {
1918
2374
  if (np.path.fields.length === 0) {
1919
2375
  env = refine(env, np.path.rootVar, np.narrowedTy);
1920
2376
  }
@@ -1922,9 +2378,15 @@ function resolveBlock(stmts, ctx) {
1922
2378
  narrowedPaths = [...narrowedPaths, np];
1923
2379
  }
1924
2380
  }
1925
- const nv = negatedVariantCheck(typed.cond);
2381
+ const nv = discriminantVariantWhen(typed.cond, false, currentCtx);
1926
2382
  if (nv)
1927
2383
  narrowedPaths = [...narrowedPaths, nv];
2384
+ const nsv = synthVariantWhen(typed.cond, false, currentCtx);
2385
+ if (nsv) {
2386
+ const updated = applyVariantNarrowing({ ...currentCtx, env, narrowedPaths }, nsv.path, nsv.unionTy, nsv.variant);
2387
+ env = updated.env;
2388
+ narrowedPaths = updated.narrowedPaths;
2389
+ }
1928
2390
  }
1929
2391
  // Map-index narrowing: `if (!(k in m)) return;` means `k in m` holds in rest.
1930
2392
  if (typed.kind === "if") {
@@ -1964,7 +2426,7 @@ function resolveStmt(s, ctx) {
1964
2426
  // type into the array literal (see the arrayLiteral case). Optionals too
1965
2427
  // (`const r: TExpr | null = cond ? {…} : null`) — the record case unwraps
1966
2428
  // one optional level when consulting returnTy.
1967
- const initCtx = (declTy.kind === "user" || declTy.kind === "array" || declTy.kind === "optional")
2429
+ const initCtx = (declTy.kind === "user" || declTy.kind === "array" || declTy.kind === "optional" || declTy.kind === "nullish")
1968
2430
  ? { ...ctx, returnTy: declTy } : ctx;
1969
2431
  let init = coerceStr(resolveExpr(s.init, initCtx), declTy, ctx.typeDecls);
1970
2432
  // Under noUncheckedIndexedAccess, TS gives `const e = arr[i]` type T | undefined
@@ -1982,9 +2444,11 @@ function resolveStmt(s, ctx) {
1982
2444
  // by inlining an alias we shadow via declare-type, or any-laden), but
1983
2445
  // LS resolved the initializer to something concrete. Take the structure
1984
2446
  // from `init.ty`, keeping only the optionality ts-morph reported.
1985
- ty = declTy.kind === "optional" && init.ty.kind !== "optional"
1986
- ? { kind: "optional", inner: init.ty }
1987
- : init.ty;
2447
+ ty = declTy.kind === "nullish" && init.ty.kind !== "nullish"
2448
+ ? { kind: "nullish", inner: init.ty.kind === "optional" ? init.ty.inner : init.ty }
2449
+ : declTy.kind === "optional" && init.ty.kind !== "optional"
2450
+ ? { ...declTy, inner: init.ty }
2451
+ : init.ty;
1988
2452
  }
1989
2453
  else if (isWidenedStringUnionTy(declTy, init.ty, ctx.typeDecls) && !ctx.overrides.has(s.name)) {
1990
2454
  // ts-morph widened a string-union to `string`; keep the initializer's
@@ -1999,7 +2463,7 @@ function resolveStmt(s, ctx) {
1999
2463
  }
2000
2464
  else {
2001
2465
  // Map indexing: TS says T, but access can fail → use Optional<T> from init
2002
- ty = (declTy.kind !== "optional" && init.ty.kind === "optional") ? init.ty : declTy;
2466
+ ty = (declTy.kind !== "optional" && declTy.kind !== "nullish" && init.ty.kind === "optional") ? init.ty : declTy;
2003
2467
  }
2004
2468
  // const collections are mutable in value-semantics world (TS mutates in place, Dafny/Lean reassign)
2005
2469
  const mutable = s.mutable || isRefMutableInTS(ty);
@@ -2011,17 +2475,57 @@ function resolveStmt(s, ctx) {
2011
2475
  throw new Error(`assignment to callback binding '${s.target}' requires materializing its argument value`);
2012
2476
  }
2013
2477
  entry?.onRead?.();
2478
+ // For dotted writes (`sh.value = ...`, `b.sh.value = ...`), record any
2479
+ // narrowed union variant at each step along the owner chain so
2480
+ // transform/emit use the right collision-renamed destructors and Lean
2481
+ // inductive match-updates at arbitrary nesting depth.
2482
+ let ownerVariants;
2483
+ let targetTy = storageLookup(ctx.env, s.target) ?? { kind: "unknown" };
2484
+ if (s.target.includes(".") && !s.target.startsWith("this.")) {
2485
+ const parts = s.target.split(".");
2486
+ const root = parts[0];
2487
+ const fields = parts.slice(1);
2488
+ const variants = [];
2489
+ let curTy = storageLookup(ctx.env, root);
2490
+ for (let i = 0; i < fields.length; i++) {
2491
+ const v = lookupNarrowedVariant({ rootVar: root, fields: fields.slice(0, i) }, ctx);
2492
+ variants.push(v);
2493
+ if (curTy) {
2494
+ const unwrapped = (curTy.kind === "optional" || curTy.kind === "nullish") ? curTy.inner : curTy;
2495
+ if (unwrapped.kind === "user") {
2496
+ const decl = findDecl(ctx, tyBaseName(unwrapped.name));
2497
+ if (decl?.kind === "discriminated-union" && decl.variants) {
2498
+ const variant = (v ? decl.variants.find(vi => vi.name === v) : undefined)
2499
+ ?? decl.variants.find(vi => vi.fields.some(f => f.name === fields[i]));
2500
+ curTy = variant?.fields.find(f => f.name === fields[i])?.type;
2501
+ }
2502
+ else if (decl?.kind === "record" && decl.fields) {
2503
+ curTy = decl.fields.find(f => f.name === fields[i])?.type;
2504
+ }
2505
+ else {
2506
+ curTy = undefined;
2507
+ }
2508
+ }
2509
+ else {
2510
+ curTy = undefined;
2511
+ }
2512
+ }
2513
+ }
2514
+ if (variants.some(v => v !== undefined))
2515
+ ownerVariants = variants;
2516
+ if (curTy)
2517
+ targetTy = curTy;
2518
+ }
2014
2519
  // Coerce RHS against the variable's declared storage type (not a narrowed
2015
2520
  // flow type) so reassignments like `v = 7` or `v = undefined` stay typed
2016
2521
  // as `Option<T>`.
2017
- const targetTy = storageLookup(ctx.env, s.target) ?? { kind: "unknown" };
2018
2522
  // Propagate the target's type as returnTy, mirroring the annotated-let
2019
2523
  // case, so record/union literals and array literals in the RHS resolve
2020
2524
  // to their named datatypes.
2021
- const valueCtx = (targetTy.kind === "user" || targetTy.kind === "array" || targetTy.kind === "optional")
2525
+ const valueCtx = (targetTy.kind === "user" || targetTy.kind === "array" || targetTy.kind === "optional" || targetTy.kind === "nullish")
2022
2526
  ? { ...ctx, returnTy: targetTy } : ctx;
2023
2527
  const value = coerceToTargetTy(resolveExpr(s.value, valueCtx), targetTy, ctx.typeDecls);
2024
- return [{ kind: "assign", target: entry?.emittedName ?? s.target, value }, ctx.env];
2528
+ return [{ kind: "assign", target: entry?.emittedName ?? s.target, value, ...(ownerVariants ? { ownerVariants } : {}) }, ctx.env];
2025
2529
  }
2026
2530
  case "return": {
2027
2531
  const value = coerceToTargetTy(resolveExpr(s.value, ctx), ctx.returnTy, ctx.typeDecls);
@@ -2045,6 +2549,23 @@ function resolveStmt(s, ctx) {
2045
2549
  if (single) {
2046
2550
  elseCtx = withEnv(ctx, refine(ctx.env, single.varName, single.innerTy));
2047
2551
  }
2552
+ else if (resolvedCond.kind === "binop" && resolvedCond.op === "||") {
2553
+ for (const n of collectEarlyReturnNarrowings(resolvedCond)) {
2554
+ elseCtx = withEnv(elseCtx, refine(elseCtx.env, n.varName, n.innerTy));
2555
+ }
2556
+ }
2557
+ const negPaths = collectEarlyReturnPathNarrowings(resolvedCond, ctx);
2558
+ if (negPaths.length > 0) {
2559
+ elseCtx = { ...elseCtx, narrowedPaths: [...elseCtx.narrowedPaths, ...negPaths] };
2560
+ }
2561
+ const elseVariant = discriminantVariantWhen(resolvedCond, false, ctx);
2562
+ if (elseVariant) {
2563
+ elseCtx = { ...elseCtx, narrowedPaths: [...elseCtx.narrowedPaths, elseVariant] };
2564
+ }
2565
+ const elseSynth = synthVariantWhen(resolvedCond, false, ctx);
2566
+ if (elseSynth) {
2567
+ elseCtx = applyVariantNarrowing(elseCtx, elseSynth.path, elseSynth.unionTy, elseSynth.variant);
2568
+ }
2048
2569
  // Narrow map index access across `k in m` / `!(k in m)` in the cond:
2049
2570
  // positive atoms (from `k in m` or &&-chains containing it) → then-branch;
2050
2571
  // negated atoms (from `!(k in m)`) → else-branch.
@@ -2056,8 +2577,8 @@ function resolveStmt(s, ctx) {
2056
2577
  // Any variable or path mutated inside the loop body cannot keep a pre-loop
2057
2578
  // narrowing across iterations (including inside the loop condition and
2058
2579
  // invariants on back-edges).
2059
- const loopMutated = collectAssignedRootsRaw(s.body);
2060
- const loopInv = invalidateNarrowings(ctx.env, ctx.narrowedPaths, loopMutated);
2580
+ const { wholeRoots, dottedTargets } = collectAssignedTargetsRaw(s.body);
2581
+ const loopInv = invalidateNarrowings(ctx.env, ctx.narrowedPaths, wholeRoots, dottedTargets, ctx.typeDecls);
2061
2582
  const loopCtx = { ...ctx, env: loopInv.env, narrowedPaths: loopInv.narrowedPaths };
2062
2583
  const whileSpecCtx = { ...loopCtx, inSpec: true };
2063
2584
  const resolvedInvariants = resolveSpecs(s.invariants, whileSpecCtx);
@@ -2107,8 +2628,8 @@ function resolveStmt(s, ctx) {
2107
2628
  const count = ctx.forofCounts.get(s.names[0]) ?? 0;
2108
2629
  ctx.forofCounts.set(s.names[0], count + 1);
2109
2630
  const idxName = freshName(`_${s.names[0]}_idx${count === 0 ? "" : count + 1}`);
2110
- const loopMutated = collectAssignedRootsRaw(s.body);
2111
- const loopInv = invalidateNarrowings(ctx.env, ctx.narrowedPaths, loopMutated);
2631
+ const { wholeRoots, dottedTargets } = collectAssignedTargetsRaw(s.body);
2632
+ const loopInv = invalidateNarrowings(ctx.env, ctx.narrowedPaths, wholeRoots, dottedTargets, ctx.typeDecls);
2112
2633
  env = loopInv.env;
2113
2634
  env = extend(env, idxName, { kind: "nat" });
2114
2635
  for (let j = 0; j < s.names.length; j++) {
@@ -2124,12 +2645,19 @@ function resolveStmt(s, ctx) {
2124
2645
  }
2125
2646
  case "throw":
2126
2647
  return [{ kind: "throw" }, ctx.env];
2127
- case "switch":
2128
- return [{
2129
- kind: "switch", expr: resolveExpr(s.expr, ctx), discriminant: s.discriminant,
2130
- cases: s.cases.map(c => ({ label: c.label, body: resolveBlock(c.body, ctx) })),
2131
- defaultBody: resolveBlock(s.defaultBody, ctx),
2132
- }, ctx.env];
2648
+ case "switch": {
2649
+ const expr = resolveExpr(s.expr, ctx);
2650
+ const decl = expr.ty.kind === "user" ? findDecl(ctx, tyBaseName(expr.ty.name)) : undefined;
2651
+ const path = decl?.kind === "discriminated-union" && decl.discriminant === s.discriminant
2652
+ ? asTExprAccessPath(expr) : null;
2653
+ const withVariant = (variant) => path && variant ? { ...ctx, narrowedPaths: [
2654
+ ...ctx.narrowedPaths, { path, narrowedTy: expr.ty, variant },
2655
+ ] } : ctx;
2656
+ const cases = s.cases.map(c => ({ label: c.label, body: resolveBlock(c.body, withVariant(c.label)) }));
2657
+ const defaultVariant = path && decl ? remainingVariant(decl, s.cases.map(c => c.label))?.name : undefined;
2658
+ return [{ kind: "switch", expr, discriminant: s.discriminant, cases,
2659
+ defaultBody: resolveBlock(s.defaultBody, withVariant(defaultVariant)) }, ctx.env];
2660
+ }
2133
2661
  case "ghostLet": {
2134
2662
  const specCtx = { ...ctx, inSpec: true };
2135
2663
  // Handle new Set<T>() / new Map<K,V>() constructors
@@ -2359,7 +2887,7 @@ function resolveFunction(fn, typeDecls, pureFns, fnParams = new Map(), fnReturns
2359
2887
  env = extend(env, opts.thisBinding.name, opts.thisBinding.ty);
2360
2888
  for (const p of params)
2361
2889
  env = extend(env, p.name, p.ty);
2362
- const baseCtx = { env, typeDecls, overrides, allowResult: false, returnTy, pureFns, fnParams, fnReturns, externs, inSpec: false, inLambda: false, narrowedPaths: [], narrowedIndices: [], forofCounts: new Map() };
2890
+ const baseCtx = { env, typeDecls, typeParams: new Set(fn.typeParams), overrides, allowResult: false, returnTy, pureFns, fnParams, fnReturns, externs, inSpec: false, inLambda: false, narrowedPaths: [], narrowedIndices: [], forofCounts: new Map() };
2363
2891
  const requiresCtx = { ...baseCtx, inSpec: true };
2364
2892
  const ensuresCtx = { ...baseCtx, env: extend(env, "\\result", returnTy), allowResult: true, inSpec: true };
2365
2893
  // Apply type parameter constraints from //@ type T (==) annotations
@@ -2371,7 +2899,7 @@ function resolveFunction(fn, typeDecls, pureFns, fnParams = new Map(), fnReturns
2371
2899
  // into the body context and the ensures context — they hold for the whole
2372
2900
  // body (pure fns) and for post-state references in the ensures (map params
2373
2901
  // aren't mutated through their binding in the Dafny translation).
2374
- const resolvedRequires = resolveSpecs(fn.requires, requiresCtx);
2902
+ const resolvedRequires = resolveSpecs(fn.requires, requiresCtx, true);
2375
2903
  const requiresAtoms = resolvedRequires.flatMap(extractInAtoms);
2376
2904
  const bodyCtx = withInAtoms(baseCtx, requiresAtoms);
2377
2905
  const ensuresCtxNarrowed = withInAtoms(ensuresCtx, requiresAtoms);
@@ -2466,7 +2994,7 @@ export function resolveModule(raw) {
2466
2994
  for (let i = 0; i < ext.params.length; i++) {
2467
2995
  env = extend(env, ext.params[i].name, sig.params[i]);
2468
2996
  }
2469
- const baseCtx = { env, typeDecls: raw.typeDecls, overrides: new Map(), allowResult: false, returnTy: sig.returnTy, pureFns, fnParams, fnReturns, externs, inSpec: true, inLambda: false, narrowedPaths: [], narrowedIndices: [], forofCounts: new Map() };
2997
+ const baseCtx = { env, typeDecls: raw.typeDecls, typeParams: new Set(ext.typeParams), overrides: new Map(), allowResult: false, returnTy: sig.returnTy, pureFns, fnParams, fnReturns, externs, inSpec: true, inLambda: false, narrowedPaths: [], narrowedIndices: [], forofCounts: new Map() };
2470
2998
  const ensuresCtx = { ...baseCtx, env: extend(env, "\\result", sig.returnTy), allowResult: true };
2471
2999
  const resolveClauses = (kind, ctx) => ext[kind].map(s => {
2472
3000
  try {
@@ -2488,7 +3016,7 @@ export function resolveModule(raw) {
2488
3016
  impure: ext.impure,
2489
3017
  };
2490
3018
  });
2491
- const emptyCtx = { env: null, typeDecls: raw.typeDecls, overrides: new Map(), allowResult: false, returnTy: { kind: "int" }, pureFns, fnParams, fnReturns, externs, inSpec: false, inLambda: false, narrowedPaths: [], narrowedIndices: [], forofCounts: new Map() };
3019
+ const emptyCtx = { env: null, typeDecls: raw.typeDecls, typeParams: new Set(), overrides: new Map(), allowResult: false, returnTy: { kind: "int" }, pureFns, fnParams, fnReturns, externs, inSpec: false, inLambda: false, narrowedPaths: [], narrowedIndices: [], forofCounts: new Map() };
2492
3020
  const constants = (raw.constants ?? []).map(c => {
2493
3021
  const declaredTy = expandAlias(parseTsType(c.tsType), raw.typeDecls);
2494
3022
  // Propagate the declared type into the value's resolution context so that