tla-ts 0.0.3-dev.949cce6 → 0.0.3-dev.9b15ea6

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 (80) hide show
  1. package/dist/cli.cjs +1 -1
  2. package/dist/cli.js +1 -1
  3. package/dist/index.cjs +1 -1
  4. package/dist/index.d.cts +146 -8
  5. package/dist/index.d.ts +146 -8
  6. package/dist/index.js +1 -1
  7. package/dist/parallel-worker.cjs +1 -1
  8. package/dist/parallel-worker.js +2 -2
  9. package/dist/parallel.cjs +1 -1
  10. package/dist/parallel.js +2 -2
  11. package/dist/run-cli.cjs +1351 -20
  12. package/dist/run-cli.js +1351 -20
  13. package/dist/transfer.cjs +86 -28
  14. package/dist/transfer.js +86 -28
  15. package/package.json +5 -1
  16. package/src/ast.ts +48 -6
  17. package/src/bags.ts +4 -7
  18. package/src/builtins.ts +29 -11
  19. package/src/bundled-modules.ts +3 -3
  20. package/src/canonical.ts +4 -3
  21. package/src/check.ts +1352 -215
  22. package/src/cli.ts +8 -1
  23. package/src/codegen.ts +68 -18
  24. package/src/config.ts +252 -179
  25. package/src/environment.ts +451 -129
  26. package/src/errors.ts +217 -3
  27. package/src/evaluate.ts +724 -117
  28. package/src/exit-codes.ts +5 -4
  29. package/src/index.ts +1 -0
  30. package/src/instances.ts +4 -2
  31. package/src/java-overrides.ts +104 -25
  32. package/src/levels.ts +183 -37
  33. package/src/lexer.ts +14 -1
  34. package/src/live-check.ts +211 -89
  35. package/src/liveness.ts +192 -65
  36. package/src/obligation-expression.ts +2 -2
  37. package/src/obligation-source.ts +2 -0
  38. package/src/parallel-worker.ts +8 -3
  39. package/src/parallel.ts +56 -5
  40. package/src/parser.ts +423 -126
  41. package/src/pcal-ast.ts +770 -0
  42. package/src/pcal-parse.ts +1523 -0
  43. package/src/pcal-tokenize.ts +516 -0
  44. package/src/pcal-translate.ts +1230 -0
  45. package/src/pcal-validate.ts +454 -0
  46. package/src/randomization.ts +24 -7
  47. package/src/resolve.ts +1363 -405
  48. package/src/run-cli.ts +1167 -155
  49. package/src/runtime.ts +16 -0
  50. package/src/sany-builtins.ts +147 -0
  51. package/src/sany-generator.ts +3112 -0
  52. package/src/sany-levels.ts +1208 -0
  53. package/src/sany-lexer.ts +545 -0
  54. package/src/sany-linter.ts +122 -0
  55. package/src/sany-modules.ts +1398 -0
  56. package/src/sany-nodes.ts +463 -0
  57. package/src/sany-parse-error.ts +2161 -0
  58. package/src/sany-report.ts +354 -0
  59. package/src/sany-selectors.ts +738 -0
  60. package/src/sany-source.ts +248 -0
  61. package/src/sany-xml.ts +1017 -0
  62. package/src/spec-description.ts +26 -7
  63. package/src/standard-modules.ts +203 -146
  64. package/src/standard-ranges.ts +116 -0
  65. package/src/state-graph.ts +29 -6
  66. package/src/subexpressions.ts +221 -161
  67. package/src/substitution-levels.ts +38 -17
  68. package/src/successors.ts +162 -114
  69. package/src/symmetry.ts +180 -52
  70. package/src/tableau.ts +4 -2
  71. package/src/tlc-ext.ts +13 -17
  72. package/src/tlc-messages.ts +329 -0
  73. package/src/tlc-module.ts +46 -18
  74. package/src/tlc-order.ts +56 -6
  75. package/src/tlc-random.ts +28 -3
  76. package/src/tlc-replay.ts +655 -0
  77. package/src/tlc-version.ts +18 -0
  78. package/src/transfer.ts +15 -3
  79. package/src/value-sources.ts +29 -0
  80. package/src/values.ts +684 -204
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,
@@ -30,6 +34,20 @@ interface Permutation {
30
34
  cacheLimit: number;
31
35
  }
32
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
+
33
51
  const getPermutationKey = (permutation: Images) =>
34
52
  [...permutation]
35
53
  .map(([name, image]) => `${name}>${image.name}`)
@@ -47,40 +65,90 @@ const composePermutations = (first: Images, second: Images) => {
47
65
  return composed;
48
66
  };
49
67
 
50
- const toImages = (value: Value, name: string) => {
51
- if (!isFunctionValue(value)) {
52
- throw new TlaConfigError(`The symmetry values of ${name} must be functions`);
53
- }
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) => {
54
74
  const functionValue = toFiniteFunction(value);
55
75
  const permutation: Images = new Map();
56
76
  functionValue.domain.forEach((key, index) => {
57
77
  const image = functionValue.range[index];
58
78
  if (!isModelValue(key) || !isModelValue(image)) {
59
- 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.");
60
80
  }
61
81
  if (key.name !== image.name) permutation.set(key.name, image);
62
82
  });
63
83
  return permutation;
64
84
  };
65
85
 
66
- 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 => {
67
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
+ }
68
114
  if (definition?.kind !== "Operator" || definition.params.length > 0) {
69
- 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.`);
70
116
  }
71
- const value = evaluate(definition.body, {
72
- environment,
73
- scope: undefined,
74
- state: undefined,
75
- next: undefined,
76
- });
117
+ const evaluateConstant = (expression: Expression) =>
118
+ evaluate(expression, { environment, scope: undefined, state: undefined, next: undefined });
119
+ const value = evaluateConstant(definition.body);
77
120
  if (!isSetValue(value) || !isEnumerable(value)) {
78
- 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;
79
151
  }
80
- const permutations = toFiniteSet(value).elements.map((element) => toImages(element, name));
81
- const isDisabled =
82
- definition.body.kind === "Apply" && definition.body.args.length >= permutations.length;
83
- if (isDisabled) return [];
84
152
  const group = new Map<string, Images>();
85
153
  permutations.forEach((permutation) => {
86
154
  if (permutation.size > 0) group.set(getPermutationKey(permutation), permutation);
@@ -99,13 +167,38 @@ export const getSymmetryGroup = (name: string, environment: Environment): Permut
99
167
  );
100
168
  frontier.start = end;
101
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;
102
190
  const cacheLimit = Math.max(256, Math.floor(CACHE_LIMIT / group.size));
103
- return [...group.values()].map((images) => ({
104
- images,
105
- cache: new WeakMap<ObjectValue, Value>(),
106
- cacheSize: 0,
107
- cacheLimit,
108
- }));
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
+ };
109
202
  };
110
203
 
111
204
  const permuteElements = (elements: Value[], permutation: Permutation) => {
@@ -208,41 +301,76 @@ const computePermutedValue = (value: ObjectValue, permutation: Permutation) => {
208
301
  return elements ? createSet(elements) : set;
209
302
  };
210
303
 
211
- const permuteRemaining = (state: Value[], permuted: Value[], permutation: Permutation) => {
212
- for (let index = permuted.length; index < state.length; index++) {
213
- 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;
214
310
  }
215
- return permuted;
311
+ const orbit: Orbit = { images: [value], comparisons: [] };
312
+ group.orbits.set(value, orbit);
313
+ group.orbitCount++;
314
+ return orbit;
216
315
  };
217
316
 
218
- const getSmallerPermutation = (
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;
341
+ };
342
+
343
+ const isSmallerImage = (
219
344
  state: Value[],
220
- minimum: Value[],
221
- permutation: Permutation,
222
- order: number[] | undefined,
345
+ permutation: number,
346
+ minimum: number,
347
+ group: SymmetryGroup,
348
+ order: number[],
223
349
  ) => {
224
- const permuted: Value[] = [];
225
- for (let position = 0; position < state.length; position++) {
226
- const index = order ? order[position] : position;
227
- const value = permuteValue(state[index], permutation);
228
- const comparison = compareValues(value, minimum[index]);
229
- if (comparison > 0) return undefined;
230
- if (!order) permuted.push(value);
231
- if (comparison < 0) {
232
- return order
233
- ? state.map((item) => permuteValue(item, permutation))
234
- : permuteRemaining(state, permuted, permutation);
235
- }
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;
236
355
  }
237
- return undefined;
356
+ return false;
238
357
  };
239
358
 
359
+ // TLC keeps the smallest image of the state in its variable order, replacing it only with a
360
+ // strictly smaller one.
240
361
  export const getRepresentative = (
241
362
  state: Value[],
242
- group: Permutation[],
243
- order?: number[],
244
- ): Value[] =>
245
- group.reduce(
246
- (minimum, permutation) => getSmallerPermutation(state, minimum, permutation, order) ?? minimum,
247
- 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,
248
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
@@ -289,7 +289,7 @@ const toDisjunctiveNormalForm = (expression: LiveExpression): LiveExpression =>
289
289
  total.value *= normal.operands.length;
290
290
  if (total.value > MAXIMUM_DISJUNCTS) {
291
291
  throw new TlaEvaluationError(
292
- "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.",
293
293
  );
294
294
  }
295
295
  }
@@ -528,6 +528,8 @@ const getParticleClosure = (terms: LiveExpression[]) => {
528
528
  const createTableauNode = (particle: LiveExpression[]): TableauNode => ({
529
529
  particle,
530
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).
531
533
  statePredicates: particle.filter((term) => getLiveLevel(term) <= STATE_LEVEL),
532
534
  });
533
535
 
@@ -582,7 +584,7 @@ const classify = (expression: LiveExpression, classification: Classification) =>
582
584
  }
583
585
  if (containsAction(expression)) {
584
586
  throw new TlaEvaluationError(
585
- "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.",
586
588
  );
587
589
  }
588
590
  classification.formulas.push(expression);
package/src/tlc-ext.ts CHANGED
@@ -10,9 +10,9 @@ import {
10
10
  } from "./builtins";
11
11
  import { TlaEvaluationError, TlaModuleError, TlaUnsupportedError } from "./errors";
12
12
  import { getTlcFingerprint } from "./tlc-random";
13
+ import { formatNestedMessage } from "./tlc-messages";
13
14
  import { evaluate, expectBoolean, getDefinition, type Builtin, type Environment } from "./evaluate";
14
15
  import { getChildren, isLocallyResolved, type Definition, type Expression } from "./ast";
15
- import type { TraceStep } from "./check";
16
16
  import {
17
17
  getNamedRegisters,
18
18
  getPossibleCounts,
@@ -67,27 +67,21 @@ export const createActionRecord = (action: string | undefined) =>
67
67
  ]);
68
68
 
69
69
  // TLC's CounterExample is a graph of the violating behavior: the states numbered from 1, an edge
70
- // 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.
71
72
  export const createCounterExample = (
72
- trace: TraceStep[],
73
- loop: { start: number; action: string | undefined } | undefined,
73
+ stateRecords: Record<string, Value>[],
74
+ actions: Value[],
75
+ loop: { start: number; action: Value } | undefined,
74
76
  ) => {
75
- const states = trace.map((step, index) =>
76
- createTuple([index + 1, createRecord(Object.entries(step.state))]),
77
+ const states = stateRecords.map((state, index) =>
78
+ createTuple([index + 1, createRecord(Object.entries(state))]),
77
79
  );
78
80
  const steps = states
79
81
  .slice(1)
80
- .map((state, index) =>
81
- createTuple([states[index], createActionRecord(trace[index + 1].action), state]),
82
- );
82
+ .map((state, index) => createTuple([states[index], actions[index], state]));
83
83
  const closing = loop
84
- ? [
85
- createTuple([
86
- states[states.length - 1],
87
- createActionRecord(loop.action),
88
- states[loop.start],
89
- ]),
90
- ]
84
+ ? [createTuple([states[states.length - 1], loop.action, states[loop.start]])]
91
85
  : [];
92
86
  return createRecord([
93
87
  ["action", createSet([...steps, ...closing])],
@@ -201,7 +195,9 @@ export const createTlcExtOperators = (
201
195
  try {
202
196
  getThunk(args, 1, "AssertError")();
203
197
  } catch (error) {
204
- if (error instanceof TlaEvaluationError) return error.message === expected;
198
+ if (error instanceof TlaEvaluationError) {
199
+ return formatNestedMessage(error.message, runtime.isTool) === expected;
200
+ }
205
201
  throw error;
206
202
  }
207
203
  return false;