lemmascript 0.6.14 → 0.6.16

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.
@@ -62,6 +62,7 @@ let _validateDependency = () => { };
62
62
  /** Counter for synthetic names used by let-statement array destructuring
63
63
  * when the initializer isn't a bare variable (single-eval temp). */
64
64
  let _destrCounter = 0;
65
+ let _switchBreakCounter = 0;
65
66
  let _lexicalNames = null;
66
67
  const sourceName = (node) => _lexicalNames?.name(node) ?? node.getText();
67
68
  /** Register the call's callee as a cross-file extern if applicable, then
@@ -1883,23 +1884,89 @@ function extractScopedStmts(stmts) {
1883
1884
  const switchExpr = exprAst.kind === "field" ? exprAst.obj : exprAst;
1884
1885
  const cases = [];
1885
1886
  let defaultBody = [];
1886
- // Two JS-`switch` faithfulness concerns the Dafny `match` doesn't share:
1887
- // (1) Fall-through: stacked `case A: case B: body` is several clauses
1888
- // where the leading ones have no statements; those labels share the
1889
- // next clause's body (we duplicate it per label).
1890
- // (2) `break` is the switch exit, not a loop break. We extract the full
1891
- // body (extractStmts flattens `{ }` blocks but keeps loop bodies
1892
- // nested) and strip the *top-level* breaks — so a `break` written
1893
- // inside a `{ }` case block is stripped, while a `break` inside a
1894
- // nested loop stays put.
1895
- const stripExitBreaks = (b) => b.filter(st => st.kind !== "break");
1896
- const isExit = (st) => !!st && ["break", "return", "throw", "continue"].includes(st.kind);
1897
- // Resolve JS fall-through positionally: a clause's effective body is its
1898
- // own statements concatenated with each following clause's statements up
1899
- // to and including the first clause that ends in break/return/throw (or
1900
- // the switch end). This covers both empty stacked labels (`case A: case
1901
- // B: body`) and a *non-empty* case that falls through (`case A: sA; case
1902
- // B: ...`) — the stripped breaks are the switch exits.
1887
+ // Two JS-`switch` faithfulness concerns Dafny `match` / Lean `if`-chains don't share:
1888
+ // (1) Fall-through: stacked `case A: case B: body` or non-exiting clauses
1889
+ // continue into the following clause's statements.
1890
+ // (2) `break` is the switch exit, not a loop break. A top-level `break`
1891
+ // terminates the clause, and a guarded `if (c) break;` inside a clause
1892
+ // must exit only the switch, never surviving into `match` where it
1893
+ // would escape to an enclosing `while`/`for` loop. Nested loops and
1894
+ // nested switches own their own `break`s and are not descended into.
1895
+ const hasSwitchBreak = (stmts) => stmts.some(st => st.kind === "break" ||
1896
+ (st.kind === "if" && (hasSwitchBreak(st.then) || hasSwitchBreak(st.else))));
1897
+ const canFallThrough = (stmts) => {
1898
+ for (const st of stmts) {
1899
+ if (st.kind === "break" || st.kind === "return" || st.kind === "throw" || st.kind === "continue") {
1900
+ return false;
1901
+ }
1902
+ if (st.kind === "if" && !canFallThrough(st.then) && !canFallThrough(st.else)) {
1903
+ return false;
1904
+ }
1905
+ }
1906
+ return true;
1907
+ };
1908
+ // Single-pass switch-break lowering organized around which branches of each
1909
+ // `if` can reach the following statements (`rest`):
1910
+ // - Neither branch reaches `rest`: omit `rest`.
1911
+ // - Neither branch contains a switch break: keep the ordinary `if` and continue.
1912
+ // - Exactly one branch reaches `rest`: place `rest` directly in that branch
1913
+ // (emitted once, preserving TypeScript narrowing from `head.cond`).
1914
+ // - Both branches can reach `rest` and an inner path can also break: guard
1915
+ // `rest` once after the `if` with a lazily allocated switch-exit flag.
1916
+ const eliminateSwitchBreaks = (stmts, cont, exitFlag, ensureFlag) => {
1917
+ if (stmts.length === 0)
1918
+ return cont;
1919
+ const [head, ...tail] = stmts;
1920
+ if (head.kind === "break") {
1921
+ return exitFlag === null
1922
+ ? []
1923
+ : [{ kind: "assign", target: exitFlag, value: { kind: "bool", value: true }, line: head.line }];
1924
+ }
1925
+ if (head.kind === "return" || head.kind === "throw" || head.kind === "continue") {
1926
+ return [head];
1927
+ }
1928
+ if (head.kind === "if") {
1929
+ const thenFalls = canFallThrough(head.then);
1930
+ const elseFalls = canFallThrough(head.else);
1931
+ if (!thenFalls && !elseFalls) {
1932
+ return [{
1933
+ ...head,
1934
+ then: eliminateSwitchBreaks(head.then, [], exitFlag, ensureFlag),
1935
+ else: eliminateSwitchBreaks(head.else, [], exitFlag, ensureFlag),
1936
+ }];
1937
+ }
1938
+ if (!hasSwitchBreak(head.then) && !hasSwitchBreak(head.else)) {
1939
+ return [head, ...eliminateSwitchBreaks(tail, cont, exitFlag, ensureFlag)];
1940
+ }
1941
+ const rest = eliminateSwitchBreaks(tail, cont, exitFlag, ensureFlag);
1942
+ if (!thenFalls || !elseFalls) {
1943
+ return [{
1944
+ ...head,
1945
+ then: eliminateSwitchBreaks(head.then, thenFalls ? rest : [], exitFlag, ensureFlag),
1946
+ else: eliminateSwitchBreaks(head.else, elseFalls ? rest : [], exitFlag, ensureFlag),
1947
+ }];
1948
+ }
1949
+ const flag = rest.length > 0 ? (exitFlag ?? ensureFlag()) : exitFlag;
1950
+ const ifStmt = {
1951
+ ...head,
1952
+ then: eliminateSwitchBreaks(head.then, [], flag, ensureFlag),
1953
+ else: eliminateSwitchBreaks(head.else, [], flag, ensureFlag),
1954
+ };
1955
+ if (rest.length === 0)
1956
+ return [ifStmt];
1957
+ return [
1958
+ ifStmt,
1959
+ {
1960
+ kind: "if",
1961
+ cond: { kind: "unop", op: "!", expr: { kind: "var", name: flag } },
1962
+ then: rest,
1963
+ else: [],
1964
+ line: head.line,
1965
+ },
1966
+ ];
1967
+ }
1968
+ return [head, ...eliminateSwitchBreaks(tail, cont, exitFlag, ensureFlag)];
1969
+ };
1903
1970
  const clauseInfos = s.getClauses().map(clause => {
1904
1971
  const stmts = extractStmts(clause.getStatements());
1905
1972
  let label = null;
@@ -1910,20 +1977,37 @@ function extractScopedStmts(stmts) {
1910
1977
  }
1911
1978
  label = labelExpr.value;
1912
1979
  }
1913
- return {
1914
- label,
1915
- stmts,
1916
- exits: isExit(stmts[stmts.length - 1]),
1917
- };
1980
+ return { label, stmts };
1918
1981
  });
1919
1982
  const fallThroughBody = (start) => {
1920
- let body = [];
1983
+ const stmts = [];
1921
1984
  for (let j = start; j < clauseInfos.length; j++) {
1922
- body = body.concat(clauseInfos[j].stmts);
1923
- if (clauseInfos[j].exits)
1985
+ const clauseStmts = clauseInfos[j].stmts;
1986
+ stmts.push(...clauseStmts);
1987
+ if (!canFallThrough(clauseStmts))
1924
1988
  break;
1925
1989
  }
1926
- return stripExitBreaks(body);
1990
+ let flag = null;
1991
+ const ensureFlag = () => {
1992
+ if (flag === null) {
1993
+ const suffix = _switchBreakCounter === 0 ? "" : String(_switchBreakCounter);
1994
+ _switchBreakCounter += 1;
1995
+ flag = freshName(`_switchBroken${suffix}`);
1996
+ }
1997
+ return flag;
1998
+ };
1999
+ const body = eliminateSwitchBreaks(stmts, [], null, ensureFlag);
2000
+ if (flag === null)
2001
+ return body;
2002
+ const decl = {
2003
+ kind: "let",
2004
+ name: flag,
2005
+ mutable: true,
2006
+ tsType: "boolean",
2007
+ init: { kind: "bool", value: false },
2008
+ line,
2009
+ };
2010
+ return [decl, ...body];
1927
2011
  };
1928
2012
  for (let i = 0; i < clauseInfos.length; i++) {
1929
2013
  const c = clauseInfos[i];
@@ -2180,6 +2264,7 @@ export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDep
2180
2264
  // tests) must not leak a havoc key, temp-name counter, or function-local maps.
2181
2265
  _havocKey = null;
2182
2266
  _destrCounter = 0;
2267
+ _switchBreakCounter = 0;
2183
2268
  _lexicalNames = null;
2184
2269
  _typeParamMap = new Map();
2185
2270
  // Seed the fresh-name check (names.ts) before anything mints: every
@@ -4,8 +4,8 @@
4
4
  * opaque-tainted types, discriminator/destructor lowering, method dispatch,
5
5
  * and support-import selection.
6
6
  */
7
- import { anyExpr, anyExprInStmts, decimalNumberLiteral, usesNameInDecl, patternBinders } from "./ir.js";
8
- import { freshName, freshNameWhere } from "./names.js";
7
+ import { anyExpr, anyExprInStmts, decimalNumberLiteral, usesName, usesNameInDecl, patternBinders } from "./ir.js";
8
+ import { freshName, freshNameWhere, isUserName } from "./names.js";
9
9
  // ── Ty → Lean type string ──────────────────────────────────
10
10
  function tyToLean(ty) {
11
11
  switch (ty.kind) {
@@ -64,7 +64,7 @@ function tyToLean(ty) {
64
64
  }
65
65
  case "user": return ty.name;
66
66
  case "fn": {
67
- const params = ty.params.map(p => {
67
+ const params = ty.params.length === 0 ? ["Unit"] : ty.params.map(p => {
68
68
  const s = tyToLean(p);
69
69
  return s.includes(" ") ? `(${s})` : s;
70
70
  });
@@ -419,7 +419,9 @@ function emitExpr(e, parentPrec) {
419
419
  return emitMethodCall(e.objTy.kind, e.method, e.monadic, receiver, args);
420
420
  }
421
421
  case "lambda": {
422
- const params = e.params.map(p => e.typedParams ? `(${p.name} : ${tyToLean(p.type)})` : p.name).join(" ");
422
+ const params = e.params.length === 0
423
+ ? (e.typedParams ? "(_ : Unit)" : "()")
424
+ : e.params.map(p => e.typedParams ? `(${p.name} : ${tyToLean(p.type)})` : p.name).join(" ");
423
425
  // Single return statement → expression lambda
424
426
  if (e.body.length === 1 && e.body[0].kind === "return") {
425
427
  return `(fun ${params} => ${emitExpr(e.body[0].value)})`;
@@ -468,7 +470,7 @@ function emitExpr(e, parentPrec) {
468
470
  const l = emitExpr(e.left);
469
471
  const r = emitExpr(e.right);
470
472
  const condProp = isPropValued(e.left) ? l : `(${l}) = true`;
471
- const h = `_h${_depIfCounter++}`;
473
+ const h = freshName(`_h${_depIfCounter++}`);
472
474
  const tVal = _boolCtx ? "true" : "True";
473
475
  const fVal = _boolCtx ? "false" : "False";
474
476
  const rExpr = _boolCtx && isPropValued(e.right) ? `decide (${r})` : r;
@@ -504,7 +506,7 @@ function emitExpr(e, parentPrec) {
504
506
  if (tailHasCU(i)) {
505
507
  const pStr = emitExpr(p);
506
508
  const pProp = isPropValued(p) ? pStr : `(${pStr}) = true`;
507
- const h = `_h${_depIfCounter++}`;
509
+ const h = freshName(`_h${_depIfCounter++}`);
508
510
  acc = `∀ (${h} : ${pProp}), ${acc}`;
509
511
  }
510
512
  else {
@@ -517,7 +519,7 @@ function emitExpr(e, parentPrec) {
517
519
  // A bare negative literal argument (`f -7 2`) parses as subtraction in Lean.
518
520
  const args = e.args.map(a => {
519
521
  const s = emitExpr(a);
520
- return (a.kind === "binop" || a.kind === "unop" || a.kind === "implies" || a.kind === "app" || a.kind === "methodCall" || s.startsWith("-")) ? `(${s})` : s;
522
+ return (a.kind === "binop" || a.kind === "unop" || a.kind === "implies" || a.kind === "app" || a.kind === "methodCall" || a.kind === "if" || a.kind === "let" || a.kind === "match" || s.startsWith("-")) ? `(${s})` : s;
521
523
  });
522
524
  // Datatype constructor (tagged by transform): Lean needs the qualified name
523
525
  // `BaseType.variant`; a bare `variant` is an unknown identifier. (Dafny keeps
@@ -561,15 +563,29 @@ function emitExpr(e, parentPrec) {
561
563
  // access with a discriminator test, so that branch is never reached.
562
564
  if (e.fromUnion) {
563
565
  const ctors = _unionCtors.get(e.fromUnion);
564
- // Pin the owning ctor when given (field names repeat across variants);
565
- // otherwise fall back to the sole variant carrying this field name.
566
- const owner = (e.ctor ? ctors?.find(c => c.name === e.ctor) : undefined)
567
- ?? ctors?.find(c => c.fields.some(f => f.name === e.field));
568
- if (owner) {
569
- const idx = owner.fields.findIndex(f => f.name === e.field);
570
- const pats = owner.fields.map((_, i) => (i === idx ? "_v" : "_")).join(" ");
571
- const fty = tyToLean(owner.fields[idx].type);
572
- return `(match ${emitExpr(e.obj)} with | .${leanCtorName(owner.name)} ${pats} => _v | _ => (default : ${fty}))`;
566
+ // Pin the owning ctor when given (field names repeat across variants
567
+ // with distinct types or narrowed provenance); otherwise project the
568
+ // field from every constructor carrying it with a common Lean type so
569
+ // reads after reassignment return the live variant's value rather than `default`.
570
+ let owners = e.ctor
571
+ ? ctors?.filter(c => c.name === e.ctor)
572
+ : ctors?.filter(c => c.fields.some(f => f.name === e.field));
573
+ if (owners && owners.length > 0 && ctors) {
574
+ const firstIdx = owners[0].fields.findIndex(f => f.name === e.field);
575
+ const fty = tyToLean(owners[0].fields[firstIdx].type);
576
+ const compatible = Boolean(e.ctor) || owners.every(c => {
577
+ const idx = c.fields.findIndex(f => f.name === e.field);
578
+ return idx >= 0 && tyToLean(c.fields[idx].type) === fty;
579
+ });
580
+ if (compatible) {
581
+ const arms = owners.map(owner => {
582
+ const idx = owner.fields.findIndex(f => f.name === e.field);
583
+ const pats = owner.fields.map((_, i) => (i === idx ? "_v" : "_")).join(" ");
584
+ return `| .${leanCtorName(owner.name)} ${pats} => _v`;
585
+ });
586
+ const fallback = owners.length < ctors.length ? ` | _ => (default : ${fty})` : "";
587
+ return `(match ${emitExpr(e.obj)} with ${arms.join(" ")}${fallback})`;
588
+ }
573
589
  }
574
590
  }
575
591
  const obj = emitExpr(e.obj);
@@ -601,6 +617,41 @@ function emitExpr(e, parentPrec) {
601
617
  return `${wrap ? `(${arr})` : arr}[${emitExpr(e.idx)}]!`;
602
618
  }
603
619
  case "record": {
620
+ if (e.spread && e.ctorOf && _unionCtors.has(e.ctorOf)) {
621
+ const ctors = _unionCtors.get(e.ctorOf);
622
+ const hasAllFields = (c) => e.fields.every(f => c.fields.some(cf => cf.name === f.name));
623
+ const targetCtors = (e.ctor ? ctors.filter(c => c.name === e.ctor) : ctors).filter(hasAllFields);
624
+ if (targetCtors.length > 0) {
625
+ const updatesByName = new Map(e.fields.map(f => [f.name, emitExpr(f.value)]));
626
+ const updText = [...updatesByName.values()].join(" ");
627
+ const arms = targetCtors.map(c => {
628
+ const pats = [];
629
+ const args = [];
630
+ const usedBinders = new Set();
631
+ c.fields.forEach((cf, i) => {
632
+ const upd = updatesByName.get(cf.name);
633
+ if (upd !== undefined) {
634
+ pats.push("_");
635
+ args.push(`(${upd})`);
636
+ }
637
+ else {
638
+ const bv = freshNameWhere(`_f${i}`, name => isUserName(name) ||
639
+ usedBinders.has(name) ||
640
+ e.fields.some(f => usesName(f.value, name)) ||
641
+ updText.includes(name));
642
+ usedBinders.add(bv);
643
+ pats.push(bv);
644
+ args.push(bv);
645
+ }
646
+ });
647
+ const patStr = pats.length > 0 ? `.${leanCtorName(c.name)} ${pats.join(" ")}` : `.${leanCtorName(c.name)}`;
648
+ const rhsStr = args.length > 0 ? `${e.ctorOf}.${leanCtorName(c.name)} ${args.join(" ")}` : `${e.ctorOf}.${leanCtorName(c.name)}`;
649
+ return `| ${patStr} => ${rhsStr}`;
650
+ });
651
+ const fallback = targetCtors.length < ctors.length ? " | _other => _other" : "";
652
+ return `(match ${emitExpr(e.spread)} with ${arms.join(" ")}${fallback})`;
653
+ }
654
+ }
604
655
  const fields = e.fields.map(f => `${escapeName(f.name)} := ${emitExpr(f.value)}`);
605
656
  if (e.spread)
606
657
  return `{ ${emitExpr(e.spread)} with ${fields.join(", ")} }`;
@@ -611,7 +662,7 @@ function emitExpr(e, parentPrec) {
611
662
  if (hasCU) {
612
663
  const c = emitExpr(e.cond);
613
664
  const condProp = isPropValued(e.cond) ? c : `(${c}) = true`;
614
- const h = `_h${_depIfCounter++}`;
665
+ const h = freshName(`_h${_depIfCounter++}`);
615
666
  const t = emitExpr(e.then);
616
667
  const f = emitExpr(e.else);
617
668
  const tExpr = _boolCtx && isPropValued(e.then) ? `decide (${t})` : t;
@@ -671,7 +722,7 @@ function emitStmts(stmts, indent) {
671
722
  anyExprInStmts(rest, x => x.kind === "checkedUnwrap")) {
672
723
  const c = emitExpr(s.cond);
673
724
  const condProp = isPropValued(s.cond) ? c : `(${c}) = true`;
674
- const h = `_h${_depIfCounter++}`;
725
+ const h = freshName(`_h${_depIfCounter++}`);
675
726
  out.push(`${pad}if ${h} : ${condProp} then\n${emitStmts(s.then, indent + 1)}\n${pad}else\n${emitStmts(rest, indent + 1)}`);
676
727
  break;
677
728
  }
@@ -720,25 +771,26 @@ function emitStmt(s, indent) {
720
771
  case "break": return `${pad}break`;
721
772
  case "continue": return `${pad}continue`;
722
773
  case "if": {
774
+ const emitBlock = (stmts, ind) => stmts.length === 0 ? `${" ".repeat(ind)}pure ()` : emitStmts(stmts, ind);
723
775
  const hasCU = anyExprInStmts(s.then, x => x.kind === "checkedUnwrap") ||
724
776
  anyExprInStmts(s.else, x => x.kind === "checkedUnwrap");
725
777
  const condText = hasCU
726
778
  ? (() => {
727
779
  const c = emitExpr(s.cond);
728
780
  const condProp = isPropValued(s.cond) ? c : `(${c}) = true`;
729
- return `_h${_depIfCounter++} : ${condProp}`;
781
+ return `${freshName(`_h${_depIfCounter++}`)} : ${condProp}`;
730
782
  })()
731
783
  : emitExpr(s.cond);
732
- let out = `${pad}if ${condText} then\n${emitStmts(s.then, indent + 1)}`;
784
+ let out = `${pad}if ${condText} then\n${emitBlock(s.then, indent + 1)}`;
733
785
  if (s.else.length > 0) {
734
786
  if (!hasCU && s.else.length === 1 && s.else[0].kind === "if") {
735
787
  const ei = s.else[0];
736
- out += `\n${pad}else if ${emitExpr(ei.cond)} then\n${emitStmts(ei.then, indent + 1)}`;
788
+ out += `\n${pad}else if ${emitExpr(ei.cond)} then\n${emitBlock(ei.then, indent + 1)}`;
737
789
  if (ei.else.length > 0)
738
- out += `\n${pad}else\n${emitStmts(ei.else, indent + 1)}`;
790
+ out += `\n${pad}else\n${emitBlock(ei.else, indent + 1)}`;
739
791
  }
740
792
  else {
741
- out += `\n${pad}else\n${emitStmts(s.else, indent + 1)}`;
793
+ out += `\n${pad}else\n${emitBlock(s.else, indent + 1)}`;
742
794
  }
743
795
  }
744
796
  return out;
@@ -751,7 +803,7 @@ function emitStmt(s, indent) {
751
803
  const noneArm = s.arms.find(a => a.pattern.kind === "ctor" && a.pattern.ctor === "none");
752
804
  if (someArm && noneArm) {
753
805
  const boundVar = patternBinders(someArm.pattern)[0]; // ".some x" ⇒ "x"
754
- const hName = `h_${scrut.replace(/[^a-zA-Z0-9_]/g, "_")}`;
806
+ const hName = freshName(`h_${scrut.replace(/[^a-zA-Z0-9_]/g, "_")}`);
755
807
  const lines = [
756
808
  `${pad}if ${hName} : (${scrut}).isSome = true then`,
757
809
  `${pad} let ${boundVar} := (${scrut}).get ${hName}`,
@@ -999,7 +1051,7 @@ function emitPureExpr(e, indent) {
999
1051
  if (hasCU) {
1000
1052
  const c = emitExpr(e.cond);
1001
1053
  const condProp = isPropValued(e.cond) ? c : `(${c}) = true`;
1002
- const h = `_h${_depIfCounter++}`;
1054
+ const h = freshName(`_h${_depIfCounter++}`);
1003
1055
  return `${pad}if ${h} : ${condProp} then\n${emitPureExpr(e.then, indent + 1)}\n${pad}else\n${emitPureExpr(e.else, indent + 1)}`;
1004
1056
  }
1005
1057
  return `${pad}if ${emitExpr(e.cond)} then\n${emitPureExpr(e.then, indent + 1)}\n${pad}else\n${emitPureExpr(e.else, indent + 1)}`;
package/tools/dist/lsc.js CHANGED
@@ -17,14 +17,14 @@ import { transformModuleLean, transformModuleDafny } from "./transform.js";
17
17
  import { peepholeModule } from "./peephole.js";
18
18
  import { emitLeanFile, resetLeanModule } from "./lean-emit.js";
19
19
  import { emitDafnyFile, emittedNameMap } from "./dafny-emit.js";
20
- import { dafnyGen, dafnyCheckDiff, dafnyVerify, dafnyRegen } from "./dafny-commands.js";
20
+ import { dafnyGen, dafnyCheckDiff, dafnyVerify, dafnyRegen, readDafnyProofFiles } from "./dafny-commands.js";
21
21
  import { leanGen, leanCheck } from "./lean-commands.js";
22
22
  import { runInfo, runTypedInfo } from "./info-command.js";
23
23
  import { RunLog, resolveLogDir, runLogEnabled, safely } from "./run-log.js";
24
24
  import { runRuns } from "./runs-command.js";
25
25
  import { runGuard } from "./guard-command.js";
26
26
  import { SourceProjects } from "./source-projects.js";
27
- import { loadConfigOptions, parseFileOptions, resolveDafnyArtifactDir, resolveOptions, } from "./config.js";
27
+ import { loadConfigOptions, parseFileOptions, resolveDafnyArtifactDir, resolveDafnyProofFiles, resolveOptions, } from "./config.js";
28
28
  /** Version of the lemmascript package — the root package.json sits two levels
29
29
  * above this module from both tools/src/ (tsx) and tools/dist/ (installed). */
30
30
  function lscVersion() {
@@ -383,14 +383,19 @@ function runFile(cmd, filePath, backend, timeLimit, extraFlags, noVerify = false
383
383
  mkdirSync(artifactDir, { recursive: true });
384
384
  // Record check/regen runs in the run log. Created after the proof-dir guard
385
385
  // so an aborted run leaves no snapshot; each helper records the stage it detects.
386
+ const proofFiles = resolveDafnyProofFiles(absPath, configFile, options);
386
387
  const logCmd = cmd === "check" || cmd === "regen" ? cmd : null;
387
388
  const log = logCmd && runLogOn
388
- ? new RunLog({ logDir: resolveLogDir(absPath, configFile), cmd: logCmd, sourcePath: absPath, extraFlags, lscVersion: safely(lscVersion) })
389
+ ? new RunLog({
390
+ logDir: resolveLogDir(absPath, configFile), cmd: logCmd, sourcePath: absPath,
391
+ proofFiles, extraFlags, lscVersion: safely(lscVersion),
392
+ })
389
393
  : undefined;
390
394
  if (cmd === "gen") {
391
395
  dafnyGen(genPath, dfyPath, text, basePath);
392
396
  return;
393
397
  }
398
+ const proofs = readDafnyProofFiles(proofFiles, dfyPath, log);
394
399
  if (cmd === "gen-check") {
395
400
  dafnyGen(genPath, dfyPath, text, basePath);
396
401
  if (!dafnyCheckDiff(genPath, dfyPath, undefined, basePath))
@@ -401,12 +406,12 @@ function runFile(cmd, filePath, backend, timeLimit, extraFlags, noVerify = false
401
406
  dafnyGen(genPath, dfyPath, text, basePath);
402
407
  if (!dafnyCheckDiff(genPath, dfyPath, log, basePath))
403
408
  process.exit(1);
404
- if (!dafnyVerify(dfyPath, artifactDir, timeLimit, extraFlags, log))
409
+ if (!dafnyVerify(dfyPath, artifactDir, timeLimit, extraFlags, log, proofs))
405
410
  process.exit(1);
406
411
  return;
407
412
  }
408
413
  if (cmd === "regen") {
409
- dafnyRegen(genPath, dfyPath, basePath, text, artifactDir, timeLimit, extraFlags, noVerify, log);
414
+ dafnyRegen(genPath, dfyPath, basePath, text, artifactDir, timeLimit, extraFlags, noVerify, log, proofs);
410
415
  return;
411
416
  }
412
417
  console.error(`Unknown command: ${cmd}`);
@@ -35,7 +35,7 @@
35
35
  */
36
36
  import { isTerminatorKind } from "./typedir.js";
37
37
  import { builtinSpec } from "./builtins.js";
38
- import { optionalPresentFact, leadingPresent, leadingIsArray, flattenOr, noneDetector, bindPresentFact, freshPathBinder, binderHintForMapAccess, freshOcBinder, applyChain, restoreDiscriminantFlag, arrayBoundsCond, exprEqual, isArrayFact, typeofStringFact, variantFact, negVariantFact, presentMatchStmts, presentMatchExpr, } from "./condition-facts.js";
38
+ import { optionalPresentFact, leadingPresent, leadingIsArray, flattenOr, noneDetector, excludesUndefined, bindPresentFact, freshPathBinder, binderHintForMapAccess, freshOcBinder, applyChain, restoreDiscriminantFlag, arrayBoundsCond, exprEqual, isArrayFact, typeofStringFact, variantFact, negVariantFact, presentMatchStmts, presentMatchExpr, } from "./condition-facts.js";
39
39
  import { insertCheckedUnwraps } from "./checked-reads.js";
40
40
  // ── Walkers ──────────────────────────────────────────────────
41
41
  function walkExpr(e, ctx) {
@@ -170,53 +170,43 @@ function exprPathStr(e) {
170
170
  return null;
171
171
  }
172
172
  /** True if `stmts` contains an assignment to `pathStr` (or any prefix of
173
- * `pathStr`, e.g. `box = ...` when narrowing `box.val`) that could clear it
174
- * to `undefined` or an arbitrary `Option<T>` (not a `Some(...)` wrapper),
175
- * meaning a `someMatch` binder would become stale (#342). */
176
- function stmtsMayClearPath(stmts, pathStr) {
173
+ * `pathStr`, e.g. `box = ...` when narrowing `box.val`). Direct reassignment
174
+ * of a `someMatch` scrutinee (`x = 5`, `x = undefined`, `box = newBox`) would
175
+ * either assign to an immutable Dafny match binder or leave the binder stale;
176
+ * deferring to `if` + `checkedUnwrap` keeps all reads and writes on live storage. */
177
+ function stmtsMayReassignPath(stmts, pathStr) {
177
178
  for (const s of stmts) {
178
179
  if (s.kind === "assign") {
179
- if (s.target === pathStr) {
180
- const isPresentWrap = s.value.kind === "call" && s.value.fn.kind === "var" &&
181
- (s.value.fn.name === "Some" || s.value.fn.name === "NullishValue") && s.value.args.length === 1;
182
- if (!isPresentWrap && (s.value.ty.kind === "optional" || s.value.ty.kind === "nullish" ||
183
- s.value.ty.kind === "void" || s.value.ty.kind === "null" ||
184
- (s.value.kind === "var" && (s.value.name === "undefined" || s.value.name === "null")))) {
185
- return true;
186
- }
187
- }
188
- else if (pathStr.startsWith(`${s.target}.`)) {
189
- // Reassigning a container prefix (e.g. `box = newBox`) can replace the
190
- // narrowed field with None, making a binder on `box.val` stale.
180
+ if (s.target === pathStr || pathStr.startsWith(`${s.target}.`)) {
191
181
  return true;
192
182
  }
193
183
  }
194
184
  else if (s.kind === "if") {
195
- if (stmtsMayClearPath(s.then, pathStr) || stmtsMayClearPath(s.else, pathStr))
185
+ if (stmtsMayReassignPath(s.then, pathStr) || stmtsMayReassignPath(s.else, pathStr))
196
186
  return true;
197
187
  }
198
188
  else if (s.kind === "while" || s.kind === "forof") {
199
- if (stmtsMayClearPath(s.body, pathStr))
189
+ if (stmtsMayReassignPath(s.body, pathStr))
200
190
  return true;
201
191
  }
202
192
  else if (s.kind === "switch") {
203
- if (s.cases.some(c => stmtsMayClearPath(c.body, pathStr)) || stmtsMayClearPath(s.defaultBody, pathStr))
193
+ if (s.cases.some(c => stmtsMayReassignPath(c.body, pathStr)) || stmtsMayReassignPath(s.defaultBody, pathStr))
204
194
  return true;
205
195
  }
206
196
  else if (s.kind === "someMatch") {
207
- if (stmtsMayClearPath(s.someBody, pathStr) || stmtsMayClearPath(s.noneBody, pathStr))
197
+ if (stmtsMayReassignPath(s.someBody, pathStr) || stmtsMayReassignPath(s.noneBody, pathStr))
208
198
  return true;
209
199
  }
210
200
  else if (s.kind === "tagMatch") {
211
- if (s.cases.some(c => stmtsMayClearPath(c.body, pathStr)) || stmtsMayClearPath(s.fallthrough, pathStr))
201
+ if (s.cases.some(c => stmtsMayReassignPath(c.body, pathStr)) || stmtsMayReassignPath(s.fallthrough, pathStr))
212
202
  return true;
213
203
  }
214
204
  }
215
205
  return false;
216
206
  }
217
- function scrutineeMayBeCleared(scrutinee, stmts) {
207
+ function scrutineeMayBeReassigned(scrutinee, stmts) {
218
208
  const pathStr = exprPathStr(scrutinee);
219
- return pathStr !== null && stmtsMayClearPath(stmts, pathStr);
209
+ return pathStr !== null && stmtsMayReassignPath(stmts, pathStr);
220
210
  }
221
211
  /** Driver: `if (e !== undefined) then else` — presence fact in if position.
222
212
  * → `someMatch e { Some(_e_val) => then, None => else }`. Requires a
@@ -232,7 +222,7 @@ function ruleIfOptionalSimple(s, ctx) {
232
222
  const noneBody = check.negated ? s.then : s.else;
233
223
  if (someBody.length === 0)
234
224
  return null;
235
- if (scrutineeMayBeCleared(check.scrutinee, someBody))
225
+ if (scrutineeMayBeReassigned(check.scrutinee, someBody))
236
226
  return null;
237
227
  return presentMatchStmts(check, someBody, noneBody, ctx);
238
228
  }
@@ -253,7 +243,7 @@ function ruleEarlyReturnConsume(s, rest, ctx) {
253
243
  return null;
254
244
  if (!isTerminating(noneBranch))
255
245
  return null;
256
- if (scrutineeMayBeCleared(check.scrutinee, rest))
246
+ if (scrutineeMayBeReassigned(check.scrutinee, rest))
257
247
  return null;
258
248
  return presentMatchStmts(check, rest, noneBranch, ctx);
259
249
  }
@@ -294,7 +284,7 @@ function ruleEarlyReturnOrChain(s, rest, ctx) {
294
284
  }
295
285
  if (detectors.length === 0)
296
286
  return null;
297
- if (detectors.some(d => scrutineeMayBeCleared(d.scrutinee, rest)))
287
+ if (detectors.some(d => scrutineeMayBeReassigned(d.scrutinee, rest)))
298
288
  return null;
299
289
  let inner = residualLeaves.length === 0
300
290
  ? rest
@@ -326,9 +316,11 @@ function ruleEarlyReturnOptChainCompare(s, rest, ctx) {
326
316
  const oc = c.left.kind === "optChain" ? c.left : c.right.kind === "optChain" ? c.right : null;
327
317
  if (!oc || oc.kind !== "optChain" || oc.obj.ty.kind !== "optional" || oc.obj.ty.fromNullish)
328
318
  return null;
329
- if (scrutineeMayBeCleared(oc.obj, rest))
319
+ if (scrutineeMayBeReassigned(oc.obj, rest))
330
320
  return null;
331
321
  const lit = c.left === oc ? c.right : c.left;
322
+ if (!excludesUndefined(lit, ctx.decls, ctx.typeParams))
323
+ return null;
332
324
  const innerTy = oc.obj.ty.inner;
333
325
  const binder = freshPathBinder(oc.obj, ctx);
334
326
  if (binder === null)
@@ -575,7 +567,7 @@ function ruleIfAndOptional(s, ctx) {
575
567
  if (!extracted)
576
568
  return null;
577
569
  const { check, restCond } = extracted;
578
- if (scrutineeMayBeCleared(check.scrutinee, s.then))
570
+ if (scrutineeMayBeReassigned(check.scrutinee, s.then))
579
571
  return null;
580
572
  const innerIf = { kind: "if", cond: restCond, then: s.then, else: [] };
581
573
  return presentMatchStmts(check, [walkStmt(innerIf, ctx)], [], ctx);
@@ -859,8 +851,9 @@ function narrowFunction(fn, ctx) {
859
851
  // Contracts and the body bind their payloads in separate generated scopes.
860
852
  // Do not reserve a body's names because of a contract's \result (or another
861
853
  // function's paths). Keep the shared counter's traversal order unchanged.
862
- const specCtx = { decls: ctx.decls, oc: ctx.oc };
863
- const bodyCtx = { decls: ctx.decls, oc: ctx.oc };
854
+ const typeParams = new Set(fn.typeParams.map(tp => tp.replace(/\(.*\)$/, "")));
855
+ const specCtx = { decls: ctx.decls, oc: ctx.oc, typeParams };
856
+ const bodyCtx = { decls: ctx.decls, oc: ctx.oc, typeParams };
864
857
  return {
865
858
  ...fn,
866
859
  requires: fn.requires.map(e => walkExpr(e, specCtx)),