lemmascript 0.6.3 → 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/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) {
@@ -114,8 +122,8 @@ function main() {
114
122
  extraFlags = args[extraFlagsIdx].split("=").slice(1).join("=");
115
123
  args.splice(extraFlagsIdx, 1);
116
124
  }
117
- // --slow (batch mode only): verify every entry with its own timeout instead
118
- // of degrading slow ones to gen-check.
125
+ // --slow (batch mode only): verify entries with long manifest timeouts
126
+ // instead of degrading them to gen-check.
119
127
  let slow = false;
120
128
  const slowIdx = args.indexOf("--slow");
121
129
  if (slowIdx >= 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
  }
@@ -167,7 +176,7 @@ function main() {
167
176
  return;
168
177
  }
169
178
  if (!filePath) {
170
- runBatch(cmd, backend, slow, configPath);
179
+ runBatch(cmd, backend, slow, timeLimit, extraFlags, configPath);
171
180
  return;
172
181
  }
173
182
  runFile(cmd, filePath, backend, timeLimit, extraFlags, noVerify, typedInfo, configPath);
@@ -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) {
@@ -213,22 +246,24 @@ function runConfig(filePath, configPath) {
213
246
  const artifactDir = resolveDafnyArtifactDir(sourcePath, configFile, options);
214
247
  console.log(JSON.stringify({ configFile, options, artifactDir }, null, 2));
215
248
  }
216
- // Batch over LemmaScript-files.txt. `check` entries with a timeout above 60s
217
- // (the CI limit) are gen-check only, unless --slow. Fail-fast: the first
218
- // failing entry exits. tools/check.sh drives this from source;
219
- // installed-package consumers run `lsc check`.
220
- function runBatch(cmd, backend, slow, configPath) {
249
+ // Batch over LemmaScript-files.txt. Without --slow or an explicit --time-limit,
250
+ // Dafny check entries with manifest timeouts above 60s run gen-check only.
251
+ // Fail-fast: the first failing entry exits.
252
+ function runBatch(cmd, backend, slow, timeLimit, extraFlags, configPath) {
221
253
  if (cmd !== "gen" && cmd !== "gen-check" && cmd !== "check") {
222
254
  console.error(`No file given, and batch mode supports gen|gen-check|check (not ${cmd}).`);
223
255
  process.exit(1);
224
256
  }
257
+ const verifySlow = slow || timeLimit !== undefined;
225
258
  for (const e of readEntries()) {
226
- if (cmd === "check" && backend === "dafny" && !slow && e.timeout !== undefined && e.timeout > 60) {
227
- console.log(`=== ${path.basename(e.file)} (timeout ${e.timeout}s > 60s, gen-check only) ===`);
259
+ const timeout = timeLimit ?? e.timeout;
260
+ const flags = extraFlags ?? e.flags;
261
+ if (cmd === "check" && backend === "dafny" && !verifySlow && timeout !== undefined && timeout > 60) {
262
+ console.log(`=== ${path.basename(e.file)} (timeout ${timeout}s > 60s, gen-check only) ===`);
228
263
  runFile("gen-check", e.file, backend, undefined, undefined, false, false, configPath);
229
264
  }
230
265
  else {
231
- runFile(cmd, e.file, backend, e.timeout, e.flags, false, false, configPath);
266
+ runFile(cmd, e.file, backend, timeout, flags, false, false, configPath);
232
267
  }
233
268
  }
234
269
  }
@@ -261,6 +296,8 @@ function runFile(cmd, filePath, backend, timeLimit, extraFlags, noVerify = false
261
296
  project.resolveSourceFileDependencies();
262
297
  const fullText = sourceFile.getFullText();
263
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);
264
301
  // Check //@ backend directive — skip if backend doesn't match.
265
302
  // `extract` and `info` are backend-neutral and always run.
266
303
  const backendDirective = fullText.match(/\/\/@ backend (\w+)/);
@@ -275,8 +312,12 @@ function runFile(cmd, filePath, backend, timeLimit, extraFlags, noVerify = false
275
312
  // both can be separate Lean libraries. Lean-only — Dafny is unaffected.
276
313
  const leanModuleDirective = fullText.match(/\/\/@ lean-module ([A-Za-z0-9_.\-]+)/);
277
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);
278
319
  // Extract: ts-morph → Raw IR
279
- const raw = extractModule(sourceFile, options);
320
+ const raw = extractModule(sourceFile, options, validateDependency);
280
321
  if (cmd === "extract") {
281
322
  console.log(JSON.stringify(raw, null, 2));
282
323
  return;
@@ -331,6 +372,12 @@ function runFile(cmd, filePath, backend, timeLimit, extraFlags, noVerify = false
331
372
  const basePath = path.join(artifactDir, `${base}.dfy.base`);
332
373
  guardRelocatedDafnyProof(dir, artifactDir, base, dfyPath);
333
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;
334
381
  if (cmd === "gen") {
335
382
  dafnyGen(genPath, dfyPath, text);
336
383
  return;
@@ -343,20 +390,27 @@ function runFile(cmd, filePath, backend, timeLimit, extraFlags, noVerify = false
343
390
  }
344
391
  if (cmd === "check") {
345
392
  dafnyGen(genPath, dfyPath, text);
346
- if (!dafnyCheckDiff(genPath, dfyPath))
393
+ if (!dafnyCheckDiff(genPath, dfyPath, log))
347
394
  process.exit(1);
348
- if (!dafnyVerify(dfyPath, artifactDir, timeLimit, extraFlags))
395
+ if (!dafnyVerify(dfyPath, artifactDir, timeLimit, extraFlags, log))
349
396
  process.exit(1);
350
397
  return;
351
398
  }
352
399
  if (cmd === "regen") {
353
- dafnyRegen(genPath, dfyPath, basePath, text, artifactDir, timeLimit, extraFlags, noVerify);
400
+ dafnyRegen(genPath, dfyPath, basePath, text, artifactDir, timeLimit, extraFlags, noVerify, log);
354
401
  return;
355
402
  }
356
403
  console.error(`Unknown command: ${cmd}`);
357
404
  process.exit(1);
358
405
  }
359
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
+ }
360
414
  const leanBase = leanModuleOverride ?? base;
361
415
  const specPath = path.join(dir, `${leanBase}.spec.lean`);
362
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
+ }