lemmascript 0.6.14 → 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.
@@ -9,8 +9,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)
@@ -261,11 +263,11 @@ function negatedVarPresence(cond) {
261
263
  * (x === undefined || y === undefined). */
262
264
  /** Extract field-path or optional-chain narrowings guaranteed after an early
263
265
  * return (`if (d.b === undefined) return;` or `if (b?.tag !== 1) return;`, #354). */
264
- function collectEarlyReturnPathNarrowings(cond) {
266
+ function collectEarlyReturnPathNarrowings(cond, ctx) {
265
267
  if (cond.kind === "binop" && cond.op === "||") {
266
268
  return [
267
- ...collectEarlyReturnPathNarrowings(cond.left),
268
- ...collectEarlyReturnPathNarrowings(cond.right),
269
+ ...collectEarlyReturnPathNarrowings(cond.left, ctx),
270
+ ...collectEarlyReturnPathNarrowings(cond.right, ctx),
269
271
  ];
270
272
  }
271
273
  // Negated field-path presence: `d.b === undefined` or `!d.b`
@@ -284,8 +286,7 @@ function collectEarlyReturnPathNarrowings(cond) {
284
286
  : cond.right.kind === "optChain"
285
287
  ? [cond.right, cond.left]
286
288
  : [null, null];
287
- if (ocSide && otherSide && !(otherSide.kind === "var" && otherSide.name === "undefined") &&
288
- otherSide.ty.kind !== "optional" && otherSide.ty.kind !== "void" &&
289
+ if (ocSide && otherSide && excludesUndefined(otherSide, ctx.typeDecls, ctx.typeParams) &&
289
290
  ocSide.obj.ty.kind === "optional") {
290
291
  const path = asTExprAccessPath(ocSide.obj);
291
292
  if (path)
@@ -320,18 +321,125 @@ function collectEarlyReturnNarrowings(cond) {
320
321
  const n = negatedVarPresence(cond);
321
322
  return n ? [n] : [];
322
323
  }
323
- /** Negated discriminant check (`path.kind !== "lit"`) on a var or field path.
324
- * After `if (path.kind !== "lit") return`, the rest of the block knows the
325
- * path is that variant. */
326
- function negatedVariantCheck(cond) {
327
- if (cond.kind === "binop" && cond.op === "!==" && cond.right.kind === "str" &&
328
- cond.left.kind === "field" && cond.left.isDiscriminant && cond.left.obj.ty.kind === "user") {
329
- const path = asTExprAccessPath(cond.left.obj);
330
- if (path)
331
- 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" };
332
366
  }
333
367
  return null;
334
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
+ }
335
443
  /** TExpr → AccessPath. Counterpart to `asRawAccessPath` for resolved trees.
336
444
  * Used by `extractInAtoms` when pulling atoms out of typed spec expressions. */
337
445
  function asTExprAccessPath(e) {
@@ -410,13 +518,22 @@ function collectAndChainNarrowings(cond, ctx) {
410
518
  }
411
519
  return ctx;
412
520
  }
413
- // Positive discriminant check (`x.kind === "bool"`): record the variant so
414
- // 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
+ }
415
532
  const vf = variantFact(cond, { decls: ctx.typeDecls, oc: { n: 0 } });
416
533
  if (vf) {
417
534
  const path = asTExprAccessPath(vf.scrutinee);
418
535
  if (path) {
419
- return { ...ctx, narrowedPaths: [...ctx.narrowedPaths, { path, narrowedTy: vf.scrutinee.ty, variant: vf.variant }] };
536
+ return applyVariantNarrowing(ctx, path, vf.scrutinee.ty, vf.variant);
420
537
  }
421
538
  }
422
539
  return ctx;
@@ -440,6 +557,14 @@ function collectOrChainNarrowings(cond, ctx) {
440
557
  return { ...ctx, narrowedPaths: [...ctx.narrowedPaths, { path, narrowedTy: f.innerTy }] };
441
558
  }
442
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
+ }
443
568
  return ctx;
444
569
  }
445
570
  /** TS reference types that become value types in Dafny/Lean — const bindings need mutable var. */
@@ -1067,11 +1192,13 @@ function lookupFieldTy(objTy, field, ctx) {
1067
1192
  return { ty: f.type, isDiscriminant };
1068
1193
  }
1069
1194
  if (decl?.kind === "discriminated-union" && decl.variants) {
1070
- for (const variant of decl.variants) {
1071
- const f = variant.fields.find(f => f.name === field);
1072
- if (f)
1073
- 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 };
1074
1200
  }
1201
+ return { ty: { kind: "unknown" }, isDiscriminant };
1075
1202
  }
1076
1203
  return { ty: { kind: "unknown" }, isDiscriminant };
1077
1204
  }
@@ -1296,6 +1423,12 @@ function resolveExprInner(e, ctx) {
1296
1423
  warnRefEq(e.op, left.ty, right.ty);
1297
1424
  }
1298
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
+ }
1299
1432
  let ty = { kind: "unknown" };
1300
1433
  // <==> is bool like the comparisons; unlike ==>, neither side narrows
1301
1434
  // the other (no premise to assume).
@@ -1336,7 +1469,13 @@ function resolveExprInner(e, ctx) {
1336
1469
  return { kind: "binop", op: e.op, left, right, ty };
1337
1470
  }
1338
1471
  case "unop": {
1339
- 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
+ }
1340
1479
  const ty = e.op === "!" ? { kind: "bool" } : e.op === "typeof" ? { kind: "string" }
1341
1480
  : e.op === "-" && expr.ty.kind === "nat" ? { ...expr.ty, kind: "int" } : expr.ty;
1342
1481
  return { kind: "unop", op: e.op, expr, ty };
@@ -1390,7 +1529,7 @@ function resolveExprInner(e, ctx) {
1390
1529
  throw new Error(`impure extern ${qualified} cannot be called from a specification`);
1391
1530
  if (ext.impure && ctx.inLambda)
1392
1531
  throw new Error(`impure extern ${qualified} cannot be called from a lambda`);
1393
- const args = e.args.map(a => resolveExpr(a, ctx));
1532
+ const args = projectStructuralCallArgs(e.args.map(a => resolveExpr(a, ctx)), ext.params, ctx);
1394
1533
  const fn = { kind: "var", name: ext.flat, ty: { kind: "unknown" } };
1395
1534
  return {
1396
1535
  kind: "call", fn, args, ty: ext.returnTy,
@@ -1400,35 +1539,44 @@ function resolveExprInner(e, ctx) {
1400
1539
  }
1401
1540
  }
1402
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;
1403
1544
  const rawArgs = inferLambdaParamTypes(fn, e.args, ctx);
1404
- // For .push() on a typed array, resolve args with element type context
1405
- let argCtx = ctx;
1406
- if (fn.kind === "field" && fn.obj.ty.kind === "array" && fn.field === "push" &&
1407
- fn.obj.ty.elem.kind === "user") {
1408
- argCtx = { ...ctx, returnTy: fn.obj.ty.elem };
1409
- }
1410
- // Propagate parameter types to arguments for record literal resolution
1411
- // (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.).
1412
1548
  const paramTypes = fn.kind === "var" && !binding(ctx.env, fn.name) ? ctx.fnParams.get(fn.name) ?? null : null;
1413
1549
  const initial = fn.kind === "field" && fn.field === "reduce" && rawArgs.length >= 2
1414
- ? resolveExpr(rawArgs[1], argCtx) : undefined;
1550
+ ? resolveExpr(rawArgs[1], ctx) : undefined;
1415
1551
  const callback = callbackContext(fn, initial);
1416
1552
  let args = coerceCallArgs(rawArgs.map((a, i) => {
1417
- let aCtx = argCtx;
1418
- if (paramTypes && i < paramTypes.length &&
1419
- (paramTypes[i].kind === "user" || paramTypes[i].kind === "array" || paramTypes[i].kind === "optional" || paramTypes[i].kind === "nullish")) {
1420
- 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 };
1421
1559
  }
1422
1560
  if (i === 0 && a.kind === "lambda" && callback)
1423
1561
  return resolveCallback(a, callback.actual, callback.baseArity, aCtx);
1424
- 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;
1425
1569
  }), fn, ctx);
1426
- // Array method `.with(i, v)`: coerce the value arg to the element type
1427
- // so `arr[i] = v` on `(T|null)[]` wraps `T` → `Some(T)` (and similarly
1428
- // for synth array-unions). Same shape as the record-field coercion
1429
- // below: assigning a narrower value into a wider slot.
1430
- if (fn.kind === "field" && fn.field === "with" && fn.obj.ty.kind === "array" && args.length === 2) {
1431
- 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
+ }
1432
1580
  }
1433
1581
  let ty = inferMethodReturnTy(fn, args, ctx);
1434
1582
  // For same-file function calls, use the known return type
@@ -1455,7 +1603,6 @@ function resolveExprInner(e, ctx) {
1455
1603
  && (filterSentinel === "both" || filterSentinel === optAbsent(fn.obj.ty.elem))) {
1456
1604
  return { kind: "call", fn: { ...fn, field: "filterSome" }, args: [], ty: { kind: "array", elem: fn.obj.ty.elem.inner }, callKind: "method" };
1457
1605
  }
1458
- const builtinId = fn.kind === "field" ? recognizeBuiltin(fn.obj.ty, fn.field) : null;
1459
1606
  return { kind: "call", fn, args, ty, callKind: classifyCall(e.fn, ctx),
1460
1607
  ...(builtinId ? { builtinId } : {}),
1461
1608
  ...(paramTypes ? { paramTys: paramTypes } : {}) };
@@ -1471,7 +1618,7 @@ function resolveExprInner(e, ctx) {
1471
1618
  return member;
1472
1619
  }
1473
1620
  const obj = resolveExpr(e.obj, ctx);
1474
- const idx = resolveExpr(e.idx, ctx);
1621
+ let idx = resolveExpr(e.idx, ctx);
1475
1622
  // Map bracket access: default to Option<V>. But if the enclosing scope has a
1476
1623
  // known `k in m` atom matching (obj, idx) — from requires, assert, an enclosing
1477
1624
  // `if (k in m)`, or a loop invariant — narrow to V. Parallels how `narrowedPaths`
@@ -1494,6 +1641,7 @@ function resolveExprInner(e, ctx) {
1494
1641
  idxTy = elems[idx.value];
1495
1642
  }
1496
1643
  else if (obj.ty.kind === "map") {
1644
+ idx = coerceToTargetTy(idx, obj.ty.key, ctx.typeDecls);
1497
1645
  const objPath = asTExprAccessPath(obj);
1498
1646
  const idxPath = asTExprAccessPath(idx);
1499
1647
  const narrowed = objPath && idxPath && ctx.narrowedIndices.some(n => accessPathsEqual(n.obj, objPath) && accessPathsEqual(n.idx, idxPath));
@@ -1531,10 +1679,11 @@ function resolveExprInner(e, ctx) {
1531
1679
  }
1532
1680
  }
1533
1681
  }
1534
- // A variant narrowing on the object picks the field's type from that
1535
- // 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.
1536
1685
  let ofVariant;
1537
- if (ty.kind === "unknown" && ctx.narrowedPaths.length > 0 && obj.ty.kind === "user") {
1686
+ if (ctx.narrowedPaths.length > 0 && obj.ty.kind === "user") {
1538
1687
  const objPath = asRawAccessPath(e.obj);
1539
1688
  let np;
1540
1689
  if (objPath) {
@@ -1550,8 +1699,9 @@ function resolveExprInner(e, ctx) {
1550
1699
  const decl = findDecl(ctx, tyBaseName(obj.ty.name));
1551
1700
  const f = decl?.variants?.find(v => v.name === np.variant)?.fields.find(f => f.name === e.field);
1552
1701
  if (f?.type) {
1553
- ty = f.type;
1554
1702
  ofVariant = np.variant;
1703
+ if (ty.kind === "unknown")
1704
+ ty = f.type;
1555
1705
  }
1556
1706
  }
1557
1707
  }
@@ -1610,7 +1760,9 @@ function resolveExprInner(e, ctx) {
1610
1760
  stepInTy = fieldTy;
1611
1761
  }
1612
1762
  else if (step.kind === "index") {
1613
- 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);
1614
1766
  const idxTy = stepInTy.kind === "array" ? stepInTy.elem
1615
1767
  : stepInTy.kind === "string" ? { kind: "string" }
1616
1768
  : stepInTy.kind === "map" ? { kind: "optional", inner: stepInTy.value }
@@ -1634,15 +1786,22 @@ function resolveExprInner(e, ctx) {
1634
1786
  : ((obj.ty.kind === "optional" || obj.ty.kind === "nullish") ? obj.ty.inner : obj.ty);
1635
1787
  const fakeObj = { kind: "var", name: "_chain_recv", ty: priorInTy };
1636
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;
1637
1791
  rawArgs = inferLambdaParamTypes(fakeFn, rawArgs);
1638
1792
  const initial = lastField.name === "reduce" && rawArgs.length >= 2 ? resolveExpr(rawArgs[1], ctx) : undefined;
1639
1793
  const callback = callbackContext(fakeFn, initial);
1640
- const args = rawArgs.map((a, i) => i === 0 && a.kind === "lambda" && callback
1641
- ? resolveCallback(a, callback.actual, callback.baseArity, ctx)
1642
- : 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
+ });
1643
1803
  callTy = inferMethodReturnTy(fakeFn, args, ctx);
1644
1804
  callKind = "method";
1645
- const builtinId = recognizeBuiltin(priorInTy, lastField.name);
1646
1805
  chain.push({ kind: "call", args, ty: callTy, callKind,
1647
1806
  ...(builtinId ? { builtinId } : {}) });
1648
1807
  stepInTy = callTy;
@@ -1689,16 +1848,27 @@ function resolveExprInner(e, ctx) {
1689
1848
  const returnTyUnwrapped = (ctx.returnTy.kind === "optional" || ctx.returnTy.kind === "nullish") ? ctx.returnTy.inner : ctx.returnTy;
1690
1849
  const recordTy = ty.kind === "user" ? ty : returnTyUnwrapped.kind === "user" ? returnTyUnwrapped : null;
1691
1850
  const decl = recordTy ? declOfKind(ctx.typeDecls, recordTy.name, "record") : undefined;
1692
- // Union-variant literal in union-typed context (a constructed IR node,
1693
- // `{ kind: "if", … }: TStmt`): contextual field types come from the
1694
- // 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.
1695
1854
  let declFields = decl?.fields;
1855
+ let ofVariant;
1856
+ let spreadOfVariant;
1696
1857
  if (!declFields && recordTy) {
1697
- const udecl = declOfKind(ctx.typeDecls, recordTy.name, "discriminated-union");
1858
+ const udecl = declOfKind(ctx.typeDecls, tyBaseName(recordTy.name), "discriminated-union");
1698
1859
  if (udecl?.discriminant && udecl.variants) {
1860
+ if (spread) {
1861
+ const spPath = asTExprAccessPath(spread);
1862
+ spreadOfVariant = spPath ? lookupNarrowedVariant(spPath, ctx) : undefined;
1863
+ }
1699
1864
  const tagRaw = e.fields.find(f => f.name === udecl.discriminant)?.value;
1700
- if (tagRaw?.kind === "str") {
1701
- 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;
1702
1872
  }
1703
1873
  }
1704
1874
  }
@@ -1730,7 +1900,14 @@ function resolveExprInner(e, ctx) {
1730
1900
  }
1731
1901
  return { name: f.name, value };
1732
1902
  });
1733
- 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
+ };
1734
1911
  }
1735
1912
  case "recordMerge":
1736
1913
  return resolveRecordMerge(e.base, e.override, ctx);
@@ -1810,9 +1987,9 @@ function resolveExprInner(e, ctx) {
1810
1987
  const body = Array.isArray(e.body)
1811
1988
  ? resolveBlock(e.body, lambdaCtx)
1812
1989
  : [{ kind: "return", value: resolveExpr(e.body, lambdaCtx) }];
1813
- // Carry the lambda's type as a fn type when its return is known, so chained
1814
- // array methods (`.map(...).filter(...)`) can infer downstream element types.
1815
- 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
1816
1993
  ? { kind: "fn", params: params.map(p => p.ty), result: lambdaReturnTy }
1817
1994
  : { kind: "unknown" };
1818
1995
  return { kind: "lambda", params, body, ty: lamTy };
@@ -1840,10 +2017,18 @@ function resolveExprInner(e, ctx) {
1840
2017
  elseCtx = withEnv(elseCtx, refine(elseCtx.env, n.varName, n.innerTy));
1841
2018
  }
1842
2019
  }
1843
- const negPaths = collectEarlyReturnPathNarrowings(cond);
2020
+ const negPaths = collectEarlyReturnPathNarrowings(cond, ctx);
1844
2021
  if (negPaths.length > 0) {
1845
2022
  elseCtx = { ...elseCtx, narrowedPaths: [...elseCtx.narrowedPaths, ...negPaths] };
1846
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
+ }
1847
2032
  // Map-index narrowing: `k in m` in the cond narrows the then-branch; `!(k in m)`
1848
2033
  // narrows the else-branch. Parallel to the if-statement hook in resolveStmt.
1849
2034
  thenCtx = withInAtoms(thenCtx, extractInAtoms(cond));
@@ -1868,12 +2053,18 @@ function resolveExprInner(e, ctx) {
1868
2053
  function resolveSpec(spec, ctx) {
1869
2054
  return resolveExpr(parseExpr(spec), ctx);
1870
2055
  }
1871
- function resolveSpecs(specs, ctx) {
2056
+ function resolveSpecs(specs, ctx, threadAcrossSpecs = false) {
1872
2057
  const result = [];
2058
+ let specCtx = ctx;
1873
2059
  for (const spec of specs) {
2060
+ let clauseCtx = specCtx;
1874
2061
  for (const clause of splitConj(parseExpr(spec))) {
1875
- result.push(resolveExpr(clause, ctx));
2062
+ const resolved = resolveExpr(clause, clauseCtx);
2063
+ result.push(resolved);
2064
+ clauseCtx = collectAndChainNarrowings(resolved, clauseCtx);
1876
2065
  }
2066
+ if (threadAcrossSpecs)
2067
+ specCtx = clauseCtx;
1877
2068
  }
1878
2069
  return result;
1879
2070
  }
@@ -1936,22 +2127,69 @@ function collectAssignedRootsRaw(stmts, out = new Set()) {
1936
2127
  }
1937
2128
  return out;
1938
2129
  }
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)
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)
1945
2173
  return { env, narrowedPaths };
1946
2174
  let nextEnv = env;
1947
- for (const root of roots) {
2175
+ for (const root of wholeRoots) {
1948
2176
  const cur = lookup(nextEnv, root);
1949
2177
  const storage = storageLookup(nextEnv, root);
1950
- if ((storage?.kind === "optional" || storage?.kind === "nullish") && cur && !tyEqual(cur, storage)) {
2178
+ const isNarrowableStorage = storage?.kind === "optional" || storage?.kind === "nullish" ||
2179
+ (storage?.kind === "user" && !!findSynthArrayUnion(storage.name, typeDecls));
2180
+ if (isNarrowableStorage && cur && !tyEqual(cur, storage)) {
1951
2181
  nextEnv = refine(nextEnv, root, storage);
1952
2182
  }
1953
2183
  }
1954
- 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
+ });
1955
2193
  return { env: nextEnv, narrowedPaths: nextPaths };
1956
2194
  }
1957
2195
  /** True if `stmts` definitely assigns a non-optional/non-nullish value
@@ -2024,36 +2262,91 @@ function resolveBlock(stmts, ctx) {
2024
2262
  const [typed, nextEnv] = resolveStmt(s, currentCtx);
2025
2263
  result.push(typed);
2026
2264
  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).
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).
2031
2270
  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(".")) {
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);
2035
2303
  const storage = storageLookup(env, s.target);
2036
2304
  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);
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
+ }
2044
2324
  }
2045
2325
  else {
2046
- 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
+ }
2047
2340
  }
2048
2341
  }
2049
2342
  }
2050
2343
  }
2051
2344
  // 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).
2345
+ // a narrowed variable or path, restore its declared storage type before
2346
+ // subsequent statements (definite-assignment guards re-narrow below).
2054
2347
  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);
2348
+ const { wholeRoots, dottedTargets } = collectAssignedTargetsRaw([s]);
2349
+ const inv = invalidateNarrowings(env, narrowedPaths, wholeRoots, dottedTargets, ctx.typeDecls);
2057
2350
  env = inv.env;
2058
2351
  narrowedPaths = inv.narrowedPaths;
2059
2352
  }
@@ -2077,7 +2370,7 @@ function resolveBlock(stmts, ctx) {
2077
2370
  for (const n of collectEarlyReturnNarrowings(typed.cond)) {
2078
2371
  env = refine(env, n.varName, n.innerTy);
2079
2372
  }
2080
- for (const np of collectEarlyReturnPathNarrowings(typed.cond)) {
2373
+ for (const np of collectEarlyReturnPathNarrowings(typed.cond, currentCtx)) {
2081
2374
  if (np.path.fields.length === 0) {
2082
2375
  env = refine(env, np.path.rootVar, np.narrowedTy);
2083
2376
  }
@@ -2085,9 +2378,15 @@ function resolveBlock(stmts, ctx) {
2085
2378
  narrowedPaths = [...narrowedPaths, np];
2086
2379
  }
2087
2380
  }
2088
- const nv = negatedVariantCheck(typed.cond);
2381
+ const nv = discriminantVariantWhen(typed.cond, false, currentCtx);
2089
2382
  if (nv)
2090
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
+ }
2091
2390
  }
2092
2391
  // Map-index narrowing: `if (!(k in m)) return;` means `k in m` holds in rest.
2093
2392
  if (typed.kind === "if") {
@@ -2176,17 +2475,57 @@ function resolveStmt(s, ctx) {
2176
2475
  throw new Error(`assignment to callback binding '${s.target}' requires materializing its argument value`);
2177
2476
  }
2178
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
+ }
2179
2519
  // Coerce RHS against the variable's declared storage type (not a narrowed
2180
2520
  // flow type) so reassignments like `v = 7` or `v = undefined` stay typed
2181
2521
  // as `Option<T>`.
2182
- const targetTy = storageLookup(ctx.env, s.target) ?? { kind: "unknown" };
2183
2522
  // Propagate the target's type as returnTy, mirroring the annotated-let
2184
2523
  // case, so record/union literals and array literals in the RHS resolve
2185
2524
  // to their named datatypes.
2186
2525
  const valueCtx = (targetTy.kind === "user" || targetTy.kind === "array" || targetTy.kind === "optional" || targetTy.kind === "nullish")
2187
2526
  ? { ...ctx, returnTy: targetTy } : ctx;
2188
2527
  const value = coerceToTargetTy(resolveExpr(s.value, valueCtx), targetTy, ctx.typeDecls);
2189
- 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];
2190
2529
  }
2191
2530
  case "return": {
2192
2531
  const value = coerceToTargetTy(resolveExpr(s.value, ctx), ctx.returnTy, ctx.typeDecls);
@@ -2215,10 +2554,18 @@ function resolveStmt(s, ctx) {
2215
2554
  elseCtx = withEnv(elseCtx, refine(elseCtx.env, n.varName, n.innerTy));
2216
2555
  }
2217
2556
  }
2218
- const negPaths = collectEarlyReturnPathNarrowings(resolvedCond);
2557
+ const negPaths = collectEarlyReturnPathNarrowings(resolvedCond, ctx);
2219
2558
  if (negPaths.length > 0) {
2220
2559
  elseCtx = { ...elseCtx, narrowedPaths: [...elseCtx.narrowedPaths, ...negPaths] };
2221
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
+ }
2222
2569
  // Narrow map index access across `k in m` / `!(k in m)` in the cond:
2223
2570
  // positive atoms (from `k in m` or &&-chains containing it) → then-branch;
2224
2571
  // negated atoms (from `!(k in m)`) → else-branch.
@@ -2230,8 +2577,8 @@ function resolveStmt(s, ctx) {
2230
2577
  // Any variable or path mutated inside the loop body cannot keep a pre-loop
2231
2578
  // narrowing across iterations (including inside the loop condition and
2232
2579
  // invariants on back-edges).
2233
- const loopMutated = collectAssignedRootsRaw(s.body);
2234
- 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);
2235
2582
  const loopCtx = { ...ctx, env: loopInv.env, narrowedPaths: loopInv.narrowedPaths };
2236
2583
  const whileSpecCtx = { ...loopCtx, inSpec: true };
2237
2584
  const resolvedInvariants = resolveSpecs(s.invariants, whileSpecCtx);
@@ -2281,8 +2628,8 @@ function resolveStmt(s, ctx) {
2281
2628
  const count = ctx.forofCounts.get(s.names[0]) ?? 0;
2282
2629
  ctx.forofCounts.set(s.names[0], count + 1);
2283
2630
  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);
2631
+ const { wholeRoots, dottedTargets } = collectAssignedTargetsRaw(s.body);
2632
+ const loopInv = invalidateNarrowings(ctx.env, ctx.narrowedPaths, wholeRoots, dottedTargets, ctx.typeDecls);
2286
2633
  env = loopInv.env;
2287
2634
  env = extend(env, idxName, { kind: "nat" });
2288
2635
  for (let j = 0; j < s.names.length; j++) {
@@ -2298,12 +2645,19 @@ function resolveStmt(s, ctx) {
2298
2645
  }
2299
2646
  case "throw":
2300
2647
  return [{ kind: "throw" }, ctx.env];
2301
- case "switch":
2302
- return [{
2303
- kind: "switch", expr: resolveExpr(s.expr, ctx), discriminant: s.discriminant,
2304
- cases: s.cases.map(c => ({ label: c.label, body: resolveBlock(c.body, ctx) })),
2305
- defaultBody: resolveBlock(s.defaultBody, ctx),
2306
- }, 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
+ }
2307
2661
  case "ghostLet": {
2308
2662
  const specCtx = { ...ctx, inSpec: true };
2309
2663
  // Handle new Set<T>() / new Map<K,V>() constructors
@@ -2533,7 +2887,7 @@ function resolveFunction(fn, typeDecls, pureFns, fnParams = new Map(), fnReturns
2533
2887
  env = extend(env, opts.thisBinding.name, opts.thisBinding.ty);
2534
2888
  for (const p of params)
2535
2889
  env = extend(env, p.name, p.ty);
2536
- 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() };
2537
2891
  const requiresCtx = { ...baseCtx, inSpec: true };
2538
2892
  const ensuresCtx = { ...baseCtx, env: extend(env, "\\result", returnTy), allowResult: true, inSpec: true };
2539
2893
  // Apply type parameter constraints from //@ type T (==) annotations
@@ -2545,7 +2899,7 @@ function resolveFunction(fn, typeDecls, pureFns, fnParams = new Map(), fnReturns
2545
2899
  // into the body context and the ensures context — they hold for the whole
2546
2900
  // body (pure fns) and for post-state references in the ensures (map params
2547
2901
  // aren't mutated through their binding in the Dafny translation).
2548
- const resolvedRequires = resolveSpecs(fn.requires, requiresCtx);
2902
+ const resolvedRequires = resolveSpecs(fn.requires, requiresCtx, true);
2549
2903
  const requiresAtoms = resolvedRequires.flatMap(extractInAtoms);
2550
2904
  const bodyCtx = withInAtoms(baseCtx, requiresAtoms);
2551
2905
  const ensuresCtxNarrowed = withInAtoms(ensuresCtx, requiresAtoms);
@@ -2640,7 +2994,7 @@ export function resolveModule(raw) {
2640
2994
  for (let i = 0; i < ext.params.length; i++) {
2641
2995
  env = extend(env, ext.params[i].name, sig.params[i]);
2642
2996
  }
2643
- 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() };
2644
2998
  const ensuresCtx = { ...baseCtx, env: extend(env, "\\result", sig.returnTy), allowResult: true };
2645
2999
  const resolveClauses = (kind, ctx) => ext[kind].map(s => {
2646
3000
  try {
@@ -2662,7 +3016,7 @@ export function resolveModule(raw) {
2662
3016
  impure: ext.impure,
2663
3017
  };
2664
3018
  });
2665
- 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() };
2666
3020
  const constants = (raw.constants ?? []).map(c => {
2667
3021
  const declaredTy = expandAlias(parseTsType(c.tsType), raw.typeDecls);
2668
3022
  // Propagate the declared type into the value's resolution context so that