@milkenjoyer/toolchain 0.10.0 → 0.12.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.
Files changed (39) hide show
  1. package/README.md +117 -0
  2. package/dist/conformance.d.mts +18 -0
  3. package/dist/conformance.mjs +31 -0
  4. package/dist/effect-plugin.mjs +1 -1
  5. package/dist/exceptions-Dybl9xpc.mjs +11 -0
  6. package/dist/exceptions.mjs +1 -1
  7. package/dist/foldkit-plugin.mjs +1 -1
  8. package/dist/formal.d.mts +188 -0
  9. package/dist/formal.mjs +1279 -0
  10. package/dist/guard.mjs +2 -2
  11. package/dist/hooks.mjs +2 -2
  12. package/dist/{lint-JSnPsGO1.mjs → lint-IhmtnBbx.mjs} +3 -3
  13. package/dist/lint.mjs +1 -1
  14. package/dist/plugin.mjs +1 -1
  15. package/dist/proof.mjs +6 -6
  16. package/dist/trace-file-KuPRWgwt.mjs +17 -0
  17. package/dist/verdict.d.mts +1 -1
  18. package/dist/verdict.mjs +2 -2
  19. package/dist/{verification-MNG9WKEH.d.mts → verification-FgQFU1YN.d.mts} +2 -2
  20. package/dist/verification.d.mts +1 -1
  21. package/dist/verification.mjs +1 -1
  22. package/package.json +9 -2
  23. package/src/formal/cfg.ts +168 -0
  24. package/src/formal/checks.ts +190 -0
  25. package/src/formal/coverage.ts +79 -0
  26. package/src/formal/gate.ts +74 -0
  27. package/src/formal/git.ts +38 -0
  28. package/src/formal/proofs.ts +217 -0
  29. package/src/formal/semantics.ts +255 -0
  30. package/src/formal/specs.ts +212 -0
  31. package/src/formal/tla.ts +306 -0
  32. package/src/formal/trace-file.ts +35 -0
  33. package/src/formal/traces.ts +293 -0
  34. package/src/formal/violations.ts +76 -0
  35. package/src/formal.ts +82 -0
  36. package/dist/exceptions-Bq-9MxoR.mjs +0 -3
  37. package/dist/{effect-plugin-kYxB-5LJ.mjs → effect-plugin-BXUx9PPu.mjs} +1 -1
  38. package/dist/{plugin-BoBRGtGf.mjs → plugin-CwxhPtui.mjs} +1 -1
  39. package/dist/{verification-2bhNnJr-.mjs → verification-oAc1Q6I9.mjs} +4 -4
@@ -0,0 +1,74 @@
1
+ import * as Cache from "effect/Cache";
2
+ import * as Context from "effect/Context";
3
+ import * as Effect from "effect/Effect";
4
+ import * as Layer from "effect/Layer";
5
+
6
+ import { coverage } from "./coverage.ts";
7
+ import type { Coverage } from "./coverage.ts";
8
+ import type { Model } from "./specs.ts";
9
+ import { Tla } from "./tla.ts";
10
+ import type { FormalError } from "./tla.ts";
11
+ type GateResult =
12
+ | {
13
+ readonly _tag: "Passed";
14
+ readonly states: string;
15
+ readonly seconds: number;
16
+ readonly coverage: Coverage;
17
+ }
18
+ | { readonly _tag: "Failed"; readonly message: string };
19
+ const make = Effect.gen(function* () {
20
+ const tla = yield* Tla;
21
+ const run = yield* Cache.make({
22
+ capacity: 10000,
23
+ lookup: Effect.fn("formal.gate")(function* (
24
+ m: Model
25
+ ): Effect.fn.Return<GateResult, FormalError> {
26
+ const r = yield* tla.tlc({
27
+ spec: `${m.root}/${m.path}`,
28
+ config: `${m.root}/${m.config.path}`,
29
+ timeoutSeconds: m.entry.timeoutSeconds,
30
+ mode: { _tag: "Check", coverage: true },
31
+ });
32
+ if (r._tag === "TimedOut")
33
+ return {
34
+ _tag: "Failed",
35
+ message: `TLC timed out after ${m.entry.timeoutSeconds} s`,
36
+ };
37
+ const failures = r.messages.filter(
38
+ (x) => x.severity >= 1 && x.severity <= 3
39
+ );
40
+ const states = r.messages
41
+ .find((x) => x.code === 2199)
42
+ ?.text.match(/([\d,]+) distinct states/u)?.[1]
43
+ ?.replaceAll(",", "");
44
+ if (
45
+ r.code !== 0 ||
46
+ failures.length ||
47
+ !r.messages.some((x) => x.code === 2193) ||
48
+ states === undefined ||
49
+ BigInt(states) === 0n
50
+ ) {
51
+ const meaning = new Map([
52
+ [11, "deadlock"],
53
+ [12, "safety violation"],
54
+ [13, "liveness violation"],
55
+ [150, "parse failure"],
56
+ ]);
57
+ return {
58
+ _tag: "Failed",
59
+ message: `TLC exited ${r.code}${meaning.has(r.code) ? ` (${meaning.get(r.code)})` : ""}; ${failures.length ? failures.map((x) => `${x.severity === 3 ? "warning" : "error"} ${x.code}: ${x.text}`).join("; ") : "requires 2193 success and nonzero distinct states (2199)"}`,
60
+ };
61
+ }
62
+ const c = coverage(r.messages);
63
+ return typeof c === "string"
64
+ ? { _tag: "Failed", message: c }
65
+ : { _tag: "Passed", states, seconds: r.seconds, coverage: c };
66
+ }),
67
+ });
68
+ return { run: (model: Model) => Cache.get(run, model) };
69
+ });
70
+ export class Gate extends Context.Service<Gate, Effect.Success<typeof make>>()(
71
+ "formal/Gate"
72
+ ) {
73
+ static readonly layer = Layer.effect(Gate, make);
74
+ }
@@ -0,0 +1,38 @@
1
+ import * as Config from "effect/Config";
2
+ import * as Effect from "effect/Effect";
3
+ import { ChildProcess } from "effect/process";
4
+ import * as Stream from "effect/Stream";
5
+ export const changes = Effect.fn("formal.changes")(function* (root: string) {
6
+ const base = yield* Config.String("BASE").pipe(
7
+ Config.withDefault("origin/main")
8
+ );
9
+ const run = (args: ReadonlyArray<string>) =>
10
+ Effect.scoped(
11
+ Effect.gen(function* () {
12
+ const p = yield* ChildProcess.make("git", args, {
13
+ cwd: root,
14
+ stdin: "ignore",
15
+ });
16
+ const [out, , code] = yield* Effect.all(
17
+ [
18
+ p.stdout.pipe(Stream.decodeText, Stream.mkString),
19
+ p.stderr.pipe(Stream.decodeText, Stream.mkString),
20
+ p.exitCode,
21
+ ],
22
+ { concurrency: "unbounded" }
23
+ );
24
+ return { out, code: Number(code) };
25
+ })
26
+ );
27
+ const merge = yield* run(["merge-base", base, "HEAD"]);
28
+ if (merge.code !== 0) return { _tag: "All" as const, base };
29
+ const sha = merge.out.trim();
30
+ const diff = yield* run(["diff", "--name-only", "-z", sha]);
31
+ return diff.code !== 0
32
+ ? { _tag: "All" as const, base }
33
+ : {
34
+ _tag: "Changed" as const,
35
+ sha,
36
+ files: diff.out.split("\0").filter(Boolean),
37
+ };
38
+ });
@@ -0,0 +1,217 @@
1
+ import { dirname, join } from "node:path";
2
+
3
+ import * as Console from "effect/Console";
4
+ import * as Effect from "effect/Effect";
5
+ import { FileSystem } from "effect/FileSystem";
6
+
7
+ import type { Check } from "./checks.ts";
8
+ import { Gate } from "./gate.ts";
9
+ import { changes } from "./git.ts";
10
+ import { FormalError } from "./tla.ts";
11
+ import { held, violate } from "./violations.ts";
12
+ const matches = (glob: string, file: string) => new Bun.Glob(glob).match(file);
13
+ export const critical: Check = (repo) =>
14
+ Effect.succeed([
15
+ ...repo.file.critical.flatMap((glob) =>
16
+ repo.tracked.some((f) => matches(glob, f))
17
+ ? []
18
+ : [
19
+ {
20
+ file: "specs.json",
21
+ message: `critical glob ${glob} matches no tracked file`,
22
+ },
23
+ ]
24
+ ),
25
+ ...Object.entries({ ...repo.file.specs, ...repo.file.kani }).flatMap(
26
+ ([file, e]) =>
27
+ e.covers.flatMap((glob) =>
28
+ repo.tracked.some((f) => matches(glob, f))
29
+ ? []
30
+ : [{ file, message: `covers glob ${glob} matches no tracked file` }]
31
+ )
32
+ ),
33
+ ...repo.tracked.flatMap((file) => {
34
+ const glob = repo.file.critical.find((g) => matches(g, file));
35
+ return glob !== undefined &&
36
+ !Object.values({ ...repo.file.specs, ...repo.file.kani }).some(
37
+ (e) => e.mode !== "library" && e.covers.some((g) => matches(g, file))
38
+ )
39
+ ? [
40
+ {
41
+ file,
42
+ message: `matches critical glob ${glob} but no spec covers it`,
43
+ },
44
+ ]
45
+ : [];
46
+ }),
47
+ ]);
48
+ export const fairness: Check = (repo) =>
49
+ Effect.succeed(
50
+ repo.specs.flatMap((s) =>
51
+ s.analysis._tag === "Parsed"
52
+ ? s.analysis.semantics.fairness
53
+ .filter((f) => !f.valid)
54
+ .map((f) => ({
55
+ file: s.path,
56
+ message: `${f.kind} at line ${f.line}; fairness must be WF_vars or SF_vars`,
57
+ }))
58
+ : []
59
+ )
60
+ );
61
+ export const coverageCheck: Check = (repo) =>
62
+ Effect.gen(function* () {
63
+ const gate = yield* Gate;
64
+ const fs = yield* FileSystem;
65
+ const problems: { file: string; message: string }[] = [];
66
+ for (const m of repo.models.filter((m) => m.entry.mode === "gate")) {
67
+ const result = yield* gate.run(m);
68
+ if (result._tag === "Failed") continue;
69
+ const start = problems.length;
70
+ for (const a of result.coverage.actions.filter((a) => a.generated === 0n))
71
+ problems.push({
72
+ file: m.path,
73
+ message: `action ${a.name} (line ${a.span.line}) is never enabled`,
74
+ });
75
+ for (const z of result.coverage.zeros) {
76
+ const candidate = join(dirname(m.path), `${z.span.module}.tla`);
77
+ const file = repo.tracked.includes(candidate) ? candidate : m.path;
78
+ const source = (yield* fs.readFileString(`${repo.root}/${file}`))
79
+ .split("\n")
80
+ .slice(z.span.line - 1, z.span.endLine)
81
+ .join("\n")
82
+ .slice(
83
+ z.span.col - 1,
84
+ z.span.endLine === z.span.line ? z.span.endCol : undefined
85
+ )
86
+ .slice(0, 60);
87
+ problems.push({
88
+ file,
89
+ message: `line ${z.span.line}, col ${z.span.col} to line ${z.span.endLine}, col ${z.span.endCol} never runs in ${z.scope}: ${source}`,
90
+ });
91
+ }
92
+ if (problems.length === start)
93
+ yield* Console.log(`coverage: ${m.path}: no dead logic`);
94
+ }
95
+ return problems;
96
+ }).pipe(Effect.mapError((e) => new FormalError({ message: String(e) })));
97
+ export const witnesses: Check = (repo) =>
98
+ Effect.gen(function* () {
99
+ const gate = yield* Gate;
100
+ const problems: { file: string; message: string }[] = [];
101
+ for (const m of repo.models) {
102
+ for (const name of m.entry.witnesses) {
103
+ const op = m.semantics.operators.get(name);
104
+ const message = !op
105
+ ? `${name} is not defined`
106
+ : op.level === 2
107
+ ? `${name} is an action; check [][${name}]_vars instead`
108
+ : op.params.length
109
+ ? `${name} must have zero arguments`
110
+ : [
111
+ ...m.config.cfg.invariants,
112
+ ...m.config.cfg.properties,
113
+ ].includes(name)
114
+ ? `${name} is already checked by ${m.config.path}`
115
+ : undefined;
116
+ if (message !== undefined) {
117
+ problems.push({ file: m.path, message });
118
+ continue;
119
+ }
120
+ if (m.entry.mode !== "gate" || (yield* gate.run(m))._tag === "Failed")
121
+ continue;
122
+ const result = yield* violate(repo, m, name);
123
+ if (result !== undefined)
124
+ problems.push({
125
+ file: m.path,
126
+ message:
127
+ result === held
128
+ ? `${name} holds; a witness must be violated`
129
+ : result,
130
+ });
131
+ else yield* Console.log(`witnesses: ${m.path}: ${name} violated`);
132
+ }
133
+ }
134
+ return problems;
135
+ }).pipe(Effect.mapError((e) => new FormalError({ message: String(e) })));
136
+ export const breaks: Check = (repo) =>
137
+ Effect.gen(function* () {
138
+ const gate = yield* Gate;
139
+ const fs = yield* FileSystem;
140
+ const changed = yield* changes(repo.root);
141
+ const problems: { file: string; message: string }[] = [];
142
+ if (changed._tag === "All")
143
+ yield* Console.log(
144
+ `breaks: BASE ${changed.base} does not resolve; running every break`
145
+ );
146
+ for (const m of repo.models) {
147
+ const targets = [...m.config.cfg.invariants, ...m.config.cfg.properties];
148
+ for (const target of targets)
149
+ if (!m.entry.breaks.some((b) => b.violates === target))
150
+ problems.push({
151
+ file: m.config.path,
152
+ message: `${target} has no break`,
153
+ });
154
+ const dirty =
155
+ changed._tag === "All" ||
156
+ changed.files.some(
157
+ (f) =>
158
+ f === "specs.json" ||
159
+ (dirname(f) === dirname(m.path) && /\.(?:tla|cfg)$/u.test(f)) ||
160
+ m.entry.breaks.some((b) => b.file === f)
161
+ );
162
+ if (!dirty && m.entry.mode === "gate")
163
+ yield* Console.log(
164
+ `breaks: ${m.path}: unchanged since ${changed.sha.slice(0, 7)}, not run`
165
+ );
166
+ for (const [index, b] of m.entry.breaks.entries()) {
167
+ const label = `break ${index + 1}`;
168
+ const file = b.file ?? m.path;
169
+ if (!targets.includes(b.violates)) {
170
+ problems.push({
171
+ file: m.path,
172
+ message: `${label}: ${b.violates} is not checked by ${m.config.path}`,
173
+ });
174
+ continue;
175
+ }
176
+ if (
177
+ !repo.tracked.includes(file) ||
178
+ !(
179
+ file === m.config.path ||
180
+ (dirname(file) === dirname(m.path) && file.endsWith(".tla"))
181
+ )
182
+ ) {
183
+ problems.push({
184
+ file: m.path,
185
+ message: `${label}: ${file} must be a tracked module in the spec directory or its config`,
186
+ });
187
+ continue;
188
+ }
189
+ const text = yield* fs.readFileString(`${repo.root}/${file}`);
190
+ const count = text.split(b.find).length - 1;
191
+ if (count !== 1) {
192
+ problems.push({
193
+ file: m.path,
194
+ message: `${label} find matches ${count} times in ${file}`,
195
+ });
196
+ continue;
197
+ }
198
+ if (
199
+ !dirty ||
200
+ m.entry.mode !== "gate" ||
201
+ (yield* gate.run(m))._tag === "Failed"
202
+ )
203
+ continue;
204
+ const result = yield* violate(repo, m, b.violates, b);
205
+ if (result !== undefined)
206
+ problems.push({
207
+ file: m.path,
208
+ message: `${label} (${b.violates}): ${result === held ? `${b.violates} still holds after the edit` : result}`,
209
+ });
210
+ else
211
+ yield* Console.log(
212
+ `breaks: ${m.path}: ${label} violated ${b.violates}`
213
+ );
214
+ }
215
+ }
216
+ return problems;
217
+ }).pipe(Effect.mapError((e) => new FormalError({ message: String(e) })));
@@ -0,0 +1,255 @@
1
+ type Operator = {
2
+ readonly name: string;
3
+ readonly level: number;
4
+ readonly params: ReadonlyArray<{
5
+ readonly name: string;
6
+ readonly arity: number;
7
+ }>;
8
+ readonly module: string;
9
+ };
10
+ export type Semantics = {
11
+ readonly operators: ReadonlyMap<string, Operator>;
12
+ readonly fairness: ReadonlyArray<{
13
+ readonly kind: string;
14
+ readonly line: string;
15
+ readonly valid: boolean;
16
+ }>;
17
+ readonly specifications: ReadonlyMap<
18
+ string,
19
+ { readonly init: string; readonly next: string }
20
+ >;
21
+ readonly variables: ReadonlyArray<string>;
22
+ readonly typeOK: ReadonlySet<string> | undefined;
23
+ };
24
+
25
+ type Node = { readonly tag: string; text: string; readonly children: Node[] };
26
+ const child = (node: Node, tag: string) =>
27
+ node.children.find((n) => n.tag === tag);
28
+ const value = (node: Node, tag: string) => child(node, tag)?.text.trim() ?? "";
29
+ const descendants = (node: Node): Node[] => [
30
+ node,
31
+ ...node.children.flatMap(descendants),
32
+ ];
33
+ export const fromXml = (xml: string): Semantics => {
34
+ const root: Node = { tag: "document", text: "", children: [] };
35
+ const stack = [root];
36
+ for (const match of xml.matchAll(
37
+ /<!\[CDATA\[[\s\S]*?\]\]>|<\?[^>]*\?>|<([^>]+)>|([^<]+)/gu
38
+ )) {
39
+ const token = match[0];
40
+ const parent = stack.at(-1);
41
+ if (parent === undefined) throw new Error("invalid SANY XML stack");
42
+ if (token.startsWith("<!") || token.startsWith("<?")) continue;
43
+ if (token.startsWith("</")) {
44
+ if (stack.pop()?.tag !== token.slice(2, -1))
45
+ throw new Error("invalid SANY XML closing tag");
46
+ } else if (token.startsWith("<")) {
47
+ const node: Node = {
48
+ tag: token.slice(1, token.endsWith("/>") ? -2 : -1),
49
+ text: "",
50
+ children: [],
51
+ };
52
+ parent.children.push(node);
53
+ if (!token.endsWith("/>")) stack.push(node);
54
+ } else
55
+ parent.text += token
56
+ .replaceAll("&lt;", "<")
57
+ .replaceAll("&gt;", ">")
58
+ .replaceAll("&amp;", "&");
59
+ }
60
+ const modules = child(root, "modules");
61
+ const context = modules && child(modules, "context");
62
+ if (stack.length !== 1 || !modules || !context)
63
+ throw new Error("missing SANY XML context");
64
+ const entries = new Map(
65
+ context.children.map((entry) => [
66
+ value(entry, "UID"),
67
+ entry.children.find((n) => n.tag !== "UID"),
68
+ ])
69
+ );
70
+ const module = [...entries.values()].find(
71
+ (n) =>
72
+ n?.tag === "ModuleNode" &&
73
+ value(n, "uniquename") === value(modules, "RootModule")
74
+ );
75
+ if (!module) throw new Error("missing root module in SANY XML");
76
+ const closure = new Set<string>();
77
+ const visitModule = (node: Node) => {
78
+ if (closure.has(value(node, "uniquename"))) return;
79
+ closure.add(value(node, "uniquename"));
80
+ for (const ref of descendants(
81
+ child(node, "extends") ?? { tag: "", text: "", children: [] }
82
+ )) {
83
+ if (ref.tag !== "uniquename") continue;
84
+ const next = [...entries.values()].find(
85
+ (entry) =>
86
+ entry?.tag === "ModuleNode" &&
87
+ value(entry, "uniquename") === ref.text.trim()
88
+ );
89
+ if (!next) throw new Error("unresolved SANY EXTENDS module");
90
+ visitModule(next);
91
+ }
92
+ };
93
+ visitModule(module);
94
+ const variables = new Map(
95
+ [...entries].flatMap(([uid, node]) =>
96
+ node?.tag === "OpDeclNode" &&
97
+ value(node, "kind") === "3" &&
98
+ closure.has(value(child(node, "location") ?? node, "filename"))
99
+ ? [[uid, value(node, "uniquename")] as const]
100
+ : []
101
+ )
102
+ );
103
+ const target = (appl: Node) => {
104
+ const ref = child(appl, "operator")?.children[0];
105
+ return ref && { ref, uid: value(ref, "UID") };
106
+ };
107
+ const operands = (appl: Node) => child(appl, "operands")?.children ?? [];
108
+ const reaches = (body: Node, seen = new Set<string>()): Set<string> => {
109
+ const reached = new Set<string>();
110
+ for (const n of descendants(body)) {
111
+ if (!n.tag.endsWith("Ref")) continue;
112
+ const uid = value(n, "UID");
113
+ const variable = variables.get(uid);
114
+ if (variable !== undefined) reached.add(variable);
115
+ if (seen.has(uid)) continue;
116
+ seen.add(uid);
117
+ const next = child(entries.get(uid) ?? n, "body");
118
+ if (next) for (const v of reaches(next, seen)) reached.add(v);
119
+ }
120
+ return reached;
121
+ };
122
+ const typed = (appl: Node, seen: Set<string>): ReadonlyArray<string> => {
123
+ if (appl.tag === "LetInNode") {
124
+ const body = child(appl, "body")?.children[0];
125
+ return body ? typed(body, seen) : [];
126
+ }
127
+ const op = target(appl);
128
+ if (appl.tag !== "OpApplNode" || op === undefined) return [];
129
+ const args = operands(appl);
130
+ if (op.ref.tag === "UserDefinedOpKindRef" && args.length === 0) {
131
+ if (seen.has(op.uid)) return [];
132
+ seen.add(op.uid);
133
+ const body = child(entries.get(op.uid) ?? appl, "body");
134
+ return body?.children[0] ? typed(body.children[0], seen) : [];
135
+ }
136
+ if (op.ref.tag !== "BuiltInKindRef") return [];
137
+ const name = value(entries.get(op.uid) ?? appl, "uniquename");
138
+ if (name === "$ConjList" || name === "\\land")
139
+ return args.flatMap((arg) => typed(arg, seen));
140
+ const [left, set] = args;
141
+ const variable =
142
+ left && target(left)?.ref.tag === "OpDeclNodeRef"
143
+ ? variables.get(target(left)?.uid ?? "")
144
+ : undefined;
145
+ return (name === "\\in" || name === "\\subseteq") &&
146
+ args.length === 2 &&
147
+ variable !== undefined &&
148
+ set !== undefined &&
149
+ !reaches(set).has(variable)
150
+ ? [variable]
151
+ : [];
152
+ };
153
+ const typeOK = module.children
154
+ .filter((n) => n.tag === "UserDefinedOpKindRef")
155
+ .map((ref) => entries.get(value(ref, "UID")))
156
+ .find(
157
+ (node) => node !== undefined && value(node, "uniquename") === "TypeOK"
158
+ );
159
+ const body = typeOK && child(typeOK, "body")?.children[0];
160
+ const definitions = [...entries.values()].filter(
161
+ (n): n is Node =>
162
+ n?.tag === "UserDefinedOpKind" &&
163
+ closure.has(value(child(n, "location") ?? n, "filename"))
164
+ );
165
+ const operators = new Map<string, Operator>();
166
+ const fairness: { kind: string; line: string; valid: boolean }[] = [];
167
+ const specifications = new Map<string, { init: string; next: string }>();
168
+ const opName = (n: Node) => {
169
+ const t = target(n);
170
+ return t ? value(entries.get(t.uid) ?? n, "uniquename") : "";
171
+ };
172
+ for (const n of definitions) {
173
+ const name = value(n, "uniquename");
174
+ const params = (child(n, "params")?.children ?? [])
175
+ .map(
176
+ (ref) =>
177
+ entries.get(value(child(ref, "FormalParamNodeRef") ?? ref, "UID")) ??
178
+ ref
179
+ )
180
+ .map((p) => ({
181
+ name: value(p, "uniquename"),
182
+ arity: Number(value(p, "arity")),
183
+ }));
184
+ operators.set(name, {
185
+ name,
186
+ level: Number(value(n, "level")),
187
+ params,
188
+ module: value(child(n, "location") ?? n, "filename"),
189
+ });
190
+ if (
191
+ value(child(n, "location") ?? n, "filename") ===
192
+ value(modules, "RootModule")
193
+ )
194
+ for (const a of descendants(child(n, "body") ?? n)) {
195
+ const kind = opName(a);
196
+ if (!["$WF", "$SF"].includes(kind)) continue;
197
+ const sub = operands(a)[0];
198
+ fairness.push({
199
+ kind: `${kind.slice(1)}_${sub && opName(sub) === "$Tuple" ? `<< ${operands(sub).map(opName).join(", ")} >>` : sub ? opName(sub) : "?"}`,
200
+ line: value(child(child(a, "location") ?? a, "line") ?? a, "begin"),
201
+ valid:
202
+ sub !== undefined &&
203
+ opName(sub) === "vars" &&
204
+ operands(sub).length === 0,
205
+ });
206
+ }
207
+ const flatten = (a: Node, seen = new Set<string>()): Node[] => {
208
+ const t = target(a);
209
+ if (["$ConjList", "\\land"].includes(opName(a)))
210
+ return operands(a).flatMap((x) => flatten(x, new Set(seen)));
211
+ if (
212
+ t &&
213
+ t.ref.tag === "UserDefinedOpKindRef" &&
214
+ Number(value(a, "level")) === 3 &&
215
+ operands(a).length === 0 &&
216
+ !seen.has(t.uid)
217
+ ) {
218
+ const b = child(entries.get(t.uid) ?? a, "body")?.children[0];
219
+ if (b) {
220
+ seen.add(t.uid);
221
+ return flatten(b, seen);
222
+ }
223
+ }
224
+ return [a];
225
+ };
226
+ const body = child(n, "body")?.children[0];
227
+ if (!body) continue;
228
+ const conjuncts = flatten(body);
229
+ const state = conjuncts.filter((a) => Number(value(a, "level")) === 1);
230
+ const boxes = conjuncts.filter((a) => opName(a) === "[]");
231
+ const box = boxes[0] && operands(boxes[0])[0];
232
+ const next =
233
+ box && opName(box) === "$SquareAct" ? operands(box)[0] : undefined;
234
+ if (
235
+ state.length === 1 &&
236
+ boxes.length === 1 &&
237
+ next &&
238
+ operands(next).length === 0
239
+ ) {
240
+ const init =
241
+ state[0] && operands(state[0]).length === 0
242
+ ? opName(state[0])
243
+ : undefined;
244
+ if (init !== undefined && init !== "")
245
+ specifications.set(name, { init, next: opName(next) });
246
+ }
247
+ }
248
+ return {
249
+ operators,
250
+ fairness,
251
+ specifications,
252
+ variables: [...new Set(variables.values())],
253
+ typeOK: typeOK && new Set(body ? typed(body, new Set()) : []),
254
+ };
255
+ };