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

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/run-cli.ts CHANGED
@@ -27,14 +27,14 @@ import { getAtPrefix, getLocusText } from "./obligation-expression";
27
27
  import { formatSummary, getObligations, WHOLE_MODULE, type ModuleObligations } from "./obligations";
28
28
  import { check } from "./parallel";
29
29
  import { parseModule } from "./parser";
30
- import { prettyPrint } from "./pretty-print";
30
+ import type { StateDump } from "./state-graph";
31
31
  import {
32
32
  formatProbability,
33
33
  getActualProbability,
34
34
  getOptimisticProbability,
35
35
  getOutDegreeSummary,
36
36
  } from "./tlc-summary";
37
- import { formatValue, type Value } from "./values";
37
+ import { formatState, type Value } from "./values";
38
38
 
39
39
  const EXIT_CODES: Record<CheckStatus, number> = {
40
40
  success: EXIT_STATUS.success,
@@ -50,6 +50,11 @@ const EXIT_CODES: Record<CheckStatus, number> = {
50
50
  const CHECK_COMMAND = defineCommand("tla-ts <Spec.tla|Spec.cfg|glob>... {options}", [
51
51
  { flag: "-config <Spec.cfg>" },
52
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
+ },
53
58
  { flag: "-lncheck <final|default>" },
54
59
  { flag: "-seed <num>" },
55
60
  { flag: "-workers <count|auto>" },
@@ -97,14 +102,24 @@ const getWorkerCount = (values: string[] | undefined) => {
97
102
  : Math.max(1, Number.parseInt(values[0], 10) || 1);
98
103
  };
99
104
 
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("");
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
+ };
108
123
  };
109
124
 
110
125
  const printTrace = (trace: TraceStep[], heading = "Error: The behavior up to this point is:") => {
@@ -231,12 +246,25 @@ const checkSpec = async (specPath: string, args: ParsedArgs) => {
231
246
  console.error("Error: expect a strategy such as final for -lncheck option.");
232
247
  return 1;
233
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
+ }
234
261
  const directory = dirname(specPath);
235
262
  console.log(`Checking ${basename(specPath)} with ${basename(configPath)}`);
236
263
  const result = await check({
237
264
  workers: getWorkerCount(args.get("-workers")),
238
265
  livenessCheck: ["final", "seqfinal", "off"].includes(livenessCheck) ? "final" : "default",
239
266
  seed: BigInt(seed),
267
+ dump: dumpValues && getDump(dumpValues),
240
268
  source,
241
269
  config,
242
270
  onPause: () => readSync(0, Buffer.alloc(1)),
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
  };
@@ -469,10 +469,17 @@ export const getNextActions = (
469
469
  instanceActions: Map<string, InstanceAction>,
470
470
  ) => describe(config, environment, instanceActions).actions;
471
471
 
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
- };
472
+ const formatParameters = (action: SpecAction) =>
473
+ action.parameters.length === 0
474
+ ? ""
475
+ : `(${action.parameters.map((parameter) => formatValue(parameter[1])).join(",")})`;
476
+
477
+ export const getActionLabel = (action: SpecAction) =>
478
+ `${action.name === UNNAMED_ACTION ? "Action" : action.name}${formatParameters(action)} ${formatRange(action.location.range ?? BUILTIN_RANGE)}`;
479
+
480
+ // TLC's Action.getInvocationSignature, which names the action and the values of its parameters.
481
+ export const getActionSignature = (action: SpecAction) =>
482
+ `${action.name}${formatParameters(action)}`;
476
483
 
477
484
  export const getSpecificationValue = (
478
485
  config: ModelConfig,
@@ -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);
package/src/successors.ts CHANGED
@@ -4,9 +4,10 @@ import {
4
4
  type Bound,
5
5
  type Definition,
6
6
  type Expression,
7
+ type QuantifierExpression,
7
8
  } from "./ast";
8
9
  import { getReadVariables } from "./dependencies";
9
- import { TlaEvaluationError, UNEXPECTED_EXCEPTION } from "./errors";
10
+ import { TlaEvaluationError, TlaIncompleteStateError } from "./errors";
10
11
  import { EXIT_STATUS, setExitCode } from "./exit-codes";
11
12
  import {
12
13
  describeLocation,
@@ -17,6 +18,7 @@ import {
17
18
  bindValue,
18
19
  compileArgumentScope,
19
20
  evaluate,
21
+ getEntryEvaluator,
20
22
  expectBoolean,
21
23
  forEachBinding,
22
24
  getBoundsDomain,
@@ -28,6 +30,7 @@ import {
28
30
  resolveGlobalOperator,
29
31
  type Context,
30
32
  type Environment,
33
+ type Evaluator,
31
34
  type Scope,
32
35
  type State,
33
36
  } from "./evaluate";
@@ -86,15 +89,25 @@ const assign = (partial: State, index: number, value: Value) => {
86
89
  return copy;
87
90
  };
88
91
 
89
- const holds = (expression: Expression, context: Context) => {
90
- const value = evaluate(expression, context);
92
+ // TLC's Tool.getInitStates and Tool.getNextStates report a value where they expect a formula.
93
+ const expectFormula = (expression: Expression, value: Value, isInit: boolean) => {
91
94
  if (typeof value === "boolean") return value;
92
- try {
93
- return expectBoolean(value, `the action at ${describeLocation(expression)}`);
94
- } catch (error) {
95
- // TLC fails with an unexpected exception when the next-state relation isn't a boolean.
96
- throw context.next === undefined ? error : setExitCode(error, EXIT_STATUS.error);
95
+ throw new TlaEvaluationError(
96
+ `In computing ${isInit ? "initial" : "next"} states, TLC expected a boolean expression,\nbut instead found ${formatValue(value)}.\n${describeRange(expression)}`,
97
+ );
98
+ };
99
+
100
+ const holds = (expression: Expression, context: Context, value = evaluate(expression, context)) => {
101
+ // TLC rejects a number in the next-state relation when it splits the relation into actions.
102
+ if (context.next !== undefined && expression.kind === "Number") {
103
+ throw setExitCode(
104
+ new TlaEvaluationError(
105
+ `The next state relation is not a boolean expression.\n${expression.text ?? expression.value}`,
106
+ ),
107
+ EXIT_STATUS.error,
108
+ );
97
109
  }
110
+ return expectFormula(expression, value, context.next === undefined);
98
111
  };
99
112
 
100
113
  const isAssignmentOperator = (operator: string) =>
@@ -292,12 +305,34 @@ const toConjunct = (
292
305
  return { kind: "Branch", expression, runner: getRunner(expression, environment, isInit) };
293
306
  };
294
307
 
308
+ // The leading guards of `\E x \in S, y \in T : P /\ Q` that read no inner bound hold for every inner
309
+ // binding alike, so they can run once for each element of the outermost bound.
310
+ const getHoistedGuards = (expression: QuantifierExpression, environment: Environment) => {
311
+ if (expression.bounds.length < 2 || expression.body.kind !== "And") return undefined;
312
+ const names = expression.bounds.flatMap((bound) =>
313
+ bound.pattern.kind === "Name" ? [bound.pattern.name] : [],
314
+ );
315
+ if (names.length !== expression.bounds.length) return undefined;
316
+ const innerNames = new Set(names.slice(0, -1));
317
+ const operands = expression.body.operands;
318
+ const index = operands.findIndex((operand) => {
319
+ if (getReadVariables(operand, environment) === undefined) return true;
320
+ if (hasBranches(operand, environment, new Set())) return true;
321
+ const readLocals = getReadLocals(operand, NO_NAMES);
322
+ return !readLocals || readLocals.some((name) => innerNames.has(name));
323
+ });
324
+ const count = index === -1 ? operands.length : index;
325
+ if (count === 0) return undefined;
326
+ return { names, guards: operands.slice(0, count), rest: operands.slice(count) };
327
+ };
328
+
295
329
  const compileConjunction = (
296
330
  operands: Expression[],
297
331
  environment: Environment,
298
332
  isInit: boolean,
299
333
  ): Runner => {
300
334
  const conjuncts = operands.map((operand) => toConjunct(operand, environment, isInit));
335
+ const evaluators: (Evaluator | undefined)[] = conjuncts.map(() => undefined);
301
336
  const runFrom = (
302
337
  start: number,
303
338
  run: Run,
@@ -320,12 +355,17 @@ const compileConjunction = (
320
355
  const conjunct = conjuncts[index];
321
356
  if (conjunct.kind === "Guard") {
322
357
  context ??= getContext(run, scope, current);
323
- if (!holds(conjunct.expression, context)) return;
358
+ const evaluator = (evaluators[index] ??= getEntryEvaluator(
359
+ conjunct.expression,
360
+ environment,
361
+ ));
362
+ if (!holds(conjunct.expression, context, evaluator(context))) return;
324
363
  continue;
325
364
  }
326
365
  if (conjunct.kind === "Assign") {
327
366
  context ??= getContext(run, scope, current);
328
- const value = evaluate(conjunct.value, context);
367
+ const evaluator = (evaluators[index] ??= getEntryEvaluator(conjunct.value, environment));
368
+ const value = evaluator(context);
329
369
  const assigned = current[conjunct.index];
330
370
  if (assigned === undefined) {
331
371
  current = assign(current, conjunct.index, value);
@@ -362,10 +402,7 @@ const compileConjunction = (
362
402
  };
363
403
 
364
404
  const holdsInInit = (expression: Expression, context: Context) =>
365
- expectBoolean(
366
- evaluate(expression, context),
367
- `the initial predicate at ${describeLocation(expression)}`,
368
- );
405
+ expectFormula(expression, evaluate(expression, context), true);
369
406
 
370
407
  const compileGuard =
371
408
  (expression: Expression): Runner =>
@@ -390,7 +427,7 @@ const compileMembership = (
390
427
  expression.operator === "\\subseteq" ? { kind: "Subset", base: evaluated } : evaluated;
391
428
  if (!isEnumerable(value)) {
392
429
  throw new TlaEvaluationError(
393
- `In computing next states, the right side of \\in is not enumerable: ${formatValue(value)} at ${describeLocation(expression)}`,
430
+ `In computing ${run.isInit ? "initial" : "next"} states, the right side of \\IN is not enumerable.\n${describeRange(expression)}`,
394
431
  );
395
432
  }
396
433
  const elements = getStreamedElements(value);
@@ -734,6 +771,33 @@ const compileAction = (
734
771
  }
735
772
  };
736
773
  }
774
+ const hoisted = isInit ? undefined : getHoistedGuards(expression, environment);
775
+ if (hoisted) {
776
+ const rest = compileConjunction(hoisted.rest, environment, isInit);
777
+ return (run, scope, partial, action, isFixed, onComplete) => {
778
+ const context = getContext(run, scope, partial);
779
+ const sets = expression.bounds.map((innerBound) =>
780
+ getEnumeratedElements(evaluate(innerBound.set, context), innerBound.set),
781
+ );
782
+ if (sets.some((elements) => elements.length === 0)) return;
783
+ const visit = (index: number, boundScope: Scope | undefined): void => {
784
+ if (index < 0) {
785
+ rest(run, boundScope, partial, action, isFixed, onComplete);
786
+ return;
787
+ }
788
+ for (const element of sets[index]) {
789
+ if (run.isStopped) return;
790
+ const elementScope = bindValue(boundScope, hoisted.names[index], element);
791
+ if (index === sets.length - 1) {
792
+ const guardContext = getContext(run, elementScope, partial);
793
+ if (!hoisted.guards.every((guard) => holds(guard, guardContext))) continue;
794
+ }
795
+ visit(index - 1, elementScope);
796
+ }
797
+ };
798
+ visit(sets.length - 1, scope);
799
+ };
800
+ }
737
801
  return (run, scope, partial, action, isFixed, onComplete) => {
738
802
  forEachBinding(expression.bounds, getContext(run, scope, partial), (boundScope) => {
739
803
  body(run, boundScope, partial, action, isFixed, onComplete);
@@ -810,7 +874,7 @@ const compileAction = (
810
874
  const body = arm?.body ?? other;
811
875
  if (!body)
812
876
  throw new TlaEvaluationError(
813
- `${UNEXPECTED_EXCEPTION}In computing next states, TLC encountered a CASE with no conditions true.\n${describeRange(expression)}`,
877
+ `In computing ${run.isInit ? "initial" : "next"} states, TLC encountered a CASE with no conditions true.\n${describeRange(expression)}`,
814
878
  );
815
879
  body(run, scope, partial, action, isFixed, onComplete);
816
880
  };
@@ -1001,8 +1065,10 @@ export const forEachSuccessor = (
1001
1065
  (partial, action) => {
1002
1066
  if (run.isStopped) return;
1003
1067
  if (!isComplete(partial)) {
1004
- throw new TlaEvaluationError(
1005
- `Successor state is not completely specified by action ${action ?? "Next"}. The following variables are not assigned: ${getMissingVariables(partial, environment).join(", ")}`,
1068
+ throw new TlaIncompleteStateError(
1069
+ partial,
1070
+ action,
1071
+ getMissingVariables(partial, environment).sort(),
1006
1072
  );
1007
1073
  }
1008
1074
  counter.successors++;
package/src/symmetry.ts CHANGED
@@ -1,5 +1,6 @@
1
- import { TlaConfigError } from "./errors";
1
+ import { TlaConfigError, TlaEvaluationError, UNEXPECTED_EXCEPTION } from "./errors";
2
2
  import { evaluate, type Environment } from "./evaluate";
3
+ import { EXIT_STATUS, setExitCode } from "./exit-codes";
3
4
  import {
4
5
  compareValues,
5
6
  createFunction,
@@ -47,9 +48,13 @@ const composePermutations = (first: Images, second: Images) => {
47
48
  return composed;
48
49
  };
49
50
 
50
- const toImages = (value: Value, name: string) => {
51
+ // TLC checks the symmetry set outside any phase that reports an error itself.
52
+ const createSymmetryError = (message: string) =>
53
+ setExitCode(new TlaEvaluationError(`${UNEXPECTED_EXCEPTION}${message}`), EXIT_STATUS.error);
54
+
55
+ const toImages = (value: Value) => {
51
56
  if (!isFunctionValue(value)) {
52
- throw new TlaConfigError(`The symmetry values of ${name} must be functions`);
57
+ throw createSymmetryError("The symmetry values must be function records.");
53
58
  }
54
59
  const functionValue = toFiniteFunction(value);
55
60
  const permutation: Images = new Map();
@@ -65,8 +70,13 @@ const toImages = (value: Value, name: string) => {
65
70
 
66
71
  export const getSymmetryGroup = (name: string, environment: Environment): Permutation[] => {
67
72
  const definition = environment.definitions.get(name);
73
+ if (definition === undefined && !environment.constants.has(name)) {
74
+ throw new TlaConfigError(
75
+ `The symmetry function ${name} specified in the configuration file\nis not defined in the specification.`,
76
+ );
77
+ }
68
78
  if (definition?.kind !== "Operator" || definition.params.length > 0) {
69
- throw new TlaConfigError(`The symmetry function ${name} must specify a set of permutations`);
79
+ throw createSymmetryError(`The symmetry function ${name} must specify a set of permutations.`);
70
80
  }
71
81
  const value = evaluate(definition.body, {
72
82
  environment,
@@ -75,9 +85,9 @@ export const getSymmetryGroup = (name: string, environment: Environment): Permut
75
85
  next: undefined,
76
86
  });
77
87
  if (!isSetValue(value) || !isEnumerable(value)) {
78
- throw new TlaConfigError("The symmetry operator must specify a set of functions");
88
+ throw createSymmetryError("The symmetry operator must specify a set of functions.");
79
89
  }
80
- const permutations = toFiniteSet(value).elements.map((element) => toImages(element, name));
90
+ const permutations = toFiniteSet(value).elements.map(toImages);
81
91
  const isDisabled =
82
92
  definition.body.kind === "Apply" && definition.body.args.length >= permutations.length;
83
93
  if (isDisabled) return [];
package/src/tableau.ts CHANGED
@@ -162,22 +162,39 @@ const containsAction = (expression: LiveExpression): boolean => {
162
162
  }
163
163
  };
164
164
 
165
- const isEqual = (left: LiveExpression, right: LiveExpression): boolean => {
166
- if (left.kind !== right.kind) return false;
167
- if (left.kind === "Boolean" && right.kind === "Boolean") return left.value === right.value;
168
- if (isAtom(left)) return left === right;
169
- if ("body" in left && "body" in right) return isEqual(left.body, right.body);
170
- if ("operands" in left && "operands" in right) {
171
- return (
172
- left.operands.length === right.operands.length &&
173
- left.operands.every((operand, index) => isEqual(operand, right.operands[index]))
174
- );
175
- }
176
- return false;
165
+ const termKeys = new WeakMap<LiveExpression, string>();
166
+ const atoms = { count: 0 };
167
+
168
+ // A term's structure as a string in which each atom stands for itself, so equal terms share a key.
169
+ export const getTermKey = (expression: LiveExpression): string => {
170
+ const cached = termKeys.get(expression);
171
+ if (cached !== undefined) return cached;
172
+ const key = (() => {
173
+ switch (expression.kind) {
174
+ case "Boolean":
175
+ return String(expression.value);
176
+ case "State":
177
+ case "Enabled":
178
+ case "Action":
179
+ return `#${atoms.count++}`;
180
+ case "And":
181
+ case "Or":
182
+ return `${expression.kind}(${expression.operands.map(getTermKey).join(",")})`;
183
+ default:
184
+ return `${expression.kind}(${getTermKey(expression.body)})`;
185
+ }
186
+ })();
187
+ termKeys.set(expression, key);
188
+ return key;
177
189
  };
178
190
 
179
- const isMember = (items: LiveExpression[], expression: LiveExpression) =>
180
- items.some((item) => isEqual(item, expression));
191
+ const isEqual = (left: LiveExpression, right: LiveExpression) =>
192
+ left === right || getTermKey(left) === getTermKey(right);
193
+
194
+ const isMember = (items: LiveExpression[], expression: LiveExpression) => {
195
+ const key = getTermKey(expression);
196
+ return items.some((item) => item === expression || getTermKey(item) === key);
197
+ };
181
198
 
182
199
  const getDual = (kind: LiveJunction["kind"]) => (kind === "And" ? "Or" : "And");
183
200
 
@@ -272,7 +289,7 @@ const toDisjunctiveNormalForm = (expression: LiveExpression): LiveExpression =>
272
289
  total.value *= normal.operands.length;
273
290
  if (total.value > MAXIMUM_DISJUNCTS) {
274
291
  throw new TlaEvaluationError(
275
- "TLC cannot handle the temporal formula because it exceeds the maximum supported size in disjunctive normal form",
292
+ "TLC cannot handle the temporal formula because it exceeds the maximum supported size in disjunctive normal form.",
276
293
  );
277
294
  }
278
295
  }
@@ -446,13 +463,14 @@ const getTriples = (
446
463
  return parts ? [{ whole: term, first: parts.first, second: parts.second }] : [];
447
464
  });
448
465
 
449
- const isSameParticle = (left: LiveExpression[], right: LiveExpression[]) =>
450
- left.every((term) => isMember(right, term)) && right.every((term) => isMember(left, term));
466
+ // A particle is a set of terms, so its key ignores order and repeats.
467
+ const getParticleKey = (particle: LiveExpression[]) =>
468
+ [...new Set(particle.map(getTermKey))].sort().join("|");
451
469
 
452
- const unionParticles = (left: LiveExpression[][], right: LiveExpression[][]) => [
453
- ...left.filter((particle) => !right.some((other) => isSameParticle(particle, other))),
454
- ...right,
455
- ];
470
+ const unionParticles = (left: LiveExpression[][], right: LiveExpression[][]) => {
471
+ const rightKeys = new Set(right.map(getParticleKey));
472
+ return [...left.filter((particle) => !rightKeys.has(getParticleKey(particle))), ...right];
473
+ };
456
474
 
457
475
  const getParticleClosure = (terms: LiveExpression[]) => {
458
476
  const closure = getPositiveClosure(terms);
@@ -516,14 +534,23 @@ const createTableauNode = (particle: LiveExpression[]): TableauNode => ({
516
534
  const createTableau = (formula: LiveExpression) => {
517
535
  const nodes = getParticleClosure([formula]).map(createTableauNode);
518
536
  const initialCount = nodes.length;
537
+ const indices = new Map<string, number>();
538
+ nodes.forEach((node, index) => {
539
+ const key = getParticleKey(node.particle);
540
+ if (!indices.has(key)) indices.set(key, index);
541
+ });
519
542
  for (let index = 0; index < nodes.length; index++) {
520
543
  const implied = nodes[index].particle.flatMap((term) =>
521
544
  term.kind === "Next" ? [term.body] : [],
522
545
  );
523
546
  for (const particle of getParticleClosure(implied)) {
524
- const existing = nodes.findIndex((node) => isSameParticle(node.particle, particle));
525
- if (existing === -1) nodes.push(createTableauNode(particle));
526
- nodes[index].successors.push(existing === -1 ? nodes.length - 1 : existing);
547
+ const key = getParticleKey(particle);
548
+ const existing = indices.get(key);
549
+ if (existing === undefined) {
550
+ indices.set(key, nodes.length);
551
+ nodes.push(createTableauNode(particle));
552
+ }
553
+ nodes[index].successors.push(existing ?? nodes.length - 1);
527
554
  }
528
555
  }
529
556
  return { nodes, initialCount };