tla-ts 0.0.3-dev.e927a09 → 0.0.3-dev.eba78ea
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 +5 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +8 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +1 -1
- package/dist/parallel-worker.cjs +1 -1
- package/dist/parallel-worker.js +2 -2
- package/dist/parallel.cjs +1 -1
- package/dist/parallel.js +2 -2
- package/dist/run-cli.cjs +17 -17
- package/dist/run-cli.js +6 -6
- package/dist/transfer.cjs +24 -16
- package/dist/transfer.js +24 -16
- package/package.json +1 -1
- package/src/check.ts +141 -33
- package/src/cli-options.ts +11 -5
- package/src/environment.ts +65 -6
- package/src/errors.ts +4 -2
- package/src/evaluate.ts +9 -6
- package/src/exit-codes.ts +1 -13
- package/src/instances.ts +3 -3
- package/src/parallel.ts +3 -0
- package/src/run-cli.ts +49 -11
- package/src/runtime.ts +2 -0
- package/src/spec-description.ts +11 -4
- package/src/standard-modules.ts +2 -7
- package/src/state-graph.ts +157 -0
- package/src/successors.ts +49 -0
- package/src/tlc-ext.ts +27 -2
- package/src/tlc-module.ts +9 -28
- package/src/values.ts +33 -7
package/src/run-cli.ts
CHANGED
|
@@ -19,20 +19,22 @@ import {
|
|
|
19
19
|
TlaError,
|
|
20
20
|
TlaEvaluationError,
|
|
21
21
|
TlaProofError,
|
|
22
|
+
TlaSyntaxError,
|
|
22
23
|
} from "./errors";
|
|
23
24
|
import { EXIT_STATUS } from "./exit-codes";
|
|
24
25
|
import type { LineRange } from "./obligation-generate";
|
|
25
26
|
import { getAtPrefix, getLocusText } from "./obligation-expression";
|
|
26
27
|
import { formatSummary, getObligations, WHOLE_MODULE, type ModuleObligations } from "./obligations";
|
|
27
28
|
import { check } from "./parallel";
|
|
28
|
-
import {
|
|
29
|
+
import { parseModule } from "./parser";
|
|
30
|
+
import type { StateDump } from "./state-graph";
|
|
29
31
|
import {
|
|
30
32
|
formatProbability,
|
|
31
33
|
getActualProbability,
|
|
32
34
|
getOptimisticProbability,
|
|
33
35
|
getOutDegreeSummary,
|
|
34
36
|
} from "./tlc-summary";
|
|
35
|
-
import {
|
|
37
|
+
import { formatState, type Value } from "./values";
|
|
36
38
|
|
|
37
39
|
const EXIT_CODES: Record<CheckStatus, number> = {
|
|
38
40
|
success: EXIT_STATUS.success,
|
|
@@ -48,6 +50,11 @@ const EXIT_CODES: Record<CheckStatus, number> = {
|
|
|
48
50
|
const CHECK_COMMAND = defineCommand("tla-ts <Spec.tla|Spec.cfg|glob>... {options}", [
|
|
49
51
|
{ flag: "-config <Spec.cfg>" },
|
|
50
52
|
{ flag: "-deadlock" },
|
|
53
|
+
// Like TLC, -dump takes a format only when the next argument starts with dot and a file follows.
|
|
54
|
+
{
|
|
55
|
+
flag: "-dump [<format>] <file>",
|
|
56
|
+
getArity: (rest) => (rest.length > 1 && rest[0].startsWith("dot") ? 2 : 1),
|
|
57
|
+
},
|
|
51
58
|
{ flag: "-lncheck <final|default>" },
|
|
52
59
|
{ flag: "-seed <num>" },
|
|
53
60
|
{ flag: "-workers <count|auto>" },
|
|
@@ -95,14 +102,24 @@ const getWorkerCount = (values: string[] | undefined) => {
|
|
|
95
102
|
: Math.max(1, Number.parseInt(values[0], 10) || 1);
|
|
96
103
|
};
|
|
97
104
|
|
|
98
|
-
const printState = (state: Record<string, Value>) =>
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
)
|
|
105
|
-
|
|
105
|
+
const printState = (state: Record<string, Value>) => console.log(formatState(state));
|
|
106
|
+
|
|
107
|
+
const UNSUPPORTED_DUMP_FORMATS = ["constrained", "stuttering", "strict"];
|
|
108
|
+
|
|
109
|
+
// TLC names the file of a -dump by its format unless the name already ends that way.
|
|
110
|
+
const getDumpPath = (path: string, extension: string) =>
|
|
111
|
+
path.endsWith(extension) ? path : `${path}${extension}`;
|
|
112
|
+
|
|
113
|
+
const getDump = (values: string[]): StateDump => {
|
|
114
|
+
if (values.length === 1) return { path: getDumpPath(values[0], ".dump") };
|
|
115
|
+
const format = values[0].toLowerCase();
|
|
116
|
+
return {
|
|
117
|
+
path: getDumpPath(values[1], ".dot"),
|
|
118
|
+
dot: true,
|
|
119
|
+
colorize: format.includes("colorize"),
|
|
120
|
+
actionLabels: format.includes("actionlabels"),
|
|
121
|
+
snapshot: format.includes("snapshot"),
|
|
122
|
+
};
|
|
106
123
|
};
|
|
107
124
|
|
|
108
125
|
const printTrace = (trace: TraceStep[], heading = "Error: The behavior up to this point is:") => {
|
|
@@ -198,6 +215,14 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
|
|
|
198
215
|
console.error(`Cannot find the specification file ${specPath}`);
|
|
199
216
|
return EXIT_STATUS.configParseError;
|
|
200
217
|
}
|
|
218
|
+
const source = readFileSync(specPath, "utf8");
|
|
219
|
+
const fileName = basename(specPath, ".tla");
|
|
220
|
+
const moduleName = parseModule(source).name;
|
|
221
|
+
if (moduleName !== fileName) {
|
|
222
|
+
throw new TlaSyntaxError(
|
|
223
|
+
`File name '${fileName}' does not match the name '${moduleName}' of the top level module it contains.`,
|
|
224
|
+
);
|
|
225
|
+
}
|
|
201
226
|
const configPath =
|
|
202
227
|
args.get("-config")?.[0] ??
|
|
203
228
|
(args.has("-config") ? undefined : specPath.replace(/\.tla$/, ".cfg"));
|
|
@@ -221,13 +246,26 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
|
|
|
221
246
|
console.error("Error: expect a strategy such as final for -lncheck option.");
|
|
222
247
|
return 1;
|
|
223
248
|
}
|
|
249
|
+
const dumpValues = args.get("-dump");
|
|
250
|
+
if (dumpValues?.length === 0) {
|
|
251
|
+
console.error("Error: A file name for dumping states required.");
|
|
252
|
+
return 1;
|
|
253
|
+
}
|
|
254
|
+
const unsupportedFormat =
|
|
255
|
+
dumpValues?.length === 2 &&
|
|
256
|
+
UNSUPPORTED_DUMP_FORMATS.find((format) => dumpValues[0].toLowerCase().includes(format));
|
|
257
|
+
if (unsupportedFormat) {
|
|
258
|
+
console.error(`Error: tla-ts does not support the -dump format ${unsupportedFormat}.`);
|
|
259
|
+
return 1;
|
|
260
|
+
}
|
|
224
261
|
const directory = dirname(specPath);
|
|
225
262
|
console.log(`Checking ${basename(specPath)} with ${basename(configPath)}`);
|
|
226
263
|
const result = await check({
|
|
227
264
|
workers: getWorkerCount(args.get("-workers")),
|
|
228
265
|
livenessCheck: ["final", "seqfinal", "off"].includes(livenessCheck) ? "final" : "default",
|
|
229
266
|
seed: BigInt(seed),
|
|
230
|
-
|
|
267
|
+
dump: dumpValues && getDump(dumpValues),
|
|
268
|
+
source,
|
|
231
269
|
config,
|
|
232
270
|
onPause: () => readSync(0, Buffer.alloc(1)),
|
|
233
271
|
loadModule: (name) => {
|
package/src/runtime.ts
CHANGED
|
@@ -24,6 +24,7 @@ export interface CheckerRuntime {
|
|
|
24
24
|
properties: Map<string, string>;
|
|
25
25
|
possibleCounts: Map<string, number>;
|
|
26
26
|
isStopped: boolean;
|
|
27
|
+
isStarted: boolean;
|
|
27
28
|
checkDeadlock: boolean;
|
|
28
29
|
startedAt: number;
|
|
29
30
|
}
|
|
@@ -75,6 +76,7 @@ export const createRuntime = (checkDeadlock: boolean, seed = 0n): CheckerRuntime
|
|
|
75
76
|
properties: new Map(),
|
|
76
77
|
possibleCounts: new Map(),
|
|
77
78
|
isStopped: false,
|
|
79
|
+
isStarted: false,
|
|
78
80
|
checkDeadlock,
|
|
79
81
|
startedAt: Date.now(),
|
|
80
82
|
};
|
package/src/spec-description.ts
CHANGED
|
@@ -469,10 +469,17 @@ export const getNextActions = (
|
|
|
469
469
|
instanceActions: Map<string, InstanceAction>,
|
|
470
470
|
) => describe(config, environment, instanceActions).actions;
|
|
471
471
|
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
}
|
|
472
|
+
const formatParameters = (action: SpecAction) =>
|
|
473
|
+
action.parameters.length === 0
|
|
474
|
+
? ""
|
|
475
|
+
: `(${action.parameters.map((parameter) => formatValue(parameter[1])).join(",")})`;
|
|
476
|
+
|
|
477
|
+
export const getActionLabel = (action: SpecAction) =>
|
|
478
|
+
`${action.name === UNNAMED_ACTION ? "Action" : action.name}${formatParameters(action)} ${formatRange(action.location.range ?? BUILTIN_RANGE)}`;
|
|
479
|
+
|
|
480
|
+
// TLC's Action.getInvocationSignature, which names the action and the values of its parameters.
|
|
481
|
+
export const getActionSignature = (action: SpecAction) =>
|
|
482
|
+
`${action.name}${formatParameters(action)}`;
|
|
476
483
|
|
|
477
484
|
export const getSpecificationValue = (
|
|
478
485
|
config: ModelConfig,
|
package/src/standard-modules.ts
CHANGED
|
@@ -40,6 +40,7 @@ import {
|
|
|
40
40
|
isEnumerable,
|
|
41
41
|
isFiniteSet,
|
|
42
42
|
isFunctionValue,
|
|
43
|
+
isReducible,
|
|
43
44
|
isSetValue,
|
|
44
45
|
toFiniteSet,
|
|
45
46
|
unionSorted,
|
|
@@ -47,7 +48,7 @@ import {
|
|
|
47
48
|
createEnumeratedSet,
|
|
48
49
|
EMPTY_SET,
|
|
49
50
|
isEnumeratedSet,
|
|
50
|
-
type
|
|
51
|
+
type ReducibleSet,
|
|
51
52
|
type MixedSetValue,
|
|
52
53
|
type SetOperationValue,
|
|
53
54
|
type SetValue,
|
|
@@ -75,12 +76,6 @@ const unionInTree = (sets: SetValue[], start: number, end: number): SetValue =>
|
|
|
75
76
|
|
|
76
77
|
const SET_OPERATORS: SetOperationValue["operator"][] = ["\\cup", "\\cap", "\\"];
|
|
77
78
|
|
|
78
|
-
type ReducibleSet = SetValue | MixedSetValue | IntervalValue;
|
|
79
|
-
|
|
80
|
-
const isReducible = (value: Value): value is ReducibleSet =>
|
|
81
|
-
typeof value === "object" &&
|
|
82
|
-
(value.kind === "Set" || value.kind === "MixedSet" || value.kind === "Interval");
|
|
83
|
-
|
|
84
79
|
const isMixedSet = (value: Value) => typeof value === "object" && value.kind === "MixedSet";
|
|
85
80
|
|
|
86
81
|
const getReducibleElements = (set: ReducibleSet) =>
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
// A port of TLC's -dump writers, tlc2.util.StateWriter and tlc2.util.DotStateWriter.
|
|
2
|
+
|
|
3
|
+
export interface StateDump {
|
|
4
|
+
path: string;
|
|
5
|
+
dot?: boolean;
|
|
6
|
+
colorize?: boolean;
|
|
7
|
+
actionLabels?: boolean;
|
|
8
|
+
snapshot?: boolean;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface GraphState {
|
|
12
|
+
fingerprint: bigint;
|
|
13
|
+
level: number;
|
|
14
|
+
// The state as TLC prints it after evaluating the alias, and as it prints it without the alias.
|
|
15
|
+
getLabel: () => string;
|
|
16
|
+
getText: () => string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export interface GraphAction {
|
|
20
|
+
name: string;
|
|
21
|
+
signature: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface StateWriter {
|
|
25
|
+
writeInitialState: (state: GraphState) => void;
|
|
26
|
+
writeSuccessor: (
|
|
27
|
+
state: GraphState,
|
|
28
|
+
successor: GraphState,
|
|
29
|
+
isSeen: boolean,
|
|
30
|
+
action: GraphAction | undefined,
|
|
31
|
+
) => void;
|
|
32
|
+
close: () => void;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
type WriteFile = ((path: string, content: string) => void) | undefined;
|
|
36
|
+
|
|
37
|
+
const COLOR_SCHEME = "paired12";
|
|
38
|
+
const LOAD_FACTOR = 0.75;
|
|
39
|
+
const INITIAL_CAPACITY = 16;
|
|
40
|
+
|
|
41
|
+
const getCapacity = (size: number, capacity = INITIAL_CAPACITY): number =>
|
|
42
|
+
size <= capacity * LOAD_FACTOR ? capacity : getCapacity(size, capacity * 2);
|
|
43
|
+
|
|
44
|
+
// The order in which a java.util.HashMap iterates over keys put in this order: by bucket, and in
|
|
45
|
+
// insertion order within a bucket. A bucket only becomes a tree once 8 keys collide in it.
|
|
46
|
+
const getJavaHashOrder = <Key>(keys: Key[], getHash: (key: Key) => number) => {
|
|
47
|
+
const mask = getCapacity(keys.length) - 1;
|
|
48
|
+
const getBucket = (key: Key) => {
|
|
49
|
+
const hash = getHash(key);
|
|
50
|
+
return (hash ^ (hash >>> 16)) & mask;
|
|
51
|
+
};
|
|
52
|
+
return keys
|
|
53
|
+
.map((key, position) => ({ key, position, bucket: getBucket(key) }))
|
|
54
|
+
.sort((left, right) => left.bucket - right.bucket || left.position - right.position)
|
|
55
|
+
.map((entry) => entry.key);
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
const getLongHash = (value: bigint) =>
|
|
59
|
+
Number(BigInt.asIntN(32, value ^ (BigInt.asUintN(64, value) >> 32n)));
|
|
60
|
+
|
|
61
|
+
const getStringHash = (text: string) =>
|
|
62
|
+
[...Array(text.length).keys()].reduce(
|
|
63
|
+
(hash, index) => (Math.imul(31, hash) + text.charCodeAt(index)) | 0,
|
|
64
|
+
0,
|
|
65
|
+
);
|
|
66
|
+
|
|
67
|
+
const escape = (text: string) => text.replaceAll("\\", "\\\\").replaceAll('"', '\\"').trim();
|
|
68
|
+
|
|
69
|
+
const toDot = (text: string) => escape(text).replaceAll("\n", "\\n");
|
|
70
|
+
|
|
71
|
+
const createPlainWriter = (dump: StateDump, writeFile: WriteFile): StateWriter => {
|
|
72
|
+
const states: string[] = [];
|
|
73
|
+
const writeState = (state: GraphState) =>
|
|
74
|
+
states.push(`State ${states.length + 1}:\n${state.getText()}\n`);
|
|
75
|
+
return {
|
|
76
|
+
writeInitialState: writeState,
|
|
77
|
+
writeSuccessor: (_state, successor, isSeen) => {
|
|
78
|
+
if (!isSeen) writeState(successor);
|
|
79
|
+
},
|
|
80
|
+
close: () => writeFile?.(dump.path, states.join("")),
|
|
81
|
+
};
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
const createDotWriter = (dump: StateDump, writeFile: WriteFile): StateWriter => {
|
|
85
|
+
const lines = [
|
|
86
|
+
"strict digraph DiskGraph {\n",
|
|
87
|
+
"node [shape=box,style=rounded]\n",
|
|
88
|
+
dump.colorize ? `edge [colorscheme="${COLOR_SCHEME}"]\n` : "",
|
|
89
|
+
"nodesep=0.35;\n",
|
|
90
|
+
"subgraph cluster_graph {\n",
|
|
91
|
+
'color="white";\n',
|
|
92
|
+
];
|
|
93
|
+
const ranks = new Map<number, Set<bigint>>();
|
|
94
|
+
const colors = new Map<string, number>();
|
|
95
|
+
const addRank = (state: GraphState) => {
|
|
96
|
+
const rank = ranks.get(state.level) ?? new Set();
|
|
97
|
+
ranks.set(state.level, rank.add(state.fingerprint));
|
|
98
|
+
};
|
|
99
|
+
// TLC colors an edge by the name of its action, numbering the names from 2 as it finds them.
|
|
100
|
+
const getColor = (action: GraphAction | undefined) => {
|
|
101
|
+
if (!action) return 1;
|
|
102
|
+
const color = colors.get(action.name) ?? colors.size + 2;
|
|
103
|
+
colors.set(action.name, color);
|
|
104
|
+
return color;
|
|
105
|
+
};
|
|
106
|
+
const getLegend = () =>
|
|
107
|
+
[
|
|
108
|
+
`subgraph cluster_legend {graph[style=bold];label = "Next State Actions" style="solid"\n`,
|
|
109
|
+
`node [ labeljust="l",colorscheme="${COLOR_SCHEME}",style=filled,shape=record ]\n`,
|
|
110
|
+
...getJavaHashOrder([...colors.keys()], getStringHash).map(
|
|
111
|
+
(name) => `${name.replaceAll("!", ":")} [label="${name}",fillcolor=${colors.get(name)}]\n`,
|
|
112
|
+
),
|
|
113
|
+
"}",
|
|
114
|
+
].join("");
|
|
115
|
+
const getEnding = () =>
|
|
116
|
+
[
|
|
117
|
+
...getJavaHashOrder([...ranks], (rank) => rank[0]).map(
|
|
118
|
+
(rank) =>
|
|
119
|
+
`{rank = same; ${getJavaHashOrder([...rank[1]], getLongHash)
|
|
120
|
+
.map((fingerprint) => `${fingerprint};`)
|
|
121
|
+
.join("")}}\n`,
|
|
122
|
+
),
|
|
123
|
+
"}\n",
|
|
124
|
+
dump.colorize && colors.size > 1 ? getLegend() : "",
|
|
125
|
+
"}",
|
|
126
|
+
].join("");
|
|
127
|
+
const writeSnapshot = () => {
|
|
128
|
+
if (dump.snapshot) {
|
|
129
|
+
writeFile?.(dump.path.replaceAll(".dot", "_snapshot.dot"), lines.join("") + getEnding());
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
return {
|
|
133
|
+
writeInitialState: (state) => {
|
|
134
|
+
lines.push(`${state.fingerprint} [label="${toDot(state.getLabel())}",style = filled]\n`);
|
|
135
|
+
addRank(state);
|
|
136
|
+
writeSnapshot();
|
|
137
|
+
},
|
|
138
|
+
writeSuccessor: (state, successor, isSeen, action) => {
|
|
139
|
+
const color = dump.colorize ? String(getColor(action)) : "black";
|
|
140
|
+
const label = dump.actionLabels && action ? escape(action.signature) : "";
|
|
141
|
+
lines.push(
|
|
142
|
+
`${state.fingerprint} -> ${successor.fingerprint} [label="${label}",color="${color}",fontcolor="${color}"];\n`,
|
|
143
|
+
);
|
|
144
|
+
if (!isSeen) {
|
|
145
|
+
lines.push(
|
|
146
|
+
`${successor.fingerprint} [label="${toDot(successor.getLabel())}",tooltip="${toDot(successor.getText())}"];\n`,
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
addRank(state);
|
|
150
|
+
writeSnapshot();
|
|
151
|
+
},
|
|
152
|
+
close: () => writeFile?.(dump.path, lines.join("") + getEnding()),
|
|
153
|
+
};
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
export const createStateWriter = (dump: StateDump, writeFile: WriteFile) =>
|
|
157
|
+
dump.dot ? createDotWriter(dump, writeFile) : createPlainWriter(dump, writeFile);
|
package/src/successors.ts
CHANGED
|
@@ -4,6 +4,7 @@ import {
|
|
|
4
4
|
type Bound,
|
|
5
5
|
type Definition,
|
|
6
6
|
type Expression,
|
|
7
|
+
type QuantifierExpression,
|
|
7
8
|
} from "./ast";
|
|
8
9
|
import { getReadVariables } from "./dependencies";
|
|
9
10
|
import { TlaEvaluationError, UNEXPECTED_EXCEPTION } from "./errors";
|
|
@@ -292,6 +293,27 @@ const toConjunct = (
|
|
|
292
293
|
return { kind: "Branch", expression, runner: getRunner(expression, environment, isInit) };
|
|
293
294
|
};
|
|
294
295
|
|
|
296
|
+
// The leading guards of `\E x \in S, y \in T : P /\ Q` that read no inner bound hold for every inner
|
|
297
|
+
// binding alike, so they can run once for each element of the outermost bound.
|
|
298
|
+
const getHoistedGuards = (expression: QuantifierExpression, environment: Environment) => {
|
|
299
|
+
if (expression.bounds.length < 2 || expression.body.kind !== "And") return undefined;
|
|
300
|
+
const names = expression.bounds.flatMap((bound) =>
|
|
301
|
+
bound.pattern.kind === "Name" ? [bound.pattern.name] : [],
|
|
302
|
+
);
|
|
303
|
+
if (names.length !== expression.bounds.length) return undefined;
|
|
304
|
+
const innerNames = new Set(names.slice(0, -1));
|
|
305
|
+
const operands = expression.body.operands;
|
|
306
|
+
const index = operands.findIndex((operand) => {
|
|
307
|
+
if (getReadVariables(operand, environment) === undefined) return true;
|
|
308
|
+
if (hasBranches(operand, environment, new Set())) return true;
|
|
309
|
+
const readLocals = getReadLocals(operand, NO_NAMES);
|
|
310
|
+
return !readLocals || readLocals.some((name) => innerNames.has(name));
|
|
311
|
+
});
|
|
312
|
+
const count = index === -1 ? operands.length : index;
|
|
313
|
+
if (count === 0) return undefined;
|
|
314
|
+
return { names, guards: operands.slice(0, count), rest: operands.slice(count) };
|
|
315
|
+
};
|
|
316
|
+
|
|
295
317
|
const compileConjunction = (
|
|
296
318
|
operands: Expression[],
|
|
297
319
|
environment: Environment,
|
|
@@ -734,6 +756,33 @@ const compileAction = (
|
|
|
734
756
|
}
|
|
735
757
|
};
|
|
736
758
|
}
|
|
759
|
+
const hoisted = isInit ? undefined : getHoistedGuards(expression, environment);
|
|
760
|
+
if (hoisted) {
|
|
761
|
+
const rest = compileConjunction(hoisted.rest, environment, isInit);
|
|
762
|
+
return (run, scope, partial, action, isFixed, onComplete) => {
|
|
763
|
+
const context = getContext(run, scope, partial);
|
|
764
|
+
const sets = expression.bounds.map((innerBound) =>
|
|
765
|
+
getEnumeratedElements(evaluate(innerBound.set, context), innerBound.set),
|
|
766
|
+
);
|
|
767
|
+
if (sets.some((elements) => elements.length === 0)) return;
|
|
768
|
+
const visit = (index: number, boundScope: Scope | undefined): void => {
|
|
769
|
+
if (index < 0) {
|
|
770
|
+
rest(run, boundScope, partial, action, isFixed, onComplete);
|
|
771
|
+
return;
|
|
772
|
+
}
|
|
773
|
+
for (const element of sets[index]) {
|
|
774
|
+
if (run.isStopped) return;
|
|
775
|
+
const elementScope = bindValue(boundScope, hoisted.names[index], element);
|
|
776
|
+
if (index === sets.length - 1) {
|
|
777
|
+
const guardContext = getContext(run, elementScope, partial);
|
|
778
|
+
if (!hoisted.guards.every((guard) => holds(guard, guardContext))) continue;
|
|
779
|
+
}
|
|
780
|
+
visit(index - 1, elementScope);
|
|
781
|
+
}
|
|
782
|
+
};
|
|
783
|
+
visit(sets.length - 1, scope);
|
|
784
|
+
};
|
|
785
|
+
}
|
|
737
786
|
return (run, scope, partial, action, isFixed, onComplete) => {
|
|
738
787
|
forEachBinding(expression.bounds, getContext(run, scope, partial), (boundScope) => {
|
|
739
788
|
body(run, boundScope, partial, action, isFixed, onComplete);
|
package/src/tlc-ext.ts
CHANGED
|
@@ -103,15 +103,35 @@ const getRegister = (runtime: CheckerRuntime, key: Value) => {
|
|
|
103
103
|
return undefined;
|
|
104
104
|
};
|
|
105
105
|
|
|
106
|
-
|
|
106
|
+
// TLC's TLCSet. TLCExt's TLCGetAndSet is a TLA+ definition that calls it.
|
|
107
|
+
export const setTlcValue = (
|
|
108
|
+
runtime: CheckerRuntime,
|
|
109
|
+
print: (text: string) => void,
|
|
110
|
+
key: Value,
|
|
111
|
+
value: Value,
|
|
112
|
+
) => {
|
|
107
113
|
if (typeof key === "number" && key >= 0) {
|
|
108
114
|
runtime.registers.set(key, value);
|
|
109
115
|
return;
|
|
110
116
|
}
|
|
117
|
+
if (key === "exit") {
|
|
118
|
+
if (value === true) runtime.isStopped = true;
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
if (key === "pause") {
|
|
122
|
+
if (value !== true) return;
|
|
123
|
+
print("Press enter to resume model checking.");
|
|
124
|
+
runtime.pause();
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
111
127
|
if (typeof key === "string" && key.startsWith(NAMED_REGISTER_PREFIX)) {
|
|
112
128
|
runtime.namedRegisters.set(key, value);
|
|
113
129
|
return;
|
|
114
130
|
}
|
|
131
|
+
if (typeof key === "string" && key.startsWith("-D")) {
|
|
132
|
+
runtime.properties.set(key.slice(2), formatValue(value));
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
115
135
|
throw new TlaModuleError(
|
|
116
136
|
`The first argument of TLCSet should be a nonnegative integer, but instead it is:\n${formatValue(key)}`,
|
|
117
137
|
);
|
|
@@ -195,7 +215,12 @@ export const createTlcExtOperators = (
|
|
|
195
215
|
const key = getValue(args, 0, "TLCGetAndSet");
|
|
196
216
|
const previous = getRegister(runtime, key) ?? getValue(args, 3, "TLCGetAndSet");
|
|
197
217
|
const update = getOperator(args, 1, "TLCGetAndSet");
|
|
198
|
-
|
|
218
|
+
setTlcValue(
|
|
219
|
+
runtime,
|
|
220
|
+
print,
|
|
221
|
+
key,
|
|
222
|
+
update.call([previous, getValue(args, 2, "TLCGetAndSet")]),
|
|
223
|
+
);
|
|
199
224
|
return previous;
|
|
200
225
|
}),
|
|
201
226
|
isStateLevel: true,
|
package/src/tlc-module.ts
CHANGED
|
@@ -15,7 +15,7 @@ import {
|
|
|
15
15
|
getValue,
|
|
16
16
|
} from "./builtins";
|
|
17
17
|
import { getNamedRegisters, NAMED_REGISTER_PREFIX, type CheckerRuntime } from "./runtime";
|
|
18
|
-
import { createActionRecord } from "./tlc-ext";
|
|
18
|
+
import { createActionRecord, setTlcValue } from "./tlc-ext";
|
|
19
19
|
import { getRandomElement } from "./tlc-random";
|
|
20
20
|
import {
|
|
21
21
|
ANY_SET,
|
|
@@ -39,11 +39,17 @@ const formatCalendarVersion = (date: Date) =>
|
|
|
39
39
|
const getRegisterFunction = <Key extends Value>(registers: Map<Key, Value>) =>
|
|
40
40
|
createFunction([...registers].map(([key, value]): [Value, Value] => [key, createTuple([value])]));
|
|
41
41
|
|
|
42
|
+
// TLC creates its model checker after it processes the spec, so these are undefined before then.
|
|
43
|
+
const CHECKER_KEYS = new Set(["diameter", "generated", "distinct", "queue", "stats", "config"]);
|
|
44
|
+
|
|
42
45
|
const getRuntimeValue = (
|
|
43
46
|
runtime: CheckerRuntime,
|
|
44
47
|
key: string,
|
|
45
48
|
state: (Value | undefined)[] | undefined,
|
|
46
49
|
) => {
|
|
50
|
+
if (!runtime.isStarted && CHECKER_KEYS.has(key)) {
|
|
51
|
+
throw new TlaModuleError(`TLCGet(${key}) was undefined.`);
|
|
52
|
+
}
|
|
47
53
|
const duration = Math.floor((Date.now() - runtime.startedAt) / 1000);
|
|
48
54
|
switch (key) {
|
|
49
55
|
case "level":
|
|
@@ -203,33 +209,8 @@ export const createTlcOperators = (
|
|
|
203
209
|
}),
|
|
204
210
|
defineStateOperator("TLCSet", 2, (args) => {
|
|
205
211
|
const key = getValue(args, 0, "TLCSet");
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
runtime.registers.set(key, value);
|
|
209
|
-
return true;
|
|
210
|
-
}
|
|
211
|
-
if (key === "exit") {
|
|
212
|
-
if (value === true) runtime.isStopped = true;
|
|
213
|
-
return true;
|
|
214
|
-
}
|
|
215
|
-
if (key === "pause") {
|
|
216
|
-
if (value === true) {
|
|
217
|
-
print("Press enter to resume model checking.");
|
|
218
|
-
runtime.pause();
|
|
219
|
-
}
|
|
220
|
-
return true;
|
|
221
|
-
}
|
|
222
|
-
if (typeof key === "string" && key.startsWith(NAMED_REGISTER_PREFIX)) {
|
|
223
|
-
runtime.namedRegisters.set(key, value);
|
|
224
|
-
return true;
|
|
225
|
-
}
|
|
226
|
-
if (typeof key === "string" && key.startsWith("-D")) {
|
|
227
|
-
runtime.properties.set(key.slice(2), formatValue(value));
|
|
228
|
-
return true;
|
|
229
|
-
}
|
|
230
|
-
throw new TlaModuleError(
|
|
231
|
-
`The first argument of TLCSet should be a nonnegative integer, but instead it is:\n${formatValue(key)}`,
|
|
232
|
-
);
|
|
212
|
+
setTlcValue(runtime, print, key, getValue(args, 1, "TLCSet"));
|
|
213
|
+
return true;
|
|
233
214
|
}),
|
|
234
215
|
defineConstant("Any", ANY_SET),
|
|
235
216
|
defineOperator("RandomElement", 1, (args) =>
|
package/src/values.ts
CHANGED
|
@@ -137,6 +137,13 @@ export const isSetValue = (value: Value) =>
|
|
|
137
137
|
value.kind !== "Function" &&
|
|
138
138
|
value.kind !== "LazyFunction";
|
|
139
139
|
|
|
140
|
+
export type ReducibleSet = SetValue | MixedSetValue | IntervalValue;
|
|
141
|
+
|
|
142
|
+
// TLC reduces a set enumeration or an interval eagerly, and keeps every other set lazy.
|
|
143
|
+
export const isReducible = (value: Value): value is ReducibleSet =>
|
|
144
|
+
typeof value === "object" &&
|
|
145
|
+
(value.kind === "Set" || value.kind === "MixedSet" || value.kind === "Interval");
|
|
146
|
+
|
|
140
147
|
export const isFunctionValue = (value: Value): value is FunctionValue | LazyFunctionValue =>
|
|
141
148
|
typeof value === "object" && (value.kind === "Function" || value.kind === "LazyFunction");
|
|
142
149
|
|
|
@@ -1069,13 +1076,16 @@ const isTlcEnumerable = (value: Value) => isSetValue(value) && !isOverriddenSet(
|
|
|
1069
1076
|
const formatUnion = (value: UnionValue, isStrict = false) =>
|
|
1070
1077
|
`UNION(${formatValue(value.base, isStrict)})`;
|
|
1071
1078
|
|
|
1072
|
-
const getUnionSets = (
|
|
1079
|
+
const getUnionSets = (
|
|
1080
|
+
value: UnionValue,
|
|
1081
|
+
getElements = (set: Value) => toFiniteSet(set).elements,
|
|
1082
|
+
) => {
|
|
1073
1083
|
if (!isTlcEnumerable(value.base)) {
|
|
1074
1084
|
throw new TlaEvaluationError(
|
|
1075
1085
|
`Attempted to enumerate the nonenumerable set:\n${formatUnion(value)}`,
|
|
1076
1086
|
);
|
|
1077
1087
|
}
|
|
1078
|
-
return
|
|
1088
|
+
return getElements(value.base);
|
|
1079
1089
|
};
|
|
1080
1090
|
|
|
1081
1091
|
const getUnionSet = (set: Value, index: number, union: UnionValue) => {
|
|
@@ -1111,7 +1121,7 @@ export const isEnumerable = (value: Value): boolean => {
|
|
|
1111
1121
|
case "ProductSet":
|
|
1112
1122
|
return value.factors.every(isEnumerable) || getEmptiness(value) === true;
|
|
1113
1123
|
case "Union":
|
|
1114
|
-
return isEnumerable(value.base) &&
|
|
1124
|
+
return isEnumerable(value.base) && getStreamedElements(value.base).every(isEnumerable);
|
|
1115
1125
|
case "SetOperation":
|
|
1116
1126
|
if (value.operator === "\\cup") return isEnumerable(value.left) && isEnumerable(value.right);
|
|
1117
1127
|
if (value.operator === "\\cap") return isEnumerable(value.left) || isEnumerable(value.right);
|
|
@@ -1345,8 +1355,10 @@ export const toFiniteSet = (value: Value): SetValue => {
|
|
|
1345
1355
|
// so an element that two of them share comes up once for each.
|
|
1346
1356
|
export const getStreamedElements = (value: Value): Value[] => {
|
|
1347
1357
|
if (typeof value !== "object" || finiteSets.has(value)) return toFiniteSet(value).elements;
|
|
1358
|
+
// TLC streams the sets of a UNION it hasn't enumerated, so a set that appears twice there yields
|
|
1359
|
+
// its elements twice.
|
|
1348
1360
|
if (value.kind === "Union") {
|
|
1349
|
-
return getUnionSets(value).flatMap((set, index) =>
|
|
1361
|
+
return getUnionSets(value, getStreamedElements).flatMap((set, index) =>
|
|
1350
1362
|
getStreamedElements(getUnionSet(set, index, value)),
|
|
1351
1363
|
);
|
|
1352
1364
|
}
|
|
@@ -2101,8 +2113,11 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
|
|
|
2101
2113
|
return `[${parameters} |-> <expression ${source.body}>]`;
|
|
2102
2114
|
}
|
|
2103
2115
|
const functionValue = toFiniteFunction(value);
|
|
2116
|
+
// TLC normalizes a lambda's domain to print it, but evaluates its body afterward.
|
|
2117
|
+
const formatRange = (inner: Value) =>
|
|
2118
|
+
formatValue(inner, isStrict, isNormalized && value.kind === "Function");
|
|
2104
2119
|
if (functionValue.domain.every((key, index) => key === index + 1)) {
|
|
2105
|
-
return `<<${functionValue.range.map(
|
|
2120
|
+
return `<<${functionValue.range.map(formatRange).join(", ")}>>`;
|
|
2106
2121
|
}
|
|
2107
2122
|
if (functionValue.domain.every((key) => typeof key === "string" && isFieldName(key))) {
|
|
2108
2123
|
const isSorted =
|
|
@@ -2110,9 +2125,20 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
|
|
|
2110
2125
|
const pairs = isSorted
|
|
2111
2126
|
? functionValue.domain.map((key, index) => [key, functionValue.range[index]])
|
|
2112
2127
|
: getWrittenPairs(functionValue);
|
|
2113
|
-
return `[${pairs.map((pair) => `${String(pair[0])} |-> ${
|
|
2128
|
+
return `[${pairs.map((pair) => `${String(pair[0])} |-> ${formatRange(pair[1])}`).join(", ")}]`;
|
|
2114
2129
|
}
|
|
2115
|
-
return `(${functionValue.domain.map((key, index) => `${format(key)} :> ${
|
|
2130
|
+
return `(${functionValue.domain.map((key, index) => `${format(key)} :> ${formatRange(functionValue.range[index])}`).join(" @@ ")})`;
|
|
2116
2131
|
}
|
|
2117
2132
|
}
|
|
2118
2133
|
};
|
|
2134
|
+
|
|
2135
|
+
// TLC's TLCState.toString: a line per variable, as a conjunction when there are several.
|
|
2136
|
+
export const formatState = (state: Record<string, Value>) => {
|
|
2137
|
+
const entries = Object.entries(state);
|
|
2138
|
+
return entries
|
|
2139
|
+
.map(
|
|
2140
|
+
([name, value]) =>
|
|
2141
|
+
`${entries.length === 1 ? "" : "/\\ "}${name} = ${prettyPrint(formatValue(value))}\n`,
|
|
2142
|
+
)
|
|
2143
|
+
.join("");
|
|
2144
|
+
};
|