tla-ts 0.0.3-dev.252cf06 → 0.0.3-dev.2d84a88

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +5 -1
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +53 -22
  4. package/dist/index.d.ts +53 -22
  5. package/dist/index.js +1 -1
  6. package/dist/parallel-worker.cjs +1 -1
  7. package/dist/parallel-worker.js +2 -2
  8. package/dist/parallel.cjs +1 -1
  9. package/dist/parallel.js +2 -2
  10. package/dist/run-cli.cjs +19 -17
  11. package/dist/run-cli.js +20 -18
  12. package/dist/transfer.cjs +32 -15
  13. package/dist/transfer.js +32 -15
  14. package/package.json +1 -1
  15. package/src/ast.ts +3 -0
  16. package/src/builtins.ts +9 -3
  17. package/src/check.ts +465 -97
  18. package/src/cli-options.ts +11 -5
  19. package/src/codegen.ts +14 -19
  20. package/src/config.ts +224 -170
  21. package/src/environment.ts +111 -19
  22. package/src/errors.ts +82 -3
  23. package/src/evaluate.ts +202 -47
  24. package/src/exit-codes.ts +21 -14
  25. package/src/fingerprints.ts +2 -1
  26. package/src/instances.ts +4 -4
  27. package/src/levels.ts +55 -27
  28. package/src/live-check.ts +132 -70
  29. package/src/liveness.ts +117 -22
  30. package/src/parallel-worker.ts +2 -2
  31. package/src/parallel.ts +5 -2
  32. package/src/parser.ts +21 -10
  33. package/src/resolve.ts +106 -29
  34. package/src/run-cli.ts +103 -18
  35. package/src/runtime.ts +2 -0
  36. package/src/spec-description.ts +12 -6
  37. package/src/standard-modules.ts +52 -43
  38. package/src/state-graph.ts +157 -0
  39. package/src/successors.ts +169 -33
  40. package/src/symmetry.ts +16 -6
  41. package/src/tableau.ts +51 -24
  42. package/src/tlc-ext.ts +27 -2
  43. package/src/tlc-module.ts +14 -33
  44. package/src/tlc-modules.ts +4 -0
  45. package/src/tlc-order.ts +8 -4
  46. package/src/tlc-random.ts +9 -6
  47. package/src/tlc-summary.ts +20 -5
  48. package/src/value-sources.ts +29 -0
  49. package/src/values.ts +236 -55
package/src/run-cli.ts CHANGED
@@ -10,29 +10,33 @@ import {
10
10
  import { spawnSync } from "node:child_process";
11
11
  import { basename, delimiter, dirname, join, resolve } from "node:path";
12
12
  import { availableParallelism } from "node:os";
13
- import type { CheckResult, CheckStatus, TraceStep } from "./check";
13
+ import type { CheckResult, CheckStatus, Replay, 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 { prettyPrint } from "./pretty-print";
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 { formatValue, type Value } from "./values";
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
- const entries = Object.entries(state);
100
- entries.forEach(([name, value]) =>
101
- console.log(
102
- `${entries.length === 1 ? "" : "/\\ "}${name} = ${prettyPrint(formatValue(value))}`,
103
- ),
104
- );
105
- console.log("");
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:") => {
@@ -118,14 +137,42 @@ const getTemporalHeadline = (names: string[]) =>
118
137
  ? `Error: Temporal property ${names[0]} was violated.\n`
119
138
  : `Error: Temporal properties ${names.slice(0, -1).join(", ")}${names.length > 2 ? "," : ""} and ${names[names.length - 1]} were violated.\n`;
120
139
 
140
+ const getFrames = (callStack: string[]) =>
141
+ callStack.map((frame, index) => `${index}. ${frame}\n`).join("");
142
+
143
+ const printCallStack = (frames: string) =>
144
+ console.log(
145
+ `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"}`,
146
+ );
147
+
148
+ const printReplay = (replay: Replay) => {
149
+ replay.output.forEach((line) => console.log(line));
150
+ const frames = getFrames(replay.callStack ?? []);
151
+ const fingerprint = replay.fingerprint;
152
+ if (replay.isBeforeError) {
153
+ if (frames) printCallStack(frames);
154
+ } else if (replay.callStack && fingerprint) {
155
+ const sources = fingerprint.sources.map((source) => `${source}\n`).join("");
156
+ console.log(
157
+ `Error: TLC was unable to fingerprint.\n\nFingerprint Stack Trace:\n${frames ? `${frames}\n` : sources}\nReason:\n${fingerprint.reason}`,
158
+ );
159
+ } else if (replay.callStack) {
160
+ printCallStack(frames);
161
+ }
162
+ };
163
+
121
164
  const printResult = (result: CheckResult) => {
122
165
  if (result.failure) {
166
+ const replay = result.failure.replay;
167
+ if (replay?.isBeforeError) printReplay(replay);
123
168
  console.log(`Error: ${result.failure.message}`);
124
169
  if (result.failure.initialState) {
125
170
  console.log("While working on the initial state:");
126
171
  printState(result.failure.initialState);
127
172
  }
128
173
  printTrace(result.failure.trace);
174
+ if (replay && !replay.isBeforeError) printReplay(replay);
175
+ if (result.failure.isWithoutStatistics) return;
129
176
  } else if (result.violation) {
130
177
  const violation = result.violation;
131
178
  const name = violation.name;
@@ -198,6 +245,20 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
198
245
  console.error(`Cannot find the specification file ${specPath}`);
199
246
  return EXIT_STATUS.configParseError;
200
247
  }
248
+ const source = readFileSync(specPath, "utf8");
249
+ const fileName = basename(specPath, ".tla");
250
+ const moduleName = parseModule(source).name;
251
+ if (moduleName !== fileName) {
252
+ throw createSanyError(
253
+ [
254
+ {
255
+ location: "Unknown location",
256
+ message: `File name '${fileName}' does not match the name '${moduleName}' of the top level module it contains.`,
257
+ },
258
+ ],
259
+ true,
260
+ );
261
+ }
201
262
  const configPath =
202
263
  args.get("-config")?.[0] ??
203
264
  (args.has("-config") ? undefined : specPath.replace(/\.tla$/, ".cfg"));
@@ -221,13 +282,26 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
221
282
  console.error("Error: expect a strategy such as final for -lncheck option.");
222
283
  return 1;
223
284
  }
285
+ const dumpValues = args.get("-dump");
286
+ if (dumpValues?.length === 0) {
287
+ console.error("Error: A file name for dumping states required.");
288
+ return 1;
289
+ }
290
+ const unsupportedFormat =
291
+ dumpValues?.length === 2 &&
292
+ UNSUPPORTED_DUMP_FORMATS.find((format) => dumpValues[0].toLowerCase().includes(format));
293
+ if (unsupportedFormat) {
294
+ console.error(`Error: tla-ts does not support the -dump format ${unsupportedFormat}.`);
295
+ return 1;
296
+ }
224
297
  const directory = dirname(specPath);
225
298
  console.log(`Checking ${basename(specPath)} with ${basename(configPath)}`);
226
299
  const result = await check({
227
300
  workers: getWorkerCount(args.get("-workers")),
228
301
  livenessCheck: ["final", "seqfinal", "off"].includes(livenessCheck) ? "final" : "default",
229
302
  seed: BigInt(seed),
230
- source: readFileSync(specPath, "utf8"),
303
+ dump: dumpValues && getDump(dumpValues),
304
+ source,
231
305
  config,
232
306
  onPause: () => readSync(0, Buffer.alloc(1)),
233
307
  loadModule: (name) => {
@@ -248,21 +322,32 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
248
322
  return result.failure?.exitCode ?? EXIT_CODES[result.status];
249
323
  };
250
324
 
251
- // TLC prints the errors it raises itself. tla-ts names the others, such as a module SANY rejects.
252
- const printError = (error: TlaError) => {
325
+ const formatSanyErrors = (report: SanyReport) =>
326
+ `*** Errors: ${report.errors.length}\n\n${report.errors.map((error) => `${error.location}\n\n${error.message}\n\n`).join("\n")}`;
327
+
328
+ // TLC prints the errors it raises itself, and SANY's report of a spec it rejects. tla-ts names the
329
+ // others, such as a module it cannot parse.
330
+ const printError = (error: TlaError, path?: string) => {
253
331
  if (error instanceof TlaConfigError || error instanceof TlaEvaluationError) {
254
332
  return console.log(`Error: ${error.message}`);
255
333
  }
256
- console.error(`${error.name}: ${error.message}`);
334
+ const report = error instanceof TlaSyntaxError ? error.sany : undefined;
335
+ if (!report || path === undefined) return console.error(`${error.name}: ${error.message}`);
336
+ console.log(
337
+ report.isFatal
338
+ ? `\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`
339
+ : `Semantic errors:\n\n${formatSanyErrors(report)}`,
340
+ );
341
+ console.log("Error: Parsing or semantic analysis failed.");
257
342
  };
258
343
 
259
344
  // Prints a TlaError and returns its exit code.
260
- const reportErrors = async (run: () => number | Promise<number>) => {
345
+ const reportErrors = async (run: () => number | Promise<number>, path?: string) => {
261
346
  try {
262
347
  return await run();
263
348
  } catch (error) {
264
349
  if (!(error instanceof TlaError)) throw error;
265
- printError(error);
350
+ printError(error, path);
266
351
  return getErrorExitCode(error);
267
352
  }
268
353
  };
@@ -273,7 +358,7 @@ const runEach = async (paths: string[], runPath: (path: string) => number | Prom
273
358
  const exitCodes: number[] = [];
274
359
  for (const [index, path] of paths.entries()) {
275
360
  if (index > 0) console.log("");
276
- exitCodes.push(await reportErrors(() => runPath(path)));
361
+ exitCodes.push(await reportErrors(() => runPath(path), path));
277
362
  }
278
363
  return exitCodes.find((exitCode) => exitCode !== EXIT_STATUS.success) ?? EXIT_STATUS.success;
279
364
  };
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
  };
@@ -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
- export const getActionLabel = (action: SpecAction) => {
473
- const parameters = action.parameters.map((parameter) => formatValue(parameter[1]));
474
- return `${action.name === UNNAMED_ACTION ? "Action" : action.name}${parameters.length === 0 ? "" : `(${parameters.join(",")})`} ${formatRange(action.location.range ?? BUILTIN_RANGE)}`;
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,
@@ -11,7 +11,7 @@ import {
11
11
  getNumber,
12
12
  getOperator,
13
13
  getSet,
14
- getIntegersSignature,
14
+ getArithmeticSignature,
15
15
  getJavaInteger,
16
16
  getValue,
17
17
  isOutOfRange,
@@ -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 IntervalValue,
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 = getSet(args, 1, "\\subseteq");
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
- return merge(toFiniteSet(left), toFiniteSet(right));
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);
@@ -184,51 +185,59 @@ export const CORE_OPERATORS: Builtin[] = [
184
185
  }),
185
186
  ];
186
187
 
187
- const DOT_DOT_SIGNATURE = getIntegersSignature("DotDot", "IntervalValue", 2);
188
+ const NEG_SIGNATURE = getArithmeticSignature("Integers", "Neg", "IntValue", 1);
188
189
 
189
- const NEG_SIGNATURE = getIntegersSignature("Neg", "IntValue", 1);
190
+ // TLC overrides the operators of Naturals with the Java class of Integers when a spec loads
191
+ // Integers, which names it in their errors.
192
+ const getArithmeticOperators = (javaClass: "Naturals" | "Integers") => {
193
+ const dotDotSignature = getArithmeticSignature(javaClass, "DotDot", "IntervalValue", 2);
194
+ return [
195
+ defineArithmetic(javaClass, "+", "Plus", (left, right) => left + right),
196
+ defineArithmetic(javaClass, "-", "Minus", (left, right) => left - right),
197
+ defineArithmetic(javaClass, "*", "Times", (left, right) => left * right),
198
+ defineArithmetic(javaClass, "^", "Expt", (base, exponent) => {
199
+ if (exponent < 0) {
200
+ throw new TlaModuleError(
201
+ `The second argument of ^ should be a natural number, but instead it is:\n${exponent}`,
202
+ );
203
+ }
204
+ if (base === 0 && exponent === 0) throw new TlaModuleError("0^0 is undefined.");
205
+ return base ** exponent;
206
+ }),
207
+ defineArithmetic(javaClass, "\\div", "Divide", (left, right) => {
208
+ if (right === 0) throw new TlaModuleError("The second argument of \\div is 0.");
209
+ const quotient = Math.floor(left / right);
210
+ if (isOutOfRange(quotient)) throw createOverflowError(`${left} \\div ${right}`);
211
+ return quotient;
212
+ }),
213
+ defineArithmetic(javaClass, "%", "Mod", (left, right) => {
214
+ if (right <= 0) {
215
+ throw new TlaModuleError(
216
+ `The second argument of % should be a positive number, but instead it is:\n${right}`,
217
+ );
218
+ }
219
+ return ((left % right) + right) % right;
220
+ }),
221
+ defineOperator("..", 2, (args) => ({
222
+ kind: "Interval",
223
+ low: getJavaInteger(getValue(args, 0, ".."), dotDotSignature),
224
+ high: getJavaInteger(getValue(args, 1, ".."), dotDotSignature),
225
+ })),
226
+ ];
227
+ };
190
228
 
191
229
  const NATURALS_OPERATORS = [
192
230
  defineConstant("Nat", { kind: "InfiniteSet", name: "Nat" }),
193
- defineArithmetic("+", "Plus", (left, right) => left + right),
194
- defineArithmetic("-", "Minus", (left, right) => left - right),
195
- defineArithmetic("*", "Times", (left, right) => left * right),
196
- defineArithmetic("^", "Expt", (base, exponent) => {
197
- if (exponent < 0) {
198
- throw new TlaModuleError(
199
- `The second argument of ^ should be a natural number, but instead it is:\n${exponent}`,
200
- );
201
- }
202
- if (base === 0 && exponent === 0) throw new TlaModuleError("0^0 is undefined.");
203
- return base ** exponent;
204
- }),
205
- defineArithmetic("\\div", "Divide", (left, right) => {
206
- if (right === 0) throw new TlaModuleError("The second argument of \\div is 0.");
207
- const quotient = Math.floor(left / right);
208
- if (isOutOfRange(quotient)) throw createOverflowError(`${left} \\div ${right}`);
209
- return quotient;
210
- }),
211
- defineArithmetic("%", "Mod", (left, right) => {
212
- if (right <= 0) {
213
- throw new TlaModuleError(
214
- `The second argument of % should be a positive number, but instead it is:\n${right}`,
215
- );
216
- }
217
- return ((left % right) + right) % right;
218
- }),
231
+ ...getArithmeticOperators("Naturals"),
219
232
  defineComparison("<", (left, right) => left < right),
220
233
  defineComparison(">", (left, right) => left > right),
221
234
  defineComparison("<=", (left, right) => left <= right),
222
235
  defineComparison(">=", (left, right) => left >= right),
223
- defineOperator("..", 2, (args) => ({
224
- kind: "Interval",
225
- low: getJavaInteger(getValue(args, 0, ".."), DOT_DOT_SIGNATURE),
226
- high: getJavaInteger(getValue(args, 1, ".."), DOT_DOT_SIGNATURE),
227
- })),
228
236
  ];
229
237
 
230
238
  const INTEGERS_OPERATORS = [
231
239
  defineConstant("Int", { kind: "InfiniteSet", name: "Int" }),
240
+ ...getArithmeticOperators("Integers"),
232
241
  defineOperator("-.", 1, (args) => {
233
242
  const value = getJavaInteger(getValue(args, 0, "-"), NEG_SIGNATURE);
234
243
  if (isOutOfRange(-value)) throw createOverflowError(`-${value}`);
@@ -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);