tla-ts 0.0.3 → 0.0.4-dev.5f6a4bf

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 (86) hide show
  1. package/README.md +32 -12
  2. package/dist/cli.cjs +1 -1
  3. package/dist/cli.js +1 -1
  4. package/dist/index.cjs +1 -1
  5. package/dist/index.d.cts +160 -8
  6. package/dist/index.d.ts +160 -8
  7. package/dist/index.js +1 -1
  8. package/dist/parallel-worker.cjs +2 -2
  9. package/dist/parallel-worker.js +2 -2
  10. package/dist/parallel.cjs +1 -1
  11. package/dist/parallel.js +2 -2
  12. package/dist/run-cli.cjs +45 -18
  13. package/dist/run-cli.js +45 -18
  14. package/dist/transfer.cjs +1393 -18
  15. package/dist/transfer.js +1393 -18
  16. package/package.json +5 -1
  17. package/src/ast.ts +147 -6
  18. package/src/bags.ts +4 -7
  19. package/src/builtins.ts +29 -11
  20. package/src/bundled-modules.ts +3 -3
  21. package/src/canonical.ts +4 -3
  22. package/src/check.ts +1539 -235
  23. package/src/cli-options.ts +11 -5
  24. package/src/cli.ts +8 -1
  25. package/src/codegen.ts +77 -37
  26. package/src/config.ts +254 -181
  27. package/src/dependencies.ts +2 -2
  28. package/src/environment.ts +540 -140
  29. package/src/errors.ts +224 -3
  30. package/src/evaluate.ts +796 -246
  31. package/src/exit-codes.ts +22 -43
  32. package/src/fingerprints.ts +46 -11
  33. package/src/index.ts +1 -0
  34. package/src/instances.ts +19 -16
  35. package/src/java-overrides.ts +104 -25
  36. package/src/levels.ts +191 -45
  37. package/src/lexer.ts +127 -30
  38. package/src/live-check.ts +828 -0
  39. package/src/liveness.ts +218 -572
  40. package/src/obligation-expression.ts +2 -2
  41. package/src/obligation-source.ts +2 -0
  42. package/src/parallel-worker.ts +174 -213
  43. package/src/parallel.ts +131 -39
  44. package/src/parser.ts +456 -147
  45. package/src/pcal-ast.ts +770 -0
  46. package/src/pcal-parse.ts +1523 -0
  47. package/src/pcal-tokenize.ts +516 -0
  48. package/src/pcal-translate.ts +1230 -0
  49. package/src/pcal-validate.ts +454 -0
  50. package/src/randomization.ts +24 -7
  51. package/src/resolve.ts +1481 -426
  52. package/src/run-cli.ts +1212 -143
  53. package/src/runtime.ts +19 -1
  54. package/src/sany-builtins.ts +147 -0
  55. package/src/sany-generator.ts +3128 -0
  56. package/src/sany-levels.ts +1208 -0
  57. package/src/sany-lexer.ts +545 -0
  58. package/src/sany-linter.ts +122 -0
  59. package/src/sany-modules.ts +1398 -0
  60. package/src/sany-nodes.ts +463 -0
  61. package/src/sany-parse-error.ts +2161 -0
  62. package/src/sany-report.ts +356 -0
  63. package/src/sany-selectors.ts +738 -0
  64. package/src/sany-source.ts +248 -0
  65. package/src/sany-xml.ts +1017 -0
  66. package/src/spec-description.ts +42 -11
  67. package/src/standard-modules.ts +200 -148
  68. package/src/standard-ranges.ts +116 -0
  69. package/src/state-graph.ts +180 -0
  70. package/src/subexpressions.ts +231 -171
  71. package/src/substitution-levels.ts +38 -17
  72. package/src/successors.ts +219 -107
  73. package/src/symmetry.ts +194 -54
  74. package/src/tableau.ts +54 -25
  75. package/src/tlc-ext.ts +42 -29
  76. package/src/tlc-messages.ts +329 -0
  77. package/src/tlc-module.ts +52 -43
  78. package/src/tlc-modules.ts +4 -0
  79. package/src/tlc-order.ts +78 -10
  80. package/src/tlc-random.ts +37 -9
  81. package/src/tlc-replay.ts +655 -0
  82. package/src/tlc-summary.ts +20 -5
  83. package/src/tlc-version.ts +18 -0
  84. package/src/transfer.ts +15 -3
  85. package/src/value-sources.ts +29 -0
  86. package/src/values.ts +731 -184
package/src/symmetry.ts CHANGED
@@ -1,4 +1,8 @@
1
- import { TlaConfigError } from "./errors";
1
+ import type { Expression } from "./ast";
2
+ import type { Substitution } from "./config";
3
+ import { TlaConfigError, TlaEvaluationError, UNEXPECTED_EXCEPTION } from "./errors";
4
+ import { EXIT_STATUS, setExitCode } from "./exit-codes";
5
+ import { MESSAGE_CODE } from "./tlc-messages";
2
6
  import { evaluate, type Environment } from "./evaluate";
3
7
  import {
4
8
  compareValues,
@@ -9,6 +13,7 @@ import {
9
13
  isEnumerable,
10
14
  isFunctionValue,
11
15
  isModelValue,
16
+ isSameValue,
12
17
  isSetValue,
13
18
  toFiniteFunction,
14
19
  toFiniteSet,
@@ -29,6 +34,20 @@ interface Permutation {
29
34
  cacheLimit: number;
30
35
  }
31
36
 
37
+ // The images of one value under every permutation, the identity first, and how each image compares
38
+ // with the image of each permutation the search has held as the smallest.
39
+ interface Orbit {
40
+ images: Value[];
41
+ comparisons: (Int8Array | undefined)[];
42
+ }
43
+
44
+ interface SymmetryGroup {
45
+ permutations: Permutation[];
46
+ orbits: WeakMap<ObjectValue, Orbit>;
47
+ orbitCount: number;
48
+ orbitLimit: number;
49
+ }
50
+
32
51
  const getPermutationKey = (permutation: Images) =>
33
52
  [...permutation]
34
53
  .map(([name, image]) => `${name}>${image.name}`)
@@ -46,40 +65,90 @@ const composePermutations = (first: Images, second: Images) => {
46
65
  return composed;
47
66
  };
48
67
 
49
- const toImages = (value: Value, name: string) => {
50
- if (!isFunctionValue(value)) {
51
- throw new TlaConfigError(`The symmetry values of ${name} must be functions`);
52
- }
68
+ // Tool#getSymmetryPerms fails with a RuntimeException as TLC starts, which TLC reports as one it
69
+ // did not expect.
70
+ const createSymmetryError = (message: string) =>
71
+ setExitCode(new TlaEvaluationError(`${UNEXPECTED_EXCEPTION}${message}`), EXIT_STATUS.error);
72
+
73
+ const toImages = (value: Value) => {
53
74
  const functionValue = toFiniteFunction(value);
54
75
  const permutation: Images = new Map();
55
76
  functionValue.domain.forEach((key, index) => {
56
77
  const image = functionValue.range[index];
57
78
  if (!isModelValue(key) || !isModelValue(image)) {
58
- throw new TlaConfigError("Symmetry function must have model values as domain and range");
79
+ throw createSymmetryError("Symmetry function must have model values as domain and range.");
59
80
  }
60
81
  if (key.name !== image.name) permutation.set(key.name, image);
61
82
  });
62
83
  return permutation;
63
84
  };
64
85
 
65
- export const getSymmetryGroup = (name: string, environment: Environment): Permutation[] => {
86
+ // SyntaxTreeNode.getHumanReadableImage, which joins the tokens of an expression without spaces.
87
+ const getExpressionImage = (expression: Expression): string => {
88
+ if (expression.kind === "Identifier") return expression.name;
89
+ if (expression.kind !== "Apply") return "";
90
+ const args = expression.args.map(getExpressionImage);
91
+ return /^[A-Za-z_]/.test(expression.operator)
92
+ ? `${expression.operator}(${args.join(",")})`
93
+ : args.join(expression.operator);
94
+ };
95
+
96
+ const isPermutations = (
97
+ expression: Expression,
98
+ ): expression is Expression & { kind: "Apply"; args: [Expression] } =>
99
+ expression.kind === "Apply" &&
100
+ expression.operator === "Permutations" &&
101
+ expression.args.length === 1;
102
+
103
+ export const getSymmetryGroup = (
104
+ name: string,
105
+ environment: Environment,
106
+ substitutions: Substitution[],
107
+ ): SymmetryGroup | undefined => {
66
108
  const definition = environment.definitions.get(name);
109
+ if (definition === undefined && !environment.constants.has(name)) {
110
+ throw new TlaConfigError(
111
+ `The symmetry function ${name} specified in the configuration file\nis not defined in the specification.`,
112
+ );
113
+ }
67
114
  if (definition?.kind !== "Operator" || definition.params.length > 0) {
68
- throw new TlaConfigError(`The symmetry function ${name} must specify a set of permutations`);
115
+ throw createSymmetryError(`The symmetry function ${name} must specify a set of permutations.`);
69
116
  }
70
- const value = evaluate(definition.body, {
71
- environment,
72
- scope: undefined,
73
- state: undefined,
74
- next: undefined,
75
- });
117
+ const evaluateConstant = (expression: Expression) =>
118
+ evaluate(expression, { environment, scope: undefined, state: undefined, next: undefined });
119
+ const value = evaluateConstant(definition.body);
76
120
  if (!isSetValue(value) || !isEnumerable(value)) {
77
- throw new TlaConfigError("The symmetry operator must specify a set of functions");
121
+ throw createSymmetryError("The symmetry operator must specify a set of functions.");
122
+ }
123
+ const elements = toFiniteSet(value).elements;
124
+ if (!elements.every(isFunctionValue)) {
125
+ throw createSymmetryError("The symmetry values must be function records.");
126
+ }
127
+ const permutations = elements.map(toImages);
128
+ // Tool#getSymmetryPerms warns about each permuted set with fewer than two elements, by the name
129
+ // the config substitutes for it. As many permuted sets as permutations means none has two.
130
+ const permutedSets = definition.body.kind === "Apply" ? definition.body.args : [];
131
+ const configNames = new Map(
132
+ substitutions
133
+ .filter((substitution) => substitution.module === undefined)
134
+ .map((substitution) => [substitution.target, substitution.name]),
135
+ );
136
+ const warnSmallSets = (offenders: Expression[]) => {
137
+ if (offenders.length === 0) return;
138
+ const names = offenders.map((offender) => {
139
+ const image = getExpressionImage(isPermutations(offender) ? offender.args[0] : offender);
140
+ return configNames.get(image) ?? image;
141
+ });
142
+ const isPlural = offenders.length > 1;
143
+ environment.runtime.warn(
144
+ MESSAGE_CODE.symmetrySetTooSmall,
145
+ `The set${isPlural ? "s" : ""} ${names.join(", and ")} ${isPlural ? "have" : "has"} been defined to be a symmetry set but contain${isPlural ? "" : "s"} less than two elements.`,
146
+ );
147
+ };
148
+ if (permutedSets.length >= elements.length) {
149
+ warnSmallSets(permutedSets);
150
+ return undefined;
78
151
  }
79
- const permutations = toFiniteSet(value).elements.map((element) => toImages(element, name));
80
- const isDisabled =
81
- definition.body.kind === "Apply" && definition.body.args.length >= permutations.length;
82
- if (isDisabled) return [];
83
152
  const group = new Map<string, Images>();
84
153
  permutations.forEach((permutation) => {
85
154
  if (permutation.size > 0) group.set(getPermutationKey(permutation), permutation);
@@ -98,13 +167,38 @@ export const getSymmetryGroup = (name: string, environment: Environment): Permut
98
167
  );
99
168
  frontier.start = end;
100
169
  }
170
+ const movedNames = new Set(
171
+ [...group.values()].flatMap((images) => [...images.values()].map((image) => image.name)),
172
+ );
173
+ // Only a permutation of a constant that TLC holds as an enumerated set is checked. TLC binds a
174
+ // constant the config substitutes with <- to the definition, which it skips.
175
+ const substitutedNames = new Set(substitutions.map((substitution) => substitution.name));
176
+ warnSmallSets(
177
+ permutedSets.filter((node) => {
178
+ if (!isPermutations(node)) return false;
179
+ const operand = node.args[0];
180
+ if (operand.kind !== "Identifier" || substitutedNames.has(operand.name)) return false;
181
+ const set = evaluateConstant(operand);
182
+ return (
183
+ typeof set === "object" &&
184
+ set.kind === "Set" &&
185
+ !set.elements.some((element) => isModelValue(element) && movedNames.has(element.name))
186
+ );
187
+ }),
188
+ );
189
+ if (group.size === 0) return undefined;
101
190
  const cacheLimit = Math.max(256, Math.floor(CACHE_LIMIT / group.size));
102
- return [...group.values()].map((images) => ({
103
- images,
104
- cache: new WeakMap<ObjectValue, Value>(),
105
- cacheSize: 0,
106
- cacheLimit,
107
- }));
191
+ return {
192
+ permutations: [...group.values()].map((images) => ({
193
+ images,
194
+ cache: new WeakMap<ObjectValue, Value>(),
195
+ cacheSize: 0,
196
+ cacheLimit,
197
+ })),
198
+ orbits: new WeakMap(),
199
+ orbitCount: 0,
200
+ orbitLimit: cacheLimit,
201
+ };
108
202
  };
109
203
 
110
204
  const permuteElements = (elements: Value[], permutation: Permutation) => {
@@ -163,7 +257,10 @@ const permuteValue = (value: Value, permutation: Permutation): Value => {
163
257
  if (size === 0 || size > CACHED_SIZE_LIMIT) return computePermutedValue(value, permutation);
164
258
  const cached = permutation.cache.get(value);
165
259
  if (cached !== undefined) return cached;
166
- const permuted = computePermutedValue(value, permutation);
260
+ const computed = computePermutedValue(value, permutation);
261
+ // A permutation often maps a value to an equal one. Keeping the original lets the comparison
262
+ // with the smallest state so far stop at identity.
263
+ const permuted = computed !== value && isSameValue(computed, value) ? value : computed;
167
264
  if (permutation.cacheSize >= permutation.cacheLimit) {
168
265
  permutation.cache = new WeakMap();
169
266
  permutation.cacheSize = 0;
@@ -184,7 +281,15 @@ const computePermutedValue = (value: ObjectValue, permutation: Permutation) => {
184
281
  const domain = permuteElements(functionValue.domain, permutation);
185
282
  const range = permuteElements(functionValue.range, permutation) ?? functionValue.range;
186
283
  if (domain) {
187
- return createFunction(domain.map((key, index): [Value, Value] => [key, range[index]]));
284
+ const permuted = createFunction(
285
+ domain.map((key, index): [Value, Value] => [key, range[index]]),
286
+ );
287
+ // A permutation often maps the domain to itself, such as a function over the symmetric set.
288
+ // Sharing the original domain array lets comparisons with other images skip the domain.
289
+ const isSameDomain = permuted.domain.every(
290
+ (key, index) => key === functionValue.domain[index],
291
+ );
292
+ return isSameDomain ? createSortedFunction(functionValue.domain, permuted.range) : permuted;
188
293
  }
189
294
  return range === functionValue.range
190
295
  ? functionValue
@@ -196,41 +301,76 @@ const computePermutedValue = (value: ObjectValue, permutation: Permutation) => {
196
301
  return elements ? createSet(elements) : set;
197
302
  };
198
303
 
199
- const permuteRemaining = (state: Value[], permuted: Value[], permutation: Permutation) => {
200
- for (let index = permuted.length; index < state.length; index++) {
201
- permuted.push(permuteValue(state[index], permutation));
304
+ const getOrbit = (value: ObjectValue, group: SymmetryGroup) => {
305
+ const cached = group.orbits.get(value);
306
+ if (cached !== undefined) return cached;
307
+ if (group.orbitCount >= group.orbitLimit) {
308
+ group.orbits = new WeakMap();
309
+ group.orbitCount = 0;
202
310
  }
203
- return permuted;
311
+ const orbit: Orbit = { images: [value], comparisons: [] };
312
+ group.orbits.set(value, orbit);
313
+ group.orbitCount++;
314
+ return orbit;
315
+ };
316
+
317
+ const getImage = (orbit: Orbit, permutation: number, group: SymmetryGroup) =>
318
+ (orbit.images[permutation] ??= permuteValue(
319
+ orbit.images[0],
320
+ group.permutations[permutation - 1],
321
+ ));
322
+
323
+ // Two images of a value compare the same way every time, and comparing them again changes nothing,
324
+ // so an orbit compares each pair once.
325
+ const compareImages = (
326
+ value: ObjectValue,
327
+ permutation: number,
328
+ minimum: number,
329
+ group: SymmetryGroup,
330
+ ) => {
331
+ const orbit = getOrbit(value, group);
332
+ const comparisons = (orbit.comparisons[minimum] ??= new Int8Array(group.permutations.length + 1));
333
+ if (comparisons[permutation] === 0) {
334
+ const comparison = compareValues(
335
+ getImage(orbit, permutation, group),
336
+ getImage(orbit, minimum, group),
337
+ );
338
+ comparisons[permutation] = Math.sign(comparison) + 2;
339
+ }
340
+ return comparisons[permutation] - 2;
204
341
  };
205
342
 
206
- const getSmallerPermutation = (
343
+ const isSmallerImage = (
207
344
  state: Value[],
208
- minimum: Value[],
209
- permutation: Permutation,
210
- order: number[] | undefined,
345
+ permutation: number,
346
+ minimum: number,
347
+ group: SymmetryGroup,
348
+ order: number[],
211
349
  ) => {
212
- const permuted: Value[] = [];
213
- for (let position = 0; position < state.length; position++) {
214
- const index = order ? order[position] : position;
215
- const value = permuteValue(state[index], permutation);
216
- const comparison = compareValues(value, minimum[index]);
217
- if (comparison > 0) return undefined;
218
- if (!order) permuted.push(value);
219
- if (comparison < 0) {
220
- return order
221
- ? state.map((item) => permuteValue(item, permutation))
222
- : permuteRemaining(state, permuted, permutation);
223
- }
350
+ for (const index of order) {
351
+ const value = state[index];
352
+ const comparison =
353
+ typeof value === "object" ? compareImages(value, permutation, minimum, group) : 0;
354
+ if (comparison !== 0) return comparison < 0;
224
355
  }
225
- return undefined;
356
+ return false;
226
357
  };
227
358
 
359
+ // TLC keeps the smallest image of the state in its variable order, replacing it only with a
360
+ // strictly smaller one.
228
361
  export const getRepresentative = (
229
362
  state: Value[],
230
- group: Permutation[],
231
- order?: number[],
232
- ): Value[] =>
233
- group.reduce(
234
- (minimum, permutation) => getSmallerPermutation(state, minimum, permutation, order) ?? minimum,
235
- state,
363
+ group: SymmetryGroup,
364
+ order: number[],
365
+ ): Value[] => {
366
+ const minimum = group.permutations.reduce(
367
+ (smallest, _, index) =>
368
+ isSmallerImage(state, index + 1, smallest, group, order) ? index + 1 : smallest,
369
+ 0,
236
370
  );
371
+ return minimum === 0
372
+ ? state
373
+ : state.map((value) =>
374
+ typeof value === "object" ? getImage(getOrbit(value, group), minimum, group) : value,
375
+ );
376
+ };
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);
@@ -510,20 +528,31 @@ const getParticleClosure = (terms: LiveExpression[]) => {
510
528
  const createTableauNode = (particle: LiveExpression[]): TableauNode => ({
511
529
  particle,
512
530
  successors: [],
531
+ // Constant terms count, as after TLC 1.7.4. That version checks only state atoms, so a node with a
532
+ // FALSE term stays in the graph and yields a bogus counterexample (tlaplus#604).
513
533
  statePredicates: particle.filter((term) => getLiveLevel(term) <= STATE_LEVEL),
514
534
  });
515
535
 
516
536
  const createTableau = (formula: LiveExpression) => {
517
537
  const nodes = getParticleClosure([formula]).map(createTableauNode);
518
538
  const initialCount = nodes.length;
539
+ const indices = new Map<string, number>();
540
+ nodes.forEach((node, index) => {
541
+ const key = getParticleKey(node.particle);
542
+ if (!indices.has(key)) indices.set(key, index);
543
+ });
519
544
  for (let index = 0; index < nodes.length; index++) {
520
545
  const implied = nodes[index].particle.flatMap((term) =>
521
546
  term.kind === "Next" ? [term.body] : [],
522
547
  );
523
548
  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);
549
+ const key = getParticleKey(particle);
550
+ const existing = indices.get(key);
551
+ if (existing === undefined) {
552
+ indices.set(key, nodes.length);
553
+ nodes.push(createTableauNode(particle));
554
+ }
555
+ nodes[index].successors.push(existing ?? nodes.length - 1);
527
556
  }
528
557
  }
529
558
  return { nodes, initialCount };
@@ -555,7 +584,7 @@ const classify = (expression: LiveExpression, classification: Classification) =>
555
584
  }
556
585
  if (containsAction(expression)) {
557
586
  throw new TlaEvaluationError(
558
- "TLC cannot handle the temporal formula: actions may only appear as []<>A or <>[]A",
587
+ "Temporal formulas containing actions must be of forms <>[]A or []<>A.",
559
588
  );
560
589
  }
561
590
  classification.formulas.push(expression);
package/src/tlc-ext.ts CHANGED
@@ -10,17 +10,9 @@ 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";
23
- import type { TraceStep } from "./check";
13
+ import { formatNestedMessage } from "./tlc-messages";
14
+ import { evaluate, expectBoolean, getDefinition, type Builtin, type Environment } from "./evaluate";
15
+ import { getChildren, isLocallyResolved, type Definition, type Expression } from "./ast";
24
16
  import {
25
17
  getNamedRegisters,
26
18
  getPossibleCounts,
@@ -75,27 +67,21 @@ export const createActionRecord = (action: string | undefined) =>
75
67
  ]);
76
68
 
77
69
  // TLC's CounterExample is a graph of the violating behavior: the states numbered from 1, an edge
78
- // for each step, and for a lasso an edge from the last state back to where the loop starts.
70
+ // for each step, and for a lasso an edge from the last state back to where the loop starts. Each
71
+ // edge holds the record of the action TLC found for the step.
79
72
  export const createCounterExample = (
80
- trace: TraceStep[],
81
- loop: { start: number; action: string | undefined } | undefined,
73
+ stateRecords: Record<string, Value>[],
74
+ actions: Value[],
75
+ loop: { start: number; action: Value } | undefined,
82
76
  ) => {
83
- const states = trace.map((step, index) =>
84
- createTuple([index + 1, createRecord(Object.entries(step.state))]),
77
+ const states = stateRecords.map((state, index) =>
78
+ createTuple([index + 1, createRecord(Object.entries(state))]),
85
79
  );
86
80
  const steps = states
87
81
  .slice(1)
88
- .map((state, index) =>
89
- createTuple([states[index], createActionRecord(trace[index + 1].action), state]),
90
- );
82
+ .map((state, index) => createTuple([states[index], actions[index], state]));
91
83
  const closing = loop
92
- ? [
93
- createTuple([
94
- states[states.length - 1],
95
- createActionRecord(loop.action),
96
- states[loop.start],
97
- ]),
98
- ]
84
+ ? [createTuple([states[states.length - 1], loop.action, states[loop.start]])]
99
85
  : [];
100
86
  return createRecord([
101
87
  ["action", createSet([...steps, ...closing])],
@@ -111,15 +97,35 @@ const getRegister = (runtime: CheckerRuntime, key: Value) => {
111
97
  return undefined;
112
98
  };
113
99
 
114
- const setRegister = (runtime: CheckerRuntime, key: Value, value: Value) => {
100
+ // TLC's TLCSet. TLCExt's TLCGetAndSet is a TLA+ definition that calls it.
101
+ export const setTlcValue = (
102
+ runtime: CheckerRuntime,
103
+ print: (text: string) => void,
104
+ key: Value,
105
+ value: Value,
106
+ ) => {
115
107
  if (typeof key === "number" && key >= 0) {
116
108
  runtime.registers.set(key, value);
117
109
  return;
118
110
  }
111
+ if (key === "exit") {
112
+ if (value === true) runtime.isStopped = true;
113
+ return;
114
+ }
115
+ if (key === "pause") {
116
+ if (value !== true) return;
117
+ print("Press enter to resume model checking.");
118
+ runtime.pause();
119
+ return;
120
+ }
119
121
  if (typeof key === "string" && key.startsWith(NAMED_REGISTER_PREFIX)) {
120
122
  runtime.namedRegisters.set(key, value);
121
123
  return;
122
124
  }
125
+ if (typeof key === "string" && key.startsWith("-D")) {
126
+ runtime.properties.set(key.slice(2), formatValue(value));
127
+ return;
128
+ }
123
129
  throw new TlaModuleError(
124
130
  `The first argument of TLCSet should be a nonnegative integer, but instead it is:\n${formatValue(key)}`,
125
131
  );
@@ -189,7 +195,9 @@ export const createTlcExtOperators = (
189
195
  try {
190
196
  getThunk(args, 1, "AssertError")();
191
197
  } catch (error) {
192
- if (error instanceof TlaEvaluationError) return error.message === expected;
198
+ if (error instanceof TlaEvaluationError) {
199
+ return formatNestedMessage(error.message, runtime.isTool) === expected;
200
+ }
193
201
  throw error;
194
202
  }
195
203
  return false;
@@ -203,7 +211,12 @@ export const createTlcExtOperators = (
203
211
  const key = getValue(args, 0, "TLCGetAndSet");
204
212
  const previous = getRegister(runtime, key) ?? getValue(args, 3, "TLCGetAndSet");
205
213
  const update = getOperator(args, 1, "TLCGetAndSet");
206
- setRegister(runtime, key, update.call([previous, getValue(args, 2, "TLCGetAndSet")]));
214
+ setTlcValue(
215
+ runtime,
216
+ print,
217
+ key,
218
+ update.call([previous, getValue(args, 2, "TLCGetAndSet")]),
219
+ );
207
220
  return previous;
208
221
  }),
209
222
  isStateLevel: true,