@toiroakr/chisel 0.0.0-stage → 0.2.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 +693 -2
- package/dist/absence.d.ts +27 -0
- package/dist/absence.js +228 -0
- package/dist/absence.js.map +1 -0
- package/dist/behavior.d.ts +193 -0
- package/dist/behavior.js +589 -0
- package/dist/behavior.js.map +1 -0
- package/dist/beside.d.ts +27 -0
- package/dist/beside.js +88 -0
- package/dist/beside.js.map +1 -0
- package/dist/border.d.ts +61 -0
- package/dist/border.js +434 -0
- package/dist/border.js.map +1 -0
- package/dist/bounds.d.ts +1 -0
- package/dist/bounds.js +26 -0
- package/dist/bounds.js.map +1 -0
- package/dist/cli.d.ts +7 -0
- package/dist/cli.js +835 -0
- package/dist/cli.js.map +1 -0
- package/dist/codec.d.ts +6 -0
- package/dist/codec.js +86 -0
- package/dist/codec.js.map +1 -0
- package/dist/codegen.d.ts +2 -0
- package/dist/codegen.js +61 -0
- package/dist/codegen.js.map +1 -0
- package/dist/composition.d.ts +38 -0
- package/dist/composition.js +242 -0
- package/dist/composition.js.map +1 -0
- package/dist/data.d.ts +17 -0
- package/dist/data.js +51 -0
- package/dist/data.js.map +1 -0
- package/dist/dependency.d.ts +101 -0
- package/dist/dependency.js +161 -0
- package/dist/dependency.js.map +1 -0
- package/dist/domain.d.ts +12 -0
- package/dist/domain.js +217 -0
- package/dist/domain.js.map +1 -0
- package/dist/ensures.d.ts +15 -0
- package/dist/ensures.js +88 -0
- package/dist/ensures.js.map +1 -0
- package/dist/equal.d.ts +1 -0
- package/dist/equal.js +135 -0
- package/dist/equal.js.map +1 -0
- package/dist/exact.d.ts +21 -0
- package/dist/exact.js +80 -0
- package/dist/exact.js.map +1 -0
- package/dist/feasibility.d.ts +63 -0
- package/dist/feasibility.js +1053 -0
- package/dist/feasibility.js.map +1 -0
- package/dist/guard-borders.d.ts +57 -0
- package/dist/guard-borders.js +760 -0
- package/dist/guard-borders.js.map +1 -0
- package/dist/guard-scope.d.ts +61 -0
- package/dist/guard-scope.js +364 -0
- package/dist/guard-scope.js.map +1 -0
- package/dist/index.d.ts +48 -0
- package/dist/index.js +24 -0
- package/dist/index.js.map +1 -0
- package/dist/interleave.d.ts +31 -0
- package/dist/interleave.js +202 -0
- package/dist/interleave.js.map +1 -0
- package/dist/interval.d.ts +10 -0
- package/dist/interval.js +311 -0
- package/dist/interval.js.map +1 -0
- package/dist/isolated.d.ts +9 -0
- package/dist/isolated.js +41 -0
- package/dist/isolated.js.map +1 -0
- package/dist/machine-check.d.ts +73 -0
- package/dist/machine-check.js +215 -0
- package/dist/machine-check.js.map +1 -0
- package/dist/machine.d.ts +97 -0
- package/dist/machine.js +200 -0
- package/dist/machine.js.map +1 -0
- package/dist/model.d.ts +160 -0
- package/dist/model.js +778 -0
- package/dist/model.js.map +1 -0
- package/dist/outcomes.d.ts +7 -0
- package/dist/outcomes.js +38 -0
- package/dist/outcomes.js.map +1 -0
- package/dist/pairs.d.ts +26 -0
- package/dist/pairs.js +115 -0
- package/dist/pairs.js.map +1 -0
- package/dist/partition.d.ts +45 -0
- package/dist/partition.js +354 -0
- package/dist/partition.js.map +1 -0
- package/dist/proof.d.ts +21 -0
- package/dist/proof.js +556 -0
- package/dist/proof.js.map +1 -0
- package/dist/replay.d.ts +45 -0
- package/dist/replay.js +157 -0
- package/dist/replay.js.map +1 -0
- package/dist/report-json.d.ts +11 -0
- package/dist/report-json.js +94 -0
- package/dist/report-json.js.map +1 -0
- package/dist/rule.d.ts +186 -0
- package/dist/rule.js +866 -0
- package/dist/rule.js.map +1 -0
- package/dist/runtime.d.ts +12 -0
- package/dist/runtime.js +8 -0
- package/dist/runtime.js.map +1 -0
- package/dist/schema.d.ts +163 -0
- package/dist/schema.js +528 -0
- package/dist/schema.js.map +1 -0
- package/dist/specification.d.ts +266 -0
- package/dist/specification.js +2123 -0
- package/dist/specification.js.map +1 -0
- package/dist/temporal-global.d.ts +4 -0
- package/dist/temporal-global.js +11 -0
- package/dist/temporal-global.js.map +1 -0
- package/dist/temporal.d.ts +22 -0
- package/dist/temporal.js +113 -0
- package/dist/temporal.js.map +1 -0
- package/dist/text.d.ts +1 -0
- package/dist/text.js +11 -0
- package/dist/text.js.map +1 -0
- package/dist/tla.d.ts +54 -0
- package/dist/tla.js +579 -0
- package/dist/tla.js.map +1 -0
- package/dist/verification.d.ts +7 -0
- package/dist/verification.js +5 -0
- package/dist/verification.js.map +1 -0
- package/dist/ways.d.ts +28 -0
- package/dist/ways.js +86 -0
- package/dist/ways.js.map +1 -0
- package/dist/world.d.ts +98 -0
- package/dist/world.js +467 -0
- package/dist/world.js.map +1 -0
- package/package.json +76 -4
- package/schema/report.schema.json +1062 -0
package/dist/tla.js
ADDED
|
@@ -0,0 +1,579 @@
|
|
|
1
|
+
import { check as checkTla, formatValue, prove as proveTla } from "tla-ts";
|
|
2
|
+
import { SpecificationError } from "./behavior.js";
|
|
3
|
+
import { domainOf, integralBounds } from "./domain.js";
|
|
4
|
+
import { deepEqual } from "./equal.js";
|
|
5
|
+
import { childrenOf, nodeOf } from "./model.js";
|
|
6
|
+
import { positiveLimit } from "./machine.js";
|
|
7
|
+
import { schemaAtPath } from "./schema.js";
|
|
8
|
+
import { isTerm, termData } from "./rule.js";
|
|
9
|
+
// Compiles the executable expression itself. No sampled transition table is
|
|
10
|
+
// substituted for it: tla-ts evaluates Step and the invariant independently.
|
|
11
|
+
// What one command can do when each of its effects may fail: the state it ends in and the
|
|
12
|
+
// commands it emits, for the run in which every effect succeeds and for the failure of each.
|
|
13
|
+
// The outcomes of a command with effects: every effect succeeds, the failure of each effect, and with
|
|
14
|
+
// `crashes` the process dying before the first effect and after each one.
|
|
15
|
+
function outcomesDefinition(crashes) {
|
|
16
|
+
return [
|
|
17
|
+
"Outcomes(s, c) == LET r == Step(s, c) IN",
|
|
18
|
+
" IF \"effects\" \\in DOMAIN r THEN",
|
|
19
|
+
" {[state |-> IF Len(r.effects) = 0 THEN s ELSE r.effects[Len(r.effects)].state, commands |-> r.commands, stopped |-> FALSE, died |-> FALSE]}",
|
|
20
|
+
" \\cup {[state |-> IF r.effects[i].hasFailure THEN r.effects[i].failure ELSE (IF i = 1 THEN s ELSE r.effects[i - 1].state), commands |-> <<>>, stopped |-> TRUE, died |-> FALSE] : i \\in 1..Len(r.effects)}",
|
|
21
|
+
...(crashes ? [" \\cup {[state |-> IF i = 0 THEN s ELSE r.effects[i].state, commands |-> <<>>, stopped |-> TRUE, died |-> TRUE] : i \\in IF Len(r.effects) = 0 THEN {} ELSE 0..Len(r.effects)}"] : []),
|
|
22
|
+
" ELSE {[state |-> r.state, commands |-> r.commands, stopped |-> FALSE, died |-> FALSE]}",
|
|
23
|
+
];
|
|
24
|
+
}
|
|
25
|
+
export function toTla(specification, options = {}) {
|
|
26
|
+
const machine = { ...specification.machine, invariants: specification.invariants, transitions: specification.transitions };
|
|
27
|
+
const limit = options.domainLimit ?? 10000;
|
|
28
|
+
const maxCommands = options.maxCommands ?? 1000;
|
|
29
|
+
if (!Number.isSafeInteger(limit) || limit < 1)
|
|
30
|
+
throw new SpecificationError("domainLimit must be a positive safe integer");
|
|
31
|
+
if (!Number.isSafeInteger(maxCommands) || maxCommands < 1)
|
|
32
|
+
throw new SpecificationError("maxCommands must be a positive safe integer");
|
|
33
|
+
if (hasOptional(machine.state))
|
|
34
|
+
throw new SpecificationError("TLA+ translation does not support optional state fields");
|
|
35
|
+
const states = domainOf(machine.state, limit);
|
|
36
|
+
const commands = domainOf(machine.command, limit);
|
|
37
|
+
if (!states.exhaustive || !commands.exhaustive) {
|
|
38
|
+
throw new SpecificationError("TLA+ translation requires finite, exhaustively enumerated state and command schemas");
|
|
39
|
+
}
|
|
40
|
+
if (commands.values.length === 0)
|
|
41
|
+
throw new SpecificationError("TLA+ translation requires at least one command");
|
|
42
|
+
const compiler = new Compiler(machine.state, machine.command);
|
|
43
|
+
const name = `Chisel${machine.name.replace(/[^A-Za-z0-9]+/g, " ").split(" ").filter(Boolean).map(part => part[0].toUpperCase() + part.slice(1)).join("") || "Machine"}`;
|
|
44
|
+
const step = compiler.value(machine.update, new Map([["state", "s"], ["command", "c"]]), true);
|
|
45
|
+
const properties = machine.invariants.map((invariant, index) => ({
|
|
46
|
+
name: `Inv${index}`,
|
|
47
|
+
formula: compiler.condition(invariant.holds, new Map(), "state"),
|
|
48
|
+
}));
|
|
49
|
+
const transitions = machine.transitions.map((transition, index) => ({ name: `Transition${index}`,
|
|
50
|
+
formula: transition.each
|
|
51
|
+
? compiler.paired(transition.holds, transition.each, schemaAtPath(machine.state, transition.each.path)?.kind)
|
|
52
|
+
: compiler.condition(transition.holds, new Map([["before", "previous"], ["after", "state"]]), "state") }));
|
|
53
|
+
const discriminant = machine.command.discriminant === undefined ? "" : identifier(machine.command.discriminant);
|
|
54
|
+
const effectful = hasEffect(machine.update);
|
|
55
|
+
const preconditions = Object.entries(specification.requires).map(([tag, holds], index) => {
|
|
56
|
+
const precondition = `(${compiler.condition(holds, new Map([["state", "previous"], ["command", "last"]]), "previous")})`;
|
|
57
|
+
// A command that stopped (at a failed effect, or by the process dying) may have written nothing yet, so only the other direction holds of it.
|
|
58
|
+
const agrees = effectful ? `IF stopped THEN (~${precondition} => previous = state) ELSE (${precondition} <=> previous # state)` : `${precondition} <=> previous # state`;
|
|
59
|
+
return { name: `Req${index}`, formula: `IF depth = 0 THEN TRUE ELSE IF last.${discriminant} = ${JSON.stringify(tag)} THEN ${agrees} ELSE TRUE` };
|
|
60
|
+
});
|
|
61
|
+
const last = (command) => preconditions.length > 0 ? ` /\\ last' = ${command}` : "";
|
|
62
|
+
const next = effectful ? [
|
|
63
|
+
`Next == \\/ (\\E c \\in CommandDomain: \\E r \\in Outcomes(state, c): /\\ pending = <<>> /\\ state' = r.state /\\ pending' = r.commands /\\ previous' = state /\\ depth' = 1 /\\ stopped' = r.stopped${last("c")})`,
|
|
64
|
+
` \\/ (/\\ Len(pending) > 0 /\\ depth < MaxCommands /\\ \\E r \\in Outcomes(state, Head(pending)): /\\ state' = r.state /\\ pending' = (IF r.died THEN <<>> ELSE Tail(pending) \\o r.commands) /\\ previous' = state /\\ depth' = depth + 1 /\\ stopped' = r.stopped${last("Head(pending)")})`,
|
|
65
|
+
] : [
|
|
66
|
+
`Next == \\/ (\\E c \\in CommandDomain: /\\ pending = <<>> /\\ state' = Step(state, c).state /\\ pending' = Step(state, c).commands /\\ previous' = state /\\ depth' = 1${last("c")})`,
|
|
67
|
+
` \\/ (/\\ Len(pending) > 0 /\\ depth < MaxCommands /\\ state' = Step(state, Head(pending)).state /\\ pending' = Tail(pending) \\o Step(state, Head(pending)).commands /\\ previous' = state /\\ depth' = depth + 1${last("Head(pending)")})`,
|
|
68
|
+
];
|
|
69
|
+
const stateSet = set(states.values.map(value => compiler.value(value, new Map())));
|
|
70
|
+
const commandSet = set(commands.values.map(value => compiler.value(value, new Map())));
|
|
71
|
+
const initial = set(machine.initial.map(value => compiler.value(value, new Map())));
|
|
72
|
+
const source = [
|
|
73
|
+
`---- MODULE ${name} ----`,
|
|
74
|
+
"EXTENDS Naturals, Integers, Sequences",
|
|
75
|
+
`VARIABLES state, pending, previous, depth${effectful ? ", stopped" : ""}${preconditions.length > 0 ? ", last" : ""}`,
|
|
76
|
+
`MaxCommands == ${maxCommands}`,
|
|
77
|
+
`StateDomain == ${stateSet}`,
|
|
78
|
+
`CommandDomain == ${commandSet}`,
|
|
79
|
+
`Step(s, c) == ${step}`,
|
|
80
|
+
...(effectful ? outcomesDefinition(specification.crashes) : []),
|
|
81
|
+
`Init == /\\ state \\in ${initial} /\\ pending = <<>> /\\ previous = state /\\ depth = 0${effectful ? " /\\ stopped = FALSE" : ""}${preconditions.length > 0 ? " /\\ last = <<>>" : ""}`,
|
|
82
|
+
...next,
|
|
83
|
+
"TypeOK == /\\ state \\in StateDomain /\\ \\A i \\in 1..Len(pending): pending[i] \\in CommandDomain",
|
|
84
|
+
"Budget == pending = <<>> \\/ depth < MaxCommands",
|
|
85
|
+
...properties.map(item => `${item.name} == ${item.formula}`),
|
|
86
|
+
...transitions.map(item => `${item.name} == previous = state \\/ (${item.formula})`),
|
|
87
|
+
...preconditions.map(item => `${item.name} == ${item.formula}`),
|
|
88
|
+
"====",
|
|
89
|
+
].join("\n");
|
|
90
|
+
const config = `INIT Init NEXT Next INVARIANT TypeOK ${properties.map(item => `INVARIANT ${item.name}`).join(" ")} ${transitions.map(item => `INVARIANT ${item.name}`).join(" ")} ${preconditions.map(item => `INVARIANT ${item.name}`).join(" ")} INVARIANT Budget CHECK_DEADLOCK FALSE`;
|
|
91
|
+
return { name, source, config, states: states.values.length, commands: commands.values.length };
|
|
92
|
+
}
|
|
93
|
+
export async function checkMachineTla(machine, options = {}) {
|
|
94
|
+
let module;
|
|
95
|
+
try {
|
|
96
|
+
module = toTla(machine, options);
|
|
97
|
+
}
|
|
98
|
+
catch (error) {
|
|
99
|
+
if (error instanceof SpecificationError)
|
|
100
|
+
return { status: "undetermined", states: 0, generatedStates: 0, reason: error.message };
|
|
101
|
+
throw error;
|
|
102
|
+
}
|
|
103
|
+
let result;
|
|
104
|
+
try {
|
|
105
|
+
result = await checkTla({ source: module.source, config: module.config });
|
|
106
|
+
}
|
|
107
|
+
catch (error) {
|
|
108
|
+
return { status: "undetermined", states: 0, generatedStates: 0,
|
|
109
|
+
reason: `tla-ts could not complete the check: ${error instanceof Error ? error.message : String(error)}`, module };
|
|
110
|
+
}
|
|
111
|
+
if (result.status === "success")
|
|
112
|
+
return { status: "held", states: result.distinctStates, generatedStates: result.generatedStates, module };
|
|
113
|
+
if (result.status === "invariant-violation" && result.violation?.name === "Budget")
|
|
114
|
+
return {
|
|
115
|
+
status: "undetermined", states: result.distinctStates, generatedStates: result.generatedStates,
|
|
116
|
+
reason: `TLA+ exploration exceeded maxCommands (${options.maxCommands ?? 1000})`, module,
|
|
117
|
+
};
|
|
118
|
+
const violated = result.violation?.name ?? "";
|
|
119
|
+
if (result.status === "invariant-violation")
|
|
120
|
+
return { status: "broken", states: result.distinctStates,
|
|
121
|
+
generatedStates: result.generatedStates,
|
|
122
|
+
reason: /^Inv\d+$/.test(violated)
|
|
123
|
+
? machine.invariants[Number(violated.slice(3))]?.name ?? violated
|
|
124
|
+
: /^Req\d+$/.test(violated)
|
|
125
|
+
? `${Object.keys(machine.requires)[Number(violated.slice(3))]}: its precondition disagrees with whether it changes the state`
|
|
126
|
+
: result.violation?.name ?? "An invariant was violated",
|
|
127
|
+
...(result.violation === undefined ? {} : { trace: result.violation.trace.map(step => ({
|
|
128
|
+
...(step.action === undefined ? {} : { action: step.action }),
|
|
129
|
+
state: formatValue(step.state.state), pending: formatValue(step.state.pending),
|
|
130
|
+
})) }), module };
|
|
131
|
+
return { status: "undetermined", states: result.distinctStates, generatedStates: result.generatedStates,
|
|
132
|
+
reason: `tla-ts could not complete the check: ${result.status}${result.failure ? `: ${result.failure.message}` : ""}`, module };
|
|
133
|
+
}
|
|
134
|
+
// Copies of the machine as processes sharing one state (see `checkInterleavings`). Only the
|
|
135
|
+
// native checker follows the commands a command emits, so a translation that meets one is undetermined.
|
|
136
|
+
export async function checkInterleavingsTla(specification, options) {
|
|
137
|
+
const maxCopies = positiveLimit(options.maxCopies, 2, "maxCopies");
|
|
138
|
+
if (options.copies.length > maxCopies) {
|
|
139
|
+
return { status: "undetermined", states: 0, reason: `${options.copies.length} copies exceed maxCopies (${maxCopies})` };
|
|
140
|
+
}
|
|
141
|
+
let module;
|
|
142
|
+
try {
|
|
143
|
+
module = interleavingsToTla(specification, options);
|
|
144
|
+
}
|
|
145
|
+
catch (error) {
|
|
146
|
+
if (error instanceof SpecificationError)
|
|
147
|
+
return { status: "undetermined", states: 0, reason: error.message };
|
|
148
|
+
throw error;
|
|
149
|
+
}
|
|
150
|
+
let result;
|
|
151
|
+
try {
|
|
152
|
+
result = await checkTla({ source: module.source, config: module.config });
|
|
153
|
+
}
|
|
154
|
+
catch (error) {
|
|
155
|
+
return { status: "undetermined", states: 0, module,
|
|
156
|
+
reason: `tla-ts could not complete the check: ${error instanceof Error ? error.message : String(error)}` };
|
|
157
|
+
}
|
|
158
|
+
if (result.status === "success")
|
|
159
|
+
return { status: "held", states: result.distinctStates, module };
|
|
160
|
+
const violated = result.violation?.name ?? "";
|
|
161
|
+
if (result.status === "invariant-violation" && violated === "WritesKnown")
|
|
162
|
+
return { status: "undetermined", states: result.distinctStates, module,
|
|
163
|
+
reason: "An effect writes a field the state does not have" };
|
|
164
|
+
if (result.status === "invariant-violation" && violated === "StateOK")
|
|
165
|
+
return { status: "broken", states: result.distinctStates, module,
|
|
166
|
+
reason: "A write left a value that is not a state" };
|
|
167
|
+
if (result.status === "invariant-violation" && violated === "PlanOK")
|
|
168
|
+
return { status: "broken", states: result.distinctStates, module,
|
|
169
|
+
reason: "An effect declares a state the state schema does not allow" };
|
|
170
|
+
if (result.status === "invariant-violation" && violated === "NoEmission")
|
|
171
|
+
return { status: "undetermined", states: result.distinctStates, module,
|
|
172
|
+
reason: "TLA+ translation of interleavings does not follow the commands a command emits" };
|
|
173
|
+
if (result.status === "invariant-violation")
|
|
174
|
+
return { status: "broken", states: result.distinctStates, module,
|
|
175
|
+
reason: /^Inv\d+$/.test(violated) ? specification.invariants[Number(violated.slice(3))]?.name ?? violated
|
|
176
|
+
: /^Trans\d+$/.test(violated) ? `${specification.name} moved the state in a way ${specification.transitions[Number(violated.slice(5))]?.name} does not allow` : violated };
|
|
177
|
+
return { status: "undetermined", states: result.distinctStates, module,
|
|
178
|
+
reason: `tla-ts could not complete the check: ${result.status}${result.failure ? `: ${result.failure.message}` : ""}` };
|
|
179
|
+
}
|
|
180
|
+
export function interleavingsToTla(specification, options) {
|
|
181
|
+
const machine = specification.machine;
|
|
182
|
+
if (machine.state.kind !== "object")
|
|
183
|
+
throw new SpecificationError("TLA+ translation of interleavings needs a state that is an object");
|
|
184
|
+
if (hasOptional(machine.state))
|
|
185
|
+
throw new SpecificationError("TLA+ translation does not support optional state fields");
|
|
186
|
+
if (options.copies.length === 0)
|
|
187
|
+
throw new SpecificationError(`Machine ${machine.name} has no copy to run`);
|
|
188
|
+
const compiler = new Compiler(machine.state, machine.command);
|
|
189
|
+
const step = compiler.value(machine.update, new Map([["state", "s"], ["command", "c"]]), true);
|
|
190
|
+
const name = `ChiselInterleave${machine.name.replace(/[^A-Za-z0-9]+/g, " ").split(" ").filter(Boolean).map(part => part[0].toUpperCase() + part.slice(1)).join("") || "Machine"}`;
|
|
191
|
+
const copies = options.copies.length;
|
|
192
|
+
if (options.starts?.length === 0)
|
|
193
|
+
throw new SpecificationError(`Machine ${machine.name} has no state to start from`);
|
|
194
|
+
const initial = set((options.starts ?? machine.initial).map(value => compiler.value(value, new Map())));
|
|
195
|
+
const properties = specification.invariants.map((invariant, index) => ({ name: `Inv${index}`, formula: compiler.condition(invariant.holds, new Map(), "state") }));
|
|
196
|
+
const states = domainOf(machine.state, positiveLimit(options.domainLimit, 10000, "domainLimit"));
|
|
197
|
+
if (!states.exhaustive)
|
|
198
|
+
throw new SpecificationError("TLA+ translation of interleavings requires a finite, exhaustively enumerated state schema");
|
|
199
|
+
const stateSet = set(states.values.map(value => compiler.value(value, new Map())));
|
|
200
|
+
const stateOK = `state \\in ${stateSet}`;
|
|
201
|
+
const transitions = specification.transitions.map((transition, index) => ({ name: `Trans${index}`,
|
|
202
|
+
formula: transition.each
|
|
203
|
+
? compiler.paired(transition.holds, transition.each, schemaAtPath(machine.state, transition.each.path)?.kind)
|
|
204
|
+
: compiler.condition(transition.holds, new Map([["before", "previous"], ["after", "state"]]), "state") }));
|
|
205
|
+
const variables = ["state", "previous", "version", "status", "pc", "snap", "plan", "readVersion", "unsupported"];
|
|
206
|
+
const keep = (...changed) => `UNCHANGED <<${variables.filter(item => !changed.includes(item)).join(", ")}>>`;
|
|
207
|
+
const set1 = (variable, value) => `${variable}' = [${variable} EXCEPT ![p] = ${value}]`;
|
|
208
|
+
const source = [
|
|
209
|
+
`---- MODULE ${name} ----`,
|
|
210
|
+
"EXTENDS Naturals, Integers, Sequences",
|
|
211
|
+
`VARIABLES ${variables.join(", ")}`,
|
|
212
|
+
`Copies == <<${options.copies.map(command => compiler.value(command, new Map())).join(", ")}>>`,
|
|
213
|
+
`Step(s, c) == ${step}`,
|
|
214
|
+
`Init == /\\ state \\in ${initial} /\\ previous = state /\\ version = 0 /\\ unsupported = FALSE`,
|
|
215
|
+
` /\\ status = [p \\in 1..${copies} |-> "idle"] /\\ pc = [p \\in 1..${copies} |-> 0]`,
|
|
216
|
+
` /\\ snap = [p \\in 1..${copies} |-> state] /\\ plan = [p \\in 1..${copies} |-> <<>>] /\\ readVersion = [p \\in 1..${copies} |-> 0]`,
|
|
217
|
+
"Seen(p) == IF pc[p] = 0 THEN snap[p] ELSE plan[p][pc[p]].state",
|
|
218
|
+
"Changed(p, e, k) == IF e.hasWrites THEN (\\E i \\in 1..Len(e.writes): e.writes[i] = k) ELSE e.state[k] # Seen(p)[k]",
|
|
219
|
+
"Patched(p, e) == [k \\in DOMAIN state |-> IF Changed(p, e, k) THEN e.state[k] ELSE state[k]]",
|
|
220
|
+
"Wrote(p, e) == \\E k \\in DOMAIN state: Changed(p, e, k)",
|
|
221
|
+
"Begin(p) == /\\ status[p] = \"idle\"",
|
|
222
|
+
" /\\ LET r == Step(state, Copies[p]) IN",
|
|
223
|
+
" /\\ unsupported' = (unsupported \\/ r.commands # <<>>)",
|
|
224
|
+
" /\\ IF \"effects\" \\in DOMAIN r THEN",
|
|
225
|
+
` (IF Len(r.effects) = 0 THEN (/\\ ${set1("status", '"finished"')} /\\ ${keep("status", "unsupported")})`,
|
|
226
|
+
` ELSE (/\\ ${set1("status", '"running"')} /\\ ${set1("snap", "state")} /\\ ${set1("plan", "r.effects")} /\\ ${set1("pc", "0")} /\\ ${set1("readVersion", "version")} /\\ ${keep("status", "snap", "plan", "pc", "readVersion", "unsupported")}))`,
|
|
227
|
+
` ELSE (/\\ previous' = state /\\ state' = r.state /\\ version' = (IF r.state # state THEN version + 1 ELSE version) /\\ ${set1("status", '"finished"')} /\\ ${keep("previous", "state", "version", "status", "unsupported")})`,
|
|
228
|
+
"Run(p) == /\\ status[p] = \"running\"",
|
|
229
|
+
" /\\ LET e == plan[p][pc[p] + 1] IN",
|
|
230
|
+
` IF e.ifUnchanged /\\ version # readVersion[p] THEN (/\\ ${set1("status", '"refused"')} /\\ ${keep("status")})`,
|
|
231
|
+
` ELSE (/\\ previous' = state /\\ state' = Patched(p, e) /\\ version' = (IF Wrote(p, e) THEN version + 1 ELSE version)`,
|
|
232
|
+
` /\\ ${set1("pc", "pc[p] + 1")} /\\ status' = (IF pc[p] + 1 = Len(plan[p]) THEN [status EXCEPT ![p] = "finished"] ELSE status)`,
|
|
233
|
+
` /\\ ${keep("previous", "state", "version", "pc", "status")})`,
|
|
234
|
+
`Next == \\E p \\in 1..${copies}: Begin(p) \\/ Run(p)`,
|
|
235
|
+
"NoEmission == ~unsupported",
|
|
236
|
+
`StateOK == ${stateOK}`,
|
|
237
|
+
`PlanOK == \\A p \\in 1..${copies}: \\A i \\in 1..Len(plan[p]): plan[p][i].state \\in ${stateSet}`,
|
|
238
|
+
`WritesKnown == \\A p \\in 1..${copies}: \\A i \\in 1..Len(plan[p]): \\A j \\in 1..Len(plan[p][i].writes): plan[p][i].writes[j] \\in DOMAIN state`,
|
|
239
|
+
...properties.map(item => `${item.name} == ${item.formula}`),
|
|
240
|
+
...transitions.map(item => `${item.name} == previous = state \\/ (${item.formula})`),
|
|
241
|
+
"====",
|
|
242
|
+
].join("\n");
|
|
243
|
+
const config = `INIT Init NEXT Next INVARIANT NoEmission INVARIANT WritesKnown INVARIANT StateOK INVARIANT PlanOK ${properties.map(item => `INVARIANT ${item.name}`).join(" ")} ${transitions.map(item => `INVARIANT ${item.name}`).join(" ")} CHECK_DEADLOCK FALSE`;
|
|
244
|
+
return { name, source, config, states: 0, commands: options.copies.length };
|
|
245
|
+
}
|
|
246
|
+
// This is a universal inductive proof, not finite-state model checking. A
|
|
247
|
+
// theorem is reported proved only when tla-ts discharges its obligation.
|
|
248
|
+
export async function proveMachine(specification) {
|
|
249
|
+
const machine = { ...specification.machine, invariants: specification.invariants, transitions: specification.transitions };
|
|
250
|
+
let source;
|
|
251
|
+
const requiredTags = Object.keys(specification.requires);
|
|
252
|
+
const names = ["initial", "state contract", "emitted commands", ...machine.invariants.map(item => item.name), ...machine.transitions.map(item => item.name),
|
|
253
|
+
...requiredTags.flatMap(tag => [`${tag} precondition allows the change`, `${tag} precondition forces the change`])];
|
|
254
|
+
try {
|
|
255
|
+
const compiler = new Compiler(machine.state, machine.command);
|
|
256
|
+
if (hasOptional(machine.state))
|
|
257
|
+
throw new SpecificationError("Inductive proof does not support optional state fields");
|
|
258
|
+
const step = compiler.value(machine.update, new Map([["state", "s"], ["command", "c"]]), true);
|
|
259
|
+
const stateOK = compiler.schema(machine.state, "s");
|
|
260
|
+
const commandOK = compiler.schema(machine.command, "c");
|
|
261
|
+
const invariants = machine.invariants.map((item, index) => ({ name: `Inv${index}`,
|
|
262
|
+
formula: compiler.condition(item.holds, new Map(), "s") }));
|
|
263
|
+
const assumption = ["StateOK(s)", "CommandOK(c)", ...invariants.map(item => `${item.name}(s)`)].join(" /\\ ");
|
|
264
|
+
const effectful = hasEffect(machine.update);
|
|
265
|
+
const defs = ["Step", ...(effectful ? ["Outcomes"] : []), "StateOK", "CommandOK", ...invariants.map(item => item.name)].join(", ");
|
|
266
|
+
const output = effectful ? "r" : "Step(s, c)";
|
|
267
|
+
const over = (body) => `\\A s, c: (${assumption}) => ${effectful ? `\\A r \\in Outcomes(s, c): ${body}` : body}`;
|
|
268
|
+
const transitions = machine.transitions.map(item => item.each
|
|
269
|
+
? compiler.paired(item.holds, item.each, schemaAtPath(machine.state, item.each.path)?.kind, "s", `${output}.state`)
|
|
270
|
+
: compiler.condition(item.holds, new Map([["before", "s"], ["after", `${output}.state`]]), "s"));
|
|
271
|
+
const formulae = [
|
|
272
|
+
`\\A s: InitState(s) => (StateOK(s)${invariants.map(item => ` /\\ ${item.name}(s)`).join("")})`,
|
|
273
|
+
over(`StateOK(${output}.state)`),
|
|
274
|
+
over(`\\A i \\in 1..Len(${output}.commands): CommandOK(${output}.commands[i])`),
|
|
275
|
+
...invariants.map(item => over(`${item.name}(${output}.state)`)),
|
|
276
|
+
...transitions.map(formula => over(`(s = ${output}.state \\/ (${formula}))`)),
|
|
277
|
+
...requiredTags.flatMap(tag => {
|
|
278
|
+
const pre = compiler.condition(specification.requires[tag], new Map([["state", "s"], ["command", "c"]]), "s");
|
|
279
|
+
const isTag = `c.${identifier(machine.command.discriminant)} = ${JSON.stringify(tag)}`;
|
|
280
|
+
const unchanged = unchangedFormula(machine.state, "s", `${output}.state`);
|
|
281
|
+
return [over(`(${isTag} => (${unchanged} \\/ (${pre})))`),
|
|
282
|
+
over(`(${isTag} => (${effectful ? `${output}.stopped \\/ ` : ""}~(${pre}) \\/ ~(${unchanged})))`)];
|
|
283
|
+
}),
|
|
284
|
+
];
|
|
285
|
+
source = [
|
|
286
|
+
"---- MODULE ChiselInduction ----",
|
|
287
|
+
"EXTENDS Naturals, Integers, Sequences",
|
|
288
|
+
`Step(s, c) == ${step}`,
|
|
289
|
+
...(effectful ? outcomesDefinition(specification.crashes) : []),
|
|
290
|
+
`StateOK(s) == ${stateOK}`,
|
|
291
|
+
`CommandOK(c) == ${commandOK}`,
|
|
292
|
+
`InitState(s) == s \\in ${set(machine.initial.map(value => compiler.value(value, new Map())))}`,
|
|
293
|
+
...invariants.map(item => `${item.name}(s) == ${item.formula}`),
|
|
294
|
+
...formulae.map((formula, index) => `THEOREM ${formula} PROOF BY DEF ${index === 0 ? `InitState, StateOK${invariants.map(item => `, ${item.name}`).join("")}` : defs}`),
|
|
295
|
+
"====",
|
|
296
|
+
].join("\n");
|
|
297
|
+
}
|
|
298
|
+
catch (error) {
|
|
299
|
+
if (error instanceof SpecificationError)
|
|
300
|
+
return { status: "undetermined", obligations: [], reason: error.message };
|
|
301
|
+
throw error;
|
|
302
|
+
}
|
|
303
|
+
let result;
|
|
304
|
+
try {
|
|
305
|
+
result = await proveTla({ source, backend: "tla-ts" });
|
|
306
|
+
}
|
|
307
|
+
catch (error) {
|
|
308
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
309
|
+
return { status: "undetermined", obligations: names.map(name => ({ name, status: "undetermined", reason })), source, reason };
|
|
310
|
+
}
|
|
311
|
+
const theoremLines = source.split("\n").flatMap((line, index) => line.startsWith("THEOREM ") ? [index + 1] : []);
|
|
312
|
+
const grouped = names.map(() => []);
|
|
313
|
+
let unmatched = false;
|
|
314
|
+
for (const obligation of result.obligations) {
|
|
315
|
+
const line = Number(obligation.location.split(":")[0]);
|
|
316
|
+
const index = theoremLines.indexOf(line);
|
|
317
|
+
if (index < 0 || index >= grouped.length)
|
|
318
|
+
unmatched = true;
|
|
319
|
+
else
|
|
320
|
+
grouped[index].push(obligation);
|
|
321
|
+
}
|
|
322
|
+
const obligations = grouped.map((items, index) => {
|
|
323
|
+
const failed = items.find(item => item.status === "failed" || item.status === "unsupported");
|
|
324
|
+
return { name: names[index],
|
|
325
|
+
status: items.length > 0 && items.every(item => item.status === "proved" || item.status === "trivial") ? "proved" : "undetermined",
|
|
326
|
+
...(failed && "reason" in failed ? { reason: failed.reason } : {}), };
|
|
327
|
+
});
|
|
328
|
+
return { status: !unmatched && theoremLines.length === names.length && result.missingProofCount === 0 && result.omittedProofCount === 0 && obligations.every(item => item.status === "proved") ? "proved" : "undetermined",
|
|
329
|
+
obligations, source };
|
|
330
|
+
}
|
|
331
|
+
// Compared field by field: the prover cannot discharge a whole-record equality
|
|
332
|
+
// of a step's result, but it can the same claim about each field.
|
|
333
|
+
function unchangedFormula(schema, before, after) {
|
|
334
|
+
if (schema.kind !== "object")
|
|
335
|
+
return `${before} = ${after}`;
|
|
336
|
+
const fields = Object.entries(schema.shape);
|
|
337
|
+
return `(${fields.map(([field, child]) => unchangedFormula(child, `${before}.${identifier(field)}`, `${after}.${identifier(field)}`)).join(" /\\ ") || "TRUE"})`;
|
|
338
|
+
}
|
|
339
|
+
function hasEffect(value) {
|
|
340
|
+
if (value !== null && typeof value === "object" && value.kind === "effect")
|
|
341
|
+
return true;
|
|
342
|
+
return childrenOf(value).some(hasEffect);
|
|
343
|
+
}
|
|
344
|
+
function set(values) {
|
|
345
|
+
return `{${values.join(", ")}}`;
|
|
346
|
+
}
|
|
347
|
+
function hasOptional(schema, visited = new Set()) {
|
|
348
|
+
if (schema.kind === "optional")
|
|
349
|
+
return true;
|
|
350
|
+
if (visited.has(schema))
|
|
351
|
+
return false;
|
|
352
|
+
visited.add(schema);
|
|
353
|
+
if (schema.kind === "object")
|
|
354
|
+
return Object.values(schema.shape).some(child => hasOptional(child, visited));
|
|
355
|
+
if (schema.kind === "variants")
|
|
356
|
+
return Object.values(schema.variants).some(child => hasOptional(child, visited));
|
|
357
|
+
if (schema.kind === "array")
|
|
358
|
+
return hasOptional(schema.element, visited);
|
|
359
|
+
return false;
|
|
360
|
+
}
|
|
361
|
+
class Compiler {
|
|
362
|
+
stateSchema;
|
|
363
|
+
commandSchema;
|
|
364
|
+
next = 0;
|
|
365
|
+
constructor(stateSchema, commandSchema) {
|
|
366
|
+
this.stateSchema = stateSchema;
|
|
367
|
+
this.commandSchema = commandSchema;
|
|
368
|
+
}
|
|
369
|
+
value(value, names, result = false) {
|
|
370
|
+
if (isTerm(value))
|
|
371
|
+
return this.term(termData(value), names);
|
|
372
|
+
const node = nodeOf(value);
|
|
373
|
+
if (node?.kind === "choose")
|
|
374
|
+
return `(IF ${this.rule(node.condition, names, names.get("") ?? "s")} THEN ${this.value(node.yes, names, result)} ELSE ${this.value(node.no, names, result)})`;
|
|
375
|
+
if (node?.kind === "bind") {
|
|
376
|
+
const data = isTerm(node.value) ? termData(node.value) : undefined;
|
|
377
|
+
const source = data?.kind === "position" && data.path.length === 1 ? data.path[0] : undefined;
|
|
378
|
+
if ((source !== "state" || node.schema !== this.stateSchema) &&
|
|
379
|
+
(source !== "command" || node.schema !== this.commandSchema)) {
|
|
380
|
+
throw new SpecificationError("TLA+ translation cannot preserve bind schema validation");
|
|
381
|
+
}
|
|
382
|
+
const local = `local${this.next++}`;
|
|
383
|
+
return `(LET ${local} == ${this.value(node.value, names)} IN ${this.value(node.body, new Map([...names, [node.name, local]]), result)})`;
|
|
384
|
+
}
|
|
385
|
+
if (node?.kind === "map") {
|
|
386
|
+
const data = isTerm(node.values) ? termData(node.values) : undefined;
|
|
387
|
+
if (data?.kind !== "position" || data.path.length !== 1 || data.path[0] !== "state" ||
|
|
388
|
+
this.stateSchema.kind !== "array" || this.stateSchema.element !== node.element ||
|
|
389
|
+
node.element !== node.output || !this.safeMappedBody(node.body, node.element, node.name)) {
|
|
390
|
+
throw new SpecificationError("TLA+ translation cannot preserve map element and output schema validation");
|
|
391
|
+
}
|
|
392
|
+
const sequence = this.value(node.values, names);
|
|
393
|
+
const index = `index${this.next++}`;
|
|
394
|
+
const body = this.value(node.body, new Map([...names, [node.name, `${sequence}[${index}]`]]));
|
|
395
|
+
return `[${index} \\in 1..Len(${sequence}) |-> ${body}]`;
|
|
396
|
+
}
|
|
397
|
+
if (node?.kind === "construct") {
|
|
398
|
+
if (isTerm(node.value) || nodeOf(node.value))
|
|
399
|
+
throw new SpecificationError("TLA+ translation cannot preserve dynamic constructor validation");
|
|
400
|
+
const parsed = node.schema.parse(node.value);
|
|
401
|
+
if (!parsed.success)
|
|
402
|
+
throw new SpecificationError("TLA+ translation cannot preserve invalid constructor");
|
|
403
|
+
return this.value(parsed.value, names, result);
|
|
404
|
+
}
|
|
405
|
+
if (node?.kind === "operation")
|
|
406
|
+
throw new SpecificationError("TLA+ translation cannot preserve intermediate arithmetic validation");
|
|
407
|
+
if (node)
|
|
408
|
+
throw new SpecificationError(`TLA+ translation does not support ${node.kind}${"operator" in node ? ` ${node.operator}` : ""}`);
|
|
409
|
+
if (typeof value === "string")
|
|
410
|
+
return JSON.stringify(value);
|
|
411
|
+
if (typeof value === "boolean")
|
|
412
|
+
return String(value).toUpperCase();
|
|
413
|
+
if (typeof value === "bigint")
|
|
414
|
+
return value.toString();
|
|
415
|
+
if (typeof value === "number" && Number.isSafeInteger(value))
|
|
416
|
+
return String(value);
|
|
417
|
+
if (Array.isArray(value))
|
|
418
|
+
return `<<${value.map(item => this.value(item, names)).join(", ")}>>`;
|
|
419
|
+
if (value !== null && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
|
|
420
|
+
const fields = Object.entries(value);
|
|
421
|
+
if (value.kind === "effect") {
|
|
422
|
+
const hasFailure = fields.some(([key]) => key === "failure");
|
|
423
|
+
if (!hasFailure)
|
|
424
|
+
fields.push(["failure", 0]);
|
|
425
|
+
fields.push(["hasFailure", hasFailure]);
|
|
426
|
+
if (!fields.some(([key]) => key === "ifUnchanged"))
|
|
427
|
+
fields.push(["ifUnchanged", false]);
|
|
428
|
+
const hasWrites = fields.some(([key]) => key === "writes");
|
|
429
|
+
if (!hasWrites)
|
|
430
|
+
fields.push(["writes", []]);
|
|
431
|
+
fields.push(["hasWrites", hasWrites]);
|
|
432
|
+
}
|
|
433
|
+
if (result && !fields.some(([key]) => key === "commands"))
|
|
434
|
+
fields.push(["commands", []]);
|
|
435
|
+
if (!fields.length)
|
|
436
|
+
throw new SpecificationError("TLA+ translation cannot represent an empty record");
|
|
437
|
+
return `[${fields.map(([key, child]) => `${identifier(key)} |-> ${this.value(child, names)}`).join(", ")}]`;
|
|
438
|
+
}
|
|
439
|
+
throw new SpecificationError(`TLA+ translation cannot represent ${String(value)}`);
|
|
440
|
+
}
|
|
441
|
+
safeMappedBody(value, schema, element) {
|
|
442
|
+
const node = nodeOf(value);
|
|
443
|
+
if (node?.kind === "choose")
|
|
444
|
+
return this.safeMappedBody(node.yes, schema, element) && this.safeMappedBody(node.no, schema, element);
|
|
445
|
+
if (node)
|
|
446
|
+
return false;
|
|
447
|
+
if (isTerm(value)) {
|
|
448
|
+
const data = termData(value);
|
|
449
|
+
return data.kind === "position" && data.path.length === 1 && data.path[0] === element;
|
|
450
|
+
}
|
|
451
|
+
const parsed = schema.parse(value);
|
|
452
|
+
return parsed.success && deepEqual(parsed.value, value);
|
|
453
|
+
}
|
|
454
|
+
condition(value, names, self) {
|
|
455
|
+
if (value !== null && typeof value === "object" && "kind" in value &&
|
|
456
|
+
["compare", "all", "any", "and", "or", "not"].includes(String(value.kind)))
|
|
457
|
+
return this.rule(value, names, self);
|
|
458
|
+
return this.value(value, new Map([...names, ["", self]]));
|
|
459
|
+
}
|
|
460
|
+
paired(condition, each, kind, beforeRoot = "previous", afterRoot = "state") {
|
|
461
|
+
const before = each.path.reduce((root, field) => `${root}.${identifier(field)}`, `(${beforeRoot})`);
|
|
462
|
+
const after = each.path.reduce((root, field) => `${root}.${identifier(field)}`, `(${afterRoot})`);
|
|
463
|
+
if (kind === "record") {
|
|
464
|
+
const earlier = `${before}[key]`, later = `${after}[key]`;
|
|
465
|
+
const rule = this.condition(condition, new Map([["before", earlier], ["after", later]]), later);
|
|
466
|
+
return `(\\A key \\in (DOMAIN ${before} \\cap DOMAIN ${after}): ${earlier} = ${later} \\/ (${rule}))`;
|
|
467
|
+
}
|
|
468
|
+
if (kind !== "array" || each.by === undefined)
|
|
469
|
+
throw new SpecificationError("TLA+ translation cannot pair this collection");
|
|
470
|
+
const key = identifier(each.by);
|
|
471
|
+
const bi = `${before}[i]`, aj = `${after}[j]`;
|
|
472
|
+
const rule = this.condition(condition, new Map([["before", bi], ["after", aj]]), aj);
|
|
473
|
+
const unique = (collection) => `(\\A x, y \\in 1..Len(${collection}): x = y \\/ ${collection}[x].${key} # ${collection}[y].${key})`;
|
|
474
|
+
return `(${unique(before)} /\\ ${unique(after)} /\\ \\A i \\in 1..Len(${before}): \\A j \\in 1..Len(${after}): ${bi}.${key} # ${aj}.${key} \\/ ${bi} = ${aj} \\/ (${rule}))`;
|
|
475
|
+
}
|
|
476
|
+
schema(schema, value) {
|
|
477
|
+
let type;
|
|
478
|
+
switch (schema.kind) {
|
|
479
|
+
case "integer":
|
|
480
|
+
type = `(${value} \\in Int /\\ ${value} >= ${Number.MIN_SAFE_INTEGER} /\\ ${value} <= ${Number.MAX_SAFE_INTEGER})`;
|
|
481
|
+
break;
|
|
482
|
+
case "int64":
|
|
483
|
+
type = `(${value} \\in Int /\\ ${value} >= -9223372036854775808 /\\ ${value} <= 9223372036854775807)`;
|
|
484
|
+
break;
|
|
485
|
+
case "boolean":
|
|
486
|
+
type = `${value} \\in BOOLEAN`;
|
|
487
|
+
break;
|
|
488
|
+
case "string":
|
|
489
|
+
type = `${value} \\in STRING`;
|
|
490
|
+
break;
|
|
491
|
+
case "enum":
|
|
492
|
+
type = `${value} \\in ${set(schema.values.map(item => this.value(item, new Map())))}`;
|
|
493
|
+
break;
|
|
494
|
+
case "literal":
|
|
495
|
+
type = `${value} = ${this.value(schema.value, new Map())}`;
|
|
496
|
+
break;
|
|
497
|
+
case "object": {
|
|
498
|
+
const fields = Object.entries(schema.shape);
|
|
499
|
+
type = `(DOMAIN ${value} = ${set(fields.map(([field]) => JSON.stringify(field)))} /\\ ${fields.map(([field, child]) => this.schema(child, `${value}.${identifier(field)}`)).join(" /\\ ") || "TRUE"})`;
|
|
500
|
+
break;
|
|
501
|
+
}
|
|
502
|
+
case "variants": {
|
|
503
|
+
const sum = schema;
|
|
504
|
+
type = `(${sum.variantTags.map(tag => {
|
|
505
|
+
const fields = sum.variants[tag].shape;
|
|
506
|
+
return `(${value}.${identifier(sum.discriminant)} = ${JSON.stringify(tag)} /\\ DOMAIN ${value} = ${set([sum.discriminant, ...Object.keys(fields)].map(field => JSON.stringify(field)))}${Object.entries(fields).map(([field, child]) => ` /\\ ${this.schema(child, `${value}.${identifier(field)}`)}`).join("")})`;
|
|
507
|
+
}).join(" \\/ ")})`;
|
|
508
|
+
break;
|
|
509
|
+
}
|
|
510
|
+
case "array": {
|
|
511
|
+
const child = schema.element;
|
|
512
|
+
const bounds = integralBounds(schema, "length");
|
|
513
|
+
type = `(${value} \\in Seq(${this.carrier(child)}) /\\ Len(${value}) >= ${bounds.lower}${bounds.upper === undefined ? "" : ` /\\ Len(${value}) <= ${bounds.upper}`} /\\ \\A i \\in 1..Len(${value}): ${this.schema(child, `${value}[i]`)})`;
|
|
514
|
+
break;
|
|
515
|
+
}
|
|
516
|
+
default: throw new SpecificationError(`Inductive proof does not support ${schema.kind} schema`);
|
|
517
|
+
}
|
|
518
|
+
const constraints = schema.invariants.map(rule => this.rule(rule, new Map(), value));
|
|
519
|
+
return constraints.length ? `(${type} /\\ ${constraints.join(" /\\ ")})` : type;
|
|
520
|
+
}
|
|
521
|
+
carrier(schema) {
|
|
522
|
+
if (schema.kind === "integer" || schema.kind === "int64")
|
|
523
|
+
return "Int";
|
|
524
|
+
if (schema.kind === "boolean")
|
|
525
|
+
return "BOOLEAN";
|
|
526
|
+
if (schema.kind === "string")
|
|
527
|
+
return "STRING";
|
|
528
|
+
if (schema.kind === "enum")
|
|
529
|
+
return set(schema.values.map(item => this.value(item, new Map())));
|
|
530
|
+
if (schema.kind === "literal")
|
|
531
|
+
return set([this.value(schema.value, new Map())]);
|
|
532
|
+
throw new SpecificationError(`Inductive proof cannot quantify an array of ${schema.kind}`);
|
|
533
|
+
}
|
|
534
|
+
rule(rule, names, self = "s") {
|
|
535
|
+
if (rule.kind === "compare") {
|
|
536
|
+
const operands = new Map([...names, ["", self]]);
|
|
537
|
+
const operator = rule.operator === "==" ? "=" : rule.operator === "!=" ? "#" : rule.operator;
|
|
538
|
+
return `(${this.value(rule.left, operands)} ${operator} ${this.value(rule.right, operands)})`;
|
|
539
|
+
}
|
|
540
|
+
if (rule.kind === "not")
|
|
541
|
+
return `~(${this.rule(rule.rule, names, self)})`;
|
|
542
|
+
if (rule.kind === "and" || rule.kind === "or")
|
|
543
|
+
return `(${rule.rules.map(child => this.rule(child, names, self)).join(rule.kind === "and" ? " /\\ " : " \\/ ")})`;
|
|
544
|
+
const variable = `element${this.next++}`;
|
|
545
|
+
const bound = this.value(rule.of, new Map([...names, ["", self]]));
|
|
546
|
+
const collection = `1..Len(${bound})`;
|
|
547
|
+
const elements = new Map([...names, [rule.element, `${bound}[${variable}]`]]);
|
|
548
|
+
return `(\\${rule.kind === "all" ? "A" : "E"} ${variable} \\in ${collection}: ${this.rule(rule.each, elements, self)})`;
|
|
549
|
+
}
|
|
550
|
+
term(data, names) {
|
|
551
|
+
if (data.kind === "linear") {
|
|
552
|
+
if (!Number.isSafeInteger(data.constant))
|
|
553
|
+
throw new SpecificationError("TLA+ translation requires integer arithmetic");
|
|
554
|
+
const parts = data.parts.map(part => {
|
|
555
|
+
if (!Number.isSafeInteger(part.coefficient))
|
|
556
|
+
throw new SpecificationError("TLA+ translation requires integer coefficients");
|
|
557
|
+
const value = this.position(part.path, part.measure, names);
|
|
558
|
+
return part.coefficient === 1 ? value : `(${part.coefficient} * ${value})`;
|
|
559
|
+
});
|
|
560
|
+
return `(${[...parts, String(data.constant)].join(" + ")})`;
|
|
561
|
+
}
|
|
562
|
+
return this.position(data.path, data.measure, names);
|
|
563
|
+
}
|
|
564
|
+
position(path, measure, names) {
|
|
565
|
+
if (measure !== "value")
|
|
566
|
+
throw new SpecificationError(`TLA+ translation does not support measure ${measure}`);
|
|
567
|
+
const named = names.get(path[0] ?? "");
|
|
568
|
+
const root = named ?? names.get("");
|
|
569
|
+
if (root === undefined)
|
|
570
|
+
throw new SpecificationError(`TLA+ translation cannot resolve term ${path.join(".")}`);
|
|
571
|
+
return path.slice(named === undefined ? 0 : 1).reduce((current, part) => `${current}.${identifier(part)}`, root);
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
function identifier(value) {
|
|
575
|
+
if (!/^[A-Za-z][A-Za-z0-9_]*$/.test(value))
|
|
576
|
+
throw new SpecificationError(`TLA+ translation cannot represent field ${value}`);
|
|
577
|
+
return value;
|
|
578
|
+
}
|
|
579
|
+
//# sourceMappingURL=tla.js.map
|