lemmascript 0.6.4 → 0.6.6
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 +14 -5
- package/package.json +1 -1
- package/tools/dist/condition-facts.js +54 -31
- package/tools/dist/config.js +32 -10
- package/tools/dist/dafny-commands.js +102 -17
- package/tools/dist/dafny-emit.js +161 -28
- package/tools/dist/extract.js +44 -5
- package/tools/dist/lean-emit.js +31 -19
- package/tools/dist/lsc.js +56 -4
- package/tools/dist/narrow.js +36 -34
- package/tools/dist/run-log.js +197 -0
- package/tools/dist/runs-command.js +377 -0
- package/tools/dist/transform.js +7 -3
package/tools/dist/lsc.js
CHANGED
|
@@ -20,6 +20,8 @@ import { emitDafnyFile, emittedNameMap } from "./dafny-emit.js";
|
|
|
20
20
|
import { dafnyGen, dafnyCheckDiff, dafnyVerify, dafnyRegen } from "./dafny-commands.js";
|
|
21
21
|
import { leanGen, leanCheck } from "./lean-commands.js";
|
|
22
22
|
import { runInfo, runTypedInfo } from "./info-command.js";
|
|
23
|
+
import { RunLog, resolveLogDir, runLogEnabled, safely } from "./run-log.js";
|
|
24
|
+
import { runRuns } from "./runs-command.js";
|
|
23
25
|
import { findUp, loadConfigOptions, parseFileOptions, resolveDafnyArtifactDir, resolveOptions, } from "./config.js";
|
|
24
26
|
/** Version of the lemmascript package — the root package.json sits two levels
|
|
25
27
|
* above this module from both tools/src/ (tsx) and tools/dist/ (installed). */
|
|
@@ -76,6 +78,12 @@ function main() {
|
|
|
76
78
|
}
|
|
77
79
|
return;
|
|
78
80
|
}
|
|
81
|
+
// `lsc runs` reads the run log and takes its own flags (`--json`, `--config=`),
|
|
82
|
+
// so it is dispatched before the file commands' flag parsing.
|
|
83
|
+
if (args[0] === "runs") {
|
|
84
|
+
runRuns(args.slice(1));
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
79
87
|
const backendIdx = args.findIndex(a => a.startsWith("--backend="));
|
|
80
88
|
let backend = "dafny";
|
|
81
89
|
if (backendIdx >= 0) {
|
|
@@ -155,6 +163,7 @@ function main() {
|
|
|
155
163
|
console.error(" lsc info --typed <file.ts> (machine-readable Typed IR contract to stdout)");
|
|
156
164
|
console.error(" lsc <gen|gen-check|check> [--backend=…] [--slow] (no file: batch over LemmaScript-files.txt)");
|
|
157
165
|
console.error(" lsc claimcheck [<file.ts>] [flags…] (forwards to lemmascript-claimcheck)");
|
|
166
|
+
console.error(" lsc runs [--json] [--config=path] (what verification caught, from .lemmascript/runs.jsonl)");
|
|
158
167
|
console.error(" lsc version");
|
|
159
168
|
process.exit(1);
|
|
160
169
|
}
|
|
@@ -194,6 +203,30 @@ function effectiveOptions(sourcePath, sourceText, configPath) {
|
|
|
194
203
|
const options = resolveOptions({ ...loaded.explicit, ...fileOptions }, sourcePath);
|
|
195
204
|
return { options, configFile: loaded.configFile };
|
|
196
205
|
}
|
|
206
|
+
/** Imported contracts must retain the string model used by their source files. */
|
|
207
|
+
function stringModelValidator(source, options, configPath) {
|
|
208
|
+
const seen = new Set();
|
|
209
|
+
return start => {
|
|
210
|
+
const pending = [start];
|
|
211
|
+
while (pending.length > 0) {
|
|
212
|
+
const dependency = pending.pop();
|
|
213
|
+
if (seen.has(dependency))
|
|
214
|
+
continue;
|
|
215
|
+
seen.add(dependency);
|
|
216
|
+
pending.push(...dependency.getReferencedSourceFiles());
|
|
217
|
+
// Declaration files describe host APIs; follow re-exports through them,
|
|
218
|
+
// but compare models only for source files that can carry verified code.
|
|
219
|
+
if (dependency === source || dependency.isDeclarationFile())
|
|
220
|
+
continue;
|
|
221
|
+
const { options: imported } = effectiveOptions(dependency.getFilePath(), dependency.getFullText(), configPath);
|
|
222
|
+
if (imported["string-semantics"] !== options["string-semantics"]) {
|
|
223
|
+
throw new Error(`${source.getFilePath()}: string-semantics=${options["string-semantics"]} differs from `
|
|
224
|
+
+ `${dependency.getFilePath()} (string-semantics=${imported["string-semantics"]}); `
|
|
225
|
+
+ "use the same string model across source dependencies");
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
};
|
|
229
|
+
}
|
|
197
230
|
/** `lsc config [file.ts]` — report discovery, effective values, and routing. */
|
|
198
231
|
function runConfig(filePath, configPath) {
|
|
199
232
|
if (!filePath) {
|
|
@@ -263,6 +296,8 @@ function runFile(cmd, filePath, backend, timeLimit, extraFlags, noVerify = false
|
|
|
263
296
|
project.resolveSourceFileDependencies();
|
|
264
297
|
const fullText = sourceFile.getFullText();
|
|
265
298
|
const { options, configFile } = effectiveOptions(absPath, fullText, configPath);
|
|
299
|
+
// Checked here, for every command, so a bad LSC_RUN_LOG fails like a bad config value.
|
|
300
|
+
const runLogOn = runLogEnabled(options["run-log"], process.env.LSC_RUN_LOG);
|
|
266
301
|
// Check //@ backend directive — skip if backend doesn't match.
|
|
267
302
|
// `extract` and `info` are backend-neutral and always run.
|
|
268
303
|
const backendDirective = fullText.match(/\/\/@ backend (\w+)/);
|
|
@@ -277,8 +312,12 @@ function runFile(cmd, filePath, backend, timeLimit, extraFlags, noVerify = false
|
|
|
277
312
|
// both can be separate Lean libraries. Lean-only — Dafny is unaffected.
|
|
278
313
|
const leanModuleDirective = fullText.match(/\/\/@ lean-module ([A-Za-z0-9_.\-]+)/);
|
|
279
314
|
const leanModuleOverride = leanModuleDirective ? leanModuleDirective[1] : undefined;
|
|
315
|
+
// Validate the actual dependency graph, not unrelated files in the tsconfig.
|
|
316
|
+
// Library selection may differ; only the string model changes contract meaning.
|
|
317
|
+
const validateDependency = stringModelValidator(sourceFile, options, configPath);
|
|
318
|
+
validateDependency(sourceFile);
|
|
280
319
|
// Extract: ts-morph → Raw IR
|
|
281
|
-
const raw = extractModule(sourceFile, options);
|
|
320
|
+
const raw = extractModule(sourceFile, options, validateDependency);
|
|
282
321
|
if (cmd === "extract") {
|
|
283
322
|
console.log(JSON.stringify(raw, null, 2));
|
|
284
323
|
return;
|
|
@@ -333,6 +372,12 @@ function runFile(cmd, filePath, backend, timeLimit, extraFlags, noVerify = false
|
|
|
333
372
|
const basePath = path.join(artifactDir, `${base}.dfy.base`);
|
|
334
373
|
guardRelocatedDafnyProof(dir, artifactDir, base, dfyPath);
|
|
335
374
|
mkdirSync(artifactDir, { recursive: true });
|
|
375
|
+
// Record check/regen runs in the run log. Created after the proof-dir guard
|
|
376
|
+
// so an aborted run leaves no snapshot; each helper records the stage it detects.
|
|
377
|
+
const logCmd = cmd === "check" || cmd === "regen" ? cmd : null;
|
|
378
|
+
const log = logCmd && runLogOn
|
|
379
|
+
? new RunLog({ logDir: resolveLogDir(absPath, configFile), cmd: logCmd, sourcePath: absPath, extraFlags, lscVersion: safely(lscVersion) })
|
|
380
|
+
: undefined;
|
|
336
381
|
if (cmd === "gen") {
|
|
337
382
|
dafnyGen(genPath, dfyPath, text);
|
|
338
383
|
return;
|
|
@@ -345,20 +390,27 @@ function runFile(cmd, filePath, backend, timeLimit, extraFlags, noVerify = false
|
|
|
345
390
|
}
|
|
346
391
|
if (cmd === "check") {
|
|
347
392
|
dafnyGen(genPath, dfyPath, text);
|
|
348
|
-
if (!dafnyCheckDiff(genPath, dfyPath))
|
|
393
|
+
if (!dafnyCheckDiff(genPath, dfyPath, log))
|
|
349
394
|
process.exit(1);
|
|
350
|
-
if (!dafnyVerify(dfyPath, artifactDir, timeLimit, extraFlags))
|
|
395
|
+
if (!dafnyVerify(dfyPath, artifactDir, timeLimit, extraFlags, log))
|
|
351
396
|
process.exit(1);
|
|
352
397
|
return;
|
|
353
398
|
}
|
|
354
399
|
if (cmd === "regen") {
|
|
355
|
-
dafnyRegen(genPath, dfyPath, basePath, text, artifactDir, timeLimit, extraFlags, noVerify);
|
|
400
|
+
dafnyRegen(genPath, dfyPath, basePath, text, artifactDir, timeLimit, extraFlags, noVerify, log);
|
|
356
401
|
return;
|
|
357
402
|
}
|
|
358
403
|
console.error(`Unknown command: ${cmd}`);
|
|
359
404
|
process.exit(1);
|
|
360
405
|
}
|
|
361
406
|
// ── Lean backend ──────────────────────────────────────────
|
|
407
|
+
// Dafny-only profile: Lean's `String` is a sequence of Unicode scalars and
|
|
408
|
+
// LemmaScript has no UTF-16 encoding for it (DESIGN_STRINGS.md §4). Refuse
|
|
409
|
+
// rather than emit scalar Lean for a code-unit claim.
|
|
410
|
+
if (options["string-semantics"] === "javascript-utf16") {
|
|
411
|
+
console.error('ERROR: "string-semantics": "javascript-utf16" is not available for --backend=lean; use --backend=dafny or select "unicode-scalar" in lemmascript.json or a //@ option directive.');
|
|
412
|
+
process.exit(1);
|
|
413
|
+
}
|
|
362
414
|
const leanBase = leanModuleOverride ?? base;
|
|
363
415
|
const specPath = path.join(dir, `${leanBase}.spec.lean`);
|
|
364
416
|
const specImport = existsSync(specPath) ? `«${leanBase}.spec»` : undefined;
|
package/tools/dist/narrow.js
CHANGED
|
@@ -34,13 +34,12 @@
|
|
|
34
34
|
* binder counter) threads through the walk; no module-level state.
|
|
35
35
|
*/
|
|
36
36
|
import { isTerminatorKind } from "./typedir.js";
|
|
37
|
-
import { freshName } from "./names.js";
|
|
38
37
|
import { builtinSpec } from "./builtins.js";
|
|
39
|
-
import { presentFact, leadingPresent, leadingIsArray, flattenOr, noneDetector,
|
|
38
|
+
import { presentFact, leadingPresent, leadingIsArray, flattenOr, noneDetector, bindPresentFact, freshPathBinder, binderHintForMapAccess, freshOcBinder, applyChain, restoreDiscriminantFlag, arrayBoundsCond, exprEqual, isArrayFact, typeofStringFact, variantFact, negVariantFact, presentMatchStmts, presentMatchExpr, } from "./condition-facts.js";
|
|
40
39
|
// ── Walkers ──────────────────────────────────────────────────
|
|
41
40
|
function walkExpr(e, ctx) {
|
|
42
41
|
const r = recurseExpr(e, ctx);
|
|
43
|
-
return ruleNullish(r, ctx) ?? ruleNullishIndex(r) ?? ruleOptChainIndex(r) ?? ruleOptChain(r, ctx) ?? ruleImplOptional(r, ctx) ?? ruleImplArrayIsArray(r, ctx) ?? ruleConditionalArrayIsArray(r, ctx) ?? ruleConditionalAndArrayIsArray(r, ctx) ?? ruleConditionalAndOptional(r, ctx) ?? ruleConditionalOptionalSimple(r) ?? ruleConditionalInMap(r, ctx) ?? ruleConditionalOptionalTruthy(r) ?? r;
|
|
42
|
+
return ruleNullish(r, ctx) ?? ruleNullishIndex(r) ?? ruleOptChainIndex(r) ?? ruleOptChain(r, ctx) ?? ruleImplOptional(r, ctx) ?? ruleImplArrayIsArray(r, ctx) ?? ruleConditionalArrayIsArray(r, ctx) ?? ruleConditionalAndArrayIsArray(r, ctx) ?? ruleConditionalAndOptional(r, ctx) ?? ruleConditionalOptionalSimple(r, ctx) ?? ruleConditionalInMap(r, ctx) ?? ruleConditionalOptionalTruthy(r, ctx) ?? r;
|
|
44
43
|
}
|
|
45
44
|
function recurseExpr(e, ctx) {
|
|
46
45
|
const re = (x) => walkExpr(x, ctx);
|
|
@@ -85,7 +84,7 @@ function walkStmt(s, ctx) {
|
|
|
85
84
|
// array rule fires; independent narrows commute, so the order is harmless.)
|
|
86
85
|
// && rules fire before the simple rule because they produce nested ifs whose
|
|
87
86
|
// inner shape doesn't match the simple rule directly.
|
|
88
|
-
return ruleIfAndOptional(r, ctx) ?? ruleIfAndArrayIsArray(r, ctx) ?? ruleIfOptionalSimple(r) ?? ruleExprStmtAndOptional(r, ctx) ?? ruleOptionalIndexBinding(r) ?? r;
|
|
87
|
+
return ruleIfAndOptional(r, ctx) ?? ruleIfAndArrayIsArray(r, ctx) ?? ruleIfOptionalSimple(r, ctx) ?? ruleExprStmtAndOptional(r, ctx) ?? ruleOptionalIndexBinding(r) ?? r;
|
|
89
88
|
}
|
|
90
89
|
function walkStmts(stmts, ctx) {
|
|
91
90
|
const result = [];
|
|
@@ -99,7 +98,7 @@ function walkStmts(stmts, ctx) {
|
|
|
99
98
|
i += tagged.consumed - 1;
|
|
100
99
|
continue;
|
|
101
100
|
}
|
|
102
|
-
const consumed = ruleEarlyReturnOrChain(s, rest, ctx) ?? ruleEarlyReturnConsume(s, rest) ?? ruleEarlyReturnOptChainCompare(s, rest, ctx);
|
|
101
|
+
const consumed = ruleEarlyReturnOrChain(s, rest, ctx) ?? ruleEarlyReturnConsume(s, rest, ctx) ?? ruleEarlyReturnOptChainCompare(s, rest, ctx);
|
|
103
102
|
if (consumed) {
|
|
104
103
|
result.push(walkStmt(consumed, ctx));
|
|
105
104
|
return result;
|
|
@@ -107,7 +106,7 @@ function walkStmts(stmts, ctx) {
|
|
|
107
106
|
// walkStmt first — narrow's expression rules may rewrite the let init from
|
|
108
107
|
// `conditional` to `someMatch`, in which case the let-cond desugar shouldn't fire.
|
|
109
108
|
const walked = walkStmt(s, ctx);
|
|
110
|
-
const expanded = ruleLetCondAndOptional(walked);
|
|
109
|
+
const expanded = ruleLetCondAndOptional(walked, ctx);
|
|
111
110
|
if (expanded) {
|
|
112
111
|
for (const x of expanded)
|
|
113
112
|
result.push(walkStmt(x, ctx));
|
|
@@ -159,7 +158,7 @@ function isTerminating(stmts) {
|
|
|
159
158
|
/** Driver: `if (e !== undefined) then else` — presence fact in if position.
|
|
160
159
|
* → `someMatch e { Some(_e_val) => then, None => else }`. Requires a
|
|
161
160
|
* non-empty Some branch. */
|
|
162
|
-
function ruleIfOptionalSimple(s) {
|
|
161
|
+
function ruleIfOptionalSimple(s, ctx) {
|
|
163
162
|
if (s.kind !== "if")
|
|
164
163
|
return null;
|
|
165
164
|
const check = presentFact(s.cond);
|
|
@@ -169,12 +168,12 @@ function ruleIfOptionalSimple(s) {
|
|
|
169
168
|
const noneBody = check.negated ? s.then : s.else;
|
|
170
169
|
if (someBody.length === 0)
|
|
171
170
|
return null;
|
|
172
|
-
return presentMatchStmts(check, someBody, noneBody);
|
|
171
|
+
return presentMatchStmts(check, someBody, noneBody, ctx);
|
|
173
172
|
}
|
|
174
173
|
/** Driver: `if (e === undefined) terminate; rest` — presence fact in
|
|
175
174
|
* early-return position, consuming the rest of the block into the
|
|
176
175
|
* narrowed scope. Fires when the Some branch is empty. */
|
|
177
|
-
function ruleEarlyReturnConsume(s, rest) {
|
|
176
|
+
function ruleEarlyReturnConsume(s, rest, ctx) {
|
|
178
177
|
if (s.kind !== "if")
|
|
179
178
|
return null;
|
|
180
179
|
if (rest.length === 0)
|
|
@@ -188,7 +187,7 @@ function ruleEarlyReturnConsume(s, rest) {
|
|
|
188
187
|
return null;
|
|
189
188
|
if (!isTerminating(noneBranch))
|
|
190
189
|
return null;
|
|
191
|
-
return presentMatchStmts(check, rest, noneBranch);
|
|
190
|
+
return presentMatchStmts(check, rest, noneBranch, ctx);
|
|
192
191
|
}
|
|
193
192
|
/** Driver: `if (D1 || … || Dn) terminate; rest` — De-Morgan position. Each `Di`
|
|
194
193
|
* that detects some optional `x` is None (`!x`, `x === undefined`,
|
|
@@ -217,7 +216,7 @@ function ruleEarlyReturnOrChain(s, rest, ctx) {
|
|
|
217
216
|
residualLeaves.push(leaf);
|
|
218
217
|
continue;
|
|
219
218
|
}
|
|
220
|
-
const key =
|
|
219
|
+
const key = d.binder; // memoized by full path, not by the ambiguous hint
|
|
221
220
|
if (seen.has(key))
|
|
222
221
|
return null; // two detectors on one optional: rare; leave to other rules
|
|
223
222
|
seen.add(key);
|
|
@@ -259,10 +258,9 @@ function ruleEarlyReturnOptChainCompare(s, rest, ctx) {
|
|
|
259
258
|
return null;
|
|
260
259
|
const lit = c.left === oc ? c.right : c.left;
|
|
261
260
|
const innerTy = oc.obj.ty.inner;
|
|
262
|
-
const
|
|
263
|
-
if (
|
|
261
|
+
const binder = freshPathBinder(oc.obj, ctx);
|
|
262
|
+
if (binder === null)
|
|
264
263
|
return null;
|
|
265
|
-
const binder = freshName(hint);
|
|
266
264
|
const binderVar = { kind: "var", name: binder, ty: innerTy };
|
|
267
265
|
const unwrapped = applyChain(binderVar, oc.chain);
|
|
268
266
|
restoreDiscriminantFlag(unwrapped, ctx.decls);
|
|
@@ -276,7 +274,7 @@ function ruleEarlyReturnOptChainCompare(s, rest, ctx) {
|
|
|
276
274
|
}
|
|
277
275
|
/** Driver (expression): `e !== undefined ? a : b` — presence fact in
|
|
278
276
|
* ternary position. */
|
|
279
|
-
function ruleConditionalOptionalSimple(e) {
|
|
277
|
+
function ruleConditionalOptionalSimple(e, ctx) {
|
|
280
278
|
if (e.kind !== "conditional")
|
|
281
279
|
return null;
|
|
282
280
|
const check = presentFact(e.cond);
|
|
@@ -284,7 +282,7 @@ function ruleConditionalOptionalSimple(e) {
|
|
|
284
282
|
return null;
|
|
285
283
|
const someBody = check.negated ? e.else : e.then;
|
|
286
284
|
const noneBody = check.negated ? e.then : e.else;
|
|
287
|
-
return presentMatchExpr(check, someBody, noneBody, e.ty);
|
|
285
|
+
return presentMatchExpr(check, someBody, noneBody, e.ty, ctx);
|
|
288
286
|
}
|
|
289
287
|
/** Driver (expression): `(path !== undefined [&& rest]) ==> B` — presence
|
|
290
288
|
* fact in implication position (spec premises). The premise's optional
|
|
@@ -312,6 +310,7 @@ function ruleImplOptional(e, ctx) {
|
|
|
312
310
|
const innerBody = restCond
|
|
313
311
|
? { kind: "binop", op: "==>", left: restCond, right: e.right, ty: { kind: "bool" } }
|
|
314
312
|
: e.right;
|
|
313
|
+
check = bindPresentFact(check, ctx);
|
|
315
314
|
return {
|
|
316
315
|
kind: "someMatch",
|
|
317
316
|
scrutinee: check.scrutinee, binderTy: check.innerTy,
|
|
@@ -457,15 +456,14 @@ function ruleConditionalInMap(e, ctx) {
|
|
|
457
456
|
/** Driver (expression): `opt ? a : b` (truthiness — cond itself is optional).
|
|
458
457
|
* Only fires for simple var or simple `obj.field` cond. Historical shape:
|
|
459
458
|
* no falsy gate on the bound value (unlike the other truthiness positions). */
|
|
460
|
-
function ruleConditionalOptionalTruthy(e) {
|
|
459
|
+
function ruleConditionalOptionalTruthy(e, ctx) {
|
|
461
460
|
if (e.kind !== "conditional")
|
|
462
461
|
return null;
|
|
463
462
|
if (e.cond.ty.kind !== "optional")
|
|
464
463
|
return null;
|
|
465
|
-
const
|
|
466
|
-
if (
|
|
464
|
+
const binder = freshPathBinder(e.cond, ctx);
|
|
465
|
+
if (binder === null)
|
|
467
466
|
return null;
|
|
468
|
-
const binder = freshName(hint);
|
|
469
467
|
return {
|
|
470
468
|
kind: "someMatch",
|
|
471
469
|
scrutinee: e.cond, binderTy: e.cond.ty.inner,
|
|
@@ -488,7 +486,7 @@ function ruleIfAndOptional(s, ctx) {
|
|
|
488
486
|
return null;
|
|
489
487
|
const { check, restCond } = extracted;
|
|
490
488
|
const innerIf = { kind: "if", cond: restCond, then: s.then, else: [] };
|
|
491
|
-
return presentMatchStmts(check, [walkStmt(innerIf, ctx)], []);
|
|
489
|
+
return presentMatchStmts(check, [walkStmt(innerIf, ctx)], [], ctx);
|
|
492
490
|
}
|
|
493
491
|
/** Driver: a bare expression statement `x !== undefined && rest` (the
|
|
494
492
|
* `if`-less guard idiom, TS-equivalent to `if (x !== undefined) rest;`).
|
|
@@ -507,14 +505,14 @@ function ruleExprStmtAndOptional(s, ctx) {
|
|
|
507
505
|
return null;
|
|
508
506
|
const { check, restCond } = extracted;
|
|
509
507
|
const innerStmt = { kind: "expr", expr: restCond };
|
|
510
|
-
return presentMatchStmts(check, [walkStmt(innerStmt, ctx)], []);
|
|
508
|
+
return presentMatchStmts(check, [walkStmt(innerStmt, ctx)], [], ctx);
|
|
511
509
|
}
|
|
512
510
|
/** Driver (statement): `let x = (e_opt && rest) ? a : b` — presence fact in
|
|
513
511
|
* conditional-initializer position, where rest may contain method calls.
|
|
514
512
|
* → `var x: T := b; someMatch e_opt { Some(_v) => { if rest { x := a } } }`.
|
|
515
513
|
* Statement-level form is needed because Dafny doesn't allow method calls
|
|
516
514
|
* inside match expression arms. */
|
|
517
|
-
function ruleLetCondAndOptional(s) {
|
|
515
|
+
function ruleLetCondAndOptional(s, ctx) {
|
|
518
516
|
if (s.kind !== "let" || s.mutable)
|
|
519
517
|
return null;
|
|
520
518
|
if (s.init.kind !== "conditional")
|
|
@@ -527,7 +525,7 @@ function ruleLetCondAndOptional(s) {
|
|
|
527
525
|
then: [{ kind: "assign", target: s.name, value: s.init.then }], else: [] };
|
|
528
526
|
return [
|
|
529
527
|
{ kind: "let", name: s.name, ty: s.ty, mutable: true, init: s.init.else },
|
|
530
|
-
presentMatchStmts(check, [assignIf], []),
|
|
528
|
+
presentMatchStmts(check, [assignIf], [], ctx),
|
|
531
529
|
];
|
|
532
530
|
}
|
|
533
531
|
/** Does this expression contain a method call that would be lifted to a
|
|
@@ -593,7 +591,7 @@ function ruleConditionalAndOptional(e, ctx) {
|
|
|
593
591
|
kind: "conditional",
|
|
594
592
|
cond: restCond, then: e.then, else: e.else, ty: e.ty,
|
|
595
593
|
};
|
|
596
|
-
return presentMatchExpr(check, walkExpr(innerCond, ctx), e.else, e.ty);
|
|
594
|
+
return presentMatchExpr(check, walkExpr(innerCond, ctx), e.else, e.ty, ctx);
|
|
597
595
|
}
|
|
598
596
|
// ── Variant drivers (discriminants and synth array-unions) ──
|
|
599
597
|
/** Driver (expression): `Array.isArray(x) ==> B` or `!Array.isArray(x) ==> B` —
|
|
@@ -637,15 +635,14 @@ function ruleConditionalArrayIsArray(e, ctx) {
|
|
|
637
635
|
const matched = pos ?? tof ?? (neg ? { scrutinee: neg.scrutinee, typeName: neg.typeName, variant: "NonArrayBranch" } : null);
|
|
638
636
|
if (!matched)
|
|
639
637
|
return null;
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
const elseBody = positive ? e.else : e.then;
|
|
638
|
+
// The selected variant already accounts for negation. Its arm always runs
|
|
639
|
+
// the source then-branch; swapping branches here would negate the test twice.
|
|
643
640
|
return {
|
|
644
641
|
kind: "tagMatch",
|
|
645
642
|
scrutinee: matched.scrutinee,
|
|
646
643
|
typeName: matched.typeName,
|
|
647
|
-
cases: [{ variant: matched.variant, body: walkExpr(
|
|
648
|
-
fallthrough: walkExpr(
|
|
644
|
+
cases: [{ variant: matched.variant, body: walkExpr(e.then, ctx) }],
|
|
645
|
+
fallthrough: walkExpr(e.else, ctx),
|
|
649
646
|
ty: e.ty,
|
|
650
647
|
};
|
|
651
648
|
}
|
|
@@ -766,12 +763,17 @@ function ruleDiscriminantNegEarlyReturn(stmts, ctx) {
|
|
|
766
763
|
}
|
|
767
764
|
// ── Function / module entry ──────────────────────────────────
|
|
768
765
|
function narrowFunction(fn, ctx) {
|
|
766
|
+
// Contracts and the body bind their payloads in separate generated scopes.
|
|
767
|
+
// Do not reserve a body's names because of a contract's \result (or another
|
|
768
|
+
// function's paths). Keep the shared counter's traversal order unchanged.
|
|
769
|
+
const specCtx = { decls: ctx.decls, oc: ctx.oc };
|
|
770
|
+
const bodyCtx = { decls: ctx.decls, oc: ctx.oc };
|
|
769
771
|
return {
|
|
770
772
|
...fn,
|
|
771
|
-
requires: fn.requires.map(e => walkExpr(e,
|
|
772
|
-
ensures: fn.ensures.map(e => walkExpr(e,
|
|
773
|
-
decreases: fn.decreases ? walkExpr(fn.decreases,
|
|
774
|
-
body: walkStmts(fn.body,
|
|
773
|
+
requires: fn.requires.map(e => walkExpr(e, specCtx)),
|
|
774
|
+
ensures: fn.ensures.map(e => walkExpr(e, specCtx)),
|
|
775
|
+
decreases: fn.decreases ? walkExpr(fn.decreases, specCtx) : null,
|
|
776
|
+
body: walkStmts(fn.body, bodyCtx),
|
|
775
777
|
};
|
|
776
778
|
}
|
|
777
779
|
export function narrowModule(mod) {
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Run log: record each Dafny `lsc check` / `lsc regen` run in
|
|
3
|
+
* `.lemmascript/runs.jsonl` (a run where Dafny is not installed records
|
|
4
|
+
* nothing), with a snapshot of the source, so that a later
|
|
5
|
+
* report can tell which failures were fixed and whether the fix changed the
|
|
6
|
+
* program or only the proof, and read the records back for that report.
|
|
7
|
+
* Logging must never change lsc's output or exit code, so every filesystem
|
|
8
|
+
* step is best-effort and swallows its own errors.
|
|
9
|
+
*/
|
|
10
|
+
import { createHash, randomUUID } from "crypto";
|
|
11
|
+
import { appendFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "fs";
|
|
12
|
+
import { tmpdir } from "os";
|
|
13
|
+
import path from "path";
|
|
14
|
+
import { findUp } from "./config.js";
|
|
15
|
+
export const RUN_LOG_SCHEMA_VERSION = 1;
|
|
16
|
+
/**
|
|
17
|
+
* Combine the `run-log` option with the `LSC_RUN_LOG` value lsc.ts read:
|
|
18
|
+
* `false` turns logging off for one run; `true` or unset leaves it to the
|
|
19
|
+
* config. Like lemmascript.json, any other value is an error.
|
|
20
|
+
*/
|
|
21
|
+
export function runLogEnabled(option, value) {
|
|
22
|
+
if (value === undefined || value === "" || value === "true")
|
|
23
|
+
return option;
|
|
24
|
+
if (value === "false")
|
|
25
|
+
return false;
|
|
26
|
+
throw new Error(`LSC_RUN_LOG must be true or false (got ${JSON.stringify(value)})`);
|
|
27
|
+
}
|
|
28
|
+
/** The selected lemmascript.json's directory, else LemmaScript-files.txt's, else the source's git root, else cwd. */
|
|
29
|
+
export function resolveLogDir(sourcePath, configFile) {
|
|
30
|
+
if (configFile)
|
|
31
|
+
return path.dirname(path.resolve(configFile));
|
|
32
|
+
const manifest = findUp("LemmaScript-files.txt", sourcePath);
|
|
33
|
+
if (manifest)
|
|
34
|
+
return path.dirname(manifest);
|
|
35
|
+
const git = findUp(".git", sourcePath);
|
|
36
|
+
return git ? path.dirname(git) : process.cwd();
|
|
37
|
+
}
|
|
38
|
+
/** A filtered Dafny run verifies only some members, so absences mean nothing. */
|
|
39
|
+
export function isPartialRun(extraFlags) {
|
|
40
|
+
return /--filter-(symbol|position)\b/.test(extraFlags ?? "");
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Parse Dafny's `--log-format text` file. Each member gets one entry per
|
|
44
|
+
* check (`correctness`, `well-formedness`); it passes only if every check's
|
|
45
|
+
* outcome is `Correct`.
|
|
46
|
+
*/
|
|
47
|
+
export function parseTextLog(text) {
|
|
48
|
+
const seen = new Set();
|
|
49
|
+
const failed = new Set();
|
|
50
|
+
for (const m of text.matchAll(/^Results for (.+?) \([a-z-]+\)\r?\n\s+Overall outcome: (\S+)/gm)) {
|
|
51
|
+
seen.add(m[1]);
|
|
52
|
+
if (m[2] !== "Correct")
|
|
53
|
+
failed.add(m[1]);
|
|
54
|
+
}
|
|
55
|
+
return {
|
|
56
|
+
passed: [...seen].filter(name => !failed.has(name)).sort(),
|
|
57
|
+
failed: [...failed].sort(),
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Whether a parsed log line is a verify record of this schema with every field
|
|
62
|
+
* reading it relies on, so a hand-edited line is skipped rather than misread.
|
|
63
|
+
*/
|
|
64
|
+
function isVerifyRecord(r) {
|
|
65
|
+
const names = (x) => Array.isArray(x) && x.every(m => typeof m === "string");
|
|
66
|
+
const hash = (x) => x === null || typeof x === "string";
|
|
67
|
+
return r?.type === "verify" && r.v === RUN_LOG_SCHEMA_VERSION
|
|
68
|
+
&& typeof r.id === "string" && typeof r.file === "string"
|
|
69
|
+
&& typeof r.ts === "string" && !Number.isNaN(Date.parse(r.ts))
|
|
70
|
+
&& typeof r.partial === "boolean" && names(r.failed) && names(r.passed)
|
|
71
|
+
&& hash(r.tsHash) && hash(r.dfyHash);
|
|
72
|
+
}
|
|
73
|
+
/** First 12 hex characters of the SHA-256 of `text`. */
|
|
74
|
+
export function hashText(text) {
|
|
75
|
+
return createHash("sha256").update(text).digest("hex").slice(0, 12);
|
|
76
|
+
}
|
|
77
|
+
export function safely(fn) {
|
|
78
|
+
try {
|
|
79
|
+
return fn();
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
/** Create `<logDir>/.lemmascript/` with a `.gitignore` that ignores the whole directory. */
|
|
86
|
+
export function ensureLogDir(logDir) {
|
|
87
|
+
const dir = path.join(logDir, ".lemmascript");
|
|
88
|
+
mkdirSync(path.join(dir, "blobs"), { recursive: true });
|
|
89
|
+
const ignore = path.join(dir, ".gitignore");
|
|
90
|
+
if (!existsSync(ignore))
|
|
91
|
+
writeFileSync(ignore, "*\n");
|
|
92
|
+
return dir;
|
|
93
|
+
}
|
|
94
|
+
/** Store the source as `blobs/<hash>.ts` unless that version is already there. */
|
|
95
|
+
export function snapshotSource(dir, text) {
|
|
96
|
+
const hash = hashText(text);
|
|
97
|
+
const blob = path.join(dir, "blobs", `${hash}.ts`);
|
|
98
|
+
if (!existsSync(blob))
|
|
99
|
+
writeFileSync(blob, text);
|
|
100
|
+
return hash;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* The `verify` records in `<logDir>/.lemmascript/runs.jsonl`, in file order.
|
|
104
|
+
* Skips lines that don't parse (such as a half-written last line), other
|
|
105
|
+
* record types, other schema versions and records missing a field or
|
|
106
|
+
* holding one of the wrong type; a missing log has no records.
|
|
107
|
+
*/
|
|
108
|
+
export function readRecords(logDir) {
|
|
109
|
+
const text = safely(() => readFileSync(path.join(logDir, ".lemmascript", "runs.jsonl"), "utf8")) ?? "";
|
|
110
|
+
const records = [];
|
|
111
|
+
for (const line of text.split("\n")) {
|
|
112
|
+
const r = safely(() => JSON.parse(line));
|
|
113
|
+
if (isVerifyRecord(r))
|
|
114
|
+
records.push(r);
|
|
115
|
+
}
|
|
116
|
+
return records;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* One verification run. `lsc.ts` creates it before generating and passes it to
|
|
120
|
+
* the Dafny helpers; whichever helper sees how the run ended calls `finish`, or
|
|
121
|
+
* `discard` when nothing was verified. Only the first of these calls counts.
|
|
122
|
+
*/
|
|
123
|
+
export class RunLog {
|
|
124
|
+
init;
|
|
125
|
+
dir;
|
|
126
|
+
tsHash;
|
|
127
|
+
startedAt = new Date().toISOString();
|
|
128
|
+
textLogDir = null;
|
|
129
|
+
done = false;
|
|
130
|
+
constructor(init) {
|
|
131
|
+
this.init = init;
|
|
132
|
+
this.dir = safely(() => ensureLogDir(init.logDir));
|
|
133
|
+
this.tsHash = this.dir === null ? null
|
|
134
|
+
: safely(() => snapshotSource(this.dir, readFileSync(init.sourcePath, "utf8")));
|
|
135
|
+
}
|
|
136
|
+
/** Extra Dafny arguments that write member outcomes to a temporary text log. */
|
|
137
|
+
dafnyArgs() {
|
|
138
|
+
this.textLogDir = safely(() => mkdtempSync(path.join(tmpdir(), "lsc-run-log-")));
|
|
139
|
+
return this.textLogDir === null ? [] : ["--log-format", `text;LogFileName=${this.textLogPath()}`];
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Member outcomes from Dafny's text log, or null when it names no members:
|
|
143
|
+
* Dafny writes no file for a parse error and an empty one for a resolution error.
|
|
144
|
+
*/
|
|
145
|
+
readResults() {
|
|
146
|
+
if (this.textLogDir === null)
|
|
147
|
+
return null;
|
|
148
|
+
const results = safely(() => parseTextLog(readFileSync(this.textLogPath(), "utf8")));
|
|
149
|
+
return results && results.passed.length + results.failed.length > 0 ? results : null;
|
|
150
|
+
}
|
|
151
|
+
/** Append this run's record. Never throws; only the first call writes. */
|
|
152
|
+
finish(outcome) {
|
|
153
|
+
if (this.done)
|
|
154
|
+
return;
|
|
155
|
+
this.done = true;
|
|
156
|
+
const dir = this.dir;
|
|
157
|
+
if (dir !== null) {
|
|
158
|
+
safely(() => {
|
|
159
|
+
const results = outcome.results ?? null;
|
|
160
|
+
const record = {
|
|
161
|
+
v: RUN_LOG_SCHEMA_VERSION,
|
|
162
|
+
type: "verify",
|
|
163
|
+
id: randomUUID(),
|
|
164
|
+
ts: this.startedAt,
|
|
165
|
+
cmd: this.init.cmd,
|
|
166
|
+
file: path.relative(this.init.logDir, this.init.sourcePath).split(path.sep).join("/"),
|
|
167
|
+
stage: outcome.stage,
|
|
168
|
+
exit: outcome.exit,
|
|
169
|
+
partial: results === null || isPartialRun(this.init.extraFlags),
|
|
170
|
+
failed: results?.failed ?? [],
|
|
171
|
+
passed: results?.passed ?? [],
|
|
172
|
+
tsHash: this.tsHash,
|
|
173
|
+
dfyHash: safely(() => hashText(readFileSync(outcome.dfyPath, "utf8"))),
|
|
174
|
+
lsc: this.init.lscVersion,
|
|
175
|
+
};
|
|
176
|
+
appendFileSync(path.join(dir, "runs.jsonl"), JSON.stringify(record) + "\n");
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
this.removeTextLogDir();
|
|
180
|
+
}
|
|
181
|
+
/** End the run without a record, because nothing was verified (for example, no Dafny). */
|
|
182
|
+
discard() {
|
|
183
|
+
if (this.done)
|
|
184
|
+
return;
|
|
185
|
+
this.done = true;
|
|
186
|
+
this.removeTextLogDir();
|
|
187
|
+
}
|
|
188
|
+
textLogPath() {
|
|
189
|
+
return path.join(this.textLogDir, "verify.txt");
|
|
190
|
+
}
|
|
191
|
+
removeTextLogDir() {
|
|
192
|
+
if (this.textLogDir === null)
|
|
193
|
+
return;
|
|
194
|
+
const tmp = this.textLogDir;
|
|
195
|
+
safely(() => rmSync(tmp, { recursive: true, force: true }));
|
|
196
|
+
}
|
|
197
|
+
}
|