lemmascript 0.6.4 → 0.6.5
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/config.js +32 -10
- package/tools/dist/dafny-commands.js +102 -17
- package/tools/dist/dafny-emit.js +121 -24
- package/tools/dist/extract.js +44 -5
- package/tools/dist/lean-emit.js +27 -18
- package/tools/dist/lsc.js +56 -4
- package/tools/dist/run-log.js +197 -0
- package/tools/dist/runs-command.js +377 -0
- package/tools/dist/transform.js +1 -2
package/tools/dist/extract.js
CHANGED
|
@@ -55,6 +55,8 @@ let _currentSourceFile = null;
|
|
|
55
55
|
let _inFunctionExtraction = false;
|
|
56
56
|
/** Effective options for the current extraction. Reset at extractModule entry. */
|
|
57
57
|
let _extractOptions = DEFAULT_OPTIONS;
|
|
58
|
+
/** The CLI validates source options before copying a cross-file contract. */
|
|
59
|
+
let _validateDependency = () => { };
|
|
58
60
|
/** Counter for synthetic names used by let-statement array destructuring
|
|
59
61
|
* when the initializer isn't a bare variable (single-eval temp). */
|
|
60
62
|
let _destrCounter = 0;
|
|
@@ -121,6 +123,8 @@ function detectCrossFileExtern(callee, sourceFile, sigTypesOut) {
|
|
|
121
123
|
const sig = callee.getType().getCallSignatures()[0];
|
|
122
124
|
if (!sig)
|
|
123
125
|
return null;
|
|
126
|
+
// Includes global declarations selected by TypeScript without an import edge.
|
|
127
|
+
_validateDependency(externalDecl.getSourceFile());
|
|
124
128
|
// Generic type parameters (e.g. `step<S, A>`). ts-morph reports param/return
|
|
125
129
|
// types in the callee's own type-parameter namespace, so these names match
|
|
126
130
|
// what `params`/`returnType` reference — declare them on the emitted axiom.
|
|
@@ -381,22 +385,22 @@ function extractExpr(node) {
|
|
|
381
385
|
// Always push the head, even when empty: a leading string literal anchors the
|
|
382
386
|
// whole chain as string-typed so each interpolated value is stringified (not
|
|
383
387
|
// added numerically — `${a}${b}` is concatenation, not `a + b`).
|
|
384
|
-
parts.push(
|
|
388
|
+
parts.push(stringLiteral(node.getHead().getLiteralText(), node));
|
|
385
389
|
for (const span of node.getTemplateSpans()) {
|
|
386
390
|
parts.push(extractExpr(span.getExpression()));
|
|
387
391
|
const text = span.getLiteral().getLiteralText();
|
|
388
392
|
if (text)
|
|
389
|
-
parts.push(
|
|
393
|
+
parts.push(stringLiteral(text, span));
|
|
390
394
|
}
|
|
391
395
|
return parts.reduce((left, right) => ({ kind: "binop", op: "+", left, right }));
|
|
392
396
|
}
|
|
393
397
|
// No-substitution template literal: `hello` → "hello"
|
|
394
398
|
if (Node.isNoSubstitutionTemplateLiteral(node)) {
|
|
395
|
-
return
|
|
399
|
+
return stringLiteral(node.getLiteralText(), node);
|
|
396
400
|
}
|
|
397
401
|
// String literal
|
|
398
402
|
if (Node.isStringLiteral(node)) {
|
|
399
|
-
return
|
|
403
|
+
return stringLiteral(node.getLiteralValue(), node);
|
|
400
404
|
}
|
|
401
405
|
// Boolean literals: true, false
|
|
402
406
|
if (Node.isTrueLiteral(node))
|
|
@@ -811,6 +815,40 @@ function hasExternModeAnnotation(node, keyword, parentStmt) {
|
|
|
811
815
|
return !!statement && statement.getLeadingCommentRanges()
|
|
812
816
|
.some(r => r.getText().trim() === `//@ ${keyword}`);
|
|
813
817
|
}
|
|
818
|
+
/** The first lone surrogate code unit in `value`, or -1. */
|
|
819
|
+
function findLoneSurrogate(value) {
|
|
820
|
+
for (let i = 0; i < value.length; i++) {
|
|
821
|
+
const unit = value.charCodeAt(i);
|
|
822
|
+
if (unit >= 0xD800 && unit <= 0xDBFF) {
|
|
823
|
+
const next = value.charCodeAt(i + 1);
|
|
824
|
+
if (next >= 0xDC00 && next <= 0xDFFF) {
|
|
825
|
+
i++;
|
|
826
|
+
continue;
|
|
827
|
+
}
|
|
828
|
+
return unit;
|
|
829
|
+
}
|
|
830
|
+
if (unit >= 0xDC00 && unit <= 0xDFFF)
|
|
831
|
+
return unit;
|
|
832
|
+
}
|
|
833
|
+
return -1;
|
|
834
|
+
}
|
|
835
|
+
/** A source string literal, admitted only if the selected string profile can
|
|
836
|
+
* represent it (DESIGN_STRINGS.md §3). Under `unicode-scalar` a lone surrogate
|
|
837
|
+
* has no Dafny value — and Node's UTF-8 writer would silently replace it on
|
|
838
|
+
* the way out — so it is refused here with the source line instead. */
|
|
839
|
+
function stringLiteral(value, node) {
|
|
840
|
+
if (_extractOptions["string-semantics"] === "unicode-scalar") {
|
|
841
|
+
const lone = findLoneSurrogate(value);
|
|
842
|
+
if (lone >= 0) {
|
|
843
|
+
const file = node.getSourceFile();
|
|
844
|
+
const { line } = file.getLineAndColumnAtPos(node.getStart());
|
|
845
|
+
throw new Error(`${file.getFilePath()}:${line}: string literal contains an unpaired surrogate ` +
|
|
846
|
+
`U+${lone.toString(16).toUpperCase()}, which "string-semantics": "unicode-scalar" cannot ` +
|
|
847
|
+
`represent; select string-semantics=javascript-utf16 and dafny-library=local in lemmascript.json or //@ option directives`);
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
return { kind: "str", value };
|
|
851
|
+
}
|
|
814
852
|
function externIsImpure(node, name, parentStmt) {
|
|
815
853
|
const pure = hasExternModeAnnotation(node, "pure", parentStmt);
|
|
816
854
|
const impure = hasExternModeAnnotation(node, "impure", parentStmt);
|
|
@@ -2066,8 +2104,9 @@ function extractFunctionInner(fn, parentAnnotations) {
|
|
|
2066
2104
|
};
|
|
2067
2105
|
}
|
|
2068
2106
|
// ── Module extraction ────────────────────────────────────────
|
|
2069
|
-
export function extractModule(sourceFile, options = DEFAULT_OPTIONS) {
|
|
2107
|
+
export function extractModule(sourceFile, options = DEFAULT_OPTIONS, validateDependency = () => { }) {
|
|
2070
2108
|
_extractOptions = options;
|
|
2109
|
+
_validateDependency = validateDependency;
|
|
2071
2110
|
// Seed the fresh-name check (names.ts) before anything mints: every
|
|
2072
2111
|
// Identifier token in the module, a deliberate over-approximation.
|
|
2073
2112
|
setUserNames(new Set(sourceFile.getDescendantsOfKind(SyntaxKind.Identifier).map(i => i.getText())));
|
package/tools/dist/lean-emit.js
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* and support-import selection.
|
|
6
6
|
*/
|
|
7
7
|
import { anyExpr, usesNameInDecl, patternBinders } from "./ir.js";
|
|
8
|
-
import { freshNameWhere } from "./names.js";
|
|
8
|
+
import { freshName, freshNameWhere } from "./names.js";
|
|
9
9
|
// ── Ty → Lean type string ──────────────────────────────────
|
|
10
10
|
function tyToLean(ty) {
|
|
11
11
|
switch (ty.kind) {
|
|
@@ -90,9 +90,11 @@ const LEAN_KEYWORDS = new Set([
|
|
|
90
90
|
// `res`, but primed (e.g. `res'`) when a module identifier is named `res` — set
|
|
91
91
|
// by the method case. `\result` in an ensures/body must use the same name.
|
|
92
92
|
let _resultName = "res";
|
|
93
|
+
let _invariantIndex = 0;
|
|
94
|
+
let _rangeIndex = 0;
|
|
93
95
|
function escapeName(name) {
|
|
94
96
|
// \result is carried through the IR as the var name "\\result"; render it
|
|
95
|
-
// as the method's return-value identifier (matches `
|
|
97
|
+
// as the method's return-value identifier (matches `returns (res : T)`).
|
|
96
98
|
if (name === "\\result")
|
|
97
99
|
return _resultName;
|
|
98
100
|
return LEAN_KEYWORDS.has(name) ? `«${name}»` : name;
|
|
@@ -351,8 +353,8 @@ function emitExpr(e, parentPrec) {
|
|
|
351
353
|
const twos = ".2".repeat(e.index);
|
|
352
354
|
return e.index === e.arity - 1 ? `${obj}${twos}` : `${obj}${twos}.1`;
|
|
353
355
|
}
|
|
354
|
-
case "emptyMap": return
|
|
355
|
-
case "emptySet": return
|
|
356
|
+
case "emptyMap": return `∅`;
|
|
357
|
+
case "emptySet": return `∅`;
|
|
356
358
|
case "default": return `(default : ${tyToLean(e.type)})`;
|
|
357
359
|
case "methodCall": {
|
|
358
360
|
const obj = emitExpr(e.obj);
|
|
@@ -671,26 +673,33 @@ function emitStmt(s, indent) {
|
|
|
671
673
|
const prevBoolCtx = _boolCtx;
|
|
672
674
|
_boolCtx = false;
|
|
673
675
|
for (const inv of s.invariants)
|
|
674
|
-
lines.push(`${pad} invariant ${emitExpr(inv)}`);
|
|
675
|
-
// `done_with True` (the auto-supplied fact for breaking loops) is a Prop;
|
|
676
|
-
// the bool literal would need a coercion, so emit the Prop `True` directly.
|
|
677
|
-
if (s.doneWith)
|
|
678
|
-
lines.push(`${pad} done_with ${s.doneWith.kind === "bool" && s.doneWith.value ? "True" : emitExpr(s.doneWith)}`);
|
|
676
|
+
lines.push(`${pad} invariant invariant_${++_invariantIndex}: (${emitExpr(inv)} : Prop)`);
|
|
679
677
|
if (s.decreasing)
|
|
680
678
|
lines.push(`${pad} decreasing ${emitExpr(s.decreasing)}`);
|
|
679
|
+
if (s.doneWith)
|
|
680
|
+
lines.push(`${pad} done_with (${emitExpr(s.doneWith)} : Prop)`);
|
|
681
681
|
_boolCtx = prevBoolCtx;
|
|
682
682
|
lines.push(`${pad}do`);
|
|
683
683
|
lines.push(emitStmts(s.body, indent + 1));
|
|
684
684
|
return lines.join("\n");
|
|
685
685
|
}
|
|
686
686
|
case "forin": {
|
|
687
|
-
|
|
687
|
+
// Velvet 2 needs an explicit exit assertion when invariants use the cursor.
|
|
688
|
+
// Preserve the range endpoint used by the old rule, including on `break`.
|
|
689
|
+
const stop = freshName(`_rangeStop${_rangeIndex++}`);
|
|
690
|
+
const idx = escapeName(s.idx);
|
|
691
|
+
const lines = [`${pad}let ${stop} : Nat := ${emitExpr(s.bound)}`,
|
|
692
|
+
`${pad}for ${idx} in [:${stop}]`];
|
|
688
693
|
const prevBoolCtx = _boolCtx;
|
|
689
|
-
_boolCtx = false;
|
|
690
|
-
|
|
691
|
-
|
|
694
|
+
_boolCtx = false;
|
|
695
|
+
const invariants = s.invariants.map(inv => `(${emitExpr(inv)} : Prop)`);
|
|
696
|
+
for (const inv of invariants)
|
|
697
|
+
lines.push(`${pad} invariant invariant_${++_invariantIndex}: ${inv}`);
|
|
698
|
+
if (invariants.length > 0)
|
|
699
|
+
lines.push(`${pad} done_with (let ${idx} : Nat := ${stop}; ${invariants.join(" ∧ ")})`);
|
|
692
700
|
_boolCtx = prevBoolCtx;
|
|
693
701
|
lines.push(`${pad}do`);
|
|
702
|
+
lines.push(`${pad} let ${idx} : Nat := ${idx}`);
|
|
694
703
|
lines.push(emitStmts(s.body, indent + 1));
|
|
695
704
|
return lines.join("\n");
|
|
696
705
|
}
|
|
@@ -815,11 +824,11 @@ function emitDecl(d) {
|
|
|
815
824
|
// fields, unrelated params), so a module-wide check would prime spuriously.
|
|
816
825
|
_resultName = freshNameWhere("res", n => d.params.some(p => escapeName(p.name) === n) ||
|
|
817
826
|
usesNameInDecl(d.requires, d.ensures, d.body, n));
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
827
|
+
_invariantIndex = 0;
|
|
828
|
+
_rangeIndex = 0;
|
|
829
|
+
const lines = [`method ${d.name} ${params} returns (${_resultName} : ${tyToLean(d.returnType)})`];
|
|
830
|
+
d.requires.forEach((r, i) => lines.push(` requires require_${i + 1}: (${emitExpr(r)} : Prop)`));
|
|
831
|
+
d.ensures.forEach((e, i) => lines.push(` ensures ensures_${i + 1}: (${emitExpr(e)} : Prop)`));
|
|
823
832
|
lines.push(" do");
|
|
824
833
|
_boolCtx = true;
|
|
825
834
|
lines.push(emitStmts(d.body, 2));
|
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 } 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: 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;
|
|
@@ -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
|
+
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
|
+
}
|