tla-ts 0.0.3-dev.3cf2ad0 → 0.0.3-dev.3ff2308

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 (51) hide show
  1. package/README.md +16 -2
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +54 -22
  4. package/dist/index.d.ts +54 -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 -16
  11. package/dist/run-cli.js +20 -17
  12. package/dist/transfer.cjs +37 -16
  13. package/dist/transfer.js +37 -16
  14. package/package.json +1 -1
  15. package/src/ast.ts +93 -0
  16. package/src/builtins.ts +9 -3
  17. package/src/check.ts +511 -99
  18. package/src/cli-options.ts +11 -5
  19. package/src/codegen.ts +15 -22
  20. package/src/config.ts +224 -170
  21. package/src/dependencies.ts +2 -2
  22. package/src/environment.ts +121 -29
  23. package/src/errors.ts +87 -3
  24. package/src/evaluate.ts +255 -159
  25. package/src/exit-codes.ts +39 -42
  26. package/src/instances.ts +16 -15
  27. package/src/levels.ts +62 -34
  28. package/src/lexer.ts +5 -1
  29. package/src/live-check.ts +772 -0
  30. package/src/liveness.ts +120 -543
  31. package/src/parallel-worker.ts +7 -3
  32. package/src/parallel.ts +20 -4
  33. package/src/parser.ts +33 -11
  34. package/src/resolve.ts +122 -44
  35. package/src/run-cli.ts +112 -20
  36. package/src/runtime.ts +3 -1
  37. package/src/spec-description.ts +19 -8
  38. package/src/standard-modules.ts +52 -43
  39. package/src/state-graph.ts +157 -0
  40. package/src/subexpressions.ts +10 -10
  41. package/src/successors.ts +183 -39
  42. package/src/symmetry.ts +25 -7
  43. package/src/tableau.ts +51 -24
  44. package/src/tlc-ext.ts +29 -12
  45. package/src/tlc-module.ts +14 -33
  46. package/src/tlc-modules.ts +4 -0
  47. package/src/tlc-order.ts +25 -7
  48. package/src/tlc-random.ts +9 -6
  49. package/src/tlc-summary.ts +20 -5
  50. package/src/value-sources.ts +29 -0
  51. package/src/values.ts +207 -53
package/src/successors.ts CHANGED
@@ -1,28 +1,41 @@
1
- import type { Bound, Definition, Expression } from "./ast";
1
+ import {
2
+ getChildren,
3
+ isLocallyResolved,
4
+ type Bound,
5
+ type Definition,
6
+ type Expression,
7
+ type QuantifierExpression,
8
+ } from "./ast";
2
9
  import { getReadVariables } from "./dependencies";
3
- import { TlaEvaluationError } from "./errors";
10
+ import {
11
+ TlaEvaluationError,
12
+ TlaIllegalStateError,
13
+ TlaIncompleteStateError,
14
+ TlaUnassignedError,
15
+ } from "./errors";
4
16
  import { EXIT_STATUS, setExitCode } from "./exit-codes";
5
17
  import {
6
18
  describeLocation,
19
+ describeRange,
7
20
  bindArgument,
8
21
  bindDefinitions,
9
22
  bindOperatorArguments,
10
23
  bindValue,
11
24
  compileArgumentScope,
12
25
  evaluate,
26
+ getEntryEvaluator,
13
27
  expectBoolean,
14
28
  forEachBinding,
15
29
  getBoundsDomain,
16
- getChildren,
17
30
  getDefinition,
18
31
  getEnumeratedElements,
19
32
  getReevaluatedDefinitions,
20
33
  lookupScope,
21
34
  resolveApplyOperator,
22
35
  resolveGlobalOperator,
23
- isLocallyResolved,
24
36
  type Context,
25
37
  type Environment,
38
+ type Evaluator,
26
39
  type Scope,
27
40
  type State,
28
41
  } from "./evaluate";
@@ -45,6 +58,7 @@ export interface Successor {
45
58
  interface Run {
46
59
  environment: Environment;
47
60
  isInit: boolean;
61
+ isEnabled: boolean;
48
62
  current: Value[] | undefined;
49
63
  isStopped: boolean;
50
64
  }
@@ -81,25 +95,54 @@ const assign = (partial: State, index: number, value: Value) => {
81
95
  return copy;
82
96
  };
83
97
 
84
- const holds = (expression: Expression, context: Context) => {
85
- const value = evaluate(expression, context);
98
+ // TLC's Tool.getInitStates and Tool.getNextStates report a value where they expect a formula.
99
+ const expectFormula = (expression: Expression, value: Value, isInit: boolean) => {
86
100
  if (typeof value === "boolean") return value;
87
- try {
88
- return expectBoolean(value, `the action at ${describeLocation(expression)}`);
89
- } catch (error) {
90
- // TLC fails with an unexpected exception when the next-state relation isn't a boolean.
91
- throw context.next === undefined ? error : setExitCode(error, EXIT_STATUS.error);
101
+ throw new TlaEvaluationError(
102
+ `In computing ${isInit ? "initial" : "next"} states, TLC expected a boolean expression,\nbut instead found ${formatValue(value)}.\n${describeRange(expression)}`,
103
+ );
104
+ };
105
+
106
+ const holds = (expression: Expression, context: Context, value = evaluate(expression, context)) => {
107
+ // TLC rejects a number in the next-state relation when it splits the relation into actions.
108
+ if (context.next !== undefined && expression.kind === "Number") {
109
+ throw setExitCode(
110
+ new TlaEvaluationError(
111
+ `The next state relation is not a boolean expression.\n${expression.text ?? expression.value}`,
112
+ ),
113
+ EXIT_STATUS.error,
114
+ );
92
115
  }
116
+ return expectFormula(expression, value, context.next === undefined);
93
117
  };
94
118
 
95
119
  const isAssignmentOperator = (operator: string) =>
96
120
  operator === "=" || operator === "\\in" || operator === "\\subseteq";
97
121
 
122
+ const tracedRunners = new WeakMap<Environment, WeakMap<Expression, Runner>[]>();
123
+
124
+ const getRunners = (environment: Environment, isInit: boolean) => {
125
+ if (!environment.trace) return isInit ? initRunners : nextRunners;
126
+ const runners = tracedRunners.get(environment) ?? [new WeakMap(), new WeakMap()];
127
+ tracedRunners.set(environment, runners);
128
+ return runners[isInit ? 0 : 1];
129
+ };
130
+
98
131
  const getRunner = (expression: Expression, environment: Environment, isInit: boolean): Runner => {
99
- const runners = isInit ? initRunners : nextRunners;
132
+ const runners = getRunners(environment, isInit);
100
133
  const cached = runners.get(expression);
101
134
  if (cached) return cached;
102
- const runner = compileAction(expression, environment, isInit);
135
+ const compiled = compileAction(expression, environment, isInit);
136
+ const trace = environment.trace;
137
+ // TLC's CallStackTool keeps an action's expression on the stack while the rest of the action runs.
138
+ const runner: Runner = trace
139
+ ? (run, scope, partial, action, isFixed, onComplete) => {
140
+ const depth = trace.length;
141
+ trace.push(expression);
142
+ compiled(run, scope, partial, action, isFixed, onComplete);
143
+ trace.length = depth;
144
+ }
145
+ : compiled;
103
146
  runners.set(expression, runner);
104
147
  return runner;
105
148
  };
@@ -183,6 +226,23 @@ const getUnchangedIndices = (
183
226
  return getUnchangedIndices(definition.body, environment, visited);
184
227
  };
185
228
 
229
+ // TLC's CallStackTool keeps each expression that UNCHANGED takes apart on the stack.
230
+ const getUnchangedFrames = (expression: Expression, environment: Environment): Expression[] => {
231
+ if (expression.kind === "Tuple") {
232
+ return [
233
+ expression,
234
+ ...expression.elements.flatMap((element) => getUnchangedFrames(element, environment)),
235
+ ];
236
+ }
237
+ const definition =
238
+ expression.kind === "Identifier" && !environment.variableIndex.has(expression.name)
239
+ ? getZeroArityBody(expression.name, environment)
240
+ : undefined;
241
+ return definition
242
+ ? [expression, ...getUnchangedFrames(definition.body, environment)]
243
+ : [expression];
244
+ };
245
+
186
246
  const ACTION_KINDS = new Set([
187
247
  "Label",
188
248
  "And",
@@ -287,12 +347,35 @@ const toConjunct = (
287
347
  return { kind: "Branch", expression, runner: getRunner(expression, environment, isInit) };
288
348
  };
289
349
 
350
+ // The leading guards of `\E x \in S, y \in T : P /\ Q` that read no inner bound hold for every inner
351
+ // binding alike, so they can run once for each element of the outermost bound.
352
+ const getHoistedGuards = (expression: QuantifierExpression, environment: Environment) => {
353
+ if (expression.bounds.length < 2 || expression.body.kind !== "And") return undefined;
354
+ const names = expression.bounds.flatMap((bound) =>
355
+ bound.pattern.kind === "Name" ? [bound.pattern.name] : [],
356
+ );
357
+ if (names.length !== expression.bounds.length) return undefined;
358
+ const innerNames = new Set(names.slice(0, -1));
359
+ const operands = expression.body.operands;
360
+ const index = operands.findIndex((operand) => {
361
+ if (getReadVariables(operand, environment) === undefined) return true;
362
+ if (hasBranches(operand, environment, new Set())) return true;
363
+ const readLocals = getReadLocals(operand, NO_NAMES);
364
+ return !readLocals || readLocals.some((name) => innerNames.has(name));
365
+ });
366
+ const count = index === -1 ? operands.length : index;
367
+ if (count === 0) return undefined;
368
+ return { names, guards: operands.slice(0, count), rest: operands.slice(count) };
369
+ };
370
+
290
371
  const compileConjunction = (
291
372
  operands: Expression[],
292
373
  environment: Environment,
293
374
  isInit: boolean,
294
375
  ): Runner => {
295
376
  const conjuncts = operands.map((operand) => toConjunct(operand, environment, isInit));
377
+ const evaluators: (Evaluator | undefined)[] = conjuncts.map(() => undefined);
378
+ const trace = environment.trace;
296
379
  const runFrom = (
297
380
  start: number,
298
381
  run: Run,
@@ -313,14 +396,25 @@ const compileConjunction = (
313
396
  return;
314
397
  }
315
398
  const conjunct = conjuncts[index];
399
+ if (trace) {
400
+ trace.push(conjunct.expression);
401
+ if (conjunct.expression.kind === "Unchanged") {
402
+ trace.push(...getUnchangedFrames(conjunct.expression.expression, environment));
403
+ }
404
+ }
316
405
  if (conjunct.kind === "Guard") {
317
406
  context ??= getContext(run, scope, current);
318
- if (!holds(conjunct.expression, context)) return;
407
+ const evaluator = (evaluators[index] ??= getEntryEvaluator(
408
+ conjunct.expression,
409
+ environment,
410
+ ));
411
+ if (!holds(conjunct.expression, context, evaluator(context))) return;
319
412
  continue;
320
413
  }
321
414
  if (conjunct.kind === "Assign") {
322
415
  context ??= getContext(run, scope, current);
323
- const value = evaluate(conjunct.value, context);
416
+ const evaluator = (evaluators[index] ??= getEntryEvaluator(conjunct.value, environment));
417
+ const value = evaluator(context);
324
418
  const assigned = current[conjunct.index];
325
419
  if (assigned === undefined) {
326
420
  current = assign(current, conjunct.index, value);
@@ -357,10 +451,7 @@ const compileConjunction = (
357
451
  };
358
452
 
359
453
  const holdsInInit = (expression: Expression, context: Context) =>
360
- expectBoolean(
361
- evaluate(expression, context),
362
- `the initial predicate at ${describeLocation(expression)}`,
363
- );
454
+ expectFormula(expression, evaluate(expression, context), true);
364
455
 
365
456
  const compileGuard =
366
457
  (expression: Expression): Runner =>
@@ -385,7 +476,7 @@ const compileMembership = (
385
476
  expression.operator === "\\subseteq" ? { kind: "Subset", base: evaluated } : evaluated;
386
477
  if (!isEnumerable(value)) {
387
478
  throw new TlaEvaluationError(
388
- `In computing next states, the right side of \\in is not enumerable: ${formatValue(value)} at ${describeLocation(expression)}`,
479
+ `In computing ${run.isInit ? "initial" : "next"} states, the right side of \\IN is not enumerable.\n${describeRange(expression)}`,
389
480
  );
390
481
  }
391
482
  const elements = getStreamedElements(value);
@@ -729,6 +820,34 @@ const compileAction = (
729
820
  }
730
821
  };
731
822
  }
823
+ const hoisted =
824
+ isInit || environment.trace ? undefined : getHoistedGuards(expression, environment);
825
+ if (hoisted) {
826
+ const rest = compileConjunction(hoisted.rest, environment, isInit);
827
+ return (run, scope, partial, action, isFixed, onComplete) => {
828
+ const context = getContext(run, scope, partial);
829
+ const sets = expression.bounds.map((innerBound) =>
830
+ getEnumeratedElements(evaluate(innerBound.set, context), innerBound.set),
831
+ );
832
+ if (sets.some((elements) => elements.length === 0)) return;
833
+ const visit = (index: number, boundScope: Scope | undefined): void => {
834
+ if (index < 0) {
835
+ rest(run, boundScope, partial, action, isFixed, onComplete);
836
+ return;
837
+ }
838
+ for (const element of sets[index]) {
839
+ if (run.isStopped) return;
840
+ const elementScope = bindValue(boundScope, hoisted.names[index], element);
841
+ if (index === sets.length - 1) {
842
+ const guardContext = getContext(run, elementScope, partial);
843
+ if (!hoisted.guards.every((guard) => holds(guard, guardContext))) continue;
844
+ }
845
+ visit(index - 1, elementScope);
846
+ }
847
+ };
848
+ visit(sets.length - 1, scope);
849
+ };
850
+ }
732
851
  return (run, scope, partial, action, isFixed, onComplete) => {
733
852
  forEachBinding(expression.bounds, getContext(run, scope, partial), (boundScope) => {
734
853
  body(run, boundScope, partial, action, isFixed, onComplete);
@@ -804,7 +923,9 @@ const compileAction = (
804
923
  );
805
924
  const body = arm?.body ?? other;
806
925
  if (!body)
807
- throw new TlaEvaluationError(`No CASE guard is true at ${describeLocation(expression)}`);
926
+ throw new TlaEvaluationError(
927
+ `In computing ${run.isInit ? "initial" : "next"} states, TLC encountered a CASE with no conditions true.\n${describeRange(expression)}`,
928
+ );
808
929
  body(run, scope, partial, action, isFixed, onComplete);
809
930
  };
810
931
  }
@@ -835,8 +956,17 @@ const compileAction = (
835
956
  const unchanged = getUnchangedWrapper(expression.subscript);
836
957
  return (run, scope, partial, action, isFixed, onComplete) =>
837
958
  body(run, scope, partial, action, isFixed, (nextPartial, nextAction) => {
838
- if (!holds(unchanged, getContext(run, scope, nextPartial)))
839
- onComplete(nextPartial, nextAction);
959
+ // ENABLED evaluates the subscript on the successor that the action specifies. TLC names
960
+ // a variable that the action leaves without a value.
961
+ try {
962
+ if (!holds(unchanged, getContext(run, scope, nextPartial)))
963
+ onComplete(nextPartial, nextAction);
964
+ } catch (error) {
965
+ if (!run.isEnabled || !(error instanceof TlaUnassignedError)) throw error;
966
+ throw new TlaEvaluationError(
967
+ `The action formula A appearing in a WF_v(A) or SF_v(A) operator does not specify the primed value of the variable ${error.variable} occurring in the state formula v.\n`,
968
+ );
969
+ }
840
970
  });
841
971
  }
842
972
  case "BoxAction":
@@ -913,18 +1043,25 @@ export const isEnabled = (expression: Expression, context: Context): boolean =>
913
1043
  );
914
1044
  }
915
1045
  const environment = context.environment;
916
- const found = { value: false };
1046
+ const run: Run = {
1047
+ environment,
1048
+ isInit: false,
1049
+ isEnabled: true,
1050
+ current: state,
1051
+ isStopped: false,
1052
+ };
1053
+ // TLC stops computing ENABLED at the first successor, so it skips the rest of the action.
917
1054
  getRunner(expression, environment, false)(
918
- { environment, isInit: false, current: state, isStopped: false },
1055
+ run,
919
1056
  context.scope,
920
1057
  getEmptyState(environment),
921
1058
  undefined,
922
1059
  false,
923
1060
  () => {
924
- found.value = true;
1061
+ run.isStopped = true;
925
1062
  },
926
1063
  );
927
- return found.value;
1064
+ return run.isStopped;
928
1065
  };
929
1066
 
930
1067
  export const forEachInitialState = (
@@ -933,7 +1070,13 @@ export const forEachInitialState = (
933
1070
  onState: (state: Value[]) => boolean,
934
1071
  scope?: Scope,
935
1072
  ) => {
936
- const run: Run = { environment, isInit: true, current: undefined, isStopped: false };
1073
+ const run: Run = {
1074
+ environment,
1075
+ isInit: true,
1076
+ isEnabled: false,
1077
+ current: undefined,
1078
+ isStopped: false,
1079
+ };
937
1080
  getRunner(expression, environment, true)(
938
1081
  run,
939
1082
  scope,
@@ -943,14 +1086,7 @@ export const forEachInitialState = (
943
1086
  (partial) => {
944
1087
  if (run.isStopped) return;
945
1088
  if (!isComplete(partial)) {
946
- // TLC reports an initial state that isn't completely specified as an illegal state, not as
947
- // an evaluation failure.
948
- throw setExitCode(
949
- new TlaEvaluationError(
950
- `The initial predicate does not assign ${getMissingVariables(partial, environment).join(", ")}`,
951
- ),
952
- EXIT_STATUS.error,
953
- );
1089
+ throw setExitCode(new TlaIllegalStateError(partial), EXIT_STATUS.error);
954
1090
  }
955
1091
  run.isStopped = onState(partial);
956
1092
  },
@@ -982,7 +1118,13 @@ export const forEachSuccessor = (
982
1118
  onSuccessor: (successor: Successor) => boolean,
983
1119
  scope?: Scope,
984
1120
  ) => {
985
- const run: Run = { environment, isInit: false, current: state, isStopped: false };
1121
+ const run: Run = {
1122
+ environment,
1123
+ isInit: false,
1124
+ isEnabled: false,
1125
+ current: state,
1126
+ isStopped: false,
1127
+ };
986
1128
  const counter = { successors: 0 };
987
1129
  getRunner(expression, environment, false)(
988
1130
  run,
@@ -993,8 +1135,10 @@ export const forEachSuccessor = (
993
1135
  (partial, action) => {
994
1136
  if (run.isStopped) return;
995
1137
  if (!isComplete(partial)) {
996
- throw new TlaEvaluationError(
997
- `Successor state is not completely specified by action ${action ?? "Next"}. The following variables are not assigned: ${getMissingVariables(partial, environment).join(", ")}`,
1138
+ throw new TlaIncompleteStateError(
1139
+ partial,
1140
+ action,
1141
+ getMissingVariables(partial, environment).sort(),
998
1142
  );
999
1143
  }
1000
1144
  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 [];
@@ -188,7 +198,15 @@ const computePermutedValue = (value: ObjectValue, permutation: Permutation) => {
188
198
  const domain = permuteElements(functionValue.domain, permutation);
189
199
  const range = permuteElements(functionValue.range, permutation) ?? functionValue.range;
190
200
  if (domain) {
191
- return createFunction(domain.map((key, index): [Value, Value] => [key, range[index]]));
201
+ const permuted = createFunction(
202
+ domain.map((key, index): [Value, Value] => [key, range[index]]),
203
+ );
204
+ // A permutation often maps the domain to itself, such as a function over the symmetric set.
205
+ // Sharing the original domain array lets comparisons with other images skip the domain.
206
+ const isSameDomain = permuted.domain.every(
207
+ (key, index) => key === functionValue.domain[index],
208
+ );
209
+ return isSameDomain ? createSortedFunction(functionValue.domain, permuted.range) : permuted;
192
210
  }
193
211
  return range === functionValue.range
194
212
  ? functionValue
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 };
package/src/tlc-ext.ts CHANGED
@@ -10,16 +10,8 @@ import {
10
10
  } from "./builtins";
11
11
  import { TlaEvaluationError, TlaModuleError, TlaUnsupportedError } from "./errors";
12
12
  import { getTlcFingerprint } from "./tlc-random";
13
- import {
14
- evaluate,
15
- expectBoolean,
16
- getChildren,
17
- getDefinition,
18
- isLocallyResolved,
19
- type Builtin,
20
- type Environment,
21
- } from "./evaluate";
22
- import type { Definition, Expression } from "./ast";
13
+ import { evaluate, expectBoolean, getDefinition, type Builtin, type Environment } from "./evaluate";
14
+ import { getChildren, isLocallyResolved, type Definition, type Expression } from "./ast";
23
15
  import type { TraceStep } from "./check";
24
16
  import {
25
17
  getNamedRegisters,
@@ -111,15 +103,35 @@ const getRegister = (runtime: CheckerRuntime, key: Value) => {
111
103
  return undefined;
112
104
  };
113
105
 
114
- const setRegister = (runtime: CheckerRuntime, key: Value, value: Value) => {
106
+ // TLC's TLCSet. TLCExt's TLCGetAndSet is a TLA+ definition that calls it.
107
+ export const setTlcValue = (
108
+ runtime: CheckerRuntime,
109
+ print: (text: string) => void,
110
+ key: Value,
111
+ value: Value,
112
+ ) => {
115
113
  if (typeof key === "number" && key >= 0) {
116
114
  runtime.registers.set(key, value);
117
115
  return;
118
116
  }
117
+ if (key === "exit") {
118
+ if (value === true) runtime.isStopped = true;
119
+ return;
120
+ }
121
+ if (key === "pause") {
122
+ if (value !== true) return;
123
+ print("Press enter to resume model checking.");
124
+ runtime.pause();
125
+ return;
126
+ }
119
127
  if (typeof key === "string" && key.startsWith(NAMED_REGISTER_PREFIX)) {
120
128
  runtime.namedRegisters.set(key, value);
121
129
  return;
122
130
  }
131
+ if (typeof key === "string" && key.startsWith("-D")) {
132
+ runtime.properties.set(key.slice(2), formatValue(value));
133
+ return;
134
+ }
123
135
  throw new TlaModuleError(
124
136
  `The first argument of TLCSet should be a nonnegative integer, but instead it is:\n${formatValue(key)}`,
125
137
  );
@@ -203,7 +215,12 @@ export const createTlcExtOperators = (
203
215
  const key = getValue(args, 0, "TLCGetAndSet");
204
216
  const previous = getRegister(runtime, key) ?? getValue(args, 3, "TLCGetAndSet");
205
217
  const update = getOperator(args, 1, "TLCGetAndSet");
206
- setRegister(runtime, key, update.call([previous, getValue(args, 2, "TLCGetAndSet")]));
218
+ setTlcValue(
219
+ runtime,
220
+ print,
221
+ key,
222
+ update.call([previous, getValue(args, 2, "TLCGetAndSet")]),
223
+ );
207
224
  return previous;
208
225
  }),
209
226
  isStateLevel: true,