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/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)),
@@ -9,7 +9,7 @@
9
9
  * and record-field assignments) always propagate back to the owning lexical
10
10
  * storage variable instead of mutating a discarded copy or match binder.
11
11
  */
12
- import { extendFieldPlace, extendUnwrapPlace, extendVariantPlace, makeVarPlace, } from "./places.js";
12
+ import { extendFieldPlace, extendUnwrapPlace, makeVarPlace, } from "./places.js";
13
13
  export function makeUnwrapFrame(binder, rootVar, fields) {
14
14
  let place = makeVarPlace(rootVar);
15
15
  for (const f of fields)
@@ -17,10 +17,6 @@ export function makeUnwrapFrame(binder, rootVar, fields) {
17
17
  place = extendUnwrapPlace(place);
18
18
  return { kind: "unwrap", binder, rootVar, fields, place };
19
19
  }
20
- export function makeVariantFrame(unionVar, typeName, ctorName, fields) {
21
- const place = extendVariantPlace(makeVarPlace(unionVar), ctorName);
22
- return { kind: "variant", unionVar, typeName, ctorName, fields, place };
23
- }
24
20
  /** True for in-place mutating collection methods modeled by functional write-back. */
25
21
  export function isMutatingCollectionMethod(recvTy, method) {
26
22
  if ((recvTy.kind === "map" || recvTy.kind === "set") &&
@@ -32,22 +28,30 @@ export function isMutatingCollectionMethod(recvTy, method) {
32
28
  }
33
29
  return false;
34
30
  }
35
- /** Build a nested record-update expression rooted at `rootVar` for `fields`
36
- * (length >= 1), setting the innermost field to `newVal`. */
37
- export function buildNestedFieldExpr(rootVar, fields, newVal) {
31
+ /** Build a nested record-update expression rooted at `base` for `fields`
32
+ * (length >= 1), setting the innermost field to `newVal`. Optional
33
+ * `unionsByDepth` pins the union constructor/type at each nesting depth `i`
34
+ * whose owner is a discriminated union (for collision-renamed destructors in
35
+ * Dafny and match-updates in Lean). */
36
+ export function buildNestedFieldExpr(base, fields, newVal, unionsByDepth) {
38
37
  const baseFor = (len) => {
39
- let cur = { kind: "var", name: rootVar };
38
+ let cur = base;
40
39
  for (let i = 0; i < len; i++) {
41
- cur = { kind: "field", obj: cur, field: fields[i], datatypeField: true };
40
+ const u = unionsByDepth?.[i];
41
+ const unionTag = u ? { fromUnion: u.ctorOf, ctor: u.ctor } : {};
42
+ cur = { kind: "field", obj: cur, field: fields[i], ...unionTag, datatypeField: true };
42
43
  }
43
44
  return cur;
44
45
  };
45
46
  let curVal = newVal;
46
47
  for (let i = fields.length - 1; i >= 0; i--) {
48
+ const u = unionsByDepth?.[i];
49
+ const unionTag = u ? { ctor: u.ctor, ctorOf: u.ctorOf } : {};
47
50
  curVal = {
48
51
  kind: "record",
49
52
  spread: baseFor(i),
50
53
  fields: [{ name: fields[i], value: curVal }],
54
+ ...unionTag,
51
55
  };
52
56
  }
53
57
  return curVal;
@@ -58,7 +62,7 @@ function optionSome(value) {
58
62
  /**
59
63
  * Given a variable `mutatedTarget` that was just assigned in the lowered IR,
60
64
  * walk `frames` from innermost to outermost and emit the cascading write-back
61
- * assignments that synchronize every enclosing narrowing binder and the owning
65
+ * assignments that synchronize every enclosing `someMatch` binder and the owning
62
66
  * lexical storage variable.
63
67
  */
64
68
  export function emitWriteBacksForTarget(mutatedTarget, frames) {
@@ -66,7 +70,7 @@ export function emitWriteBacksForTarget(mutatedTarget, frames) {
66
70
  let current = mutatedTarget;
67
71
  for (let i = frames.length - 1; i >= 0; i--) {
68
72
  const frame = frames[i];
69
- if (frame.kind === "unwrap" && frame.binder === current) {
73
+ if (frame.binder === current) {
70
74
  const wrapped = optionSome({ kind: "var", name: frame.binder });
71
75
  if (frame.fields.length === 0) {
72
76
  out.push({ kind: "assign", target: frame.rootVar, value: wrapped });
@@ -75,21 +79,10 @@ export function emitWriteBacksForTarget(mutatedTarget, frames) {
75
79
  out.push({
76
80
  kind: "assign",
77
81
  target: frame.rootVar,
78
- value: buildNestedFieldExpr(frame.rootVar, frame.fields, wrapped),
82
+ value: buildNestedFieldExpr({ kind: "var", name: frame.rootVar }, frame.fields, wrapped),
79
83
  });
80
84
  }
81
85
  current = frame.rootVar;
82
- continue;
83
- }
84
- if (frame.kind === "variant" && frame.fields.some(f => f.binder === current)) {
85
- const reconstructed = {
86
- kind: "app",
87
- fn: frame.ctorName,
88
- ctorOf: frame.typeName,
89
- args: frame.fields.map(f => ({ kind: "var", name: f.binder })),
90
- };
91
- out.push({ kind: "assign", target: frame.unionVar, value: reconstructed });
92
- current = frame.unionVar;
93
86
  }
94
87
  }
95
88
  return out;
@@ -98,8 +91,7 @@ export function emitWriteBacksForTarget(mutatedTarget, frames) {
98
91
  export function findActiveUnwrapFrame(rootVar, fields, frames) {
99
92
  for (let i = frames.length - 1; i >= 0; i--) {
100
93
  const frame = frames[i];
101
- if (frame.kind === "unwrap" &&
102
- frame.rootVar === rootVar &&
94
+ if (frame.rootVar === rootVar &&
103
95
  frame.fields.length === fields.length &&
104
96
  frame.fields.every((f, idx) => f === fields[idx])) {
105
97
  return frame;
@@ -107,54 +99,23 @@ export function findActiveUnwrapFrame(rootVar, fields, frames) {
107
99
  }
108
100
  return null;
109
101
  }
110
- /** Resolve a source dotted path like `["b", "count"]`, `["u", "v"]`, or
111
- * `["u", "box", "count"]` through any enclosing `unwrap` and `variant` frames.
112
- * Returns:
113
- * - `currentRoot`: the deepest active binder/variable reached,
114
- * - `remainingFields`: any field steps remaining below `currentRoot`,
115
- * - `leafUnwrapFrame`: if the entire path ended at an active `unwrap` frame
116
- * (so non-optional writes update `leafUnwrapFrame.binder` and cascade,
117
- * while `undefined`/optional writes update `leafUnwrapFrame.rootVar`),
118
- * - `leafVariantBinder`: if the entire path ended directly at a union
119
- * variant field binder (e.g. `u.v` -> `i_u_v`). */
102
+ /** Resolve a source dotted path like `["b", "count"]` through any enclosing
103
+ * `someMatch` unwrap frames. */
120
104
  export function resolveWriteTargetThroughFrames(rootVar, fields, frames) {
121
105
  let currentRoot = rootVar;
122
106
  let idx = 0;
123
107
  let lastUnwrap = null;
124
- let lastVariantBinder = null;
125
- // Iteratively step through active `unwrap` (0-field or prefix-field) and
126
- // `variant` (1-field) frames until no more frames match.
127
108
  while (true) {
128
- // 1. Bare unwrap on `currentRoot` (e.g. `b` -> `_b_val`, or `u` -> `_u_val`).
109
+ // 1. Bare unwrap on `currentRoot` (e.g. `b` -> `_b_val`).
129
110
  const bareUnwrap = findActiveUnwrapFrame(currentRoot, [], frames);
130
111
  if (bareUnwrap) {
131
112
  currentRoot = bareUnwrap.binder;
132
113
  lastUnwrap = bareUnwrap;
133
- lastVariantBinder = null;
134
114
  continue;
135
115
  }
136
116
  if (idx >= fields.length)
137
117
  break;
138
- // 2. Variant field projection on `currentRoot` (e.g. `u.v` -> `i_u_v`, `u.box` -> `i_u_box`).
139
- let matchedVariant = null;
140
- for (let i = frames.length - 1; i >= 0; i--) {
141
- const frame = frames[i];
142
- if (frame.kind === "variant" && frame.unionVar === currentRoot) {
143
- const hit = frame.fields.find(f => f.fieldName === fields[idx]);
144
- if (hit) {
145
- matchedVariant = hit.binder;
146
- break;
147
- }
148
- }
149
- }
150
- if (matchedVariant) {
151
- currentRoot = matchedVariant;
152
- idx += 1;
153
- lastUnwrap = null;
154
- lastVariantBinder = matchedVariant;
155
- continue;
156
- }
157
- // 3. Field-prefix unwrap on `currentRoot` (e.g. `_b_val.items` -> `_b_val_items_val`).
118
+ // 2. Field-prefix unwrap on `currentRoot` (e.g. `_b_val.items` -> `_b_val_items_val`).
158
119
  let matchedLen = 0;
159
120
  let matchedUnwrap = null;
160
121
  for (let len = fields.length - idx; len >= 1; len--) {
@@ -170,7 +131,6 @@ export function resolveWriteTargetThroughFrames(rootVar, fields, frames) {
170
131
  currentRoot = matchedUnwrap.binder;
171
132
  idx += matchedLen;
172
133
  lastUnwrap = matchedUnwrap;
173
- lastVariantBinder = null;
174
134
  continue;
175
135
  }
176
136
  break;
@@ -179,7 +139,6 @@ export function resolveWriteTargetThroughFrames(rootVar, fields, frames) {
179
139
  currentRoot,
180
140
  remainingFields: fields.slice(idx),
181
141
  leafUnwrapFrame: idx === fields.length ? lastUnwrap : null,
182
- leafVariantBinder: idx === fields.length ? lastVariantBinder : null,
183
142
  };
184
143
  }
185
144
  /** Collect every variable name assigned anywhere in lowered IR `Stmt[]`