tla-ts 0.0.3-dev.e927a09 → 0.0.3-dev.e9c5857
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 +52 -22
- package/dist/index.d.ts +52 -22
- 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 +19 -17
- package/dist/run-cli.js +20 -18
- package/dist/transfer.cjs +32 -15
- package/dist/transfer.js +32 -15
- package/package.json +1 -1
- package/src/ast.ts +3 -0
- package/src/check.ts +419 -68
- package/src/cli-options.ts +11 -5
- package/src/codegen.ts +6 -3
- package/src/config.ts +224 -170
- package/src/environment.ts +106 -18
- package/src/errors.ts +71 -3
- package/src/evaluate.ts +178 -23
- package/src/exit-codes.ts +21 -14
- package/src/instances.ts +4 -4
- package/src/levels.ts +55 -27
- package/src/live-check.ts +132 -70
- package/src/liveness.ts +117 -22
- package/src/parallel-worker.ts +2 -2
- package/src/parallel.ts +5 -2
- package/src/parser.ts +21 -10
- package/src/resolve.ts +106 -29
- package/src/run-cli.ts +90 -17
- package/src/runtime.ts +2 -0
- package/src/spec-description.ts +12 -6
- package/src/standard-modules.ts +10 -9
- package/src/state-graph.ts +157 -0
- package/src/successors.ts +131 -28
- package/src/symmetry.ts +16 -6
- package/src/tableau.ts +51 -24
- package/src/tlc-ext.ts +27 -2
- package/src/tlc-module.ts +14 -33
- package/src/tlc-modules.ts +4 -0
- package/src/tlc-order.ts +8 -4
- package/src/tlc-random.ts +9 -6
- package/src/tlc-summary.ts +20 -5
- package/src/value-sources.ts +29 -0
- package/src/values.ts +172 -53
package/src/run-cli.ts
CHANGED
|
@@ -14,25 +14,29 @@ import type { CheckResult, CheckStatus, TraceStep } from "./check";
|
|
|
14
14
|
import { defineCommand, type ParsedArgs } from "./cli-options";
|
|
15
15
|
import { parseConfig } from "./config";
|
|
16
16
|
import {
|
|
17
|
+
createSanyError,
|
|
17
18
|
getErrorExitCode,
|
|
18
19
|
TlaConfigError,
|
|
19
20
|
TlaError,
|
|
20
21
|
TlaEvaluationError,
|
|
21
22
|
TlaProofError,
|
|
23
|
+
TlaSyntaxError,
|
|
24
|
+
type SanyReport,
|
|
22
25
|
} from "./errors";
|
|
23
26
|
import { EXIT_STATUS } from "./exit-codes";
|
|
24
27
|
import type { LineRange } from "./obligation-generate";
|
|
25
28
|
import { getAtPrefix, getLocusText } from "./obligation-expression";
|
|
26
29
|
import { formatSummary, getObligations, WHOLE_MODULE, type ModuleObligations } from "./obligations";
|
|
27
30
|
import { check } from "./parallel";
|
|
28
|
-
import {
|
|
31
|
+
import { parseModule } from "./parser";
|
|
32
|
+
import type { StateDump } from "./state-graph";
|
|
29
33
|
import {
|
|
30
34
|
formatProbability,
|
|
31
35
|
getActualProbability,
|
|
32
36
|
getOptimisticProbability,
|
|
33
37
|
getOutDegreeSummary,
|
|
34
38
|
} from "./tlc-summary";
|
|
35
|
-
import {
|
|
39
|
+
import { formatState, type Value } from "./values";
|
|
36
40
|
|
|
37
41
|
const EXIT_CODES: Record<CheckStatus, number> = {
|
|
38
42
|
success: EXIT_STATUS.success,
|
|
@@ -48,6 +52,11 @@ const EXIT_CODES: Record<CheckStatus, number> = {
|
|
|
48
52
|
const CHECK_COMMAND = defineCommand("tla-ts <Spec.tla|Spec.cfg|glob>... {options}", [
|
|
49
53
|
{ flag: "-config <Spec.cfg>" },
|
|
50
54
|
{ flag: "-deadlock" },
|
|
55
|
+
// Like TLC, -dump takes a format only when the next argument starts with dot and a file follows.
|
|
56
|
+
{
|
|
57
|
+
flag: "-dump [<format>] <file>",
|
|
58
|
+
getArity: (rest) => (rest.length > 1 && rest[0].startsWith("dot") ? 2 : 1),
|
|
59
|
+
},
|
|
51
60
|
{ flag: "-lncheck <final|default>" },
|
|
52
61
|
{ flag: "-seed <num>" },
|
|
53
62
|
{ flag: "-workers <count|auto>" },
|
|
@@ -95,14 +104,24 @@ const getWorkerCount = (values: string[] | undefined) => {
|
|
|
95
104
|
: Math.max(1, Number.parseInt(values[0], 10) || 1);
|
|
96
105
|
};
|
|
97
106
|
|
|
98
|
-
const printState = (state: Record<string, Value>) =>
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
)
|
|
105
|
-
|
|
107
|
+
const printState = (state: Record<string, Value>) => console.log(formatState(state));
|
|
108
|
+
|
|
109
|
+
const UNSUPPORTED_DUMP_FORMATS = ["constrained", "stuttering", "strict"];
|
|
110
|
+
|
|
111
|
+
// TLC names the file of a -dump by its format unless the name already ends that way.
|
|
112
|
+
const getDumpPath = (path: string, extension: string) =>
|
|
113
|
+
path.endsWith(extension) ? path : `${path}${extension}`;
|
|
114
|
+
|
|
115
|
+
const getDump = (values: string[]): StateDump => {
|
|
116
|
+
if (values.length === 1) return { path: getDumpPath(values[0], ".dump") };
|
|
117
|
+
const format = values[0].toLowerCase();
|
|
118
|
+
return {
|
|
119
|
+
path: getDumpPath(values[1], ".dot"),
|
|
120
|
+
dot: true,
|
|
121
|
+
colorize: format.includes("colorize"),
|
|
122
|
+
actionLabels: format.includes("actionlabels"),
|
|
123
|
+
snapshot: format.includes("snapshot"),
|
|
124
|
+
};
|
|
106
125
|
};
|
|
107
126
|
|
|
108
127
|
const printTrace = (trace: TraceStep[], heading = "Error: The behavior up to this point is:") => {
|
|
@@ -126,6 +145,22 @@ const printResult = (result: CheckResult) => {
|
|
|
126
145
|
printState(result.failure.initialState);
|
|
127
146
|
}
|
|
128
147
|
printTrace(result.failure.trace);
|
|
148
|
+
const replay = result.failure.replay;
|
|
149
|
+
replay?.output.forEach((line) => console.log(line));
|
|
150
|
+
const fingerprint = replay?.fingerprint;
|
|
151
|
+
if (replay?.callStack && fingerprint) {
|
|
152
|
+
const frames = replay.callStack.map((frame, index) => `${index}. ${frame}\n`).join("");
|
|
153
|
+
const sources = fingerprint.sources.map((source) => `${source}\n`).join("");
|
|
154
|
+
console.log(
|
|
155
|
+
`Error: TLC was unable to fingerprint.\n\nFingerprint Stack Trace:\n${frames ? `${frames}\n` : sources}\nReason:\n${fingerprint.reason}`,
|
|
156
|
+
);
|
|
157
|
+
} else if (replay?.callStack) {
|
|
158
|
+
const frames = replay.callStack.map((frame, index) => `${index}. ${frame}\n`).join("");
|
|
159
|
+
console.log(
|
|
160
|
+
`Error: The error occurred when TLC was evaluating the nested\nexpressions at the following positions:\n${frames ? `${frames}\n` : " The error call stack is empty.\n"}`,
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
if (result.failure.isWithoutStatistics) return;
|
|
129
164
|
} else if (result.violation) {
|
|
130
165
|
const violation = result.violation;
|
|
131
166
|
const name = violation.name;
|
|
@@ -198,6 +233,20 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
|
|
|
198
233
|
console.error(`Cannot find the specification file ${specPath}`);
|
|
199
234
|
return EXIT_STATUS.configParseError;
|
|
200
235
|
}
|
|
236
|
+
const source = readFileSync(specPath, "utf8");
|
|
237
|
+
const fileName = basename(specPath, ".tla");
|
|
238
|
+
const moduleName = parseModule(source).name;
|
|
239
|
+
if (moduleName !== fileName) {
|
|
240
|
+
throw createSanyError(
|
|
241
|
+
[
|
|
242
|
+
{
|
|
243
|
+
location: "Unknown location",
|
|
244
|
+
message: `File name '${fileName}' does not match the name '${moduleName}' of the top level module it contains.`,
|
|
245
|
+
},
|
|
246
|
+
],
|
|
247
|
+
true,
|
|
248
|
+
);
|
|
249
|
+
}
|
|
201
250
|
const configPath =
|
|
202
251
|
args.get("-config")?.[0] ??
|
|
203
252
|
(args.has("-config") ? undefined : specPath.replace(/\.tla$/, ".cfg"));
|
|
@@ -221,13 +270,26 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
|
|
|
221
270
|
console.error("Error: expect a strategy such as final for -lncheck option.");
|
|
222
271
|
return 1;
|
|
223
272
|
}
|
|
273
|
+
const dumpValues = args.get("-dump");
|
|
274
|
+
if (dumpValues?.length === 0) {
|
|
275
|
+
console.error("Error: A file name for dumping states required.");
|
|
276
|
+
return 1;
|
|
277
|
+
}
|
|
278
|
+
const unsupportedFormat =
|
|
279
|
+
dumpValues?.length === 2 &&
|
|
280
|
+
UNSUPPORTED_DUMP_FORMATS.find((format) => dumpValues[0].toLowerCase().includes(format));
|
|
281
|
+
if (unsupportedFormat) {
|
|
282
|
+
console.error(`Error: tla-ts does not support the -dump format ${unsupportedFormat}.`);
|
|
283
|
+
return 1;
|
|
284
|
+
}
|
|
224
285
|
const directory = dirname(specPath);
|
|
225
286
|
console.log(`Checking ${basename(specPath)} with ${basename(configPath)}`);
|
|
226
287
|
const result = await check({
|
|
227
288
|
workers: getWorkerCount(args.get("-workers")),
|
|
228
289
|
livenessCheck: ["final", "seqfinal", "off"].includes(livenessCheck) ? "final" : "default",
|
|
229
290
|
seed: BigInt(seed),
|
|
230
|
-
|
|
291
|
+
dump: dumpValues && getDump(dumpValues),
|
|
292
|
+
source,
|
|
231
293
|
config,
|
|
232
294
|
onPause: () => readSync(0, Buffer.alloc(1)),
|
|
233
295
|
loadModule: (name) => {
|
|
@@ -248,21 +310,32 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
|
|
|
248
310
|
return result.failure?.exitCode ?? EXIT_CODES[result.status];
|
|
249
311
|
};
|
|
250
312
|
|
|
251
|
-
|
|
252
|
-
|
|
313
|
+
const formatSanyErrors = (report: SanyReport) =>
|
|
314
|
+
`*** Errors: ${report.errors.length}\n\n${report.errors.map((error) => `${error.location}\n\n${error.message}\n\n`).join("\n")}`;
|
|
315
|
+
|
|
316
|
+
// TLC prints the errors it raises itself, and SANY's report of a spec it rejects. tla-ts names the
|
|
317
|
+
// others, such as a module it cannot parse.
|
|
318
|
+
const printError = (error: TlaError, path?: string) => {
|
|
253
319
|
if (error instanceof TlaConfigError || error instanceof TlaEvaluationError) {
|
|
254
320
|
return console.log(`Error: ${error.message}`);
|
|
255
321
|
}
|
|
256
|
-
|
|
322
|
+
const report = error instanceof TlaSyntaxError ? error.sany : undefined;
|
|
323
|
+
if (!report || path === undefined) return console.error(`${error.name}: ${error.message}`);
|
|
324
|
+
console.log(
|
|
325
|
+
report.isFatal
|
|
326
|
+
? `\nFatal errors while parsing TLA+ spec in file ${basename(path, ".tla")}\n\n${report.errors.map((item) => `${item.location}\n\n${item.message}\n`).join("")}${formatSanyErrors(report)}\n`
|
|
327
|
+
: `Semantic errors:\n\n${formatSanyErrors(report)}`,
|
|
328
|
+
);
|
|
329
|
+
console.log("Error: Parsing or semantic analysis failed.");
|
|
257
330
|
};
|
|
258
331
|
|
|
259
332
|
// Prints a TlaError and returns its exit code.
|
|
260
|
-
const reportErrors = async (run: () => number | Promise<number
|
|
333
|
+
const reportErrors = async (run: () => number | Promise<number>, path?: string) => {
|
|
261
334
|
try {
|
|
262
335
|
return await run();
|
|
263
336
|
} catch (error) {
|
|
264
337
|
if (!(error instanceof TlaError)) throw error;
|
|
265
|
-
printError(error);
|
|
338
|
+
printError(error, path);
|
|
266
339
|
return getErrorExitCode(error);
|
|
267
340
|
}
|
|
268
341
|
};
|
|
@@ -273,7 +346,7 @@ const runEach = async (paths: string[], runPath: (path: string) => number | Prom
|
|
|
273
346
|
const exitCodes: number[] = [];
|
|
274
347
|
for (const [index, path] of paths.entries()) {
|
|
275
348
|
if (index > 0) console.log("");
|
|
276
|
-
exitCodes.push(await reportErrors(() => runPath(path)));
|
|
349
|
+
exitCodes.push(await reportErrors(() => runPath(path), path));
|
|
277
350
|
}
|
|
278
351
|
return exitCodes.find((exitCode) => exitCode !== EXIT_STATUS.success) ?? EXIT_STATUS.success;
|
|
279
352
|
};
|
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
|
@@ -7,13 +7,12 @@ import {
|
|
|
7
7
|
} from "./ast";
|
|
8
8
|
import type { ModelConfig } from "./config";
|
|
9
9
|
import type { InstanceAction } from "./environment";
|
|
10
|
-
import { TlaError } from "./errors";
|
|
10
|
+
import { formatRange, TlaError } from "./errors";
|
|
11
11
|
import {
|
|
12
12
|
bindDefinitions,
|
|
13
13
|
bindOperatorArguments,
|
|
14
14
|
evaluate,
|
|
15
15
|
forEachBinding,
|
|
16
|
-
formatRange,
|
|
17
16
|
getDefinition,
|
|
18
17
|
isConstantLevel,
|
|
19
18
|
lookupScope,
|
|
@@ -469,10 +468,17 @@ export const getNextActions = (
|
|
|
469
468
|
instanceActions: Map<string, InstanceAction>,
|
|
470
469
|
) => describe(config, environment, instanceActions).actions;
|
|
471
470
|
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
}
|
|
471
|
+
const formatParameters = (action: SpecAction) =>
|
|
472
|
+
action.parameters.length === 0
|
|
473
|
+
? ""
|
|
474
|
+
: `(${action.parameters.map((parameter) => formatValue(parameter[1])).join(",")})`;
|
|
475
|
+
|
|
476
|
+
export const getActionLabel = (action: SpecAction) =>
|
|
477
|
+
`${action.name === UNNAMED_ACTION ? "Action" : action.name}${formatParameters(action)} ${formatRange(action.location.range ?? BUILTIN_RANGE)}`;
|
|
478
|
+
|
|
479
|
+
// TLC's Action.getInvocationSignature, which names the action and the values of its parameters.
|
|
480
|
+
export const getActionSignature = (action: SpecAction) =>
|
|
481
|
+
`${action.name}${formatParameters(action)}`;
|
|
476
482
|
|
|
477
483
|
export const getSpecificationValue = (
|
|
478
484
|
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) =>
|
|
@@ -128,7 +123,7 @@ export const CORE_OPERATORS: Builtin[] = [
|
|
|
128
123
|
),
|
|
129
124
|
defineOperator("\\subseteq", 2, (args) => {
|
|
130
125
|
const left = getSet(args, 0, "\\subseteq");
|
|
131
|
-
const right =
|
|
126
|
+
const right = getValue(args, 1, "\\subseteq");
|
|
132
127
|
const isPowerSets =
|
|
133
128
|
typeof left === "object" &&
|
|
134
129
|
left.kind === "Subset" &&
|
|
@@ -150,7 +145,13 @@ export const CORE_OPERATORS: Builtin[] = [
|
|
|
150
145
|
: operator === "\\cap"
|
|
151
146
|
? intersectSorted
|
|
152
147
|
: differenceSorted;
|
|
153
|
-
|
|
148
|
+
// Merging compares elements across the sets. Where that fails, TLC's element-by-element
|
|
149
|
+
// membership test fails or succeeds on its own.
|
|
150
|
+
try {
|
|
151
|
+
return merge(toFiniteSet(left), toFiniteSet(right));
|
|
152
|
+
} catch (error) {
|
|
153
|
+
if (!(error instanceof TlaEvaluationError)) throw error;
|
|
154
|
+
}
|
|
154
155
|
}
|
|
155
156
|
if (isReducible(left)) return combineReducible(operator, left, right);
|
|
156
157
|
if (operator !== "\\" && isReducible(right)) return combineReducible(operator, right, left);
|
|
@@ -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);
|