lemmascript 0.6.2 → 0.6.4

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lemmascript",
3
- "version": "0.6.2",
3
+ "version": "0.6.4",
4
4
  "description": "A verification toolchain for TypeScript — generates Lean 4 or Dafny from annotated TS",
5
5
  "type": "module",
6
6
  "engines": {
@@ -7,6 +7,7 @@
7
7
  */
8
8
  import { existsSync, readFileSync } from "fs";
9
9
  import path from "path";
10
+ import { ts } from "ts-morph";
10
11
  export const OPTION_SPECS = {
11
12
  "extern-default": {
12
13
  type: "enum",
@@ -74,41 +75,6 @@ export function validateOptions(raw, source) {
74
75
  }
75
76
  return out;
76
77
  }
77
- /** Last line in the leading-comment region. Directives after code are errors. */
78
- function leadingCommentLineCount(lines) {
79
- let inBlock = false;
80
- for (let i = 0; i < lines.length; i++) {
81
- let rest = lines[i];
82
- if (i === 0)
83
- rest = rest.replace(/^\uFEFF/, "");
84
- if (i === 0 && rest.startsWith("#!"))
85
- continue;
86
- while (true) {
87
- rest = rest.trimStart();
88
- if (inBlock) {
89
- const end = rest.indexOf("*/");
90
- if (end < 0)
91
- break;
92
- inBlock = false;
93
- rest = rest.slice(end + 2);
94
- continue;
95
- }
96
- if (rest.length === 0 || rest.startsWith("//"))
97
- break;
98
- if (rest.startsWith("/*")) {
99
- const end = rest.indexOf("*/", 2);
100
- if (end < 0) {
101
- inBlock = true;
102
- break;
103
- }
104
- rest = rest.slice(end + 2);
105
- continue;
106
- }
107
- return i;
108
- }
109
- }
110
- return lines.length;
111
- }
112
78
  function parseDirectiveValue(key, text, source) {
113
79
  const spec = OPTION_SPECS[key];
114
80
  if (spec.type === "boolean") {
@@ -122,10 +88,51 @@ function parseDirectiveValue(key, text, source) {
122
88
  // made file-overridable.
123
89
  return parseValue(key, text, source);
124
90
  }
91
+ /**
92
+ * Find comment lines, marking those that occur before any code.
93
+ *
94
+ * Use the parsed syntax tree to skip strings, regexes, and template text.
95
+ * Without those boundaries, the scanner can read /[/*]/ as a block comment
96
+ * or treat a template's closing backtick as the start of another template.
97
+ */
98
+ function* fileCommentLines(sourceText) {
99
+ // Normalize once so a leading BOM also works before a shebang.
100
+ sourceText = sourceText.replace(/^\uFEFF/, "");
101
+ const lines = sourceText.split(/\r\n|[\n\r\u2028\u2029]/);
102
+ const sourceFile = ts.createSourceFile("lemmascript-options.ts", sourceText, ts.ScriptTarget.Latest, false, ts.ScriptKind.TS);
103
+ const literalEnds = new Map();
104
+ const visit = (node) => {
105
+ if (ts.isStringLiteral(node) || ts.isRegularExpressionLiteral(node) || ts.isTemplateLiteralToken(node)) {
106
+ // Skip template text, keeping real comments inside ${...} visible.
107
+ // Missing recovery tokens must not send the scanner back to its start.
108
+ const start = node.getStart(sourceFile);
109
+ if (node.end > start)
110
+ literalEnds.set(start, node.end);
111
+ }
112
+ ts.forEachChild(node, visit);
113
+ };
114
+ visit(sourceFile);
115
+ const scanner = ts.createScanner(ts.ScriptTarget.Latest, false, ts.LanguageVariant.Standard, sourceText);
116
+ let inLeadingRegion = true;
117
+ for (let token = scanner.scan(); token !== ts.SyntaxKind.EndOfFileToken; token = scanner.scan()) {
118
+ if (token === ts.SyntaxKind.SingleLineCommentTrivia || token === ts.SyntaxKind.MultiLineCommentTrivia) {
119
+ const firstLine = sourceFile.getLineAndCharacterOfPosition(scanner.getTokenStart()).line;
120
+ const lastLine = sourceFile.getLineAndCharacterOfPosition(scanner.getTokenEnd() - 1).line;
121
+ for (let index = firstLine; index <= lastLine; index++) {
122
+ yield { text: lines[index], index, inLeadingRegion };
123
+ }
124
+ }
125
+ else if (token !== ts.SyntaxKind.WhitespaceTrivia && token !== ts.SyntaxKind.NewLineTrivia &&
126
+ token !== ts.SyntaxKind.ShebangTrivia) {
127
+ inLeadingRegion = false;
128
+ const end = literalEnds.get(scanner.getTokenStart());
129
+ if (end !== undefined)
130
+ scanner.resetTokenState(end);
131
+ }
132
+ }
133
+ }
125
134
  /** Parse top-of-file `//@ option key value` directives and legacy aliases. */
126
135
  export function parseFileOptions(sourceText, source) {
127
- const lines = sourceText.split(/\r?\n/);
128
- const leadingLines = leadingCommentLineCount(lines);
129
136
  const seen = new Map();
130
137
  const out = {};
131
138
  const setOption = (key, value, line) => {
@@ -171,8 +178,9 @@ export function parseFileOptions(sourceText, source) {
171
178
  return;
172
179
  }
173
180
  };
174
- for (let i = 0; i < lines.length; i++)
175
- parseLine(lines[i], i, i < leadingLines);
181
+ for (const { text, index, inLeadingRegion } of fileCommentLines(sourceText)) {
182
+ parseLine(text, index, inLeadingRegion);
183
+ }
176
184
  return out;
177
185
  }
178
186
  /** Apply defaults and all cross-option rules after explicit layers are merged. */
@@ -16,24 +16,43 @@ export function dafnyGen(genPath, dfyPath, text) {
16
16
  }
17
17
  }
18
18
  export function dafnyCheckDiff(genPath, dfyPath) {
19
- if (!existsSync(dfyPath))
20
- return true;
19
+ for (const filePath of [genPath, dfyPath]) {
20
+ if (!existsSync(filePath)) {
21
+ console.error(`ERROR: cannot verify additions-only diff; file does not exist: ${filePath}`);
22
+ return false;
23
+ }
24
+ }
21
25
  let diff = "";
22
26
  try {
23
- diff = execFileSync("git", ["diff", "--no-index", "--", genPath, dfyPath], { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] });
27
+ diff = execFileSync("git", ["diff", "--no-index", "--minimal", "--no-color", "--no-ext-diff", "--no-textconv", "--text", "--", genPath, dfyPath], { encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] });
24
28
  }
25
29
  catch (e) {
26
- // git diff exits 1 when files differ; stdout still holds the diff
27
- if (e && e.stdout != null) {
28
- diff = typeof e.stdout === "string" ? e.stdout : e.stdout.toString("utf-8");
29
- }
30
- else {
31
- // git couldn't be spawned: the check never ran, so fail loud, don't green-pass.
32
- console.error(`ERROR: could not run \`git diff\` to verify ${path.basename(dfyPath)} is additions-only (is git installed?)`);
30
+ // `git diff --no-index` exits 1 for a valid, non-empty comparison. Every
31
+ // other exit shape means the comparison did not complete, even when git
32
+ // happened to return partial stdout.
33
+ const status = e?.status;
34
+ const stdout = typeof e?.stdout === "string" ? e.stdout : "";
35
+ if (status !== 1 || e?.signal != null || e?.code != null || !stdout.startsWith("diff --git ")) {
36
+ const detail = typeof e?.stderr === "string" ? e.stderr.trim() : "";
37
+ console.error(`ERROR: could not run \`git diff\` to verify ${path.basename(dfyPath)} is additions-only` +
38
+ `${status === undefined ? " (is git installed?)" : ` (git exited ${status})`}` +
39
+ `${detail ? `: ${detail}` : ""}`);
33
40
  return false;
34
41
  }
42
+ diff = stdout;
43
+ }
44
+ // Only file headers are metadata. Inside a hunk, even a line beginning
45
+ // with "---" is a deletion (for example, text inside a multiline string).
46
+ const deletions = [];
47
+ let inHunk = false;
48
+ for (const line of diff.split("\n")) {
49
+ if (line.startsWith("diff --git "))
50
+ inHunk = false;
51
+ else if (line.startsWith("@@ "))
52
+ inHunk = true;
53
+ else if (inHunk && line.startsWith("-"))
54
+ deletions.push(line);
35
55
  }
36
- const deletions = diff.split("\n").filter(l => l.startsWith("-") && !l.startsWith("---"));
37
56
  if (deletions.length > 0) {
38
57
  console.error(`WARNING: ${path.basename(dfyPath)} has modifications to generated lines (not additions-only):`);
39
58
  for (const d of deletions.slice(0, 5))
@@ -112,6 +131,11 @@ export function dafnyRegen(genPath, dfyPath, basePath, text, dir, timeLimit, ext
112
131
  }
113
132
  // 7. Verify (skipped under --no-verify: caller verifies separately)
114
133
  if (!noVerify && !dafnyVerify(dfyPath, dir, timeLimit, extraFlags)) {
134
+ // The clean merge already incorporated this generation into the proof
135
+ // file. Keep that generation as the next merge anchor even though the
136
+ // verifier rejected the current proof state; otherwise the next regen
137
+ // compares against the pre-merge generation and can duplicate declarations.
138
+ writeFileSync(basePath, text);
115
139
  console.error(`FAILED: ${path.basename(dfyPath)} verification failed.`);
116
140
  process.exit(1);
117
141
  }
@@ -2,7 +2,7 @@
2
2
  * Lean backend commands: gen, check.
3
3
  */
4
4
  import { existsSync, writeFileSync } from "fs";
5
- import { execSync } from "child_process";
5
+ import { execFileSync } from "child_process";
6
6
  import path from "path";
7
7
  export function leanGen(typesPath, defPath, typesText, defText) {
8
8
  if (typesPath && typesText) {
@@ -12,21 +12,36 @@ export function leanGen(typesPath, defPath, typesText, defText) {
12
12
  writeFileSync(defPath, defText);
13
13
  console.log(`Generated: ${defPath}`);
14
14
  }
15
- export function leanCheck(dir, base) {
16
- let lakeDir = dir;
17
- while (lakeDir !== path.dirname(lakeDir)) {
18
- if (existsSync(path.join(lakeDir, "lakefile.lean")))
19
- break;
20
- lakeDir = path.dirname(lakeDir);
15
+ /** Find the nearest ancestor containing either supported Lake configuration. */
16
+ export function findLakeProjectRoot(dir) {
17
+ let candidate = path.resolve(dir);
18
+ while (true) {
19
+ if (existsSync(path.join(candidate, "lakefile.lean")) ||
20
+ existsSync(path.join(candidate, "lakefile.toml"))) {
21
+ return candidate;
22
+ }
23
+ const parent = path.dirname(candidate);
24
+ // Check the filesystem root above before terminating the search.
25
+ if (parent === candidate)
26
+ return null;
27
+ candidate = parent;
21
28
  }
29
+ }
30
+ export function leanCheck(dir, base) {
22
31
  const proofPath = path.join(dir, `${base}.proof.lean`);
23
32
  if (!existsSync(proofPath)) {
24
33
  console.error(`No proof file: ${proofPath}`);
25
34
  return false;
26
35
  }
36
+ const lakeDir = findLakeProjectRoot(dir);
37
+ if (lakeDir === null) {
38
+ console.error(`No Lake project found for ${path.resolve(dir)}: expected lakefile.lean or lakefile.toml ` +
39
+ "in this directory or an ancestor. Run this check inside a Lake project; lake was not started.");
40
+ return false;
41
+ }
27
42
  console.log("Running lake build...");
28
43
  try {
29
- execSync(`lake build`, { cwd: lakeDir, stdio: "inherit" });
44
+ execFileSync("lake", ["build"], { cwd: lakeDir, stdio: "inherit" });
30
45
  return true;
31
46
  }
32
47
  catch {
package/tools/dist/lsc.js CHANGED
@@ -114,8 +114,8 @@ function main() {
114
114
  extraFlags = args[extraFlagsIdx].split("=").slice(1).join("=");
115
115
  args.splice(extraFlagsIdx, 1);
116
116
  }
117
- // --slow (batch mode only): verify every entry with its own timeout instead
118
- // of degrading slow ones to gen-check.
117
+ // --slow (batch mode only): verify entries with long manifest timeouts
118
+ // instead of degrading them to gen-check.
119
119
  let slow = false;
120
120
  const slowIdx = args.indexOf("--slow");
121
121
  if (slowIdx >= 0) {
@@ -167,7 +167,7 @@ function main() {
167
167
  return;
168
168
  }
169
169
  if (!filePath) {
170
- runBatch(cmd, backend, slow, configPath);
170
+ runBatch(cmd, backend, slow, timeLimit, extraFlags, configPath);
171
171
  return;
172
172
  }
173
173
  runFile(cmd, filePath, backend, timeLimit, extraFlags, noVerify, typedInfo, configPath);
@@ -213,22 +213,24 @@ function runConfig(filePath, configPath) {
213
213
  const artifactDir = resolveDafnyArtifactDir(sourcePath, configFile, options);
214
214
  console.log(JSON.stringify({ configFile, options, artifactDir }, null, 2));
215
215
  }
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) {
216
+ // Batch over LemmaScript-files.txt. Without --slow or an explicit --time-limit,
217
+ // Dafny check entries with manifest timeouts above 60s run gen-check only.
218
+ // Fail-fast: the first failing entry exits.
219
+ function runBatch(cmd, backend, slow, timeLimit, extraFlags, configPath) {
221
220
  if (cmd !== "gen" && cmd !== "gen-check" && cmd !== "check") {
222
221
  console.error(`No file given, and batch mode supports gen|gen-check|check (not ${cmd}).`);
223
222
  process.exit(1);
224
223
  }
224
+ const verifySlow = slow || timeLimit !== undefined;
225
225
  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) ===`);
226
+ const timeout = timeLimit ?? e.timeout;
227
+ const flags = extraFlags ?? e.flags;
228
+ if (cmd === "check" && backend === "dafny" && !verifySlow && timeout !== undefined && timeout > 60) {
229
+ console.log(`=== ${path.basename(e.file)} (timeout ${timeout}s > 60s, gen-check only) ===`);
228
230
  runFile("gen-check", e.file, backend, undefined, undefined, false, false, configPath);
229
231
  }
230
232
  else {
231
- runFile(cmd, e.file, backend, e.timeout, e.flags, false, false, configPath);
233
+ runFile(cmd, e.file, backend, timeout, flags, false, false, configPath);
232
234
  }
233
235
  }
234
236
  }