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.
package/README.md CHANGED
@@ -63,6 +63,16 @@ From a sibling source checkout, the equivalent of `lsc` is `npx tsx ../LemmaScri
63
63
 
64
64
  The Dafny backend generates two files per TS source: `foo.dfy.gen` (always regeneratable) and `foo.dfy` (source of truth, with LLM/user proof additions). The diff between them must be additions-only.
65
65
 
66
+ Register standalone Dafny laws under their TypeScript source in `lemmascript.json`.
67
+
68
+ ```json
69
+ {
70
+ "proof-files": { "src/search.ts": ["proofs/search.dfy", "proofs/shared.dfy"] }
71
+ }
72
+ ```
73
+
74
+ Paths are relative to the config file. Both `lsc check src/search.ts` and a workspace `lsc check` that includes `src/search.ts` pass its registered files directly to Dafny, so errors point to the law you edit.
75
+
66
76
  ### Lean backend
67
77
 
68
78
  ```sh
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lemmascript",
3
- "version": "0.6.14",
3
+ "version": "0.6.15",
4
4
  "description": "A verification toolchain for TypeScript — generates Lean 4 or Dafny from annotated TS",
5
5
  "type": "module",
6
6
  "engines": {
@@ -358,7 +358,8 @@ function mutationInfoOfStmt(s) {
358
358
  if (s.kind === "expr") {
359
359
  const e = s.expr;
360
360
  if (e.kind === "call" && e.fn.kind === "field" && (isMutatingCollectionMethod(e.fn.obj.ty, e.fn.field) ||
361
- (e.fn.obj.ty.kind === "unknown" && ["push", "unshift", "sort", "set", "add", "delete"].includes(e.fn.field)))) {
361
+ ((e.fn.field === "pop" || e.fn.field === "shift") && e.fn.obj.ty.kind === "array") ||
362
+ (e.fn.obj.ty.kind === "unknown" && ["push", "unshift", "sort", "pop", "shift", "set", "add", "delete"].includes(e.fn.field)))) {
362
363
  const root = accessPathRoot(e.fn.obj);
363
364
  if (!root)
364
365
  return null;
@@ -14,31 +14,31 @@
14
14
  * The registry holds classification only — no lowerings. Namespace builtins
15
15
  * (`Math.*`, `Array.isArray`) are recognized syntactically in resolve and
16
16
  * are not registry entries: they are not methods on receiver values.
17
- *
18
- * Classification values mirror the historical per-pass lists exactly
19
- * (byte-for-byte gauntlet compatibility), including their quirks — e.g.
20
- * `array.shift` returns the element type un-wrapped and `array.with` types
21
- * as `unknown`. Widen such bits deliberately, with tests.
22
17
  */
23
18
  const UNKNOWN = { kind: "unknown" };
24
19
  const BOOL = () => ({ kind: "bool" });
25
20
  const INT = () => ({ kind: "int" });
26
21
  const STRING = () => ({ kind: "string" });
27
22
  const self = (objTy) => objTy;
28
- const elem = (objTy) => objTy.kind === "array" ? objTy.elem : UNKNOWN;
29
23
  const optElem = (objTy) => objTy.kind === "array" ? { kind: "optional", inner: objTy.elem } : UNKNOWN;
24
+ const arrElemAt0 = (objTy, i) => i === 0 && objTy.kind === "array" ? objTy.elem : null;
25
+ const arrElemAll = (objTy) => objTy.kind === "array" ? objTy.elem : null;
26
+ const arrElemAt1 = (objTy, i) => i === 1 && objTy.kind === "array" ? objTy.elem : null;
27
+ const mapKeyAt0 = (objTy, i) => i === 0 && objTy.kind === "map" ? objTy.key : null;
28
+ const mapKeyVal = (objTy, i) => objTy.kind === "map" ? (i === 0 ? objTy.key : i === 1 ? objTy.value : null) : null;
29
+ const setElemAt0 = (objTy, i) => i === 0 && objTy.kind === "set" ? objTy.elem : null;
30
30
  /** The table is the single source: each key is `<RecvKind>.<method>`, which
31
31
  * *is* the `BuiltinId`. */
32
32
  export const BUILTINS = {
33
33
  // ── array ─────────────────────────────────────────────────
34
34
  "array.includes": { ret: BOOL, pure: true,
35
- intArgPositions: [1], argIsKey: true },
35
+ intArgPositions: [1], argIsKey: true, argSlot: arrElemAt0 },
36
36
  "array.indexOf": { ret: INT, pure: true,
37
- intArgPositions: [1] },
38
- "array.shift": { ret: elem, pure: false },
37
+ intArgPositions: [1], argSlot: arrElemAt0 },
38
+ "array.shift": { ret: optElem, pure: false },
39
39
  "array.pop": { ret: optElem, pure: false },
40
- "array.push": { ret: self, pure: false },
41
- "array.unshift": { ret: self, pure: false },
40
+ "array.push": { ret: self, pure: false, argSlot: arrElemAll },
41
+ "array.unshift": { ret: self, pure: false, argSlot: arrElemAll },
42
42
  "array.concat": { ret: self, pure: true },
43
43
  "array.sort": { ret: self, pure: false,
44
44
  hof: { shape: "comparator" } },
@@ -80,7 +80,7 @@ export const BUILTINS = {
80
80
  return UNKNOWN;
81
81
  } },
82
82
  "array.with": { ret: (objTy) => objTy, pure: true,
83
- intArgPositions: [0] },
83
+ intArgPositions: [0], argSlot: arrElemAt1 },
84
84
  // ── string ────────────────────────────────────────────────
85
85
  "string.trim": { ret: STRING, pure: true },
86
86
  "string.trimEnd": { ret: STRING, pure: true },
@@ -96,18 +96,18 @@ export const BUILTINS = {
96
96
  "string.startsWith": { ret: BOOL, pure: true },
97
97
  "string.endsWith": { ret: BOOL, pure: true },
98
98
  // ── map ───────────────────────────────────────────────────
99
- "map.get": { pure: true, argIsKey: true,
99
+ "map.get": { pure: true, argIsKey: true, argSlot: mapKeyAt0,
100
100
  ret: (objTy, _args, c) => objTy.kind !== "map" ? UNKNOWN
101
101
  : c.inSpec ? objTy.value : { kind: "optional", inner: objTy.value } },
102
- "map.has": { ret: BOOL, pure: true, argIsKey: true },
103
- "map.set": { ret: self, pure: false },
104
- "map.delete": { ret: self, pure: false },
102
+ "map.has": { ret: BOOL, pure: true, argIsKey: true, argSlot: mapKeyAt0 },
103
+ "map.set": { ret: self, pure: false, argSlot: mapKeyVal },
104
+ "map.delete": { ret: self, pure: false, argSlot: mapKeyAt0 },
105
105
  "map.keys": { ret: () => UNKNOWN, pure: true },
106
106
  "map.values": { ret: () => UNKNOWN, pure: true },
107
107
  // ── set ───────────────────────────────────────────────────
108
- "set.has": { ret: BOOL, pure: true, argIsKey: true },
109
- "set.add": { ret: self, pure: false },
110
- "set.delete": { ret: self, pure: false },
108
+ "set.has": { ret: BOOL, pure: true, argIsKey: true, argSlot: setElemAt0 },
109
+ "set.add": { ret: self, pure: false, argSlot: setElemAt0 },
110
+ "set.delete": { ret: self, pure: false, argSlot: setElemAt0 },
111
111
  };
112
112
  /** Recognize a builtin method call by receiver type kind + method name.
113
113
  * Called by resolve (once per call node); everything downstream reads the
@@ -107,6 +107,40 @@ function enterSomeMatch(scope, scrutinee, binder, binderTy) {
107
107
  function isDefinitelyUnwrappedStamp(ty) {
108
108
  return !isNullable(ty) && ty.kind !== "unknown" && ty.kind !== "void" && ty.kind !== "null";
109
109
  }
110
+ function synthArrayProjection(storage, flowTy, mod) {
111
+ if (!storage || storage.kind !== "user")
112
+ return null;
113
+ if (flowTy.kind === "unknown" || flowTy.kind === "void" || flowTy.kind === "null")
114
+ return null;
115
+ if (flowTy.kind === "user" && flowTy.name === storage.name)
116
+ return null;
117
+ const decl = mod.typeDecls.find(d => d.name === storage.name);
118
+ if (!decl || decl.kind !== "discriminated-union" || decl.discriminant !== "__isArray__" || !decl.variants)
119
+ return null;
120
+ const variantName = flowTy.kind === "array" ? "ArrayBranch" : "NonArrayBranch";
121
+ const variant = decl.variants.find(v => v.name === variantName);
122
+ const field = variant?.fields[0]?.name;
123
+ return field ? { field, variant: variantName } : null;
124
+ }
125
+ /** Rewrite an expression whose leaf must keep its union storage type (e.g.,
126
+ * `Array.isArray(x)`, `typeof x`, or `tagMatch` scrutinee) while still
127
+ * rewriting any optional/synth-union receiver prefix. */
128
+ function rewriteUnionScrutinee(e, scope, mod) {
129
+ const storage = storageTyOf(e, scope, mod);
130
+ if (e.kind === "var" && storage && synthArrayProjection(storage, e.ty, mod)) {
131
+ return { ...e, ty: storage };
132
+ }
133
+ if (e.kind === "field") {
134
+ const obj = rewriteExpr(e.obj, scope, mod);
135
+ const updated = obj === e.obj ? e : { ...e, obj };
136
+ const fStorage = storageTyOf(updated, scope, mod);
137
+ if (fStorage && synthArrayProjection(fStorage, updated.ty, mod)) {
138
+ return { ...updated, ty: fStorage };
139
+ }
140
+ return updated;
141
+ }
142
+ return rewriteExpr(e, scope, mod);
143
+ }
110
144
  /** Rewrite an expression that is the direct operand of `===`/`!==`/`==`/`!=`
111
145
  * with `undefined` or `null`: never wrap the operand itself in `checkedUnwrap`
112
146
  * (restore its declared `Option<T>` or `Nullish<T>` storage type so
@@ -143,6 +177,10 @@ function rewriteExpr(e, scope, mod) {
143
177
  return { ...e, ty: storage };
144
178
  }
145
179
  }
180
+ const synthProj = synthArrayProjection(storage, e.ty, mod);
181
+ if (synthProj && storage) {
182
+ return { kind: "field", obj: { ...e, ty: storage }, field: synthProj.field, ty: e.ty, ofVariant: synthProj.variant };
183
+ }
146
184
  return e;
147
185
  }
148
186
  case "num":
@@ -167,6 +205,10 @@ function rewriteExpr(e, scope, mod) {
167
205
  return { ...updated, ty: storage };
168
206
  }
169
207
  }
208
+ const synthProj = synthArrayProjection(storage, updated.ty, mod);
209
+ if (synthProj && storage) {
210
+ return { kind: "field", obj: { ...updated, ty: storage }, field: synthProj.field, ty: updated.ty, ofVariant: synthProj.variant };
211
+ }
170
212
  return updated;
171
213
  }
172
214
  case "index":
@@ -190,18 +232,41 @@ function rewriteExpr(e, scope, mod) {
190
232
  return { ...e, left, right, ty };
191
233
  }
192
234
  case "unop": {
193
- const expr = rewriteExpr(e.expr, scope, mod);
235
+ const expr = e.op === "typeof"
236
+ ? rewriteUnionScrutinee(e.expr, scope, mod)
237
+ : rewriteExpr(e.expr, scope, mod);
194
238
  let ty = e.ty;
195
239
  if (e.op === "-" && isNullable(ty) && !isNullable(expr.ty))
196
240
  ty = expr.ty;
197
241
  return { ...e, expr, ty };
198
242
  }
199
- case "call":
200
- return {
201
- ...e,
202
- fn: rewriteExpr(e.fn, scope, mod),
203
- args: e.args.map(a => rewriteExpr(a, scope, mod)),
204
- };
243
+ case "call": {
244
+ if (e.fn.kind === "field" && e.fn.field === "isArray" &&
245
+ e.fn.obj.kind === "var" && e.fn.obj.name === "Array" && e.args.length === 1) {
246
+ return { ...e, args: [rewriteUnionScrutinee(e.args[0], scope, mod)] };
247
+ }
248
+ const fn = rewriteExpr(e.fn, scope, mod);
249
+ const args = e.args.map(a => rewriteExpr(a, scope, mod));
250
+ if (fn.kind === "var" && args.length === 1 && args[0].kind === "checkedUnwrap") {
251
+ const inner = args[0].expr;
252
+ // Re-wrapping a same-storage checkedUnwrap (`Some(x.value)` for Option<T>,
253
+ // `Nullish.Value(x.value)` for Nullish<T>) is a no-op; emit `x` directly.
254
+ if (fn.name === "Some" && inner.ty.kind === "optional" && !inner.ty.fromNullish) {
255
+ return inner;
256
+ }
257
+ if (fn.name === "NullishValue" && inner.ty.kind === "nullish") {
258
+ return inner;
259
+ }
260
+ }
261
+ if (fn.kind === "var" && args.length === 1 && args[0].kind === "field" &&
262
+ ((fn.name === "ArrayBranch" && args[0].ofVariant === "ArrayBranch") ||
263
+ (fn.name === "NonArrayBranch" && args[0].ofVariant === "NonArrayBranch")) &&
264
+ args[0].obj.ty.kind === "user" && e.ty.kind === "user" &&
265
+ args[0].obj.ty.name === e.ty.name) {
266
+ return args[0].obj;
267
+ }
268
+ return { ...e, fn, args };
269
+ }
205
270
  case "record":
206
271
  return {
207
272
  ...e,
@@ -253,7 +318,7 @@ function rewriteExpr(e, scope, mod) {
253
318
  case "tagMatch":
254
319
  return {
255
320
  ...e,
256
- scrutinee: rewriteExpr(e.scrutinee, scope, mod),
321
+ scrutinee: rewriteUnionScrutinee(e.scrutinee, scope, mod),
257
322
  cases: e.cases.map(c => ({ ...c, body: rewriteExpr(c.body, scope, mod) })),
258
323
  fallthrough: e.fallthrough ? rewriteExpr(e.fallthrough, scope, mod) : null,
259
324
  };
@@ -358,7 +423,7 @@ function rewriteStmts(stmts, scope, mod) {
358
423
  case "tagMatch":
359
424
  out.push({
360
425
  ...s,
361
- scrutinee: rewriteExpr(s.scrutinee, cur, mod),
426
+ scrutinee: rewriteUnionScrutinee(s.scrutinee, cur, mod),
362
427
  cases: s.cases.map(c => ({ ...c, body: rewriteStmts(c.body, cur, mod) })),
363
428
  fallthrough: rewriteStmts(s.fallthrough, cur, mod),
364
429
  });
@@ -21,7 +21,7 @@
21
21
  */
22
22
  import { isNullishStorageTy, optAbsent } from "./typedir.js";
23
23
  import { freshName, freshNameWhere, isUserName } from "./names.js";
24
- import { unionDeclOfTy, discriminantOf } from "./typedecls.js";
24
+ import { unionDeclOfTy, discriminantOf, declOfDotted, tyBaseName } from "./typedecls.js";
25
25
  /** Allocate within this context, retaining a path's name on repeated
26
26
  * detection. Semantic-only callers need no registry. */
27
27
  function freshBinder(ctx, hint, key) {
@@ -74,8 +74,17 @@ export function bindPresentFact(f, ctx) {
74
74
  * `!e` and bare `e` are truthiness forms. `!!c` is the same check as `c`.
75
75
  * Following TS, only pure access paths narrow; complex scrutinees return null. */
76
76
  export function presentFact(cond) {
77
- if (cond.kind === "unop" && cond.op === "!" && cond.expr.kind === "unop" && cond.expr.op === "!")
78
- return presentFact(cond.expr.expr);
77
+ if (cond.kind === "unop" && cond.op === "!") {
78
+ if (cond.expr.kind === "unop" && cond.expr.op === "!")
79
+ return presentFact(cond.expr.expr);
80
+ // Negated explicit sentinel check: `!(x === undefined)`, `!(x !== undefined)`,
81
+ // `!(x === null)`, `!(x == null)`, etc. (#338). Non-truthiness facts invert
82
+ // cleanly by flipping `negated`.
83
+ const inner = presentFact(cond.expr);
84
+ if (inner && !inner.truthiness) {
85
+ return { ...inner, negated: !inner.negated };
86
+ }
87
+ }
79
88
  // `!e` where e is optional or nullish — a truthiness form: false iff e is
80
89
  // absent (None / Null / Undefined) OR its inner value is itself falsy.
81
90
  if (cond.kind === "unop" && cond.op === "!" && (cond.expr.ty.kind === "optional" || cond.expr.ty.kind === "nullish")) {
@@ -202,17 +211,52 @@ export function flattenOr(e) {
202
211
  return [...flattenOr(e.left), ...flattenOr(e.right)];
203
212
  return [e];
204
213
  }
214
+ /** True when `e` cannot evaluate to `undefined` at runtime.
215
+ * Rules out `undefined`, optional/nullish/void/unknown types, function type
216
+ * parameters (which may be instantiated with `undefined`), and aliases to them,
217
+ * while keeping concrete declared types (records, unions, enums, classes). */
218
+ export function excludesUndefined(e, decls, typeParams) {
219
+ if (e.kind === "var" && e.name === "undefined")
220
+ return false;
221
+ return tyExcludesUndefined(e.ty, decls, typeParams);
222
+ }
223
+ function tyExcludesUndefined(ty, decls, typeParams, depth = 0) {
224
+ if (depth > 8)
225
+ return false;
226
+ switch (ty.kind) {
227
+ case "optional":
228
+ case "nullish":
229
+ case "void":
230
+ case "unknown":
231
+ return false;
232
+ case "user": {
233
+ const base = tyBaseName(ty.name);
234
+ if (typeParams?.has(base))
235
+ return false;
236
+ const decl = declOfDotted(decls, base);
237
+ if (decl?.kind === "alias" && decl.aliasOfTy) {
238
+ return tyExcludesUndefined(decl.aliasOfTy, decls, typeParams, depth + 1);
239
+ }
240
+ return true;
241
+ }
242
+ default:
243
+ return true;
244
+ }
245
+ }
205
246
  export function noneDetector(leaf, ctx) {
206
- // `x?.chain !== lit` — `undefined !== lit` is true when x is None.
247
+ // `x?.chain !== lit` — `undefined !== lit` is true when x is None, provided
248
+ // `lit` itself cannot evaluate to `undefined`.
207
249
  if (leaf.kind === "binop" && leaf.op === "!==") {
208
250
  const oc = leaf.left.kind === "optChain" ? leaf.left : leaf.right.kind === "optChain" ? leaf.right : null;
209
251
  if (oc && oc.kind === "optChain" && oc.obj.ty.kind === "optional" && !oc.obj.ty.fromNullish) {
252
+ const lit = leaf.left === oc ? leaf.right : leaf.left;
253
+ if (!excludesUndefined(lit, ctx.decls, ctx.typeParams))
254
+ return null;
210
255
  const binder = freshPathBinder(oc.obj, ctx);
211
256
  if (binder === null)
212
257
  return null;
213
258
  const unwrapped = applyChain({ kind: "var", name: binder, ty: oc.obj.ty.inner }, oc.chain);
214
259
  restoreDiscriminantFlag(unwrapped, ctx.decls);
215
- const lit = leaf.left === oc ? leaf.right : leaf.left;
216
260
  return { scrutinee: oc.obj, innerTy: oc.obj.ty.inner, binder, residual: { kind: "binop", op: "!==", left: unwrapped, right: lit, ty: { kind: "bool" } } };
217
261
  }
218
262
  }
@@ -29,6 +29,12 @@ export const OPTION_SPECS = {
29
29
  fileOverride: false,
30
30
  description: "Directory for Dafny artifacts, relative to lemmascript.json.",
31
31
  },
32
+ "proof-files": {
33
+ type: "proof-files",
34
+ default: {},
35
+ fileOverride: false,
36
+ description: "Additional Dafny files to verify with each source, relative to lemmascript.json.",
37
+ },
32
38
  "string-semantics": {
33
39
  type: "enum",
34
40
  values: ["unicode-scalar", "javascript-utf16"],
@@ -66,7 +72,14 @@ function fail(source, message) {
66
72
  function isKnownKey(key) {
67
73
  return Object.hasOwn(OPTION_SPECS, key);
68
74
  }
69
- /** Validate one option against the registry and return its typed value. */
75
+ function relativePath(raw, key, source) {
76
+ if (typeof raw !== "string" || raw.trim().length === 0) {
77
+ fail(source, `option '${key}' must be a non-empty relative path`);
78
+ }
79
+ if (path.isAbsolute(raw))
80
+ fail(source, `option '${key}' must be relative to lemmascript.json`);
81
+ return raw;
82
+ }
70
83
  export function parseOptionValue(key, raw, source) {
71
84
  const spec = OPTION_SPECS[key];
72
85
  if (spec.type === "boolean") {
@@ -80,12 +93,27 @@ export function parseOptionValue(key, raw, source) {
80
93
  }
81
94
  return raw;
82
95
  }
83
- if (typeof raw !== "string" || raw.trim().length === 0) {
84
- fail(source, `option '${key}' must be a non-empty relative path`);
96
+ if (spec.type === "proof-files") {
97
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
98
+ fail(source, "'proof-files' must map source paths to arrays of .dfy paths");
99
+ }
100
+ const files = Object.create(null);
101
+ for (const [name, paths] of Object.entries(raw)) {
102
+ const file = path.normalize(relativePath(name, key, source));
103
+ if (Object.hasOwn(files, file))
104
+ fail(source, `duplicate source '${name}' in proof-files`);
105
+ if (!Array.isArray(paths))
106
+ fail(source, `proof-files['${name}'] must be an array of .dfy paths`);
107
+ files[file] = [...new Set(paths.map(value => {
108
+ const proof = relativePath(value, key, source);
109
+ if (path.extname(proof) !== ".dfy")
110
+ fail(source, `expected a .dfy file for '${name}', got '${proof}'`);
111
+ return path.normalize(proof);
112
+ }))];
113
+ }
114
+ return files;
85
115
  }
86
- if (path.isAbsolute(raw))
87
- fail(source, `option '${key}' must be relative to lemmascript.json`);
88
- return raw;
116
+ return relativePath(raw, key, source);
89
117
  }
90
118
  /** Validate a parsed lemmascript.json object, returning only explicitly set keys. */
91
119
  export function validateOptions(raw, source) {
@@ -261,6 +289,14 @@ export function loadConfigOptions(sourcePath, configPath) {
261
289
  CONFIG_CACHE.set(configFile, explicit);
262
290
  return { explicit: { ...explicit }, configFile };
263
291
  }
292
+ export function resolveDafnyProofFiles(sourcePath, configFile, options) {
293
+ if (!configFile)
294
+ return [];
295
+ const dir = path.dirname(configFile);
296
+ const source = path.relative(dir, sourcePath);
297
+ const files = options["proof-files"];
298
+ return Object.hasOwn(files, source) ? files[source].map(file => path.resolve(dir, file)) : [];
299
+ }
264
300
  /** Resolve the directory containing one source file's Dafny companions. */
265
301
  export function resolveDafnyArtifactDir(sourcePath, configFile, options) {
266
302
  const source = path.resolve(sourcePath);
@@ -160,10 +160,26 @@ export function dafnyVerifyArgs(content, timeLimit, extraFlags) {
160
160
  args.push("--allow-deprecation");
161
161
  return { args };
162
162
  }
163
- export function dafnyVerify(dfyPath, dir, timeLimit, extraFlags, log) {
163
+ export function readDafnyProofFiles(files, dfyPath, log) {
164
+ try {
165
+ return files.map(file => {
166
+ const text = readFileSync(file, "utf8");
167
+ const violations = proofAdditionViolations("", text, file);
168
+ if (violations.length)
169
+ throw new Error(violations.join("\n"));
170
+ return { file, text };
171
+ });
172
+ }
173
+ catch (error) {
174
+ log?.finish({ stage: "diff", exit: 1, dfyPath });
175
+ throw error;
176
+ }
177
+ }
178
+ export function dafnyVerify(dfyPath, dir, timeLimit, extraFlags, log, proofs = []) {
164
179
  console.log("Running dafny verify...");
165
180
  try {
166
- const { args, error } = dafnyVerifyArgs(readFileSync(dfyPath, "utf-8"), timeLimit, extraFlags);
181
+ const content = [readFileSync(dfyPath, "utf8"), ...proofs.map(p => p.text)].join("\n");
182
+ const { args, error } = dafnyVerifyArgs(content, timeLimit, extraFlags);
167
183
  if (error) {
168
184
  console.error(error);
169
185
  log?.finish({ stage: "resolve", exit: 1, dfyPath });
@@ -171,7 +187,7 @@ export function dafnyVerify(dfyPath, dir, timeLimit, extraFlags, log) {
171
187
  }
172
188
  if (log)
173
189
  args.push(...log.dafnyArgs());
174
- args.push(dfyPath);
190
+ args.push(dfyPath, ...proofs.map(p => p.file));
175
191
  execFileSync("dafny", args, { cwd: dir, stdio: "inherit" });
176
192
  log?.finish({ stage: "ok", exit: 0, dfyPath, results: log.readResults() });
177
193
  return true;
@@ -188,7 +204,7 @@ export function dafnyVerify(dfyPath, dir, timeLimit, extraFlags, log) {
188
204
  return false;
189
205
  }
190
206
  }
191
- export function dafnyRegen(genPath, dfyPath, basePath, text, dir, timeLimit, extraFlags, noVerify = false, log) {
207
+ export function dafnyRegen(genPath, dfyPath, basePath, text, dir, timeLimit, extraFlags, noVerify = false, log, proofs = []) {
192
208
  // 1. Read old gen before overwriting (needed for base seeding)
193
209
  const oldGen = existsSync(genPath) ? readFileSync(genPath, "utf-8") : "";
194
210
  // 2. Always write new gen so user can inspect latest output
@@ -197,7 +213,7 @@ export function dafnyRegen(genPath, dfyPath, basePath, text, dir, timeLimit, ext
197
213
  if (!existsSync(dfyPath)) {
198
214
  writeFileSync(dfyPath, text);
199
215
  console.log(`Created: ${path.basename(dfyPath)}`);
200
- if (!noVerify && !dafnyVerify(dfyPath, dir, timeLimit, extraFlags, log)) {
216
+ if (!noVerify && !dafnyVerify(dfyPath, dir, timeLimit, extraFlags, log, proofs)) {
201
217
  console.error(`FAILED: ${path.basename(dfyPath)} verification failed on first run.`);
202
218
  process.exit(1);
203
219
  }
@@ -261,7 +277,7 @@ export function dafnyRegen(genPath, dfyPath, basePath, text, dir, timeLimit, ext
261
277
  process.exit(1);
262
278
  }
263
279
  // 7. Verify (skipped under --no-verify: caller verifies separately)
264
- if (!noVerify && !dafnyVerify(dfyPath, dir, timeLimit, extraFlags, log)) {
280
+ if (!noVerify && !dafnyVerify(dfyPath, dir, timeLimit, extraFlags, log, proofs)) {
265
281
  // The clean merge already incorporated this generation into the proof
266
282
  // file. Keep that generation as the next merge anchor even though the
267
283
  // verifier rejected the current proof state; otherwise the next regen
@@ -1956,7 +1956,7 @@ function translatePattern(p) {
1956
1956
  const ctorName = (Object.hasOwn(CTOR_MAP, p.ctor) ? CTOR_MAP[p.ctor] : undefined) ?? dafnyCtorName(p.ctor);
1957
1957
  if (p.binders.length === 0)
1958
1958
  return ctorName;
1959
- return `${ctorName}(${p.binders.map(escapeName).join(", ")})`;
1959
+ return `${ctorName}(${p.binders.map(b => b === "_" ? "_" : escapeName(b)).join(", ")})`;
1960
1960
  }
1961
1961
  export function emitDafnyFile(file, tsFileName, options = DEFAULT_OPTIONS) {
1962
1962
  // Programmatic callers share the CLI's compatibility checks.
@@ -419,7 +419,7 @@ const OTHER_LINE_BREAK = /[\r\u2028\u2029]/;
419
419
  */
420
420
  export function proofAdditionViolations(generated, proof, proofName) {
421
421
  const proofLines = proof.split("\n");
422
- const genLines = generated.split("\n");
422
+ const genLines = generated === "" ? [] : generated.split("\n");
423
423
  const matched = matchGeneratedLines(genLines, proofLines);
424
424
  if (!matched)
425
425
  return [`${proofName}: generated lines are not contained in order in the proof`];
@@ -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)})`;
@@ -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(", ")} }`;