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/README.md +14 -5
- package/package.json +1 -1
- package/tools/dist/config.js +79 -49
- package/tools/dist/dafny-commands.js +137 -28
- package/tools/dist/dafny-emit.js +121 -24
- package/tools/dist/extract.js +44 -5
- package/tools/dist/lean-commands.js +23 -8
- package/tools/dist/lean-emit.js +27 -18
- package/tools/dist/lsc.js +69 -15
- package/tools/dist/run-log.js +197 -0
- package/tools/dist/runs-command.js +377 -0
- package/tools/dist/transform.js +1 -2
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# LemmaScript (Tech Preview)
|
|
2
2
|
|
|
3
|
-
A verification toolchain for TypeScript. Write ordinary TypeScript with `//@ ` specification annotations. The toolchain generates verifiable code from your TypeScript — either in Dafny or Lean 4 (with Velvet
|
|
3
|
+
A verification toolchain for TypeScript. Write ordinary TypeScript with `//@ ` specification annotations. The toolchain generates verifiable code from your TypeScript — either in Dafny or Lean 4 (with Velvet 2).
|
|
4
4
|
|
|
5
5
|
See [SPEC.md](SPEC.md), [DESIGN.md](DESIGN.md), and [GETTING_STARTED.md](GETTING_STARTED.md).
|
|
6
6
|
|
|
@@ -29,7 +29,7 @@ See the external [case studies](https://github.com/search?q=topic%3Alemmascript+
|
|
|
29
29
|
- **[xyflow-lemmascript](https://github.com/midspiral/xyflow-lemmascript/blob/lemmascript/README_LemmaScript.md)** — brownfield verification of [xyflow](https://github.com/xyflow/xyflow)'s core edge and geometry utilities. 9 functions verified: `addEdge` (dedup — never loses edges, adds at most one), `reconnectEdge` (semantic: under a unique-id precondition, the result is in-place — `|result| ≤ |edges|`, no insertion — *and* when a matching edge existed with non-empty new endpoints, the output contains an edge with those endpoints. Uses `//@ assume` to characterize destructuring, `find`, and the constructed edge), `connectionExists`, `getEdgeCenter` (midpoint correctness), `clamp` (bounds), `rectToBox`/`boxToRect` (field arithmetic), `getBoundsOfBoxes` (enclosure), `getOverlappingArea` (non-negative), `areSetsEqual` (subset + same size). 14 Dafny proof obligations. Also adds a new verified feature — a **DAG connection gate**: `canReach` decides reachability soundly *and* completely, and `wouldCreateCycle` gates both new connections and edge reconnections so the graph is proven to stay acyclic, with `isAcyclic` (sound + complete) establishing the base case and a topological-rank witness giving a safe evaluation order (+29 obligations), shown live in a React Flow demo that refuses cycle-closing edges — extending the case study from verifying existing code to adding a verified feature. Dafny only.
|
|
30
30
|
- **[rallly-lemmascript](https://github.com/midspiral/rallly-lemmascript/blob/lemmascript/README_LemmaScript.md)** — brownfield verification of [rallly](https://github.com/lukevella/rallly)'s meeting-poll Next.js app. 2 functions: `validateRedirectUrl` (in-place — open-redirect predicate; non-`undefined` outputs start with `/` but not `//`) and `scorePoll` (extracted ranking core — length preservation, score bounds, top-choice characterization, score-formula equality, within-poll monotonicity, tiebreaker injectivity). The injectivity proof surfaced a real spec-level constraint on the existing `(yes + ifNeedBe) * 1000 + yes` encoding: it overflows when an option has ≥ 1000 yes votes. 10 Dafny VCs, 0 errors. Drove four toolchain additions: `s.startsWith()`, `T | null` nullability, `\result` narrowing under `==>`, `Math.max(...arr)` spread. Dafny only.
|
|
31
31
|
- **[opencode-lemmascript](https://github.com/midspiral/opencode-lemmascript/blob/lemmascript/README_LemmaScript.md)** — brownfield verification of [opencode](https://github.com/anomalyco/opencode)'s permission system and unified-diff patch parser. Highlights: (1) `Patch.parsePatch` carries conservation loop invariants over local ghost state — a parser bug here would silently corrupt user files when an AI applies a patch, and (2) the permission-engine work mechanically closes opencode bug #26514 (subagents bypassing Plan Mode's file-edit restrictions). 9 functions verified in-place, 0 errors. Dafny only.
|
|
32
|
-
- **[pi-lemmascript](https://github.com/midspiral/pi-lemmascript/blob/lemmascript/README_LemmaScript.md)** — brownfield, **in-place** verification of the context-compaction cut-point selector in **pi** (the [earendil-works](https://pi.dev) agent harness). When the context window fills, pi discards history before a chosen cut; a provider API rejects a retained prefix containing an orphaned `toolResult` (a tool result whose tool call was cut away). Both selector functions proven: the cut never lets the kept suffix *start with* — nor *split a tool-use/tool-result run* into — an orphaned tool result, even across the backward metadata snap. The no-orphan result forced the session tree's tool-pairing ordering into an explicit `requires`. 4 VCs, 0 errors. Drove five toolchain additions, headlined by an **opaque fall-through type**: a union LemmaScript can't discriminate (here an array-element union of unreachable imports) becomes a single opaque `type` — the field stays present so distinct values stay distinct, and with no constructor or tag predicate it can only be passed through, never unsoundly observed. **Dafny + Lean**: the no-orphan theorem, the changelog semver core, and both tool-output truncators also carry Lean 4 (Velvet
|
|
32
|
+
- **[pi-lemmascript](https://github.com/midspiral/pi-lemmascript/blob/lemmascript/README_LemmaScript.md)** — brownfield, **in-place** verification of the context-compaction cut-point selector in **pi** (the [earendil-works](https://pi.dev) agent harness). When the context window fills, pi discards history before a chosen cut; a provider API rejects a retained prefix containing an orphaned `toolResult` (a tool result whose tool call was cut away). Both selector functions proven: the cut never lets the kept suffix *start with* — nor *split a tool-use/tool-result run* into — an orphaned tool result, even across the backward metadata snap. The no-orphan result forced the session tree's tool-pairing ordering into an explicit `requires`. 4 VCs, 0 errors. Drove five toolchain additions, headlined by an **opaque fall-through type**: a union LemmaScript can't discriminate (here an array-element union of unreachable imports) becomes a single opaque `type` — the field stays present so distinct values stay distinct, and with no constructor or tag predicate it can only be passed through, never unsoundly observed. **Dafny + Lean**: the no-orphan theorem, the changelog semver core, and both tool-output truncators also carry Lean 4 (Velvet 2) proofs from the same annotated source, zero `sorry`; the Lean port drove the backend's brownfield batch (cross-file externs, union destructor lowering, Bool-vs-Prop contexts, `return`-in-loop elimination).
|
|
33
33
|
- **[flue-lemmascript](https://github.com/midspiral/flue-lemmascript/blob/lemmascript/README_LemmaScript.md)** — brownfield, **in-place** verification of pure logic in **Flue** ([withastro/flue](https://github.com/withastro/flue)), Astro's agent harness — crash-recovery and context-compaction functions proven byte-identical. What it drove into the toolchain: native Dafny `continue`, bounds-guarded `noUncheckedIndexedAccess` optional indexing, optional narrowing past an `opt?.disc` guard composing with discriminated-union matching, and object truthiness. Dafny only.
|
|
34
34
|
- **[balanced-match-lemmascript](https://github.com/midspiral/balanced-match-lemmascript/blob/lemmascript/README_LemmaScript.md)** — brownfield, **in-place** verification of [balanced-match](https://github.com/juliangruber/balanced-match), the ~70-line balanced-bracket finder pulled in by `npm`, `webpack`, and most of the JS tooling stack (1B+ downloads/month). The stack-based `range` core is verified by **refinement**: a pure recursive spec `range_spec` mirrors the loop one branch per recursive case, so the single equivalence `range == range_spec` transfers every property automatically — including an unconditional Dyck body-balance theorem for the interior of every returned pair. 2233 VCs, 0 errors under `--isolate-assertions` (registered on the `dafny-slow` track). Dafny only.
|
|
35
35
|
- **[guardians-lemmascript](https://github.com/midspiral/guardians-lemmascript)** — greenfield verification of the core safety argument behind [Guardians](https://github.com/metareflection/guardians) (Erik Meijer, "Guardians of the Agents", CACM Jan 2026), a generate-verify-execute checker for AI-agent workflows. Instead of verifying an app, it proves the agent *guardrail itself sound* — that a static taint/automaton check over the real recursive workflow AST can never admit an unsafe plan. Highlights: taint over **nested conditionals** as a sound branch-union over-approximation; per-source **provenance** with a join (a multi-input tool is tainted if *any* input was); **unbounded loops** discharged by a one-step pre-fixpoint (`sat = t0 ‖ bodyTaint(t0)`) that bounds taint over any iteration count without iterating to a fixpoint; and a **unified capstone** (`verifyWfSound`) — one clean verdict rules out, on *every* path, both a tainted-data-to-sink leak and a security-automaton error. 54 Dafny obligations, 0 errors. The verified cores are reached from a Guardians-style `Workflow`/`Policy` through a thin *unverified* adapter, differentially tested against the real Python Guardians (used as the oracle, not a porting target). Dafny only.
|
|
@@ -56,13 +56,22 @@ git clone https://github.com/midspiral/LemmaScript.git
|
|
|
56
56
|
cd LemmaScript && npm install && npm run build
|
|
57
57
|
```
|
|
58
58
|
|
|
59
|
-
**Lean backend
|
|
59
|
+
**Lean backend:** from the LemmaScript source checkout, clone Velvet 2 as a sibling on the **`lemma2` branch**:
|
|
60
60
|
|
|
61
61
|
```sh
|
|
62
|
-
git clone https://github.com/namin/
|
|
63
|
-
|
|
62
|
+
git clone --branch lemma2 https://github.com/namin/velvet.git ../velvet
|
|
63
|
+
lake build
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
For an existing Velvet checkout, select the branch with:
|
|
67
|
+
|
|
68
|
+
```sh
|
|
69
|
+
git -C ../velvet fetch origin
|
|
70
|
+
git -C ../velvet checkout lemma2
|
|
64
71
|
```
|
|
65
72
|
|
|
73
|
+
The `lemma` branch is for the previous Velvet version. Use the Lean version pinned in `lean-toolchain` (currently 4.34.0); Lake resolves the Mathlib dependency. Velvet 2 does not require a Loom checkout or external Z3/cvc5 binaries. See [SPEC_LEAN.md](SPEC_LEAN.md) for the project layout and proof workflow.
|
|
74
|
+
|
|
66
75
|
## Usage
|
|
67
76
|
|
|
68
77
|
### Dafny backend
|
package/package.json
CHANGED
package/tools/dist/config.js
CHANGED
|
@@ -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",
|
|
@@ -28,6 +29,26 @@ export const OPTION_SPECS = {
|
|
|
28
29
|
fileOverride: false,
|
|
29
30
|
description: "Directory for Dafny artifacts, relative to lemmascript.json.",
|
|
30
31
|
},
|
|
32
|
+
"string-semantics": {
|
|
33
|
+
type: "enum",
|
|
34
|
+
values: ["unicode-scalar", "javascript-utf16"],
|
|
35
|
+
default: "unicode-scalar",
|
|
36
|
+
fileOverride: true,
|
|
37
|
+
description: "Which model of JavaScript strings a Dafny proof is made under.",
|
|
38
|
+
},
|
|
39
|
+
"dafny-library": {
|
|
40
|
+
type: "enum",
|
|
41
|
+
values: ["stdlib", "local"],
|
|
42
|
+
default: "stdlib",
|
|
43
|
+
fileOverride: true,
|
|
44
|
+
description: "Use Dafny's standard library or generated local helpers for collection operations.",
|
|
45
|
+
},
|
|
46
|
+
"run-log": {
|
|
47
|
+
type: "boolean",
|
|
48
|
+
default: true,
|
|
49
|
+
fileOverride: false,
|
|
50
|
+
description: "Record lsc check and regen runs in .lemmascript/.",
|
|
51
|
+
},
|
|
31
52
|
};
|
|
32
53
|
export const DEFAULT_OPTIONS = Object.freeze(Object.fromEntries(Object.entries(OPTION_SPECS).map(([key, spec]) => [key, spec.default])));
|
|
33
54
|
const KNOWN_KEYS = Object.keys(OPTION_SPECS);
|
|
@@ -38,7 +59,8 @@ function fail(source, message) {
|
|
|
38
59
|
function isKnownKey(key) {
|
|
39
60
|
return Object.hasOwn(OPTION_SPECS, key);
|
|
40
61
|
}
|
|
41
|
-
|
|
62
|
+
/** Validate one option against the registry and return its typed value. */
|
|
63
|
+
export function parseOptionValue(key, raw, source) {
|
|
42
64
|
const spec = OPTION_SPECS[key];
|
|
43
65
|
if (spec.type === "boolean") {
|
|
44
66
|
if (typeof raw !== "boolean")
|
|
@@ -70,45 +92,10 @@ export function validateOptions(raw, source) {
|
|
|
70
92
|
if (!isKnownKey(key)) {
|
|
71
93
|
fail(source, `unknown option '${key}' (known options: ${KNOWN_KEYS.join(", ")})`);
|
|
72
94
|
}
|
|
73
|
-
out[key] =
|
|
95
|
+
out[key] = parseOptionValue(key, value, source);
|
|
74
96
|
}
|
|
75
97
|
return out;
|
|
76
98
|
}
|
|
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
99
|
function parseDirectiveValue(key, text, source) {
|
|
113
100
|
const spec = OPTION_SPECS[key];
|
|
114
101
|
if (spec.type === "boolean") {
|
|
@@ -117,15 +104,56 @@ function parseDirectiveValue(key, text, source) {
|
|
|
117
104
|
return (text === "true");
|
|
118
105
|
}
|
|
119
106
|
if (spec.type === "enum")
|
|
120
|
-
return
|
|
107
|
+
return parseOptionValue(key, text, source);
|
|
121
108
|
// Config-only today, but keep the diagnostic precise if a future path is
|
|
122
109
|
// made file-overridable.
|
|
123
|
-
return
|
|
110
|
+
return parseOptionValue(key, text, source);
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Find comment lines, marking those that occur before any code.
|
|
114
|
+
*
|
|
115
|
+
* Use the parsed syntax tree to skip strings, regexes, and template text.
|
|
116
|
+
* Without those boundaries, the scanner can read /[/*]/ as a block comment
|
|
117
|
+
* or treat a template's closing backtick as the start of another template.
|
|
118
|
+
*/
|
|
119
|
+
function* fileCommentLines(sourceText) {
|
|
120
|
+
// Normalize once so a leading BOM also works before a shebang.
|
|
121
|
+
sourceText = sourceText.replace(/^\uFEFF/, "");
|
|
122
|
+
const lines = sourceText.split(/\r\n|[\n\r\u2028\u2029]/);
|
|
123
|
+
const sourceFile = ts.createSourceFile("lemmascript-options.ts", sourceText, ts.ScriptTarget.Latest, false, ts.ScriptKind.TS);
|
|
124
|
+
const literalEnds = new Map();
|
|
125
|
+
const visit = (node) => {
|
|
126
|
+
if (ts.isStringLiteral(node) || ts.isRegularExpressionLiteral(node) || ts.isTemplateLiteralToken(node)) {
|
|
127
|
+
// Skip template text, keeping real comments inside ${...} visible.
|
|
128
|
+
// Missing recovery tokens must not send the scanner back to its start.
|
|
129
|
+
const start = node.getStart(sourceFile);
|
|
130
|
+
if (node.end > start)
|
|
131
|
+
literalEnds.set(start, node.end);
|
|
132
|
+
}
|
|
133
|
+
ts.forEachChild(node, visit);
|
|
134
|
+
};
|
|
135
|
+
visit(sourceFile);
|
|
136
|
+
const scanner = ts.createScanner(ts.ScriptTarget.Latest, false, ts.LanguageVariant.Standard, sourceText);
|
|
137
|
+
let inLeadingRegion = true;
|
|
138
|
+
for (let token = scanner.scan(); token !== ts.SyntaxKind.EndOfFileToken; token = scanner.scan()) {
|
|
139
|
+
if (token === ts.SyntaxKind.SingleLineCommentTrivia || token === ts.SyntaxKind.MultiLineCommentTrivia) {
|
|
140
|
+
const firstLine = sourceFile.getLineAndCharacterOfPosition(scanner.getTokenStart()).line;
|
|
141
|
+
const lastLine = sourceFile.getLineAndCharacterOfPosition(scanner.getTokenEnd() - 1).line;
|
|
142
|
+
for (let index = firstLine; index <= lastLine; index++) {
|
|
143
|
+
yield { text: lines[index], index, inLeadingRegion };
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
else if (token !== ts.SyntaxKind.WhitespaceTrivia && token !== ts.SyntaxKind.NewLineTrivia &&
|
|
147
|
+
token !== ts.SyntaxKind.ShebangTrivia) {
|
|
148
|
+
inLeadingRegion = false;
|
|
149
|
+
const end = literalEnds.get(scanner.getTokenStart());
|
|
150
|
+
if (end !== undefined)
|
|
151
|
+
scanner.resetTokenState(end);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
124
154
|
}
|
|
125
155
|
/** Parse top-of-file `//@ option key value` directives and legacy aliases. */
|
|
126
156
|
export function parseFileOptions(sourceText, source) {
|
|
127
|
-
const lines = sourceText.split(/\r?\n/);
|
|
128
|
-
const leadingLines = leadingCommentLineCount(lines);
|
|
129
157
|
const seen = new Map();
|
|
130
158
|
const out = {};
|
|
131
159
|
const setOption = (key, value, line) => {
|
|
@@ -171,17 +199,19 @@ export function parseFileOptions(sourceText, source) {
|
|
|
171
199
|
return;
|
|
172
200
|
}
|
|
173
201
|
};
|
|
174
|
-
for (
|
|
175
|
-
parseLine(
|
|
202
|
+
for (const { text, index, inLeadingRegion } of fileCommentLines(sourceText)) {
|
|
203
|
+
parseLine(text, index, inLeadingRegion);
|
|
204
|
+
}
|
|
176
205
|
return out;
|
|
177
206
|
}
|
|
178
|
-
/** Apply defaults
|
|
207
|
+
/** Apply defaults, check option compatibility, and freeze the resolved configuration. */
|
|
179
208
|
export function resolveOptions(explicit, source) {
|
|
180
|
-
|
|
181
|
-
//
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
209
|
+
const options = { ...DEFAULT_OPTIONS, ...explicit };
|
|
210
|
+
// Dafny's precompiled standard library uses Unicode-scalar characters.
|
|
211
|
+
if (options["string-semantics"] === "javascript-utf16" && options["dafny-library"] === "stdlib") {
|
|
212
|
+
fail(source, '"string-semantics": "javascript-utf16" is incompatible with "dafny-library": "stdlib"; set "dafny-library": "local" explicitly');
|
|
213
|
+
}
|
|
214
|
+
return Object.freeze(options);
|
|
185
215
|
}
|
|
186
216
|
/** Find `fileName` at or above `fromPath`. */
|
|
187
217
|
export function findUp(fileName, fromPath, fromIsDirectory = false) {
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
import { existsSync, readFileSync, writeFileSync, copyFileSync, unlinkSync } from "fs";
|
|
5
5
|
import { execFileSync } from "child_process";
|
|
6
6
|
import path from "path";
|
|
7
|
+
import { DEFAULT_OPTIONS, parseOptionValue } from "./config.js";
|
|
7
8
|
function writeGen(genPath, text) {
|
|
8
9
|
writeFileSync(genPath, text);
|
|
9
10
|
console.log(`Generated: ${genPath}`);
|
|
@@ -15,25 +16,62 @@ export function dafnyGen(genPath, dfyPath, text) {
|
|
|
15
16
|
console.log(`Created: ${dfyPath}`);
|
|
16
17
|
}
|
|
17
18
|
}
|
|
18
|
-
export function dafnyCheckDiff(genPath, dfyPath) {
|
|
19
|
-
|
|
20
|
-
|
|
19
|
+
export function dafnyCheckDiff(genPath, dfyPath, log) {
|
|
20
|
+
const ok = additionsOnly(genPath, dfyPath);
|
|
21
|
+
if (!ok)
|
|
22
|
+
log?.finish({ stage: "diff", exit: 1, dfyPath });
|
|
23
|
+
return ok;
|
|
24
|
+
}
|
|
25
|
+
function additionsOnly(genPath, dfyPath) {
|
|
26
|
+
for (const filePath of [genPath, dfyPath]) {
|
|
27
|
+
if (!existsSync(filePath)) {
|
|
28
|
+
console.error(`ERROR: cannot verify additions-only diff; file does not exist: ${filePath}`);
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
// Proof additions must retain the model chosen by the generated companion.
|
|
33
|
+
try {
|
|
34
|
+
const generated = readStringSemantics(readFileSync(genPath, "utf-8"));
|
|
35
|
+
const proof = readStringSemantics(readFileSync(dfyPath, "utf-8"));
|
|
36
|
+
if (proof !== generated) {
|
|
37
|
+
throw new Error(`proof string-semantics=${proof} differs from generated string-semantics=${generated}`);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
console.error(`ERROR: ${path.basename(dfyPath)}: ${error instanceof Error ? error.message : String(error)}`);
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
21
44
|
let diff = "";
|
|
22
45
|
try {
|
|
23
|
-
diff = execFileSync("git", ["diff", "--no-index", "--minimal", "--", genPath, dfyPath], { encoding: "utf-8", stdio: ["ignore", "pipe", "
|
|
46
|
+
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
47
|
}
|
|
25
48
|
catch (e) {
|
|
26
|
-
// git diff exits 1
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
49
|
+
// `git diff --no-index` exits 1 for a valid, non-empty comparison. Every
|
|
50
|
+
// other exit shape means the comparison did not complete, even when git
|
|
51
|
+
// happened to return partial stdout.
|
|
52
|
+
const status = e?.status;
|
|
53
|
+
const stdout = typeof e?.stdout === "string" ? e.stdout : "";
|
|
54
|
+
if (status !== 1 || e?.signal != null || e?.code != null || !stdout.startsWith("diff --git ")) {
|
|
55
|
+
const detail = typeof e?.stderr === "string" ? e.stderr.trim() : "";
|
|
56
|
+
console.error(`ERROR: could not run \`git diff\` to verify ${path.basename(dfyPath)} is additions-only` +
|
|
57
|
+
`${status === undefined ? " (is git installed?)" : ` (git exited ${status})`}` +
|
|
58
|
+
`${detail ? `: ${detail}` : ""}`);
|
|
33
59
|
return false;
|
|
34
60
|
}
|
|
61
|
+
diff = stdout;
|
|
62
|
+
}
|
|
63
|
+
// Only file headers are metadata. Inside a hunk, even a line beginning
|
|
64
|
+
// with "---" is a deletion (for example, text inside a multiline string).
|
|
65
|
+
const deletions = [];
|
|
66
|
+
let inHunk = false;
|
|
67
|
+
for (const line of diff.split("\n")) {
|
|
68
|
+
if (line.startsWith("diff --git "))
|
|
69
|
+
inHunk = false;
|
|
70
|
+
else if (line.startsWith("@@ "))
|
|
71
|
+
inHunk = true;
|
|
72
|
+
else if (inHunk && line.startsWith("-"))
|
|
73
|
+
deletions.push(line);
|
|
35
74
|
}
|
|
36
|
-
const deletions = diff.split("\n").filter(l => l.startsWith("-") && !l.startsWith("---"));
|
|
37
75
|
if (deletions.length > 0) {
|
|
38
76
|
console.error(`WARNING: ${path.basename(dfyPath)} has modifications to generated lines (not additions-only):`);
|
|
39
77
|
for (const d of deletions.slice(0, 5))
|
|
@@ -42,32 +80,94 @@ export function dafnyCheckDiff(genPath, dfyPath) {
|
|
|
42
80
|
}
|
|
43
81
|
return true;
|
|
44
82
|
}
|
|
45
|
-
|
|
83
|
+
/** Read the saved model, rejecting ambiguous headers before verification. */
|
|
84
|
+
function readStringSemantics(content) {
|
|
85
|
+
const headers = [...content.matchAll(/^\/\/ lsc options:(.*)$/gm)];
|
|
86
|
+
if (headers.length > 1)
|
|
87
|
+
throw new Error("generated header: duplicate lsc options header (string-semantics must be unambiguous)");
|
|
88
|
+
let model = DEFAULT_OPTIONS["string-semantics"];
|
|
89
|
+
let seen = false;
|
|
90
|
+
for (const token of (headers[0]?.[1] ?? "").trim().split(/\s+/).filter(Boolean)) {
|
|
91
|
+
const eq = token.indexOf("=");
|
|
92
|
+
const key = eq < 0 ? token : token.slice(0, eq);
|
|
93
|
+
if (key !== "string-semantics")
|
|
94
|
+
continue;
|
|
95
|
+
if (seen)
|
|
96
|
+
throw new Error("generated header: duplicate string-semantics option");
|
|
97
|
+
seen = true;
|
|
98
|
+
model = parseOptionValue(key, eq < 0 ? "" : token.slice(eq + 1), "generated header");
|
|
99
|
+
}
|
|
100
|
+
return model;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Build verifier arguments from the generated file's `// lsc options:` header.
|
|
104
|
+
* Reading the saved string model instead of the current project config keeps
|
|
105
|
+
* verification consistent with generation, even if the config later changes.
|
|
106
|
+
* Always pass `--unicode-char` explicitly. UTF-16 mode also needs
|
|
107
|
+
* `--allow-deprecation` because Dafny 4.11 deprecates `--unicode-char:false`.
|
|
108
|
+
* Other warning categories remain fatal.
|
|
109
|
+
*/
|
|
110
|
+
export function dafnyVerifyArgs(content, timeLimit, extraFlags) {
|
|
111
|
+
let stringSemantics;
|
|
112
|
+
try {
|
|
113
|
+
stringSemantics = readStringSemantics(content);
|
|
114
|
+
}
|
|
115
|
+
catch (error) {
|
|
116
|
+
return { args: [], error: `ERROR: ${error instanceof Error ? error.message : String(error)}` };
|
|
117
|
+
}
|
|
118
|
+
const utf16 = stringSemantics === "javascript-utf16";
|
|
119
|
+
const usesStandardLibrary = content.includes("Std.");
|
|
120
|
+
if (utf16 && usesStandardLibrary) {
|
|
121
|
+
return { args: [], error: "ERROR: this proof combines \"string-semantics\": \"javascript-utf16\" with Dafny's standard library. " +
|
|
122
|
+
"Dafny 4.11 cannot load its Unicode-scalar standard library under --unicode-char:false. " +
|
|
123
|
+
"Set \"dafny-library\": \"local\" in lemmascript.json or add //@ option dafny-library local, " +
|
|
124
|
+
"then run lsc regen to regenerate collection helpers. " +
|
|
125
|
+
"This does not rewrite handwritten Std.* imports or calls; replace those with local proofs or helpers separately." };
|
|
126
|
+
}
|
|
127
|
+
const args = ["verify"];
|
|
128
|
+
if (usesStandardLibrary)
|
|
129
|
+
args.push("--standard-libraries");
|
|
130
|
+
if (timeLimit)
|
|
131
|
+
args.push("--verification-time-limit", String(timeLimit));
|
|
132
|
+
if (extraFlags) {
|
|
133
|
+
for (const tok of extraFlags.split(/\s+/))
|
|
134
|
+
if (tok)
|
|
135
|
+
args.push(tok);
|
|
136
|
+
}
|
|
137
|
+
args.push(utf16 ? "--unicode-char:false" : "--unicode-char:true");
|
|
138
|
+
if (utf16)
|
|
139
|
+
args.push("--allow-deprecation");
|
|
140
|
+
return { args };
|
|
141
|
+
}
|
|
142
|
+
export function dafnyVerify(dfyPath, dir, timeLimit, extraFlags, log) {
|
|
46
143
|
console.log("Running dafny verify...");
|
|
47
144
|
try {
|
|
48
|
-
const
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
args.push("--verification-time-limit", String(timeLimit));
|
|
54
|
-
if (extraFlags) {
|
|
55
|
-
for (const tok of extraFlags.split(/\s+/))
|
|
56
|
-
if (tok)
|
|
57
|
-
args.push(tok);
|
|
145
|
+
const { args, error } = dafnyVerifyArgs(readFileSync(dfyPath, "utf-8"), timeLimit, extraFlags);
|
|
146
|
+
if (error) {
|
|
147
|
+
console.error(error);
|
|
148
|
+
log?.finish({ stage: "resolve", exit: 1, dfyPath });
|
|
149
|
+
return false;
|
|
58
150
|
}
|
|
151
|
+
if (log)
|
|
152
|
+
args.push(...log.dafnyArgs());
|
|
59
153
|
args.push(dfyPath);
|
|
60
154
|
execFileSync("dafny", args, { cwd: dir, stdio: "inherit" });
|
|
155
|
+
log?.finish({ stage: "ok", exit: 0, dfyPath, results: log.readResults() });
|
|
61
156
|
return true;
|
|
62
157
|
}
|
|
63
158
|
catch (e) {
|
|
64
159
|
if (e?.code === "ENOENT") {
|
|
65
160
|
console.error("ERROR: `dafny` not found on PATH — verification never ran. Install Dafny 4.x: https://dafny.org/");
|
|
161
|
+
log?.discard();
|
|
162
|
+
return false;
|
|
66
163
|
}
|
|
164
|
+
// Dafny writes no results when it stops at parsing or resolution.
|
|
165
|
+
const results = log?.readResults() ?? null;
|
|
166
|
+
log?.finish({ stage: results ? "verify" : "resolve", exit: 1, dfyPath, results });
|
|
67
167
|
return false;
|
|
68
168
|
}
|
|
69
169
|
}
|
|
70
|
-
export function dafnyRegen(genPath, dfyPath, basePath, text, dir, timeLimit, extraFlags, noVerify = false) {
|
|
170
|
+
export function dafnyRegen(genPath, dfyPath, basePath, text, dir, timeLimit, extraFlags, noVerify = false, log) {
|
|
71
171
|
// 1. Read old gen before overwriting (needed for base seeding)
|
|
72
172
|
const oldGen = existsSync(genPath) ? readFileSync(genPath, "utf-8") : "";
|
|
73
173
|
// 2. Always write new gen so user can inspect latest output
|
|
@@ -76,10 +176,11 @@ export function dafnyRegen(genPath, dfyPath, basePath, text, dir, timeLimit, ext
|
|
|
76
176
|
if (!existsSync(dfyPath)) {
|
|
77
177
|
writeFileSync(dfyPath, text);
|
|
78
178
|
console.log(`Created: ${path.basename(dfyPath)}`);
|
|
79
|
-
if (!noVerify && !dafnyVerify(dfyPath, dir, timeLimit, extraFlags)) {
|
|
179
|
+
if (!noVerify && !dafnyVerify(dfyPath, dir, timeLimit, extraFlags, log)) {
|
|
80
180
|
console.error(`FAILED: ${path.basename(dfyPath)} verification failed on first run.`);
|
|
81
181
|
process.exit(1);
|
|
82
182
|
}
|
|
183
|
+
log?.finish({ stage: "ok", exit: 0, dfyPath });
|
|
83
184
|
return;
|
|
84
185
|
}
|
|
85
186
|
// 4. Determine anchor: base file if it exists (dirty state), otherwise old gen
|
|
@@ -100,22 +201,30 @@ export function dafnyRegen(genPath, dfyPath, basePath, text, dir, timeLimit, ext
|
|
|
100
201
|
copyFileSync(dfyPath, mergedPath);
|
|
101
202
|
writeFileSync(dfyPath, savedDfy);
|
|
102
203
|
console.error(`CONFLICT: ${path.basename(dfyPath)} — merge had conflicts, dfy restored. See ${path.basename(mergedPath)}`);
|
|
204
|
+
log?.finish({ stage: "conflict", exit: 1, dfyPath });
|
|
103
205
|
process.exit(1);
|
|
104
206
|
}
|
|
105
207
|
throw e;
|
|
106
208
|
}
|
|
107
209
|
}
|
|
108
210
|
// 6. Check gen invariant (unconditional)
|
|
109
|
-
if (!dafnyCheckDiff(genPath, dfyPath)) {
|
|
211
|
+
if (!dafnyCheckDiff(genPath, dfyPath, log)) {
|
|
110
212
|
console.error(`FAILED: ${path.basename(dfyPath)} has modifications to generated lines.`);
|
|
111
213
|
process.exit(1);
|
|
112
214
|
}
|
|
113
215
|
// 7. Verify (skipped under --no-verify: caller verifies separately)
|
|
114
|
-
if (!noVerify && !dafnyVerify(dfyPath, dir, timeLimit, extraFlags)) {
|
|
216
|
+
if (!noVerify && !dafnyVerify(dfyPath, dir, timeLimit, extraFlags, log)) {
|
|
217
|
+
// The clean merge already incorporated this generation into the proof
|
|
218
|
+
// file. Keep that generation as the next merge anchor even though the
|
|
219
|
+
// verifier rejected the current proof state; otherwise the next regen
|
|
220
|
+
// compares against the pre-merge generation and can duplicate declarations.
|
|
221
|
+
writeFileSync(basePath, text);
|
|
115
222
|
console.error(`FAILED: ${path.basename(dfyPath)} verification failed.`);
|
|
116
223
|
process.exit(1);
|
|
117
224
|
}
|
|
118
|
-
// 8. Success — delete base (gen is now the anchor)
|
|
225
|
+
// 8. Success — delete base (gen is now the anchor). After a verified run
|
|
226
|
+
// dafnyVerify has already recorded the outcome; this records --no-verify.
|
|
119
227
|
if (existsSync(basePath))
|
|
120
228
|
unlinkSync(basePath);
|
|
229
|
+
log?.finish({ stage: "ok", exit: 0, dfyPath });
|
|
121
230
|
}
|