@milkenjoyer/toolchain 0.9.0 → 0.11.0
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 +38 -1
- package/dist/formal.d.mts +60 -0
- package/dist/formal.mjs +628 -0
- package/dist/hooks.mjs +2 -2
- package/dist/proof.mjs +6 -6
- package/dist/verdict.d.mts +3 -0
- package/dist/verdict.mjs +39 -0
- package/dist/verification-6s2chr4X.mjs +111 -0
- package/dist/verification-p2rSx5lc.d.mts +40 -0
- package/dist/verification.d.mts +2 -28
- package/dist/verification.mjs +1 -97
- package/package.json +6 -1
- package/src/formal/cfg.ts +111 -0
- package/src/formal/checks.ts +203 -0
- package/src/formal/semantics.ts +145 -0
- package/src/formal/specs.ts +166 -0
- package/src/formal/tla.ts +284 -0
- package/src/formal.ts +75 -0
- package/src/verdict.ts +50 -0
- package/src/verification.ts +50 -22
package/dist/formal.mjs
ADDED
|
@@ -0,0 +1,628 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
import * as Data from "effect/Data";
|
|
3
|
+
import * as Option from "effect/Option";
|
|
4
|
+
import * as Schema from "effect/Schema";
|
|
5
|
+
import * as Effect from "effect/Effect";
|
|
6
|
+
import * as Result from "effect/Result";
|
|
7
|
+
import { NodeServices } from "@effect/platform-node";
|
|
8
|
+
import * as Cause from "effect/Cause";
|
|
9
|
+
import * as Console from "effect/Console";
|
|
10
|
+
import * as Exit from "effect/Exit";
|
|
11
|
+
import { ChildProcess, ChildProcessSpawner } from "effect/process";
|
|
12
|
+
import * as Stream from "effect/Stream";
|
|
13
|
+
import { FileSystem } from "effect/FileSystem";
|
|
14
|
+
import { createHash } from "node:crypto";
|
|
15
|
+
import * as Clock from "effect/Clock";
|
|
16
|
+
import * as Config from "effect/Config";
|
|
17
|
+
import * as Context from "effect/Context";
|
|
18
|
+
import { FetchHttpClient, HttpClient } from "effect/http";
|
|
19
|
+
import * as Layer from "effect/Layer";
|
|
20
|
+
import { Path } from "effect/Path";
|
|
21
|
+
import * as SchemaIssue from "effect/SchemaIssue";
|
|
22
|
+
// src/formal/cfg.ts
|
|
23
|
+
const keywords = /* @__PURE__ */ new Set([
|
|
24
|
+
"CONSTANT",
|
|
25
|
+
"CONSTANTS",
|
|
26
|
+
"INIT",
|
|
27
|
+
"NEXT",
|
|
28
|
+
"SPECIFICATION",
|
|
29
|
+
"INVARIANT",
|
|
30
|
+
"INVARIANTS",
|
|
31
|
+
"PROPERTY",
|
|
32
|
+
"PROPERTIES",
|
|
33
|
+
"CONSTRAINT",
|
|
34
|
+
"CONSTRAINTS",
|
|
35
|
+
"ACTION_CONSTRAINT",
|
|
36
|
+
"ACTION_CONSTRAINTS",
|
|
37
|
+
"SYMMETRY",
|
|
38
|
+
"VIEW",
|
|
39
|
+
"ALIAS",
|
|
40
|
+
"POSTCONDITION",
|
|
41
|
+
"CHECK_DEADLOCK"
|
|
42
|
+
]);
|
|
43
|
+
const parseCfg = (source) => {
|
|
44
|
+
const tokens = source.replaceAll(/\(\*[\s\S]*?\*\)|\\\*[^\n]*/gu, " ").match(/"(?:\\.|[^"\\])*"|<-|[A-Za-z_][A-Za-z0-9_!]*|-?\d+|[^\s]/gu) ?? [];
|
|
45
|
+
const constants = [];
|
|
46
|
+
const invariants = [];
|
|
47
|
+
const checkDeadlock = [];
|
|
48
|
+
const fail = (message) => ({
|
|
49
|
+
_tag: "CfgError",
|
|
50
|
+
message
|
|
51
|
+
});
|
|
52
|
+
let i = 0;
|
|
53
|
+
while (i < tokens.length) {
|
|
54
|
+
const keyword = tokens[i++];
|
|
55
|
+
if (keyword === void 0 || !keywords.has(keyword)) return fail(`unknown config keyword ${keyword}`);
|
|
56
|
+
const operands = [];
|
|
57
|
+
while (i < tokens.length && !keywords.has(tokens[i] ?? "")) operands.push(tokens[i++] ?? "");
|
|
58
|
+
if (operands.length === 0) return fail(`missing operand for ${keyword}`);
|
|
59
|
+
if (keyword === "CONSTANT" || keyword === "CONSTANTS") {
|
|
60
|
+
let j = 0;
|
|
61
|
+
while (j < operands.length) {
|
|
62
|
+
const name = operands[j++];
|
|
63
|
+
const assignment = operands[j++];
|
|
64
|
+
if (name === void 0 || !/^[A-Za-z_][A-Za-z0-9_!]*$/u.test(name) || assignment !== "=" && assignment !== "<-") return fail(`unparseable constant ${name}`);
|
|
65
|
+
const value = [];
|
|
66
|
+
let depth = 0;
|
|
67
|
+
while (j < operands.length) {
|
|
68
|
+
const token = operands[j] ?? "";
|
|
69
|
+
if (depth === 0 && value.length > 0 && ["=", "<-"].includes(operands[j + 1] ?? "")) break;
|
|
70
|
+
if (token === "{") depth++;
|
|
71
|
+
if (token === "}") depth--;
|
|
72
|
+
value.push(token);
|
|
73
|
+
j++;
|
|
74
|
+
}
|
|
75
|
+
const raw = value.join(" ");
|
|
76
|
+
if (depth !== 0 || !/^(?:-?\d+|[A-Za-z_][A-Za-z0-9_!]*|"(?:\\.|[^"\\])*"|\{[\s\S]*\})$/u.test(raw)) return fail(`unparseable constant ${name} ${assignment} ${raw}`);
|
|
77
|
+
constants.push(assignment === "=" ? {
|
|
78
|
+
_tag: "Value",
|
|
79
|
+
name,
|
|
80
|
+
value: raw
|
|
81
|
+
} : {
|
|
82
|
+
_tag: "Substitution",
|
|
83
|
+
name,
|
|
84
|
+
by: raw
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
} else if (keyword === "CHECK_DEADLOCK") {
|
|
88
|
+
if (operands.length !== 1 || !["TRUE", "FALSE"].includes(operands[0] ?? "")) return fail("CHECK_DEADLOCK needs TRUE or FALSE");
|
|
89
|
+
checkDeadlock.push(operands[0] === "TRUE");
|
|
90
|
+
} else {
|
|
91
|
+
if (!operands.every((token) => /^[A-Za-z_][A-Za-z0-9_!]*$/u.test(token))) return fail(`invalid operands for ${keyword}`);
|
|
92
|
+
if (keyword.startsWith("INVARIANT")) invariants.push(...operands);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return {
|
|
96
|
+
constants,
|
|
97
|
+
invariants,
|
|
98
|
+
checkDeadlock
|
|
99
|
+
};
|
|
100
|
+
};
|
|
101
|
+
const integer = (constant) => constant._tag === "Value" && /^-?\d+$/u.test(constant.value) ? BigInt(constant.value) : void 0;
|
|
102
|
+
// src/formal/semantics.ts
|
|
103
|
+
const child = (node, tag) => node.children.find((n) => n.tag === tag);
|
|
104
|
+
const value = (node, tag) => child(node, tag)?.text.trim() ?? "";
|
|
105
|
+
const descendants = (node) => [node, ...node.children.flatMap(descendants)];
|
|
106
|
+
const fromXml = (xml) => {
|
|
107
|
+
const root = {
|
|
108
|
+
tag: "document",
|
|
109
|
+
text: "",
|
|
110
|
+
children: []
|
|
111
|
+
};
|
|
112
|
+
const stack = [root];
|
|
113
|
+
for (const match of xml.matchAll(/<!\[CDATA\[[\s\S]*?\]\]>|<\?[^>]*\?>|<([^>]+)>|([^<]+)/gu)) {
|
|
114
|
+
const token = match[0];
|
|
115
|
+
const parent = stack.at(-1);
|
|
116
|
+
if (parent === void 0) throw new Error("invalid SANY XML stack");
|
|
117
|
+
if (token.startsWith("<!") || token.startsWith("<?")) continue;
|
|
118
|
+
if (token.startsWith("</")) {
|
|
119
|
+
if (stack.pop()?.tag !== token.slice(2, -1)) throw new Error("invalid SANY XML closing tag");
|
|
120
|
+
} else if (token.startsWith("<")) {
|
|
121
|
+
const node = {
|
|
122
|
+
tag: token.slice(1, token.endsWith("/>") ? -2 : -1),
|
|
123
|
+
text: "",
|
|
124
|
+
children: []
|
|
125
|
+
};
|
|
126
|
+
parent.children.push(node);
|
|
127
|
+
if (!token.endsWith("/>")) stack.push(node);
|
|
128
|
+
} else parent.text += token.replaceAll("<", "<").replaceAll(">", ">").replaceAll("&", "&");
|
|
129
|
+
}
|
|
130
|
+
const modules = child(root, "modules");
|
|
131
|
+
const context = modules && child(modules, "context");
|
|
132
|
+
if (stack.length !== 1 || !modules || !context) throw new Error("missing SANY XML context");
|
|
133
|
+
const entries = new Map(context.children.map((entry) => [value(entry, "UID"), entry.children.find((n) => n.tag !== "UID")]));
|
|
134
|
+
const module = [...entries.values()].find((n) => n?.tag === "ModuleNode" && value(n, "uniquename") === value(modules, "RootModule"));
|
|
135
|
+
if (!module) throw new Error("missing root module in SANY XML");
|
|
136
|
+
const closure = /* @__PURE__ */ new Set();
|
|
137
|
+
const visitModule = (node) => {
|
|
138
|
+
if (closure.has(value(node, "uniquename"))) return;
|
|
139
|
+
closure.add(value(node, "uniquename"));
|
|
140
|
+
for (const ref of descendants(child(node, "extends") ?? {
|
|
141
|
+
tag: "",
|
|
142
|
+
text: "",
|
|
143
|
+
children: []
|
|
144
|
+
})) {
|
|
145
|
+
if (ref.tag !== "uniquename") continue;
|
|
146
|
+
const next = [...entries.values()].find((entry) => entry?.tag === "ModuleNode" && value(entry, "uniquename") === ref.text.trim());
|
|
147
|
+
if (!next) throw new Error("unresolved SANY EXTENDS module");
|
|
148
|
+
visitModule(next);
|
|
149
|
+
}
|
|
150
|
+
};
|
|
151
|
+
visitModule(module);
|
|
152
|
+
const variables = new Map([...entries].flatMap(([uid, node]) => node?.tag === "OpDeclNode" && value(node, "kind") === "3" && closure.has(value(child(node, "location") ?? node, "filename")) ? [[uid, value(node, "uniquename")]] : []));
|
|
153
|
+
const target = (appl) => {
|
|
154
|
+
const ref = child(appl, "operator")?.children[0];
|
|
155
|
+
return ref && {
|
|
156
|
+
ref,
|
|
157
|
+
uid: value(ref, "UID")
|
|
158
|
+
};
|
|
159
|
+
};
|
|
160
|
+
const operands = (appl) => child(appl, "operands")?.children ?? [];
|
|
161
|
+
const reaches = (body, seen = /* @__PURE__ */ new Set()) => {
|
|
162
|
+
const reached = /* @__PURE__ */ new Set();
|
|
163
|
+
for (const n of descendants(body)) {
|
|
164
|
+
if (!n.tag.endsWith("Ref")) continue;
|
|
165
|
+
const uid = value(n, "UID");
|
|
166
|
+
const variable = variables.get(uid);
|
|
167
|
+
if (variable !== void 0) reached.add(variable);
|
|
168
|
+
if (seen.has(uid)) continue;
|
|
169
|
+
seen.add(uid);
|
|
170
|
+
const next = child(entries.get(uid) ?? n, "body");
|
|
171
|
+
if (next) for (const v of reaches(next, seen)) reached.add(v);
|
|
172
|
+
}
|
|
173
|
+
return reached;
|
|
174
|
+
};
|
|
175
|
+
const typed = (appl, seen) => {
|
|
176
|
+
if (appl.tag === "LetInNode") {
|
|
177
|
+
const body = child(appl, "body")?.children[0];
|
|
178
|
+
return body ? typed(body, seen) : [];
|
|
179
|
+
}
|
|
180
|
+
const op = target(appl);
|
|
181
|
+
if (appl.tag !== "OpApplNode" || op === void 0) return [];
|
|
182
|
+
const args = operands(appl);
|
|
183
|
+
if (op.ref.tag === "UserDefinedOpKindRef" && args.length === 0) {
|
|
184
|
+
if (seen.has(op.uid)) return [];
|
|
185
|
+
seen.add(op.uid);
|
|
186
|
+
const body = child(entries.get(op.uid) ?? appl, "body");
|
|
187
|
+
return body?.children[0] ? typed(body.children[0], seen) : [];
|
|
188
|
+
}
|
|
189
|
+
if (op.ref.tag !== "BuiltInKindRef") return [];
|
|
190
|
+
const name = value(entries.get(op.uid) ?? appl, "uniquename");
|
|
191
|
+
if (name === "$ConjList" || name === "\\land") return args.flatMap((arg) => typed(arg, seen));
|
|
192
|
+
const [left, set] = args;
|
|
193
|
+
const variable = left && target(left)?.ref.tag === "OpDeclNodeRef" ? variables.get(target(left)?.uid ?? "") : void 0;
|
|
194
|
+
return (name === "\\in" || name === "\\subseteq") && args.length === 2 && variable !== void 0 && set !== void 0 && !reaches(set).has(variable) ? [variable] : [];
|
|
195
|
+
};
|
|
196
|
+
const typeOK = module.children.filter((n) => n.tag === "UserDefinedOpKindRef").map((ref) => entries.get(value(ref, "UID"))).find((node) => node !== void 0 && value(node, "uniquename") === "TypeOK");
|
|
197
|
+
const body = typeOK && child(typeOK, "body")?.children[0];
|
|
198
|
+
return {
|
|
199
|
+
variables: [...new Set(variables.values())],
|
|
200
|
+
typeOK: typeOK && new Set(body ? typed(body, /* @__PURE__ */ new Set()) : [])
|
|
201
|
+
};
|
|
202
|
+
};
|
|
203
|
+
// src/formal/tla.ts
|
|
204
|
+
var FormalError = class extends Data.TaggedError("FormalError") {};
|
|
205
|
+
const pins = [{
|
|
206
|
+
file: "tla2tools-1.8.0.jar",
|
|
207
|
+
url: "https://github.com/tlaplus/tlaplus/releases/download/v1.8.0/tla2tools.jar",
|
|
208
|
+
sha256: "e1f11b75c4b5bc4478ba0ac5cb6ae28e40a01b0016bc33e0aa97da22dfdbcd7f"
|
|
209
|
+
}, {
|
|
210
|
+
file: "CommunityModules-deps-202611060952.jar",
|
|
211
|
+
url: "https://github.com/tlaplus/CommunityModules/releases/download/202611060952/CommunityModules-deps-202611060952.jar",
|
|
212
|
+
sha256: "a3b27c40f1fb5085f30c6ead37e918457f8cfc62c1e50a1dc668ef592ad2b5fb"
|
|
213
|
+
}];
|
|
214
|
+
const error = (cause) => new FormalError({ message: cause instanceof Error ? cause.message : String(cause) });
|
|
215
|
+
const digest = (bytes) => createHash("sha256").update(bytes).digest("hex");
|
|
216
|
+
const messages = (output) => [...output.matchAll(/@!@!@STARTMSG (\d+):([0-4]) @!@!@([\s\S]*?)@!@!@ENDMSG \1 @!@!@/gu)].map((match) => ({
|
|
217
|
+
code: Number(match[1]),
|
|
218
|
+
severity: Number(match[2]),
|
|
219
|
+
text: (match[3] ?? "").trim()
|
|
220
|
+
}));
|
|
221
|
+
const sanyReport = (output) => output.split("\n").filter((line) => !/^(?:\*{6} SANY2 Version|Parsing file |Semantic processing of module |Linting of module )/u.test(line)).join("\n").trim();
|
|
222
|
+
const make = Effect.gen(function* () {
|
|
223
|
+
const fs = yield* FileSystem;
|
|
224
|
+
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
|
225
|
+
const path = yield* Path;
|
|
226
|
+
const cacheHome = yield* Config.String("XDG_CACHE_HOME").pipe(Config.withDefault(""));
|
|
227
|
+
const home = cacheHome !== "" ? cacheHome : path.join(yield* Config.String("HOME"), ".cache");
|
|
228
|
+
const cache = path.join(home, "tla");
|
|
229
|
+
yield* fs.makeDirectory(cache, { recursive: true });
|
|
230
|
+
const jars = [];
|
|
231
|
+
for (const pin of pins) {
|
|
232
|
+
const file = path.join(cache, pin.file);
|
|
233
|
+
if (yield* fs.exists(file)) {
|
|
234
|
+
const actual = digest(yield* fs.readFile(file));
|
|
235
|
+
if (actual !== pin.sha256) return yield* new FormalError({ message: `${file} has sha256 ${actual}, expected ${pin.sha256}; delete it to refetch` });
|
|
236
|
+
} else yield* Effect.scoped(Effect.gen(function* () {
|
|
237
|
+
const temp = yield* fs.makeTempFileScoped({
|
|
238
|
+
directory: cache,
|
|
239
|
+
prefix: `.${pin.file}.`,
|
|
240
|
+
suffix: ".part"
|
|
241
|
+
});
|
|
242
|
+
const bytes = yield* HttpClient.get(pin.url).pipe(Effect.flatMap((response) => response.status === 200 ? response.arrayBuffer.pipe(Effect.mapError(error)) : Effect.fail(new FormalError({ message: pin.url + ": HTTP " + response.status }))), Effect.map((buffer) => new Uint8Array(buffer)), Effect.timeout("120 seconds"), Effect.provide(FetchHttpClient.layer));
|
|
243
|
+
yield* fs.writeFile(temp, bytes);
|
|
244
|
+
const actual = digest(bytes);
|
|
245
|
+
if (actual !== pin.sha256) return yield* new FormalError({ message: `${pin.url} has sha256 ${actual}, expected ${pin.sha256}` });
|
|
246
|
+
return yield* fs.rename(temp, file);
|
|
247
|
+
}));
|
|
248
|
+
jars.push(file);
|
|
249
|
+
}
|
|
250
|
+
const classpath = jars.join(":");
|
|
251
|
+
const run = Effect.fn("formal.java")(function* (args, cwd, seconds = 120) {
|
|
252
|
+
return yield* Effect.scoped(Effect.gen(function* () {
|
|
253
|
+
const process = yield* ChildProcess.make("java", args, {
|
|
254
|
+
cwd,
|
|
255
|
+
stdin: "ignore",
|
|
256
|
+
killSignal: "SIGKILL"
|
|
257
|
+
});
|
|
258
|
+
return yield* Effect.all([
|
|
259
|
+
process.stdout.pipe(Stream.decodeText, Stream.mkString),
|
|
260
|
+
process.stderr.pipe(Stream.decodeText, Stream.mkString),
|
|
261
|
+
process.exitCode
|
|
262
|
+
], { concurrency: "unbounded" });
|
|
263
|
+
}).pipe(Effect.timeoutOption(`${seconds} seconds`), Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), Effect.mapError(error)));
|
|
264
|
+
});
|
|
265
|
+
const version = yield* run(["-XshowSettings:properties", "-version"], cache);
|
|
266
|
+
if (Option.isNone(version) || Number(version.value[2]) !== 0 || !/^\s*java\.specification\.version = 17\s*$/mu.test(version.value[1])) return yield* new FormalError({ message: "Java 17 is required on PATH" });
|
|
267
|
+
const invoke = (args, cwd, seconds) => run([
|
|
268
|
+
"-XX:+UseParallelGC",
|
|
269
|
+
"-cp",
|
|
270
|
+
classpath,
|
|
271
|
+
...args
|
|
272
|
+
], cwd, seconds);
|
|
273
|
+
return {
|
|
274
|
+
fixCommand: (file) => `java -cp ${JSON.stringify(classpath)} formatter.Main ${JSON.stringify(file)} ${JSON.stringify(file)}`,
|
|
275
|
+
analyze: Effect.fn("formal.analyze")(function* (file) {
|
|
276
|
+
const sany = yield* invoke([
|
|
277
|
+
"tla2sany.SANY",
|
|
278
|
+
"-error-codes",
|
|
279
|
+
"-messagesAsErrors",
|
|
280
|
+
"4800,4801,4802,4803,4804,4805",
|
|
281
|
+
path.basename(file)
|
|
282
|
+
], path.dirname(file));
|
|
283
|
+
if (Option.isNone(sany)) return {
|
|
284
|
+
_tag: "Unparsed",
|
|
285
|
+
output: "SANY timed out"
|
|
286
|
+
};
|
|
287
|
+
const [stdout, stderr, code] = sany.value;
|
|
288
|
+
if (Number(code) !== 0 || /\*\*\* Warnings:/u.test(stdout + stderr)) return {
|
|
289
|
+
_tag: "Unparsed",
|
|
290
|
+
output: sanyReport(stdout + stderr)
|
|
291
|
+
};
|
|
292
|
+
const xml = yield* invoke([
|
|
293
|
+
"tla2sany.xml.XMLExporter",
|
|
294
|
+
"-o",
|
|
295
|
+
"-t",
|
|
296
|
+
path.basename(file)
|
|
297
|
+
], path.dirname(file));
|
|
298
|
+
if (Option.isNone(xml)) return {
|
|
299
|
+
_tag: "Unparsed",
|
|
300
|
+
output: "XMLExporter timed out"
|
|
301
|
+
};
|
|
302
|
+
if (Number(xml.value[2]) !== 0) return {
|
|
303
|
+
_tag: "Unparsed",
|
|
304
|
+
output: xml.value[0] + xml.value[1]
|
|
305
|
+
};
|
|
306
|
+
return yield* Effect.try({
|
|
307
|
+
try: () => ({
|
|
308
|
+
_tag: "Parsed",
|
|
309
|
+
semantics: fromXml(xml.value[0])
|
|
310
|
+
}),
|
|
311
|
+
catch: error
|
|
312
|
+
});
|
|
313
|
+
}),
|
|
314
|
+
format: Effect.fn("formal.format")(function* (file) {
|
|
315
|
+
return yield* Effect.scoped(Effect.gen(function* () {
|
|
316
|
+
const temp = yield* fs.makeTempDirectoryScoped({ prefix: "formal-format-" });
|
|
317
|
+
const output = path.join(temp, path.basename(file));
|
|
318
|
+
const result = yield* invoke([
|
|
319
|
+
"formatter.Main",
|
|
320
|
+
"-v",
|
|
321
|
+
"ERROR",
|
|
322
|
+
file,
|
|
323
|
+
output
|
|
324
|
+
], path.dirname(file));
|
|
325
|
+
if (Option.isNone(result)) return {
|
|
326
|
+
_tag: "Failed",
|
|
327
|
+
output: "formatter timed out"
|
|
328
|
+
};
|
|
329
|
+
if (Number(result.value[2]) !== 0 || !(yield* fs.exists(output))) return {
|
|
330
|
+
_tag: "Failed",
|
|
331
|
+
output: `formatter exited ${result.value[2]}: ${result.value[0]} ${result.value[1]}`
|
|
332
|
+
};
|
|
333
|
+
return {
|
|
334
|
+
_tag: "Formatted",
|
|
335
|
+
text: yield* fs.readFileString(output)
|
|
336
|
+
};
|
|
337
|
+
})).pipe(Effect.mapError(error));
|
|
338
|
+
}),
|
|
339
|
+
tlc: Effect.fn("formal.tlc")(function* (input) {
|
|
340
|
+
return yield* Effect.scoped(Effect.gen(function* () {
|
|
341
|
+
const temp = yield* fs.makeTempDirectoryScoped({ prefix: "formal-tlc-" });
|
|
342
|
+
const started = yield* Clock.currentTimeMillis;
|
|
343
|
+
const result = yield* invoke([
|
|
344
|
+
"tlc2.TLC",
|
|
345
|
+
"-tool",
|
|
346
|
+
"-workers",
|
|
347
|
+
"auto",
|
|
348
|
+
"-metadir",
|
|
349
|
+
temp,
|
|
350
|
+
"-noGenerateSpecTE",
|
|
351
|
+
"-config",
|
|
352
|
+
input.config,
|
|
353
|
+
path.basename(input.spec)
|
|
354
|
+
], path.dirname(input.spec), input.timeoutSeconds);
|
|
355
|
+
const seconds = ((yield* Clock.currentTimeMillis) - started) / 1e3;
|
|
356
|
+
if (Option.isNone(result)) return { _tag: "TimedOut" };
|
|
357
|
+
return {
|
|
358
|
+
_tag: "Exited",
|
|
359
|
+
seconds,
|
|
360
|
+
code: Number(result.value[2]),
|
|
361
|
+
messages: messages(result.value[0] + result.value[1])
|
|
362
|
+
};
|
|
363
|
+
})).pipe(Effect.mapError(error));
|
|
364
|
+
})
|
|
365
|
+
};
|
|
366
|
+
}).pipe(Effect.mapError(error));
|
|
367
|
+
var Tla = class Tla extends Context.Service()("formal/Tla") {
|
|
368
|
+
static layer = Layer.effect(Tla, make);
|
|
369
|
+
};
|
|
370
|
+
// src/formal/checks.ts
|
|
371
|
+
const configs = (repo) => repo.specs.filter((s) => s.analysis._tag === "Parsed").flatMap((s) => s.configs).flatMap((c) => "_tag" in c.cfg ? [] : [{
|
|
372
|
+
path: c.path,
|
|
373
|
+
cfg: c.cfg
|
|
374
|
+
}]);
|
|
375
|
+
const specs = (repo) => Effect.succeed([
|
|
376
|
+
...repo.decodeErrors.map((message) => ({
|
|
377
|
+
file: "specs.json",
|
|
378
|
+
message
|
|
379
|
+
})),
|
|
380
|
+
...repo.specs.flatMap((s) => [
|
|
381
|
+
...!s.entry && repo.decodeErrors.length === 0 ? [{
|
|
382
|
+
file: s.path,
|
|
383
|
+
message: "tracked spec has no specs.json entry"
|
|
384
|
+
}] : [],
|
|
385
|
+
...s.entry?.mode === "gate" && !s.configs.some((c) => c.path === s.path.replace(/\.tla$/u, ".cfg")) ? [{
|
|
386
|
+
file: s.path,
|
|
387
|
+
message: "gate spec has no matching .cfg"
|
|
388
|
+
}] : [],
|
|
389
|
+
...s.configs.flatMap((c) => "_tag" in c.cfg ? [{
|
|
390
|
+
file: c.path,
|
|
391
|
+
message: c.cfg.message
|
|
392
|
+
}] : [])
|
|
393
|
+
]),
|
|
394
|
+
...Object.keys(repo.file).filter((f) => f.endsWith(".tla") && !repo.tracked.includes(f)).map((file) => ({
|
|
395
|
+
file,
|
|
396
|
+
message: "entry names no tracked file"
|
|
397
|
+
})),
|
|
398
|
+
...repo.orphans.map((file) => ({
|
|
399
|
+
file,
|
|
400
|
+
message: "orphan config has no matching module"
|
|
401
|
+
}))
|
|
402
|
+
]);
|
|
403
|
+
const sany = (repo) => Effect.succeed(repo.specs.flatMap((s) => s.analysis._tag === "Unparsed" ? [{
|
|
404
|
+
file: s.path,
|
|
405
|
+
message: s.analysis.output
|
|
406
|
+
}] : []));
|
|
407
|
+
const typeok = (repo) => Effect.succeed([...configs(repo).filter((c) => !c.cfg.invariants.includes("TypeOK")).map((c) => ({
|
|
408
|
+
file: c.path,
|
|
409
|
+
message: "does not check INVARIANT TypeOK"
|
|
410
|
+
})), ...repo.specs.flatMap((s) => {
|
|
411
|
+
if (s.analysis._tag !== "Parsed" || s.configs.length === 0) return [];
|
|
412
|
+
const typed = s.analysis.semantics.typeOK;
|
|
413
|
+
if (!typed) return s.configs.some((c) => !("_tag" in c.cfg) && c.cfg.invariants.includes("TypeOK")) ? [{
|
|
414
|
+
file: s.path,
|
|
415
|
+
message: "TypeOK is not defined"
|
|
416
|
+
}] : [];
|
|
417
|
+
const missing = s.analysis.semantics.variables.filter((v) => !typed.has(v));
|
|
418
|
+
return missing.length ? [{
|
|
419
|
+
file: s.path,
|
|
420
|
+
message: `TypeOK does not constrain ${missing.join(", ")}; give each a conjunct such as ${missing[0]} \\in S`
|
|
421
|
+
}] : [];
|
|
422
|
+
})]);
|
|
423
|
+
const deadlock = (repo) => Effect.succeed(configs(repo).filter((c) => c.cfg.checkDeadlock.includes(false)).map((c) => ({
|
|
424
|
+
file: c.path,
|
|
425
|
+
message: "CHECK_DEADLOCK FALSE; give the bounded spec an explicit finished step"
|
|
426
|
+
})));
|
|
427
|
+
const constants = (repo) => Effect.succeed(configs(repo).flatMap((c) => {
|
|
428
|
+
const groups = /* @__PURE__ */ new Map();
|
|
429
|
+
for (const constant of c.cfg.constants) {
|
|
430
|
+
const n = integer(constant);
|
|
431
|
+
if (n === void 0) continue;
|
|
432
|
+
groups.set(n, [...groups.get(n) ?? [], constant.name]);
|
|
433
|
+
}
|
|
434
|
+
return [...groups].filter(([, names]) => names.length > 1).map(([n, names]) => ({
|
|
435
|
+
file: c.path,
|
|
436
|
+
message: `${names.length === 2 ? names.join(" and ") : `${names.slice(0, -1).join(", ")} and ${names.at(-1)}`} ${names.length === 2 ? "both" : "all"} equal ${n}`
|
|
437
|
+
}));
|
|
438
|
+
}));
|
|
439
|
+
const format = (repo) => Effect.gen(function* () {
|
|
440
|
+
const tla = yield* Tla;
|
|
441
|
+
const fs = yield* FileSystem;
|
|
442
|
+
return (yield* Effect.forEach(repo.specs.filter((s) => s.analysis._tag === "Parsed"), (s) => Effect.gen(function* () {
|
|
443
|
+
const result = yield* tla.format(`${repo.root}/${s.path}`);
|
|
444
|
+
if (result._tag === "Failed") return [{
|
|
445
|
+
file: s.path,
|
|
446
|
+
message: result.output
|
|
447
|
+
}];
|
|
448
|
+
const text = yield* fs.readFileString(`${repo.root}/${s.path}`);
|
|
449
|
+
if (text === result.text) return [];
|
|
450
|
+
const lines = text.split("\n");
|
|
451
|
+
const expected = result.text.split("\n");
|
|
452
|
+
let line = 0;
|
|
453
|
+
while (line < Math.max(lines.length, expected.length) && lines[line] === expected[line]) line++;
|
|
454
|
+
return [{
|
|
455
|
+
file: s.path,
|
|
456
|
+
message: `differs from formatter.Main at line ${line + 1}; run ${tla.fixCommand(s.path)}`
|
|
457
|
+
}];
|
|
458
|
+
}), { concurrency: 4 })).flat();
|
|
459
|
+
}).pipe(Effect.mapError((cause) => new FormalError({ message: String(cause) })));
|
|
460
|
+
const tlc = (repo) => Effect.gen(function* () {
|
|
461
|
+
const tla = yield* Tla;
|
|
462
|
+
const problems = [];
|
|
463
|
+
for (const s of repo.specs) {
|
|
464
|
+
if (s.analysis._tag !== "Parsed" || s.entry?.mode !== "gate") continue;
|
|
465
|
+
const config = s.configs.find((c) => c.path === s.path.replace(/\.tla$/u, ".cfg"));
|
|
466
|
+
if (!config || "_tag" in config.cfg) continue;
|
|
467
|
+
const run = yield* tla.tlc({
|
|
468
|
+
spec: `${repo.root}/${s.path}`,
|
|
469
|
+
config: `${repo.root}/${config.path}`,
|
|
470
|
+
timeoutSeconds: s.entry.timeoutSeconds
|
|
471
|
+
});
|
|
472
|
+
if (run._tag === "TimedOut") {
|
|
473
|
+
problems.push({
|
|
474
|
+
file: config.path,
|
|
475
|
+
message: `TLC timed out after ${s.entry.timeoutSeconds} s`
|
|
476
|
+
});
|
|
477
|
+
continue;
|
|
478
|
+
}
|
|
479
|
+
const failures = run.messages.filter((m) => m.severity >= 1 && m.severity <= 3);
|
|
480
|
+
const states = run.messages.find((m) => m.code === 2199)?.text.match(/([\d,]+) distinct states/u)?.[1]?.replaceAll(",", "");
|
|
481
|
+
if (failures.length || run.code !== 0 || !run.messages.some((m) => m.code === 2193) || states === void 0 || BigInt(states) === 0n) {
|
|
482
|
+
const meaning = /* @__PURE__ */ new Map([
|
|
483
|
+
[11, "deadlock"],
|
|
484
|
+
[12, "safety violation"],
|
|
485
|
+
[13, "liveness violation"],
|
|
486
|
+
[150, "parse failure"]
|
|
487
|
+
]);
|
|
488
|
+
problems.push({
|
|
489
|
+
file: config.path,
|
|
490
|
+
message: `TLC exited ${run.code}${meaning.has(run.code) ? ` (${meaning.get(run.code)})` : ""}; ${failures.length ? failures.map((m) => `${m.severity === 3 ? "warning" : "error"} ${m.code}: ${m.text}`).join("; ") : "requires 2193 success and nonzero distinct states (2199)"}`
|
|
491
|
+
});
|
|
492
|
+
} else yield* Console.log(`tlc: ${config.path}: ${states} distinct states in ${run.seconds} s`);
|
|
493
|
+
}
|
|
494
|
+
return problems;
|
|
495
|
+
});
|
|
496
|
+
const checks = {
|
|
497
|
+
specs,
|
|
498
|
+
sany,
|
|
499
|
+
typeok,
|
|
500
|
+
deadlock,
|
|
501
|
+
constants,
|
|
502
|
+
format,
|
|
503
|
+
tlc
|
|
504
|
+
};
|
|
505
|
+
// src/formal/specs.ts
|
|
506
|
+
const RepoPath = Schema.String.check(Schema.isPattern(/^(?!\/)(?!(?:.*\/)?\.\.(?:\/|$))[^\0\\]+$/u));
|
|
507
|
+
const OperatorName = Schema.String.check(Schema.isPattern(/^[A-Za-z_][A-Za-z0-9_]*$/u));
|
|
508
|
+
const Entry = Schema.Struct({
|
|
509
|
+
synced: Schema.String.check(Schema.isPattern(/^[0-9a-f]{40}$/u)),
|
|
510
|
+
covers: Schema.NonEmptyArray(Schema.NonEmptyString),
|
|
511
|
+
mode: Schema.Literals(["gate", "manual"]),
|
|
512
|
+
timeoutSeconds: Schema.Int.check(Schema.isBetween({
|
|
513
|
+
minimum: 1,
|
|
514
|
+
maximum: 1800
|
|
515
|
+
})).pipe(Schema.withDecodingDefaultKey(Effect.succeed(60))),
|
|
516
|
+
witnesses: Schema.Array(OperatorName).pipe(Schema.withDecodingDefaultKey(Effect.succeed([]))),
|
|
517
|
+
breaks: Schema.Array(Schema.Struct({
|
|
518
|
+
violates: OperatorName,
|
|
519
|
+
find: Schema.NonEmptyString,
|
|
520
|
+
replace: Schema.String,
|
|
521
|
+
file: Schema.optionalKey(RepoPath)
|
|
522
|
+
})).pipe(Schema.withDecodingDefaultKey(Effect.succeed([]))),
|
|
523
|
+
traces: Schema.optionalKey(Schema.Struct({
|
|
524
|
+
seed: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
|
|
525
|
+
depth: Schema.Int.check(Schema.isBetween({
|
|
526
|
+
minimum: 1,
|
|
527
|
+
maximum: 1e4
|
|
528
|
+
})),
|
|
529
|
+
count: Schema.Int.check(Schema.isBetween({
|
|
530
|
+
minimum: 1,
|
|
531
|
+
maximum: 1e5
|
|
532
|
+
}))
|
|
533
|
+
})),
|
|
534
|
+
conformance: Schema.optionalKey(RepoPath)
|
|
535
|
+
}).check(Schema.makeFilter((entry) => entry.traces === void 0 === (entry.conformance === void 0) || "traces and conformance go together"));
|
|
536
|
+
const SpecsFile = Schema.Record(RepoPath.check(Schema.isPattern(/\.(?:tla|rs)$/u)), Entry);
|
|
537
|
+
const load = Effect.fn("formal.load")(function* (root) {
|
|
538
|
+
const fs = yield* FileSystem;
|
|
539
|
+
const path = yield* Path;
|
|
540
|
+
const tla = yield* Tla;
|
|
541
|
+
const git = yield* ChildProcess.make("git", ["ls-files", "-z"], {
|
|
542
|
+
cwd: root,
|
|
543
|
+
stdin: "ignore"
|
|
544
|
+
});
|
|
545
|
+
const [files, code] = yield* Effect.all([git.stdout.pipe(Stream.decodeText, Stream.mkString), git.exitCode], { concurrency: "unbounded" });
|
|
546
|
+
if (Number(code) !== 0) return yield* new FormalError({ message: "git ls-files failed" });
|
|
547
|
+
const tracked = yield* Effect.filter(files.split("\0").filter(Boolean), (file) => fs.exists(path.join(root, file)));
|
|
548
|
+
let file = {};
|
|
549
|
+
let decodeErrors = [];
|
|
550
|
+
if (yield* fs.exists(path.join(root, "specs.json"))) {
|
|
551
|
+
const raw = yield* fs.readFileString(path.join(root, "specs.json"));
|
|
552
|
+
const decoded = Schema.decodeResult(Schema.fromJsonString(SpecsFile))(raw, {
|
|
553
|
+
errors: "all",
|
|
554
|
+
onExcessProperty: "error"
|
|
555
|
+
});
|
|
556
|
+
if (Result.isSuccess(decoded)) file = decoded.success;
|
|
557
|
+
else decodeErrors = SchemaIssue.makeFormatterStandardSchemaV1()(decoded.failure.issue).issues.map(({ message, path: at = [] }) => at.length === 0 ? message : `${at.map((key) => `[${JSON.stringify(typeof key === "object" ? key.key : key)}]`).join("")}: ${message}`);
|
|
558
|
+
}
|
|
559
|
+
const modules = tracked.filter((f) => f.endsWith(".tla"));
|
|
560
|
+
const configs = tracked.filter((f) => f.endsWith(".cfg") && modules.some((m) => path.dirname(m) === path.dirname(f)));
|
|
561
|
+
const paired = /* @__PURE__ */ new Set();
|
|
562
|
+
const specs = yield* Effect.forEach(modules, (module) => Effect.gen(function* () {
|
|
563
|
+
const stem = module.slice(0, -4);
|
|
564
|
+
const matches = configs.filter((c) => c === `${stem}.cfg` || c.startsWith(`${stem}.`) && path.dirname(c) === path.dirname(module));
|
|
565
|
+
const parsed = yield* Effect.forEach(matches, (c) => Effect.gen(function* () {
|
|
566
|
+
paired.add(c);
|
|
567
|
+
return {
|
|
568
|
+
path: c,
|
|
569
|
+
cfg: parseCfg(yield* fs.readFileString(path.join(root, c)))
|
|
570
|
+
};
|
|
571
|
+
}), { concurrency: 1 });
|
|
572
|
+
return {
|
|
573
|
+
path: module,
|
|
574
|
+
entry: file[module],
|
|
575
|
+
analysis: yield* tla.analyze(path.join(root, module)),
|
|
576
|
+
configs: parsed
|
|
577
|
+
};
|
|
578
|
+
}), { concurrency: 4 });
|
|
579
|
+
return {
|
|
580
|
+
root,
|
|
581
|
+
tracked,
|
|
582
|
+
file,
|
|
583
|
+
specs,
|
|
584
|
+
orphans: configs.filter((c) => !paired.has(c)),
|
|
585
|
+
decodeErrors
|
|
586
|
+
};
|
|
587
|
+
});
|
|
588
|
+
// src/formal.ts
|
|
589
|
+
const singleLine = (message) => message.replaceAll(/\s+/gu, " ").trim();
|
|
590
|
+
const checkName = (name) => Object.hasOwn(checks, name);
|
|
591
|
+
const formal = Effect.fn("formal")(function* (root) {
|
|
592
|
+
const repo = yield* load(root);
|
|
593
|
+
const findings = [];
|
|
594
|
+
for (const name of Object.keys(checks)) {
|
|
595
|
+
if (!checkName(name)) continue;
|
|
596
|
+
const problems = yield* checks[name](repo);
|
|
597
|
+
findings.push(...problems.map((problem) => ({
|
|
598
|
+
...problem,
|
|
599
|
+
check: name
|
|
600
|
+
})));
|
|
601
|
+
}
|
|
602
|
+
findings.sort((a, b) => a.file.localeCompare(b.file) || a.check.localeCompare(b.check));
|
|
603
|
+
if (findings.length) {
|
|
604
|
+
for (const f of findings) yield* Console.error(`${f.file}: ${f.check}: ${singleLine(f.message)}`);
|
|
605
|
+
yield* Console.error(`formal: ${findings.length} ${findings.length === 1 ? "finding" : "findings"}`);
|
|
606
|
+
} else yield* Console.log(`formal: ${repo.specs.length} specs, ${repo.specs.reduce((n, s) => n + s.configs.length, 0)} configs, no findings`);
|
|
607
|
+
return findings.length ? 1 : 0;
|
|
608
|
+
});
|
|
609
|
+
if (import.meta.main) {
|
|
610
|
+
if (process.argv.length > 2) {
|
|
611
|
+
process.stderr.write("usage: formal\n");
|
|
612
|
+
process.exitCode = 2;
|
|
613
|
+
} else {
|
|
614
|
+
const exit = await Effect.runPromiseExit(Effect.scoped(Effect.gen(function* () {
|
|
615
|
+
const git = yield* ChildProcess.make("git", ["rev-parse", "--show-toplevel"], { stdin: "ignore" });
|
|
616
|
+
const [root, code] = yield* Effect.all([git.stdout.pipe(Stream.decodeText, Stream.mkString), git.exitCode], { concurrency: "unbounded" });
|
|
617
|
+
if (Number(code) !== 0) return yield* new FormalError({ message: "run formal inside a git repository" });
|
|
618
|
+
return yield* formal(root.trim()).pipe(Effect.provide(Tla.layer));
|
|
619
|
+
})).pipe(Effect.provide(NodeServices.layer)));
|
|
620
|
+
if (Exit.isSuccess(exit)) process.exitCode = exit.value;
|
|
621
|
+
else {
|
|
622
|
+
const error = Cause.squash(exit.cause);
|
|
623
|
+
process.stderr.write(`formal: ${singleLine(error instanceof Error ? error.message : String(error))}\n`);
|
|
624
|
+
process.exitCode = 1;
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
export { formal };
|
package/dist/hooks.mjs
CHANGED
|
@@ -2,10 +2,10 @@ import * as Arr from "effect/Array";
|
|
|
2
2
|
import * as Schema from "effect/Schema";
|
|
3
3
|
import * as Str from "effect/String";
|
|
4
4
|
import * as Effect from "effect/Effect";
|
|
5
|
-
import { FileSystem } from "effect/FileSystem";
|
|
6
|
-
import { Path } from "effect/Path";
|
|
7
5
|
import { ChildProcess } from "effect/process";
|
|
8
6
|
import * as Stream from "effect/Stream";
|
|
7
|
+
import { FileSystem } from "effect/FileSystem";
|
|
8
|
+
import { Path } from "effect/Path";
|
|
9
9
|
// src/hooks.ts
|
|
10
10
|
const worktreePrePush = `#!/bin/sh
|
|
11
11
|
if ! root=$(git rev-parse --show-toplevel); then
|
package/dist/proof.mjs
CHANGED
|
@@ -2,16 +2,16 @@
|
|
|
2
2
|
import * as Data from "effect/Data";
|
|
3
3
|
import * as Schema from "effect/Schema";
|
|
4
4
|
import * as Effect from "effect/Effect";
|
|
5
|
-
import { FileSystem } from "effect/FileSystem";
|
|
6
|
-
import { Path } from "effect/Path";
|
|
7
|
-
import { ChildProcess } from "effect/process";
|
|
8
|
-
import * as Stream from "effect/Stream";
|
|
9
5
|
import { NodeServices } from "@effect/platform-node";
|
|
10
|
-
import { Octokit } from "@octokit/rest";
|
|
11
6
|
import * as Cause from "effect/Cause";
|
|
7
|
+
import * as Exit from "effect/Exit";
|
|
8
|
+
import { ChildProcess } from "effect/process";
|
|
9
|
+
import * as Stream from "effect/Stream";
|
|
10
|
+
import { FileSystem } from "effect/FileSystem";
|
|
12
11
|
import * as Config from "effect/Config";
|
|
12
|
+
import { Path } from "effect/Path";
|
|
13
|
+
import { Octokit } from "@octokit/rest";
|
|
13
14
|
import { Base64 } from "effect/encoding";
|
|
14
|
-
import * as Exit from "effect/Exit";
|
|
15
15
|
import * as Redacted from "effect/Redacted";
|
|
16
16
|
// src/proof.ts
|
|
17
17
|
var ProofError = class extends Data.TaggedError("ProofError") {};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { i as VerificationError } from "./verification-p2rSx5lc.mjs";
|
|
2
|
+
import * as Effect from "effect/Effect";
|
|
3
|
+
export declare const checkVerdict: Effect.Effect<number, import("effect/Config").ConfigError | import("effect/PlatformError").PlatformError | import("effect/Schema").SchemaError | VerificationError, import("effect/FileSystem").FileSystem>;
|