tla-ts 0.0.3-dev.f362080 → 0.0.3-dev.fac17cc

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 (81) 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 +149 -8
  5. package/dist/index.d.ts +149 -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 +56 -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 +1348 -227
  22. package/src/cli.ts +8 -1
  23. package/src/codegen.ts +68 -21
  24. package/src/config.ts +252 -179
  25. package/src/environment.ts +431 -120
  26. package/src/errors.ts +210 -5
  27. package/src/evaluate.ts +716 -136
  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 +32 -4
  34. package/src/live-check.ts +204 -146
  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 +6 -1
  39. package/src/parallel.ts +57 -6
  40. package/src/parser.ts +425 -144
  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 +1408 -400
  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 +168 -50
  70. package/src/tableau.ts +3 -1
  71. package/src/tlc-ext.ts +13 -17
  72. package/src/tlc-messages.ts +329 -0
  73. package/src/tlc-module.ts +49 -21
  74. package/src/tlc-modules.ts +0 -4
  75. package/src/tlc-order.ts +55 -9
  76. package/src/tlc-random.ts +28 -3
  77. package/src/tlc-replay.ts +655 -0
  78. package/src/tlc-version.ts +18 -0
  79. package/src/transfer.ts +15 -3
  80. package/src/value-sources.ts +29 -0
  81. package/src/values.ts +683 -256
package/src/symmetry.ts CHANGED
@@ -1,6 +1,9 @@
1
+ import type { Expression } from "./ast";
2
+ import type { Substitution } from "./config";
1
3
  import { TlaConfigError, TlaEvaluationError, UNEXPECTED_EXCEPTION } from "./errors";
2
- import { evaluate, type Environment } from "./evaluate";
3
4
  import { EXIT_STATUS, setExitCode } from "./exit-codes";
5
+ import { MESSAGE_CODE } from "./tlc-messages";
6
+ import { evaluate, type Environment } from "./evaluate";
4
7
  import {
5
8
  compareValues,
6
9
  createFunction,
@@ -31,6 +34,20 @@ interface Permutation {
31
34
  cacheLimit: number;
32
35
  }
33
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
+
34
51
  const getPermutationKey = (permutation: Images) =>
35
52
  [...permutation]
36
53
  .map(([name, image]) => `${name}>${image.name}`)
@@ -48,27 +65,46 @@ const composePermutations = (first: Images, second: Images) => {
48
65
  return composed;
49
66
  };
50
67
 
51
- // TLC checks the symmetry set outside any phase that reports an error itself.
68
+ // Tool#getSymmetryPerms fails with a RuntimeException as TLC starts, which TLC reports as one it
69
+ // did not expect.
52
70
  const createSymmetryError = (message: string) =>
53
71
  setExitCode(new TlaEvaluationError(`${UNEXPECTED_EXCEPTION}${message}`), EXIT_STATUS.error);
54
72
 
55
73
  const toImages = (value: Value) => {
56
- if (!isFunctionValue(value)) {
57
- throw createSymmetryError("The symmetry values must be function records.");
58
- }
59
74
  const functionValue = toFiniteFunction(value);
60
75
  const permutation: Images = new Map();
61
76
  functionValue.domain.forEach((key, index) => {
62
77
  const image = functionValue.range[index];
63
78
  if (!isModelValue(key) || !isModelValue(image)) {
64
- 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.");
65
80
  }
66
81
  if (key.name !== image.name) permutation.set(key.name, image);
67
82
  });
68
83
  return permutation;
69
84
  };
70
85
 
71
- 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 => {
72
108
  const definition = environment.definitions.get(name);
73
109
  if (definition === undefined && !environment.constants.has(name)) {
74
110
  throw new TlaConfigError(
@@ -78,19 +114,41 @@ export const getSymmetryGroup = (name: string, environment: Environment): Permut
78
114
  if (definition?.kind !== "Operator" || definition.params.length > 0) {
79
115
  throw createSymmetryError(`The symmetry function ${name} must specify a set of permutations.`);
80
116
  }
81
- const value = evaluate(definition.body, {
82
- environment,
83
- scope: undefined,
84
- state: undefined,
85
- next: undefined,
86
- });
117
+ const evaluateConstant = (expression: Expression) =>
118
+ evaluate(expression, { environment, scope: undefined, state: undefined, next: undefined });
119
+ const value = evaluateConstant(definition.body);
87
120
  if (!isSetValue(value) || !isEnumerable(value)) {
88
121
  throw createSymmetryError("The symmetry operator must specify a set of functions.");
89
122
  }
90
- const permutations = toFiniteSet(value).elements.map(toImages);
91
- const isDisabled =
92
- definition.body.kind === "Apply" && definition.body.args.length >= permutations.length;
93
- if (isDisabled) return [];
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;
151
+ }
94
152
  const group = new Map<string, Images>();
95
153
  permutations.forEach((permutation) => {
96
154
  if (permutation.size > 0) group.set(getPermutationKey(permutation), permutation);
@@ -109,13 +167,38 @@ export const getSymmetryGroup = (name: string, environment: Environment): Permut
109
167
  );
110
168
  frontier.start = end;
111
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;
112
190
  const cacheLimit = Math.max(256, Math.floor(CACHE_LIMIT / group.size));
113
- return [...group.values()].map((images) => ({
114
- images,
115
- cache: new WeakMap<ObjectValue, Value>(),
116
- cacheSize: 0,
117
- cacheLimit,
118
- }));
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
+ };
119
202
  };
120
203
 
121
204
  const permuteElements = (elements: Value[], permutation: Permutation) => {
@@ -218,41 +301,76 @@ const computePermutedValue = (value: ObjectValue, permutation: Permutation) => {
218
301
  return elements ? createSet(elements) : set;
219
302
  };
220
303
 
221
- const permuteRemaining = (state: Value[], permuted: Value[], permutation: Permutation) => {
222
- for (let index = permuted.length; index < state.length; index++) {
223
- 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;
224
310
  }
225
- 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;
226
341
  };
227
342
 
228
- const getSmallerPermutation = (
343
+ const isSmallerImage = (
229
344
  state: Value[],
230
- minimum: Value[],
231
- permutation: Permutation,
232
- order: number[] | undefined,
345
+ permutation: number,
346
+ minimum: number,
347
+ group: SymmetryGroup,
348
+ order: number[],
233
349
  ) => {
234
- const permuted: Value[] = [];
235
- for (let position = 0; position < state.length; position++) {
236
- const index = order ? order[position] : position;
237
- const value = permuteValue(state[index], permutation);
238
- const comparison = compareValues(value, minimum[index]);
239
- if (comparison > 0) return undefined;
240
- if (!order) permuted.push(value);
241
- if (comparison < 0) {
242
- return order
243
- ? state.map((item) => permuteValue(item, permutation))
244
- : permuteRemaining(state, permuted, permutation);
245
- }
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;
246
355
  }
247
- return undefined;
356
+ return false;
248
357
  };
249
358
 
359
+ // TLC keeps the smallest image of the state in its variable order, replacing it only with a
360
+ // strictly smaller one.
250
361
  export const getRepresentative = (
251
362
  state: Value[],
252
- group: Permutation[],
253
- order?: number[],
254
- ): Value[] =>
255
- group.reduce(
256
- (minimum, permutation) => getSmallerPermutation(state, minimum, permutation, order) ?? minimum,
257
- 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,
258
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
@@ -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;