tla-ts 0.0.3-dev.3cf2ad0 → 0.0.3-dev.45d0f50
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 +16 -2
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +9 -0
- package/dist/index.d.ts +9 -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 -16
- package/dist/run-cli.js +6 -5
- package/dist/transfer.cjs +27 -15
- package/dist/transfer.js +27 -15
- package/package.json +1 -1
- package/src/ast.ts +90 -0
- package/src/check.ts +264 -78
- package/src/cli-options.ts +11 -5
- package/src/codegen.ts +15 -22
- package/src/dependencies.ts +2 -2
- package/src/environment.ts +94 -24
- package/src/errors.ts +18 -2
- package/src/evaluate.ts +122 -147
- package/src/exit-codes.ts +21 -43
- package/src/instances.ts +15 -14
- package/src/levels.ts +8 -8
- package/src/lexer.ts +5 -1
- package/src/live-check.ts +770 -0
- package/src/liveness.ts +54 -535
- package/src/parallel-worker.ts +7 -3
- package/src/parallel.ts +20 -4
- package/src/parser.ts +12 -1
- package/src/resolve.ts +16 -15
- package/src/run-cli.ts +58 -13
- package/src/runtime.ts +3 -1
- package/src/spec-description.ts +18 -6
- package/src/standard-modules.ts +2 -7
- package/src/state-graph.ts +157 -0
- package/src/subexpressions.ts +10 -10
- package/src/successors.ts +79 -15
- package/src/symmetry.ts +25 -7
- package/src/tableau.ts +51 -24
- package/src/tlc-ext.ts +29 -12
- package/src/tlc-module.ts +14 -33
- package/src/tlc-modules.ts +4 -0
- package/src/tlc-order.ts +25 -7
- package/src/tlc-random.ts +9 -6
- package/src/tlc-summary.ts +20 -5
- package/src/values.ts +121 -20
package/src/parallel-worker.ts
CHANGED
|
@@ -15,7 +15,7 @@ import type {
|
|
|
15
15
|
WorkerMessage,
|
|
16
16
|
} from "./parallel";
|
|
17
17
|
import { getSuccessors, type Successor } from "./successors";
|
|
18
|
-
import { getTlcStringOrder,
|
|
18
|
+
import { getTlcStringOrder, getTlcDeclarationOrder } from "./tlc-order";
|
|
19
19
|
import { OUT_DEGREE_BUCKETS } from "./tlc-summary";
|
|
20
20
|
import { createStateDecoder, createStateEncoder, type EncodedStates } from "./transfer";
|
|
21
21
|
import { getRankedStringCount, setStringOrder, type Value } from "./values";
|
|
@@ -61,7 +61,7 @@ const run = (start: StartMessage, parent: Port) => {
|
|
|
61
61
|
});
|
|
62
62
|
const environment = specification.environment;
|
|
63
63
|
const search = createSearch(start.config, environment, () =>
|
|
64
|
-
|
|
64
|
+
getTlcDeclarationOrder(start.source, loadModule, "variable"),
|
|
65
65
|
);
|
|
66
66
|
const nextAction = search?.spec.next;
|
|
67
67
|
if (!search || nextAction === undefined)
|
|
@@ -128,7 +128,11 @@ const run = (start: StartMessage, parent: Port) => {
|
|
|
128
128
|
if (isSharedFingerprintsFull(shared.fingerprints)) return "paused";
|
|
129
129
|
const successor = successors[expansion.index];
|
|
130
130
|
if (search.findViolatedActionProperty(state, successor.state)) return undefined;
|
|
131
|
-
if (!search.satisfiesActionConstraints(state, successor.state))
|
|
131
|
+
if (!search.satisfiesActionConstraints(state, successor.state)) {
|
|
132
|
+
// TLC checks the invariants of every successor it has not seen, even outside the model.
|
|
133
|
+
if (search.findViolatedInvariant(successor.state, state)) return undefined;
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
132
136
|
if (generatedStates) {
|
|
133
137
|
writeStateFingerprint(successor.state, fingerprint);
|
|
134
138
|
if (!generatedStates.insert(fingerprint[0], fingerprint[1])) continue;
|
package/src/parallel.ts
CHANGED
|
@@ -20,7 +20,7 @@ import {
|
|
|
20
20
|
type SharedFingerprints,
|
|
21
21
|
} from "./fingerprints";
|
|
22
22
|
import { getInitialStates } from "./successors";
|
|
23
|
-
import { getTlcStringOrder,
|
|
23
|
+
import { getTlcStringOrder, getTlcDeclarationOrder } from "./tlc-order";
|
|
24
24
|
import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc-summary";
|
|
25
25
|
import { createStateEncoder, type EncodedStates } from "./transfer";
|
|
26
26
|
import { getRankedStringCount, setStringOrder, type Value } from "./values";
|
|
@@ -102,11 +102,24 @@ const spawnWorker = async (onMessage: (message: WorkerMessage) => void): Promise
|
|
|
102
102
|
|
|
103
103
|
export const check = async (options: CheckOptions): Promise<CheckResult> => {
|
|
104
104
|
const config = typeof options.config === "string" ? parseConfig(options.config) : options.config;
|
|
105
|
-
const
|
|
105
|
+
const print = options.onPrint ?? console.log;
|
|
106
|
+
const printed = { count: 0 };
|
|
107
|
+
// The search on the calling thread prints what this one printed while it started, so it skips that.
|
|
108
|
+
const fallBack = () => {
|
|
109
|
+
const skipped = { count: printed.count };
|
|
110
|
+
return checkSequentially({
|
|
111
|
+
...options,
|
|
112
|
+
config,
|
|
113
|
+
onPrint: (text) => (skipped.count-- > 0 ? undefined : print(text)),
|
|
114
|
+
});
|
|
115
|
+
};
|
|
106
116
|
const count = options.workers ?? 1;
|
|
117
|
+
// TLC's workers write the -dump state graph in whichever order they find it, so one worker
|
|
118
|
+
// writes the graph a single TLC worker does.
|
|
107
119
|
const isSequential =
|
|
108
120
|
count < 2 ||
|
|
109
121
|
typeof SharedArrayBuffer !== "function" ||
|
|
122
|
+
options.dump !== undefined ||
|
|
110
123
|
config.view !== undefined ||
|
|
111
124
|
config.postconditions.length > 0 ||
|
|
112
125
|
config.possible.length > 0;
|
|
@@ -129,12 +142,15 @@ export const check = async (options: CheckOptions): Promise<CheckResult> => {
|
|
|
129
142
|
source: options.source,
|
|
130
143
|
loadModule,
|
|
131
144
|
loadClass,
|
|
132
|
-
print:
|
|
145
|
+
print: (text) => {
|
|
146
|
+
printed.count++;
|
|
147
|
+
print(text);
|
|
148
|
+
},
|
|
133
149
|
files: { readFile: options.readFile, writeFile: options.writeFile },
|
|
134
150
|
});
|
|
135
151
|
const environment = specification.environment;
|
|
136
152
|
const search = createSearch(config, environment, () =>
|
|
137
|
-
|
|
153
|
+
getTlcDeclarationOrder(options.source, loadModule, "variable"),
|
|
138
154
|
);
|
|
139
155
|
if (findAssumptionViolation(specification.assumptions, environment)) return fallBack();
|
|
140
156
|
if (
|
package/src/parser.ts
CHANGED
|
@@ -135,6 +135,8 @@ const INFIX_OPERATORS = new Map<string, InfixOperator>([
|
|
|
135
135
|
["^^", createInfix(14, 14, false)],
|
|
136
136
|
]);
|
|
137
137
|
|
|
138
|
+
const NEGATION_PRECEDENCE = 12;
|
|
139
|
+
|
|
138
140
|
const POSTFIX_OPERATORS = new Set(["^+", "^*", "^#"]);
|
|
139
141
|
|
|
140
142
|
const PREFIX_OPERATOR_REFERENCES = new Set(["-", "~", "-."]);
|
|
@@ -977,7 +979,12 @@ const parse = (source: string, isTlapm: boolean): Module => {
|
|
|
977
979
|
return { kind: "Apply", operator: "~", args: [parseExpression(5)], location };
|
|
978
980
|
case "-":
|
|
979
981
|
advance();
|
|
980
|
-
return {
|
|
982
|
+
return {
|
|
983
|
+
kind: "Apply",
|
|
984
|
+
operator: "-.",
|
|
985
|
+
args: [parseExpression(NEGATION_PRECEDENCE + 1)],
|
|
986
|
+
location,
|
|
987
|
+
};
|
|
981
988
|
case "[]":
|
|
982
989
|
advance();
|
|
983
990
|
return { kind: "Always", expression: parseExpression(16), location };
|
|
@@ -1054,6 +1061,10 @@ const parse = (source: string, isTlapm: boolean): Module => {
|
|
|
1054
1061
|
}
|
|
1055
1062
|
}
|
|
1056
1063
|
advance();
|
|
1064
|
+
// SANY reads - after an infix operator as prefix -, and rejects it after one that binds tighter.
|
|
1065
|
+
if (infix.low > NEGATION_PRECEDENCE && isAt("-")) {
|
|
1066
|
+
throw createError(`Precedence conflict between ${token.text} and -`, peek());
|
|
1067
|
+
}
|
|
1057
1068
|
const right = parseExpression(infix.high + 1);
|
|
1058
1069
|
const left = state.left;
|
|
1059
1070
|
if (token.text === "/\\" || token.text === "\\/") {
|
package/src/resolve.ts
CHANGED
|
@@ -1,20 +1,21 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
1
|
+
import {
|
|
2
|
+
getChildren,
|
|
3
|
+
isLocallyResolved,
|
|
4
|
+
type AssumeProve,
|
|
5
|
+
type Bound,
|
|
6
|
+
type BoundPattern,
|
|
7
|
+
type Definition,
|
|
8
|
+
type Expression,
|
|
9
|
+
type Instance,
|
|
10
|
+
type Module,
|
|
11
|
+
type NewSymbol,
|
|
12
|
+
type OperatorParam,
|
|
13
|
+
type Proof,
|
|
14
|
+
type ProofStep,
|
|
15
|
+
type SourceLocation,
|
|
16
|
+
type Theorem,
|
|
15
17
|
} from "./ast";
|
|
16
18
|
import { TlaSyntaxError } from "./errors";
|
|
17
|
-
import { getChildren, isLocallyResolved } from "./evaluate";
|
|
18
19
|
|
|
19
20
|
export interface ModuleSymbol {
|
|
20
21
|
key: string;
|
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:") => {
|
|
@@ -113,6 +130,11 @@ const printTrace = (trace: TraceStep[], heading = "Error: The behavior up to thi
|
|
|
113
130
|
});
|
|
114
131
|
};
|
|
115
132
|
|
|
133
|
+
const getTemporalHeadline = (names: string[]) =>
|
|
134
|
+
names.length === 1
|
|
135
|
+
? `Error: Temporal property ${names[0]} was violated.\n`
|
|
136
|
+
: `Error: Temporal properties ${names.slice(0, -1).join(", ")}${names.length > 2 ? "," : ""} and ${names[names.length - 1]} were violated.\n`;
|
|
137
|
+
|
|
116
138
|
const printResult = (result: CheckResult) => {
|
|
117
139
|
if (result.failure) {
|
|
118
140
|
console.log(`Error: ${result.failure.message}`);
|
|
@@ -140,10 +162,10 @@ const printResult = (result: CheckResult) => {
|
|
|
140
162
|
"invariant-violation": isInitial
|
|
141
163
|
? `Error: Invariant ${name} is violated by the initial state:`
|
|
142
164
|
: `Error: Invariant ${name} is violated.`,
|
|
143
|
-
"property-violation":
|
|
165
|
+
"property-violation": getTemporalHeadline(violation.properties ?? [name]),
|
|
144
166
|
"liveness-violation":
|
|
145
167
|
loopStart !== undefined
|
|
146
|
-
?
|
|
168
|
+
? getTemporalHeadline(violation.properties ?? [name])
|
|
147
169
|
: isInitial
|
|
148
170
|
? `Error: Property ${name} is violated by the initial state:`
|
|
149
171
|
: `Error: Action property ${name} is violated.`,
|
|
@@ -152,6 +174,8 @@ const printResult = (result: CheckResult) => {
|
|
|
152
174
|
if (violation.counts) console.log(violation.counts);
|
|
153
175
|
console.log(headline);
|
|
154
176
|
if (isInitial) printState(violation.trace[0].state);
|
|
177
|
+
else if (result.status === "property-violation")
|
|
178
|
+
printTrace(violation.trace, "Error: The following behavior constitutes a counter-example:\n");
|
|
155
179
|
else if (loopStart === undefined) printTrace(violation.trace);
|
|
156
180
|
else {
|
|
157
181
|
printTrace(violation.trace, "Error: The following behavior constitutes a counter-example:\n");
|
|
@@ -191,6 +215,14 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
|
|
|
191
215
|
console.error(`Cannot find the specification file ${specPath}`);
|
|
192
216
|
return EXIT_STATUS.configParseError;
|
|
193
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
|
+
}
|
|
194
226
|
const configPath =
|
|
195
227
|
args.get("-config")?.[0] ??
|
|
196
228
|
(args.has("-config") ? undefined : specPath.replace(/\.tla$/, ".cfg"));
|
|
@@ -214,13 +246,26 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
|
|
|
214
246
|
console.error("Error: expect a strategy such as final for -lncheck option.");
|
|
215
247
|
return 1;
|
|
216
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
|
+
}
|
|
217
261
|
const directory = dirname(specPath);
|
|
218
262
|
console.log(`Checking ${basename(specPath)} with ${basename(configPath)}`);
|
|
219
263
|
const result = await check({
|
|
220
264
|
workers: getWorkerCount(args.get("-workers")),
|
|
221
265
|
livenessCheck: ["final", "seqfinal", "off"].includes(livenessCheck) ? "final" : "default",
|
|
222
266
|
seed: BigInt(seed),
|
|
223
|
-
|
|
267
|
+
dump: dumpValues && getDump(dumpValues),
|
|
268
|
+
source,
|
|
224
269
|
config,
|
|
225
270
|
onPause: () => readSync(0, Buffer.alloc(1)),
|
|
226
271
|
loadModule: (name) => {
|
package/src/runtime.ts
CHANGED
|
@@ -6,7 +6,7 @@ export interface CheckerRuntime {
|
|
|
6
6
|
getBehavior: (state: Value[]) => Value[][];
|
|
7
7
|
getSpecification: () => Value;
|
|
8
8
|
counterExample: Value | undefined;
|
|
9
|
-
setLivenessSource: (index: number) => void;
|
|
9
|
+
setLivenessSource: (index: number | undefined) => void;
|
|
10
10
|
getCurrentState: () => Value[] | undefined;
|
|
11
11
|
getFingerprint: (state: Value[]) => bigint;
|
|
12
12
|
getRandom: () => JavaRandom;
|
|
@@ -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
|
@@ -1,4 +1,10 @@
|
|
|
1
|
-
import
|
|
1
|
+
import {
|
|
2
|
+
isLocallyResolved,
|
|
3
|
+
type Definition,
|
|
4
|
+
type Expression,
|
|
5
|
+
type SourceLocation,
|
|
6
|
+
type SourceRange,
|
|
7
|
+
} from "./ast";
|
|
2
8
|
import type { ModelConfig } from "./config";
|
|
3
9
|
import type { InstanceAction } from "./environment";
|
|
4
10
|
import { TlaError } from "./errors";
|
|
@@ -10,7 +16,6 @@ import {
|
|
|
10
16
|
formatRange,
|
|
11
17
|
getDefinition,
|
|
12
18
|
isConstantLevel,
|
|
13
|
-
isLocallyResolved,
|
|
14
19
|
lookupScope,
|
|
15
20
|
resolveGlobalOperator,
|
|
16
21
|
type Closure,
|
|
@@ -464,10 +469,17 @@ export const getNextActions = (
|
|
|
464
469
|
instanceActions: Map<string, InstanceAction>,
|
|
465
470
|
) => describe(config, environment, instanceActions).actions;
|
|
466
471
|
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
}
|
|
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)}`;
|
|
471
483
|
|
|
472
484
|
export const getSpecificationValue = (
|
|
473
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/subexpressions.ts
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
import
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
1
|
+
import {
|
|
2
|
+
getChildren,
|
|
3
|
+
type Bound,
|
|
4
|
+
type Definition,
|
|
5
|
+
type Expression,
|
|
6
|
+
type Instance,
|
|
7
|
+
type Module,
|
|
8
|
+
type OperatorParam,
|
|
9
|
+
type Selector,
|
|
10
|
+
type SourceLocation,
|
|
10
11
|
} from "./ast";
|
|
11
12
|
import { TlaSyntaxError } from "./errors";
|
|
12
|
-
import { getChildren } from "./evaluate";
|
|
13
13
|
import { getSourceName, mapChildren, mapDefinition } from "./instances";
|
|
14
14
|
import { getArity, getBoundNames, getPatternNames, LOCAL_RESOLUTION } from "./resolve";
|
|
15
15
|
|