tla-ts 0.0.3-dev.fb38eba → 0.0.3-dev.fd18eec

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/src/parser.ts CHANGED
@@ -22,7 +22,7 @@ import type {
22
22
  StepBody,
23
23
  UseOrHide,
24
24
  } from "./ast";
25
- import { TlaSyntaxError } from "./errors";
25
+ import { createSanyError, formatRange, TlaSyntaxError } from "./errors";
26
26
  import { getNumeralValue, tokenize, type Token } from "./lexer";
27
27
 
28
28
  interface InfixOperator {
@@ -631,11 +631,15 @@ const parse = (source: string, isTlapm: boolean): Module => {
631
631
  return parseExpression();
632
632
  };
633
633
 
634
+ const lastArguments: { range: SourceRange | undefined } = { range: undefined };
635
+
634
636
  const parseArguments = () =>
635
637
  withoutOffside(() => {
638
+ const start = cursor.index;
636
639
  expect("(");
637
640
  const args = parseSeparated(parseArgument);
638
641
  expect(")");
642
+ lastArguments.range = getRange(start);
639
643
  return args;
640
644
  });
641
645
 
@@ -856,7 +860,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
856
860
  const args = hasArguments ? parseArguments() : [];
857
861
  if (!isSelectorAhead()) {
858
862
  return hasArguments
859
- ? { kind: "Apply", operator: name, args, location }
863
+ ? { kind: "Apply", operator: name, args, argumentsRange: lastArguments.range, location }
860
864
  : { kind: "Identifier", name, location };
861
865
  }
862
866
  const instance = openModules
@@ -885,9 +889,10 @@ const parse = (source: string, isTlapm: boolean): Module => {
885
889
  const argumentCounts = selectors.map((selector) =>
886
890
  "args" in selector ? selector.args.length : 0,
887
891
  );
892
+ const argumentsRange = lastArguments.range;
888
893
  return argumentCounts.slice(0, -1).some((count) => count > 0)
889
- ? { kind: "Apply", operator, args: qualifiedArgs, argumentCounts, location }
890
- : { kind: "Apply", operator, args: qualifiedArgs, location };
894
+ ? { kind: "Apply", operator, args: qualifiedArgs, argumentCounts, argumentsRange, location }
895
+ : { kind: "Apply", operator, args: qualifiedArgs, argumentsRange, location };
891
896
  }
892
897
  if (token.kind === "Operator" && isOperatorName(token.text) && isAt("("))
893
898
  return { kind: "Apply", operator: token.text, args: parseArguments(), location };
@@ -1423,11 +1428,14 @@ const parse = (source: string, isTlapm: boolean): Module => {
1423
1428
  location: getLocation(keyword),
1424
1429
  };
1425
1430
  const invalid =
1426
- use.kind === "Hide" && !isTlapm ? use.facts.find((fact) => !isHideFact(fact)) : undefined;
1427
- if (invalid) {
1428
- throw createError(
1429
- "The only expression allowed as a fact in a HIDE is the name of a theorem, assumption, or step",
1430
- invalid.location,
1431
+ use.kind === "Hide" && !isTlapm ? use.facts.filter((fact) => !isHideFact(fact)) : [];
1432
+ if (invalid.length > 0) {
1433
+ throw createSanyError(
1434
+ invalid.map((fact) => ({
1435
+ location: formatRange(fact.location.range ?? getRange(start)),
1436
+ message:
1437
+ "The only expression allowed as a fact in a HIDE is \nthe name of a theorem, assumption, or step.",
1438
+ })),
1431
1439
  );
1432
1440
  }
1433
1441
  return withRange(use, start);
package/src/resolve.ts CHANGED
@@ -13,9 +13,10 @@ import {
13
13
  type Proof,
14
14
  type ProofStep,
15
15
  type SourceLocation,
16
+ type SourceRange,
16
17
  type Theorem,
17
18
  } from "./ast";
18
- import { TlaSyntaxError } from "./errors";
19
+ import { createSanyError, createSemanticError, formatRange, TlaSyntaxError } from "./errors";
19
20
 
20
21
  export interface ModuleSymbol {
21
22
  key: string;
@@ -103,6 +104,21 @@ const findSymbol = (name: string, unit: Unit): ModuleSymbol | undefined => {
103
104
  : unit.imported.get(name);
104
105
  };
105
106
 
107
+ // SANY reports a name at the range of its text.
108
+ const getNameRange = (location: SourceLocation, name: string): SourceRange => ({
109
+ module: location.range?.module ?? "",
110
+ start: location,
111
+ end: { line: location.line, column: location.column + name.length - 1 },
112
+ });
113
+
114
+ // SANY reports an operator symbol applied to operands as one it cannot resolve.
115
+ const getFixity = (expression: Expression) => {
116
+ if (expression.kind !== "Apply") return undefined;
117
+ if (expression.args.length === 2) return "infix";
118
+ if (expression.args.length !== 1) return undefined;
119
+ return isBefore(expression.location, expression.args[0].location) ? "prefix" : "postfix";
120
+ };
121
+
106
122
  // SANY names an undefined operator symbol such as + differently from an undefined identifier.
107
123
  const isOperatorSymbol = (name: string) =>
108
124
  name[0].toLowerCase() === name[0].toUpperCase() &&
@@ -144,11 +160,23 @@ const getSymbolArity = (
144
160
  if (isSelected) {
145
161
  return expression.kind === "Apply" ? expression.args.length : 0;
146
162
  }
147
- const position = `at line ${location.line}, column ${location.column}`;
148
- throw new TlaSyntaxError(
149
- isOperatorSymbol(name)
150
- ? `Could not find declaration or definition of symbol '${name}' ${position}`
151
- : `Unknown operator: \`${name}' ${position}`,
163
+ const range = getNameRange(location, name === "-." ? "-" : name);
164
+ if (!isOperatorSymbol(name)) throw createSemanticError(`Unknown operator: \`${name}'.`, range);
165
+ const missing = {
166
+ location: formatRange(range),
167
+ message: `Could not find declaration or definition of symbol '${name}'.`,
168
+ };
169
+ const fixity = getFixity(expression);
170
+ throw createSanyError(
171
+ fixity && location.range
172
+ ? [
173
+ missing,
174
+ {
175
+ location: formatRange(location.range),
176
+ message: `Couldn't resolve ${fixity} operator symbol \`${name}'.`,
177
+ },
178
+ ]
179
+ : [missing],
152
180
  );
153
181
  };
154
182
 
@@ -235,13 +263,13 @@ const resolveApply = (
235
263
  scope: LocalName | undefined,
236
264
  unit: Unit,
237
265
  ) => {
238
- const callee = lookupLocal(scope, expression.operator)
239
- ? undefined
240
- : getVisibleDefinition(expression.operator, unit);
241
- const arity = getSymbolArity(expression, expression.operator, scope, unit);
266
+ const operator = expression.operator;
267
+ const callee = lookupLocal(scope, operator) ? undefined : getVisibleDefinition(operator, unit);
268
+ const arity = getSymbolArity(expression, operator, scope, unit);
242
269
  if (arity !== expression.args.length) {
243
- throw new TlaSyntaxError(
244
- `The operator ${expression.operator} requires ${arity} arguments at line ${expression.location.line}, column ${expression.location.column}`,
270
+ throw createSemanticError(
271
+ `The operator ${operator} requires ${arity} arguments.`,
272
+ expression.argumentsRange ?? getNameRange(expression.location, operator),
245
273
  );
246
274
  }
247
275
  expression.args.forEach((arg, index) => {
@@ -275,10 +303,12 @@ const resolveExpression = (
275
303
  case "ExceptAt":
276
304
  return;
277
305
  case "Identifier": {
278
- const arity = getSymbolArity(expression, expression.name, scope, unit);
306
+ const name = expression.name;
307
+ const arity = getSymbolArity(expression, name, scope, unit);
279
308
  if (arity > 0) {
280
- throw new TlaSyntaxError(
281
- `The operator ${expression.name} requires ${arity} arguments at line ${expression.location.line}, column ${expression.location.column}`,
309
+ throw createSemanticError(
310
+ `The operator ${name} requires ${arity} arguments.`,
311
+ getNameRange(expression.location, name),
282
312
  );
283
313
  }
284
314
  return;
package/src/run-cli.ts CHANGED
@@ -14,12 +14,14 @@ 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,
22
23
  TlaSyntaxError,
24
+ type SanyReport,
23
25
  } from "./errors";
24
26
  import { EXIT_STATUS } from "./exit-codes";
25
27
  import type { LineRange } from "./obligation-generate";
@@ -27,14 +29,14 @@ import { getAtPrefix, getLocusText } from "./obligation-expression";
27
29
  import { formatSummary, getObligations, WHOLE_MODULE, type ModuleObligations } from "./obligations";
28
30
  import { check } from "./parallel";
29
31
  import { parseModule } from "./parser";
30
- import { prettyPrint } from "./pretty-print";
32
+ import type { StateDump } from "./state-graph";
31
33
  import {
32
34
  formatProbability,
33
35
  getActualProbability,
34
36
  getOptimisticProbability,
35
37
  getOutDegreeSummary,
36
38
  } from "./tlc-summary";
37
- import { formatValue, type Value } from "./values";
39
+ import { formatState, type Value } from "./values";
38
40
 
39
41
  const EXIT_CODES: Record<CheckStatus, number> = {
40
42
  success: EXIT_STATUS.success,
@@ -50,6 +52,11 @@ const EXIT_CODES: Record<CheckStatus, number> = {
50
52
  const CHECK_COMMAND = defineCommand("tla-ts <Spec.tla|Spec.cfg|glob>... {options}", [
51
53
  { flag: "-config <Spec.cfg>" },
52
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
+ },
53
60
  { flag: "-lncheck <final|default>" },
54
61
  { flag: "-seed <num>" },
55
62
  { flag: "-workers <count|auto>" },
@@ -97,14 +104,24 @@ const getWorkerCount = (values: string[] | undefined) => {
97
104
  : Math.max(1, Number.parseInt(values[0], 10) || 1);
98
105
  };
99
106
 
100
- const printState = (state: Record<string, Value>) => {
101
- const entries = Object.entries(state);
102
- entries.forEach(([name, value]) =>
103
- console.log(
104
- `${entries.length === 1 ? "" : "/\\ "}${name} = ${prettyPrint(formatValue(value))}`,
105
- ),
106
- );
107
- 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
+ };
108
125
  };
109
126
 
110
127
  const printTrace = (trace: TraceStep[], heading = "Error: The behavior up to this point is:") => {
@@ -204,8 +221,14 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
204
221
  const fileName = basename(specPath, ".tla");
205
222
  const moduleName = parseModule(source).name;
206
223
  if (moduleName !== fileName) {
207
- throw new TlaSyntaxError(
208
- `File name '${fileName}' does not match the name '${moduleName}' of the top level module it contains.`,
224
+ throw createSanyError(
225
+ [
226
+ {
227
+ location: "Unknown location",
228
+ message: `File name '${fileName}' does not match the name '${moduleName}' of the top level module it contains.`,
229
+ },
230
+ ],
231
+ true,
209
232
  );
210
233
  }
211
234
  const configPath =
@@ -231,12 +254,25 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
231
254
  console.error("Error: expect a strategy such as final for -lncheck option.");
232
255
  return 1;
233
256
  }
257
+ const dumpValues = args.get("-dump");
258
+ if (dumpValues?.length === 0) {
259
+ console.error("Error: A file name for dumping states required.");
260
+ return 1;
261
+ }
262
+ const unsupportedFormat =
263
+ dumpValues?.length === 2 &&
264
+ UNSUPPORTED_DUMP_FORMATS.find((format) => dumpValues[0].toLowerCase().includes(format));
265
+ if (unsupportedFormat) {
266
+ console.error(`Error: tla-ts does not support the -dump format ${unsupportedFormat}.`);
267
+ return 1;
268
+ }
234
269
  const directory = dirname(specPath);
235
270
  console.log(`Checking ${basename(specPath)} with ${basename(configPath)}`);
236
271
  const result = await check({
237
272
  workers: getWorkerCount(args.get("-workers")),
238
273
  livenessCheck: ["final", "seqfinal", "off"].includes(livenessCheck) ? "final" : "default",
239
274
  seed: BigInt(seed),
275
+ dump: dumpValues && getDump(dumpValues),
240
276
  source,
241
277
  config,
242
278
  onPause: () => readSync(0, Buffer.alloc(1)),
@@ -258,21 +294,32 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
258
294
  return result.failure?.exitCode ?? EXIT_CODES[result.status];
259
295
  };
260
296
 
261
- // TLC prints the errors it raises itself. tla-ts names the others, such as a module SANY rejects.
262
- const printError = (error: TlaError) => {
297
+ const formatSanyErrors = (report: SanyReport) =>
298
+ `*** Errors: ${report.errors.length}\n\n${report.errors.map((error) => `${error.location}\n\n${error.message}\n\n`).join("\n")}`;
299
+
300
+ // TLC prints the errors it raises itself, and SANY's report of a spec it rejects. tla-ts names the
301
+ // others, such as a module it cannot parse.
302
+ const printError = (error: TlaError, path?: string) => {
263
303
  if (error instanceof TlaConfigError || error instanceof TlaEvaluationError) {
264
304
  return console.log(`Error: ${error.message}`);
265
305
  }
266
- console.error(`${error.name}: ${error.message}`);
306
+ const report = error instanceof TlaSyntaxError ? error.sany : undefined;
307
+ if (!report || path === undefined) return console.error(`${error.name}: ${error.message}`);
308
+ console.log(
309
+ report.isFatal
310
+ ? `\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`
311
+ : `Semantic errors:\n\n${formatSanyErrors(report)}`,
312
+ );
313
+ console.log("Error: Parsing or semantic analysis failed.");
267
314
  };
268
315
 
269
316
  // Prints a TlaError and returns its exit code.
270
- const reportErrors = async (run: () => number | Promise<number>) => {
317
+ const reportErrors = async (run: () => number | Promise<number>, path?: string) => {
271
318
  try {
272
319
  return await run();
273
320
  } catch (error) {
274
321
  if (!(error instanceof TlaError)) throw error;
275
- printError(error);
322
+ printError(error, path);
276
323
  return getErrorExitCode(error);
277
324
  }
278
325
  };
@@ -283,7 +330,7 @@ const runEach = async (paths: string[], runPath: (path: string) => number | Prom
283
330
  const exitCodes: number[] = [];
284
331
  for (const [index, path] of paths.entries()) {
285
332
  if (index > 0) console.log("");
286
- exitCodes.push(await reportErrors(() => runPath(path)));
333
+ exitCodes.push(await reportErrors(() => runPath(path), path));
287
334
  }
288
335
  return exitCodes.find((exitCode) => exitCode !== EXIT_STATUS.success) ?? EXIT_STATUS.success;
289
336
  };
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,
@@ -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) =>
@@ -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);