tla-ts 0.0.3-dev.e927a09 → 0.0.3-dev.e9c5857

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 (47) hide show
  1. package/README.md +5 -1
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +52 -22
  4. package/dist/index.d.ts +52 -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 -17
  11. package/dist/run-cli.js +20 -18
  12. package/dist/transfer.cjs +32 -15
  13. package/dist/transfer.js +32 -15
  14. package/package.json +1 -1
  15. package/src/ast.ts +3 -0
  16. package/src/check.ts +419 -68
  17. package/src/cli-options.ts +11 -5
  18. package/src/codegen.ts +6 -3
  19. package/src/config.ts +224 -170
  20. package/src/environment.ts +106 -18
  21. package/src/errors.ts +71 -3
  22. package/src/evaluate.ts +178 -23
  23. package/src/exit-codes.ts +21 -14
  24. package/src/instances.ts +4 -4
  25. package/src/levels.ts +55 -27
  26. package/src/live-check.ts +132 -70
  27. package/src/liveness.ts +117 -22
  28. package/src/parallel-worker.ts +2 -2
  29. package/src/parallel.ts +5 -2
  30. package/src/parser.ts +21 -10
  31. package/src/resolve.ts +106 -29
  32. package/src/run-cli.ts +90 -17
  33. package/src/runtime.ts +2 -0
  34. package/src/spec-description.ts +12 -6
  35. package/src/standard-modules.ts +10 -9
  36. package/src/state-graph.ts +157 -0
  37. package/src/successors.ts +131 -28
  38. package/src/symmetry.ts +16 -6
  39. package/src/tableau.ts +51 -24
  40. package/src/tlc-ext.ts +27 -2
  41. package/src/tlc-module.ts +14 -33
  42. package/src/tlc-modules.ts +4 -0
  43. package/src/tlc-order.ts +8 -4
  44. package/src/tlc-random.ts +9 -6
  45. package/src/tlc-summary.ts +20 -5
  46. package/src/value-sources.ts +29 -0
  47. package/src/values.ts +172 -53
package/src/successors.ts CHANGED
@@ -4,9 +4,10 @@ import {
4
4
  type Bound,
5
5
  type Definition,
6
6
  type Expression,
7
+ type QuantifierExpression,
7
8
  } from "./ast";
8
9
  import { getReadVariables } from "./dependencies";
9
- import { TlaEvaluationError, UNEXPECTED_EXCEPTION } from "./errors";
10
+ import { TlaEvaluationError, TlaIllegalStateError, TlaIncompleteStateError } from "./errors";
10
11
  import { EXIT_STATUS, setExitCode } from "./exit-codes";
11
12
  import {
12
13
  describeLocation,
@@ -17,6 +18,7 @@ import {
17
18
  bindValue,
18
19
  compileArgumentScope,
19
20
  evaluate,
21
+ getEntryEvaluator,
20
22
  expectBoolean,
21
23
  forEachBinding,
22
24
  getBoundsDomain,
@@ -28,6 +30,7 @@ import {
28
30
  resolveGlobalOperator,
29
31
  type Context,
30
32
  type Environment,
33
+ type Evaluator,
31
34
  type Scope,
32
35
  type State,
33
36
  } from "./evaluate";
@@ -86,25 +89,54 @@ const assign = (partial: State, index: number, value: Value) => {
86
89
  return copy;
87
90
  };
88
91
 
89
- const holds = (expression: Expression, context: Context) => {
90
- const value = evaluate(expression, context);
92
+ // TLC's Tool.getInitStates and Tool.getNextStates report a value where they expect a formula.
93
+ const expectFormula = (expression: Expression, value: Value, isInit: boolean) => {
91
94
  if (typeof value === "boolean") return value;
92
- try {
93
- return expectBoolean(value, `the action at ${describeLocation(expression)}`);
94
- } catch (error) {
95
- // TLC fails with an unexpected exception when the next-state relation isn't a boolean.
96
- throw context.next === undefined ? error : setExitCode(error, EXIT_STATUS.error);
95
+ throw new TlaEvaluationError(
96
+ `In computing ${isInit ? "initial" : "next"} states, TLC expected a boolean expression,\nbut instead found ${formatValue(value)}.\n${describeRange(expression)}`,
97
+ );
98
+ };
99
+
100
+ const holds = (expression: Expression, context: Context, value = evaluate(expression, context)) => {
101
+ // TLC rejects a number in the next-state relation when it splits the relation into actions.
102
+ if (context.next !== undefined && expression.kind === "Number") {
103
+ throw setExitCode(
104
+ new TlaEvaluationError(
105
+ `The next state relation is not a boolean expression.\n${expression.text ?? expression.value}`,
106
+ ),
107
+ EXIT_STATUS.error,
108
+ );
97
109
  }
110
+ return expectFormula(expression, value, context.next === undefined);
98
111
  };
99
112
 
100
113
  const isAssignmentOperator = (operator: string) =>
101
114
  operator === "=" || operator === "\\in" || operator === "\\subseteq";
102
115
 
116
+ const tracedRunners = new WeakMap<Environment, WeakMap<Expression, Runner>[]>();
117
+
118
+ const getRunners = (environment: Environment, isInit: boolean) => {
119
+ if (!environment.trace) return isInit ? initRunners : nextRunners;
120
+ const runners = tracedRunners.get(environment) ?? [new WeakMap(), new WeakMap()];
121
+ tracedRunners.set(environment, runners);
122
+ return runners[isInit ? 0 : 1];
123
+ };
124
+
103
125
  const getRunner = (expression: Expression, environment: Environment, isInit: boolean): Runner => {
104
- const runners = isInit ? initRunners : nextRunners;
126
+ const runners = getRunners(environment, isInit);
105
127
  const cached = runners.get(expression);
106
128
  if (cached) return cached;
107
- const runner = compileAction(expression, environment, isInit);
129
+ const compiled = compileAction(expression, environment, isInit);
130
+ const trace = environment.trace;
131
+ // TLC's CallStackTool keeps an action's expression on the stack while the rest of the action runs.
132
+ const runner: Runner = trace
133
+ ? (run, scope, partial, action, isFixed, onComplete) => {
134
+ const depth = trace.length;
135
+ trace.push(expression);
136
+ compiled(run, scope, partial, action, isFixed, onComplete);
137
+ trace.length = depth;
138
+ }
139
+ : compiled;
108
140
  runners.set(expression, runner);
109
141
  return runner;
110
142
  };
@@ -188,6 +220,23 @@ const getUnchangedIndices = (
188
220
  return getUnchangedIndices(definition.body, environment, visited);
189
221
  };
190
222
 
223
+ // TLC's CallStackTool keeps each expression that UNCHANGED takes apart on the stack.
224
+ const getUnchangedFrames = (expression: Expression, environment: Environment): Expression[] => {
225
+ if (expression.kind === "Tuple") {
226
+ return [
227
+ expression,
228
+ ...expression.elements.flatMap((element) => getUnchangedFrames(element, environment)),
229
+ ];
230
+ }
231
+ const definition =
232
+ expression.kind === "Identifier" && !environment.variableIndex.has(expression.name)
233
+ ? getZeroArityBody(expression.name, environment)
234
+ : undefined;
235
+ return definition
236
+ ? [expression, ...getUnchangedFrames(definition.body, environment)]
237
+ : [expression];
238
+ };
239
+
191
240
  const ACTION_KINDS = new Set([
192
241
  "Label",
193
242
  "And",
@@ -292,12 +341,35 @@ const toConjunct = (
292
341
  return { kind: "Branch", expression, runner: getRunner(expression, environment, isInit) };
293
342
  };
294
343
 
344
+ // The leading guards of `\E x \in S, y \in T : P /\ Q` that read no inner bound hold for every inner
345
+ // binding alike, so they can run once for each element of the outermost bound.
346
+ const getHoistedGuards = (expression: QuantifierExpression, environment: Environment) => {
347
+ if (expression.bounds.length < 2 || expression.body.kind !== "And") return undefined;
348
+ const names = expression.bounds.flatMap((bound) =>
349
+ bound.pattern.kind === "Name" ? [bound.pattern.name] : [],
350
+ );
351
+ if (names.length !== expression.bounds.length) return undefined;
352
+ const innerNames = new Set(names.slice(0, -1));
353
+ const operands = expression.body.operands;
354
+ const index = operands.findIndex((operand) => {
355
+ if (getReadVariables(operand, environment) === undefined) return true;
356
+ if (hasBranches(operand, environment, new Set())) return true;
357
+ const readLocals = getReadLocals(operand, NO_NAMES);
358
+ return !readLocals || readLocals.some((name) => innerNames.has(name));
359
+ });
360
+ const count = index === -1 ? operands.length : index;
361
+ if (count === 0) return undefined;
362
+ return { names, guards: operands.slice(0, count), rest: operands.slice(count) };
363
+ };
364
+
295
365
  const compileConjunction = (
296
366
  operands: Expression[],
297
367
  environment: Environment,
298
368
  isInit: boolean,
299
369
  ): Runner => {
300
370
  const conjuncts = operands.map((operand) => toConjunct(operand, environment, isInit));
371
+ const evaluators: (Evaluator | undefined)[] = conjuncts.map(() => undefined);
372
+ const trace = environment.trace;
301
373
  const runFrom = (
302
374
  start: number,
303
375
  run: Run,
@@ -318,14 +390,25 @@ const compileConjunction = (
318
390
  return;
319
391
  }
320
392
  const conjunct = conjuncts[index];
393
+ if (trace) {
394
+ trace.push(conjunct.expression);
395
+ if (conjunct.expression.kind === "Unchanged") {
396
+ trace.push(...getUnchangedFrames(conjunct.expression.expression, environment));
397
+ }
398
+ }
321
399
  if (conjunct.kind === "Guard") {
322
400
  context ??= getContext(run, scope, current);
323
- if (!holds(conjunct.expression, context)) return;
401
+ const evaluator = (evaluators[index] ??= getEntryEvaluator(
402
+ conjunct.expression,
403
+ environment,
404
+ ));
405
+ if (!holds(conjunct.expression, context, evaluator(context))) return;
324
406
  continue;
325
407
  }
326
408
  if (conjunct.kind === "Assign") {
327
409
  context ??= getContext(run, scope, current);
328
- const value = evaluate(conjunct.value, context);
410
+ const evaluator = (evaluators[index] ??= getEntryEvaluator(conjunct.value, environment));
411
+ const value = evaluator(context);
329
412
  const assigned = current[conjunct.index];
330
413
  if (assigned === undefined) {
331
414
  current = assign(current, conjunct.index, value);
@@ -362,10 +445,7 @@ const compileConjunction = (
362
445
  };
363
446
 
364
447
  const holdsInInit = (expression: Expression, context: Context) =>
365
- expectBoolean(
366
- evaluate(expression, context),
367
- `the initial predicate at ${describeLocation(expression)}`,
368
- );
448
+ expectFormula(expression, evaluate(expression, context), true);
369
449
 
370
450
  const compileGuard =
371
451
  (expression: Expression): Runner =>
@@ -390,7 +470,7 @@ const compileMembership = (
390
470
  expression.operator === "\\subseteq" ? { kind: "Subset", base: evaluated } : evaluated;
391
471
  if (!isEnumerable(value)) {
392
472
  throw new TlaEvaluationError(
393
- `In computing next states, the right side of \\in is not enumerable: ${formatValue(value)} at ${describeLocation(expression)}`,
473
+ `In computing ${run.isInit ? "initial" : "next"} states, the right side of \\IN is not enumerable.\n${describeRange(expression)}`,
394
474
  );
395
475
  }
396
476
  const elements = getStreamedElements(value);
@@ -734,6 +814,34 @@ const compileAction = (
734
814
  }
735
815
  };
736
816
  }
817
+ const hoisted =
818
+ isInit || environment.trace ? undefined : getHoistedGuards(expression, environment);
819
+ if (hoisted) {
820
+ const rest = compileConjunction(hoisted.rest, environment, isInit);
821
+ return (run, scope, partial, action, isFixed, onComplete) => {
822
+ const context = getContext(run, scope, partial);
823
+ const sets = expression.bounds.map((innerBound) =>
824
+ getEnumeratedElements(evaluate(innerBound.set, context), innerBound.set),
825
+ );
826
+ if (sets.some((elements) => elements.length === 0)) return;
827
+ const visit = (index: number, boundScope: Scope | undefined): void => {
828
+ if (index < 0) {
829
+ rest(run, boundScope, partial, action, isFixed, onComplete);
830
+ return;
831
+ }
832
+ for (const element of sets[index]) {
833
+ if (run.isStopped) return;
834
+ const elementScope = bindValue(boundScope, hoisted.names[index], element);
835
+ if (index === sets.length - 1) {
836
+ const guardContext = getContext(run, elementScope, partial);
837
+ if (!hoisted.guards.every((guard) => holds(guard, guardContext))) continue;
838
+ }
839
+ visit(index - 1, elementScope);
840
+ }
841
+ };
842
+ visit(sets.length - 1, scope);
843
+ };
844
+ }
737
845
  return (run, scope, partial, action, isFixed, onComplete) => {
738
846
  forEachBinding(expression.bounds, getContext(run, scope, partial), (boundScope) => {
739
847
  body(run, boundScope, partial, action, isFixed, onComplete);
@@ -810,7 +918,7 @@ const compileAction = (
810
918
  const body = arm?.body ?? other;
811
919
  if (!body)
812
920
  throw new TlaEvaluationError(
813
- `${UNEXPECTED_EXCEPTION}In computing next states, TLC encountered a CASE with no conditions true.\n${describeRange(expression)}`,
921
+ `In computing ${run.isInit ? "initial" : "next"} states, TLC encountered a CASE with no conditions true.\n${describeRange(expression)}`,
814
922
  );
815
923
  body(run, scope, partial, action, isFixed, onComplete);
816
924
  };
@@ -951,14 +1059,7 @@ export const forEachInitialState = (
951
1059
  (partial) => {
952
1060
  if (run.isStopped) return;
953
1061
  if (!isComplete(partial)) {
954
- // TLC reports an initial state that isn't completely specified as an illegal state, not as
955
- // an evaluation failure.
956
- throw setExitCode(
957
- new TlaEvaluationError(
958
- `The initial predicate does not assign ${getMissingVariables(partial, environment).join(", ")}`,
959
- ),
960
- EXIT_STATUS.error,
961
- );
1062
+ throw setExitCode(new TlaIllegalStateError(partial), EXIT_STATUS.error);
962
1063
  }
963
1064
  run.isStopped = onState(partial);
964
1065
  },
@@ -1001,8 +1102,10 @@ export const forEachSuccessor = (
1001
1102
  (partial, action) => {
1002
1103
  if (run.isStopped) return;
1003
1104
  if (!isComplete(partial)) {
1004
- throw new TlaEvaluationError(
1005
- `Successor state is not completely specified by action ${action ?? "Next"}. The following variables are not assigned: ${getMissingVariables(partial, environment).join(", ")}`,
1105
+ throw new TlaIncompleteStateError(
1106
+ partial,
1107
+ action,
1108
+ getMissingVariables(partial, environment).sort(),
1006
1109
  );
1007
1110
  }
1008
1111
  counter.successors++;
package/src/symmetry.ts CHANGED
@@ -1,5 +1,6 @@
1
- import { TlaConfigError } from "./errors";
1
+ import { TlaConfigError, TlaEvaluationError, UNEXPECTED_EXCEPTION } from "./errors";
2
2
  import { evaluate, type Environment } from "./evaluate";
3
+ import { EXIT_STATUS, setExitCode } from "./exit-codes";
3
4
  import {
4
5
  compareValues,
5
6
  createFunction,
@@ -47,9 +48,13 @@ const composePermutations = (first: Images, second: Images) => {
47
48
  return composed;
48
49
  };
49
50
 
50
- const toImages = (value: Value, name: string) => {
51
+ // TLC checks the symmetry set outside any phase that reports an error itself.
52
+ const createSymmetryError = (message: string) =>
53
+ setExitCode(new TlaEvaluationError(`${UNEXPECTED_EXCEPTION}${message}`), EXIT_STATUS.error);
54
+
55
+ const toImages = (value: Value) => {
51
56
  if (!isFunctionValue(value)) {
52
- throw new TlaConfigError(`The symmetry values of ${name} must be functions`);
57
+ throw createSymmetryError("The symmetry values must be function records.");
53
58
  }
54
59
  const functionValue = toFiniteFunction(value);
55
60
  const permutation: Images = new Map();
@@ -65,8 +70,13 @@ const toImages = (value: Value, name: string) => {
65
70
 
66
71
  export const getSymmetryGroup = (name: string, environment: Environment): Permutation[] => {
67
72
  const definition = environment.definitions.get(name);
73
+ if (definition === undefined && !environment.constants.has(name)) {
74
+ throw new TlaConfigError(
75
+ `The symmetry function ${name} specified in the configuration file\nis not defined in the specification.`,
76
+ );
77
+ }
68
78
  if (definition?.kind !== "Operator" || definition.params.length > 0) {
69
- throw new TlaConfigError(`The symmetry function ${name} must specify a set of permutations`);
79
+ throw createSymmetryError(`The symmetry function ${name} must specify a set of permutations.`);
70
80
  }
71
81
  const value = evaluate(definition.body, {
72
82
  environment,
@@ -75,9 +85,9 @@ export const getSymmetryGroup = (name: string, environment: Environment): Permut
75
85
  next: undefined,
76
86
  });
77
87
  if (!isSetValue(value) || !isEnumerable(value)) {
78
- throw new TlaConfigError("The symmetry operator must specify a set of functions");
88
+ throw createSymmetryError("The symmetry operator must specify a set of functions.");
79
89
  }
80
- const permutations = toFiniteSet(value).elements.map((element) => toImages(element, name));
90
+ const permutations = toFiniteSet(value).elements.map(toImages);
81
91
  const isDisabled =
82
92
  definition.body.kind === "Apply" && definition.body.args.length >= permutations.length;
83
93
  if (isDisabled) return [];
package/src/tableau.ts CHANGED
@@ -162,22 +162,39 @@ const containsAction = (expression: LiveExpression): boolean => {
162
162
  }
163
163
  };
164
164
 
165
- const isEqual = (left: LiveExpression, right: LiveExpression): boolean => {
166
- if (left.kind !== right.kind) return false;
167
- if (left.kind === "Boolean" && right.kind === "Boolean") return left.value === right.value;
168
- if (isAtom(left)) return left === right;
169
- if ("body" in left && "body" in right) return isEqual(left.body, right.body);
170
- if ("operands" in left && "operands" in right) {
171
- return (
172
- left.operands.length === right.operands.length &&
173
- left.operands.every((operand, index) => isEqual(operand, right.operands[index]))
174
- );
175
- }
176
- return false;
165
+ const termKeys = new WeakMap<LiveExpression, string>();
166
+ const atoms = { count: 0 };
167
+
168
+ // A term's structure as a string in which each atom stands for itself, so equal terms share a key.
169
+ export const getTermKey = (expression: LiveExpression): string => {
170
+ const cached = termKeys.get(expression);
171
+ if (cached !== undefined) return cached;
172
+ const key = (() => {
173
+ switch (expression.kind) {
174
+ case "Boolean":
175
+ return String(expression.value);
176
+ case "State":
177
+ case "Enabled":
178
+ case "Action":
179
+ return `#${atoms.count++}`;
180
+ case "And":
181
+ case "Or":
182
+ return `${expression.kind}(${expression.operands.map(getTermKey).join(",")})`;
183
+ default:
184
+ return `${expression.kind}(${getTermKey(expression.body)})`;
185
+ }
186
+ })();
187
+ termKeys.set(expression, key);
188
+ return key;
177
189
  };
178
190
 
179
- const isMember = (items: LiveExpression[], expression: LiveExpression) =>
180
- items.some((item) => isEqual(item, expression));
191
+ const isEqual = (left: LiveExpression, right: LiveExpression) =>
192
+ left === right || getTermKey(left) === getTermKey(right);
193
+
194
+ const isMember = (items: LiveExpression[], expression: LiveExpression) => {
195
+ const key = getTermKey(expression);
196
+ return items.some((item) => item === expression || getTermKey(item) === key);
197
+ };
181
198
 
182
199
  const getDual = (kind: LiveJunction["kind"]) => (kind === "And" ? "Or" : "And");
183
200
 
@@ -272,7 +289,7 @@ const toDisjunctiveNormalForm = (expression: LiveExpression): LiveExpression =>
272
289
  total.value *= normal.operands.length;
273
290
  if (total.value > MAXIMUM_DISJUNCTS) {
274
291
  throw new TlaEvaluationError(
275
- "TLC cannot handle the temporal formula because it exceeds the maximum supported size in disjunctive normal form",
292
+ "TLC cannot handle the temporal formula because it exceeds the maximum supported size in disjunctive normal form.",
276
293
  );
277
294
  }
278
295
  }
@@ -446,13 +463,14 @@ const getTriples = (
446
463
  return parts ? [{ whole: term, first: parts.first, second: parts.second }] : [];
447
464
  });
448
465
 
449
- const isSameParticle = (left: LiveExpression[], right: LiveExpression[]) =>
450
- left.every((term) => isMember(right, term)) && right.every((term) => isMember(left, term));
466
+ // A particle is a set of terms, so its key ignores order and repeats.
467
+ const getParticleKey = (particle: LiveExpression[]) =>
468
+ [...new Set(particle.map(getTermKey))].sort().join("|");
451
469
 
452
- const unionParticles = (left: LiveExpression[][], right: LiveExpression[][]) => [
453
- ...left.filter((particle) => !right.some((other) => isSameParticle(particle, other))),
454
- ...right,
455
- ];
470
+ const unionParticles = (left: LiveExpression[][], right: LiveExpression[][]) => {
471
+ const rightKeys = new Set(right.map(getParticleKey));
472
+ return [...left.filter((particle) => !rightKeys.has(getParticleKey(particle))), ...right];
473
+ };
456
474
 
457
475
  const getParticleClosure = (terms: LiveExpression[]) => {
458
476
  const closure = getPositiveClosure(terms);
@@ -516,14 +534,23 @@ const createTableauNode = (particle: LiveExpression[]): TableauNode => ({
516
534
  const createTableau = (formula: LiveExpression) => {
517
535
  const nodes = getParticleClosure([formula]).map(createTableauNode);
518
536
  const initialCount = nodes.length;
537
+ const indices = new Map<string, number>();
538
+ nodes.forEach((node, index) => {
539
+ const key = getParticleKey(node.particle);
540
+ if (!indices.has(key)) indices.set(key, index);
541
+ });
519
542
  for (let index = 0; index < nodes.length; index++) {
520
543
  const implied = nodes[index].particle.flatMap((term) =>
521
544
  term.kind === "Next" ? [term.body] : [],
522
545
  );
523
546
  for (const particle of getParticleClosure(implied)) {
524
- const existing = nodes.findIndex((node) => isSameParticle(node.particle, particle));
525
- if (existing === -1) nodes.push(createTableauNode(particle));
526
- nodes[index].successors.push(existing === -1 ? nodes.length - 1 : existing);
547
+ const key = getParticleKey(particle);
548
+ const existing = indices.get(key);
549
+ if (existing === undefined) {
550
+ indices.set(key, nodes.length);
551
+ nodes.push(createTableauNode(particle));
552
+ }
553
+ nodes[index].successors.push(existing ?? nodes.length - 1);
527
554
  }
528
555
  }
529
556
  return { nodes, initialCount };
package/src/tlc-ext.ts CHANGED
@@ -103,15 +103,35 @@ const getRegister = (runtime: CheckerRuntime, key: Value) => {
103
103
  return undefined;
104
104
  };
105
105
 
106
- 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
+ ) => {
107
113
  if (typeof key === "number" && key >= 0) {
108
114
  runtime.registers.set(key, value);
109
115
  return;
110
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
+ }
111
127
  if (typeof key === "string" && key.startsWith(NAMED_REGISTER_PREFIX)) {
112
128
  runtime.namedRegisters.set(key, value);
113
129
  return;
114
130
  }
131
+ if (typeof key === "string" && key.startsWith("-D")) {
132
+ runtime.properties.set(key.slice(2), formatValue(value));
133
+ return;
134
+ }
115
135
  throw new TlaModuleError(
116
136
  `The first argument of TLCSet should be a nonnegative integer, but instead it is:\n${formatValue(key)}`,
117
137
  );
@@ -195,7 +215,12 @@ export const createTlcExtOperators = (
195
215
  const key = getValue(args, 0, "TLCGetAndSet");
196
216
  const previous = getRegister(runtime, key) ?? getValue(args, 3, "TLCGetAndSet");
197
217
  const update = getOperator(args, 1, "TLCGetAndSet");
198
- 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
+ );
199
224
  return previous;
200
225
  }),
201
226
  isStateLevel: true,
package/src/tlc-module.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { TlaModuleError } from "./errors";
1
+ import { TlaEvaluationError, TlaModuleError } from "./errors";
2
2
  import { EXIT_STATUS } from "./exit-codes";
3
3
  import type { Builtin } from "./evaluate";
4
4
  import { prettyPrint } from "./pretty-print";
@@ -15,7 +15,7 @@ import {
15
15
  getValue,
16
16
  } from "./builtins";
17
17
  import { getNamedRegisters, NAMED_REGISTER_PREFIX, type CheckerRuntime } from "./runtime";
18
- import { createActionRecord } from "./tlc-ext";
18
+ import { createActionRecord, setTlcValue } from "./tlc-ext";
19
19
  import { getRandomElement } from "./tlc-random";
20
20
  import {
21
21
  ANY_SET,
@@ -39,11 +39,17 @@ const formatCalendarVersion = (date: Date) =>
39
39
  const getRegisterFunction = <Key extends Value>(registers: Map<Key, Value>) =>
40
40
  createFunction([...registers].map(([key, value]): [Value, Value] => [key, createTuple([value])]));
41
41
 
42
+ // TLC creates its model checker after it processes the spec, so these are undefined before then.
43
+ const CHECKER_KEYS = new Set(["diameter", "generated", "distinct", "queue", "stats", "config"]);
44
+
42
45
  const getRuntimeValue = (
43
46
  runtime: CheckerRuntime,
44
47
  key: string,
45
48
  state: (Value | undefined)[] | undefined,
46
49
  ) => {
50
+ if (!runtime.isStarted && CHECKER_KEYS.has(key)) {
51
+ throw new TlaEvaluationError(`TLCGet(${key}) was undefined.`);
52
+ }
47
53
  const duration = Math.floor((Date.now() - runtime.startedAt) / 1000);
48
54
  switch (key) {
49
55
  case "level":
@@ -98,11 +104,11 @@ const getRuntimeValue = (
98
104
  }
99
105
  if (key.startsWith(NAMED_REGISTER_PREFIX)) {
100
106
  const value = getNamedRegisters(runtime).get(key);
101
- if (value === undefined) throw new TlaModuleError(`TLCGet(${key}) was undefined.`);
107
+ if (value === undefined) throw new TlaEvaluationError(`TLCGet(${key}) was undefined.`);
102
108
  return value;
103
109
  }
104
110
  if (key.startsWith("-D")) return rankString(runtime.properties.get(key.slice(2)) ?? key);
105
- throw new TlaModuleError(`TLCGet(${key}) was undefined.`);
111
+ throw new TlaEvaluationError(`TLCGet(${key}) was undefined.`);
106
112
  };
107
113
 
108
114
  const getPermutations = (elements: Value[]): Value[][] =>
@@ -191,11 +197,11 @@ export const createTlcOperators = (
191
197
  const key = getValue(args, 0, "TLCGet");
192
198
  if (typeof key === "number" && key >= 0) {
193
199
  const value = runtime.registers.get(key);
194
- if (value === undefined) throw new TlaModuleError(`TLCGet(${key}) was undefined.`);
200
+ if (value === undefined) throw new TlaEvaluationError(`TLCGet(${key}) was undefined.`);
195
201
  return value;
196
202
  }
197
203
  if (typeof key !== "string") {
198
- throw new TlaModuleError(
204
+ throw new TlaEvaluationError(
199
205
  `The argument of TLCGet should be a nonnegative integer, but instead it is:\n${formatValue(key)}`,
200
206
  );
201
207
  }
@@ -203,33 +209,8 @@ export const createTlcOperators = (
203
209
  }),
204
210
  defineStateOperator("TLCSet", 2, (args) => {
205
211
  const key = getValue(args, 0, "TLCSet");
206
- const value = getValue(args, 1, "TLCSet");
207
- if (typeof key === "number" && key >= 0) {
208
- runtime.registers.set(key, value);
209
- return true;
210
- }
211
- if (key === "exit") {
212
- if (value === true) runtime.isStopped = true;
213
- return true;
214
- }
215
- if (key === "pause") {
216
- if (value === true) {
217
- print("Press enter to resume model checking.");
218
- runtime.pause();
219
- }
220
- return true;
221
- }
222
- if (typeof key === "string" && key.startsWith(NAMED_REGISTER_PREFIX)) {
223
- runtime.namedRegisters.set(key, value);
224
- return true;
225
- }
226
- if (typeof key === "string" && key.startsWith("-D")) {
227
- runtime.properties.set(key.slice(2), formatValue(value));
228
- return true;
229
- }
230
- throw new TlaModuleError(
231
- `The first argument of TLCSet should be a nonnegative integer, but instead it is:\n${formatValue(key)}`,
232
- );
212
+ setTlcValue(runtime, print, key, getValue(args, 1, "TLCSet"));
213
+ return true;
233
214
  }),
234
215
  defineConstant("Any", ANY_SET),
235
216
  defineOperator("RandomElement", 1, (args) =>
@@ -1013,6 +1013,10 @@ export const TLC_JAVA_METHODS = new Map([
1013
1013
  "RandomElement",
1014
1014
  "public static tlc2.value.impl.Value tlc2.module.TLC.RandomElement(tlc2.value.impl.Value)",
1015
1015
  ],
1016
+ [
1017
+ "TLCGet",
1018
+ "public static tlc2.value.impl.Value tlc2.module.TLCGetSet.TLCGetEval(tlc2.tool.impl.Tool,tla2sany.semantic.ExprOrOpArgNode[],tlc2.util.Context,tlc2.tool.TLCState,tlc2.tool.TLCState,int,tlc2.tool.coverage.CostModel)",
1019
+ ],
1016
1020
  [
1017
1021
  "TLCEval",
1018
1022
  "public static tlc2.value.impl.Value tlc2.module.TLCEval.tlcEval(tlc2.tool.impl.Tool,tla2sany.semantic.ExprOrOpArgNode[],tlc2.util.Context,tlc2.tool.TLCState,tlc2.tool.TLCState,int,tlc2.tool.coverage.CostModel)",
package/src/tlc-order.ts CHANGED
@@ -278,9 +278,13 @@ const createModuleSet = (source: string, loadModule: ModuleLoader) => {
278
278
  (name === undefined ? undefined : nestedModules.get(name)) ?? getFile(name);
279
279
  };
280
280
 
281
- // The variables in the order TLC compares them: the reverse of the root module's context
282
- // enumeration, as ModuleNode.getVariableDecls returns them.
283
- export const getTlcVariableOrder = (source: string, loadModule: ModuleLoader): string[] => {
281
+ // The constants or variables in the order of ModuleNode.getConstantDecls or getVariableDecls: the
282
+ // reverse of the root module's context enumeration. TLC compares a state's variables in this order.
283
+ export const getTlcDeclarationOrder = (
284
+ source: string,
285
+ loadModule: ModuleLoader,
286
+ kind: "constant" | "variable",
287
+ ): string[] => {
284
288
  const getParsed = createModuleSet(source, loadModule);
285
289
  const getUnits = (unit: ParsedModule) => {
286
290
  const tokens = unit.tokens;
@@ -400,7 +404,7 @@ export const getTlcVariableOrder = (source: string, loadModule: ModuleLoader): s
400
404
  };
401
405
  return getContext(undefined)
402
406
  .enumerate()
403
- .filter((entry) => entry.kind === "variable")
407
+ .filter((entry) => entry.kind === kind)
404
408
  .map((entry) => entry.name)
405
409
  .reverse();
406
410
  };
package/src/tlc-random.ts CHANGED
@@ -181,8 +181,10 @@ const createShiftTable = (length: number) => {
181
181
 
182
182
  // Extending a fingerprint by a byte is linear over GF(2), so extending it by a value's bytes
183
183
  // XORs the value's own fingerprint from zero into the fingerprint shifted by their length.
184
- // The fingerprinter caches each distinct variable value for one pass over the stored states.
185
- export const createTlcFingerprinter = () => {
184
+ // The fingerprinter caches each distinct variable value for one pass over the stored states. It
185
+ // reads a state's variables in `order` and writes each fingerprint's low and high words into
186
+ // `words`, an Int32Array over a little-endian BigInt64Array.
187
+ export const createTlcFingerprinter = (order: number[], words: Int32Array) => {
186
188
  const shiftTables = new Map<number, Int32Array>();
187
189
  const indices = new Map<Value, number>();
188
190
  const contributions: number[] = [];
@@ -204,11 +206,11 @@ export const createTlcFingerprinter = () => {
204
206
  shiftTables.set(length, table);
205
207
  return table;
206
208
  };
207
- return (state: Value[]) => {
209
+ return (state: Value[], position: number) => {
208
210
  const outer = { high, low };
209
211
  const fingerprint = { high: INITIAL_HIGH, low: INITIAL_LOW };
210
- for (const value of state) {
211
- const contribution = getContribution(value);
212
+ for (const index of order) {
213
+ const contribution = getContribution(state[index]);
212
214
  const table = getShiftTable(contributions[contribution]);
213
215
  const extended = {
214
216
  high: contributions[contribution + 1],
@@ -225,7 +227,8 @@ export const createTlcFingerprinter = () => {
225
227
  }
226
228
  high = outer.high;
227
229
  low = outer.low;
228
- return (BigInt(fingerprint.high >>> 0) << 32n) | BigInt(fingerprint.low >>> 0);
230
+ words[2 * position] = fingerprint.low;
231
+ words[2 * position + 1] = fingerprint.high;
229
232
  };
230
233
  };
231
234