tla-ts 0.0.3-dev.30014f9 → 0.0.3-dev.3082068

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 (48) hide show
  1. package/README.md +5 -1
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +48 -22
  4. package/dist/index.d.ts +48 -22
  5. package/dist/index.js +1 -1
  6. package/dist/parallel-worker.cjs +1 -1
  7. package/dist/parallel-worker.js +2 -2
  8. package/dist/parallel.cjs +1 -1
  9. package/dist/parallel.js +2 -2
  10. package/dist/run-cli.cjs +19 -16
  11. package/dist/run-cli.js +20 -17
  12. package/dist/transfer.cjs +36 -15
  13. package/dist/transfer.js +36 -15
  14. package/package.json +1 -1
  15. package/src/ast.ts +93 -0
  16. package/src/check.ts +452 -98
  17. package/src/cli-options.ts +11 -5
  18. package/src/codegen.ts +15 -22
  19. package/src/config.ts +224 -170
  20. package/src/dependencies.ts +2 -2
  21. package/src/environment.ts +116 -28
  22. package/src/errors.ts +76 -3
  23. package/src/evaluate.ts +163 -156
  24. package/src/exit-codes.ts +39 -42
  25. package/src/instances.ts +16 -15
  26. package/src/levels.ts +62 -34
  27. package/src/live-check.ts +772 -0
  28. package/src/liveness.ts +120 -543
  29. package/src/parallel-worker.ts +2 -2
  30. package/src/parallel.ts +5 -2
  31. package/src/parser.ts +21 -10
  32. package/src/resolve.ts +122 -44
  33. package/src/run-cli.ts +92 -19
  34. package/src/runtime.ts +3 -1
  35. package/src/spec-description.ts +19 -8
  36. package/src/standard-modules.ts +9 -8
  37. package/src/state-graph.ts +157 -0
  38. package/src/subexpressions.ts +10 -10
  39. package/src/successors.ts +146 -35
  40. package/src/symmetry.ts +16 -6
  41. package/src/tableau.ts +51 -24
  42. package/src/tlc-ext.ts +29 -12
  43. package/src/tlc-module.ts +14 -33
  44. package/src/tlc-modules.ts +4 -0
  45. package/src/tlc-order.ts +8 -4
  46. package/src/tlc-random.ts +9 -6
  47. package/src/tlc-summary.ts +20 -5
  48. package/src/values.ts +124 -21
package/src/tableau.ts CHANGED
@@ -162,22 +162,39 @@ const containsAction = (expression: LiveExpression): boolean => {
162
162
  }
163
163
  };
164
164
 
165
- const isEqual = (left: LiveExpression, right: LiveExpression): boolean => {
166
- if (left.kind !== right.kind) return false;
167
- if (left.kind === "Boolean" && right.kind === "Boolean") return left.value === right.value;
168
- if (isAtom(left)) return left === right;
169
- if ("body" in left && "body" in right) return isEqual(left.body, right.body);
170
- if ("operands" in left && "operands" in right) {
171
- return (
172
- left.operands.length === right.operands.length &&
173
- left.operands.every((operand, index) => isEqual(operand, right.operands[index]))
174
- );
175
- }
176
- return false;
165
+ const termKeys = new WeakMap<LiveExpression, string>();
166
+ const atoms = { count: 0 };
167
+
168
+ // A term's structure as a string in which each atom stands for itself, so equal terms share a key.
169
+ export const getTermKey = (expression: LiveExpression): string => {
170
+ const cached = termKeys.get(expression);
171
+ if (cached !== undefined) return cached;
172
+ const key = (() => {
173
+ switch (expression.kind) {
174
+ case "Boolean":
175
+ return String(expression.value);
176
+ case "State":
177
+ case "Enabled":
178
+ case "Action":
179
+ return `#${atoms.count++}`;
180
+ case "And":
181
+ case "Or":
182
+ return `${expression.kind}(${expression.operands.map(getTermKey).join(",")})`;
183
+ default:
184
+ return `${expression.kind}(${getTermKey(expression.body)})`;
185
+ }
186
+ })();
187
+ termKeys.set(expression, key);
188
+ return key;
177
189
  };
178
190
 
179
- const isMember = (items: LiveExpression[], expression: LiveExpression) =>
180
- items.some((item) => isEqual(item, expression));
191
+ const isEqual = (left: LiveExpression, right: LiveExpression) =>
192
+ left === right || getTermKey(left) === getTermKey(right);
193
+
194
+ const isMember = (items: LiveExpression[], expression: LiveExpression) => {
195
+ const key = getTermKey(expression);
196
+ return items.some((item) => item === expression || getTermKey(item) === key);
197
+ };
181
198
 
182
199
  const getDual = (kind: LiveJunction["kind"]) => (kind === "And" ? "Or" : "And");
183
200
 
@@ -272,7 +289,7 @@ const toDisjunctiveNormalForm = (expression: LiveExpression): LiveExpression =>
272
289
  total.value *= normal.operands.length;
273
290
  if (total.value > MAXIMUM_DISJUNCTS) {
274
291
  throw new TlaEvaluationError(
275
- "TLC cannot handle the temporal formula because it exceeds the maximum supported size in disjunctive normal form",
292
+ "TLC cannot handle the temporal formula because it exceeds the maximum supported size in disjunctive normal form.",
276
293
  );
277
294
  }
278
295
  }
@@ -446,13 +463,14 @@ const getTriples = (
446
463
  return parts ? [{ whole: term, first: parts.first, second: parts.second }] : [];
447
464
  });
448
465
 
449
- const isSameParticle = (left: LiveExpression[], right: LiveExpression[]) =>
450
- left.every((term) => isMember(right, term)) && right.every((term) => isMember(left, term));
466
+ // A particle is a set of terms, so its key ignores order and repeats.
467
+ const getParticleKey = (particle: LiveExpression[]) =>
468
+ [...new Set(particle.map(getTermKey))].sort().join("|");
451
469
 
452
- const unionParticles = (left: LiveExpression[][], right: LiveExpression[][]) => [
453
- ...left.filter((particle) => !right.some((other) => isSameParticle(particle, other))),
454
- ...right,
455
- ];
470
+ const unionParticles = (left: LiveExpression[][], right: LiveExpression[][]) => {
471
+ const rightKeys = new Set(right.map(getParticleKey));
472
+ return [...left.filter((particle) => !rightKeys.has(getParticleKey(particle))), ...right];
473
+ };
456
474
 
457
475
  const getParticleClosure = (terms: LiveExpression[]) => {
458
476
  const closure = getPositiveClosure(terms);
@@ -516,14 +534,23 @@ const createTableauNode = (particle: LiveExpression[]): TableauNode => ({
516
534
  const createTableau = (formula: LiveExpression) => {
517
535
  const nodes = getParticleClosure([formula]).map(createTableauNode);
518
536
  const initialCount = nodes.length;
537
+ const indices = new Map<string, number>();
538
+ nodes.forEach((node, index) => {
539
+ const key = getParticleKey(node.particle);
540
+ if (!indices.has(key)) indices.set(key, index);
541
+ });
519
542
  for (let index = 0; index < nodes.length; index++) {
520
543
  const implied = nodes[index].particle.flatMap((term) =>
521
544
  term.kind === "Next" ? [term.body] : [],
522
545
  );
523
546
  for (const particle of getParticleClosure(implied)) {
524
- const existing = nodes.findIndex((node) => isSameParticle(node.particle, particle));
525
- if (existing === -1) nodes.push(createTableauNode(particle));
526
- nodes[index].successors.push(existing === -1 ? nodes.length - 1 : existing);
547
+ const key = getParticleKey(particle);
548
+ const existing = indices.get(key);
549
+ if (existing === undefined) {
550
+ indices.set(key, nodes.length);
551
+ nodes.push(createTableauNode(particle));
552
+ }
553
+ nodes[index].successors.push(existing ?? nodes.length - 1);
527
554
  }
528
555
  }
529
556
  return { nodes, initialCount };
package/src/tlc-ext.ts CHANGED
@@ -10,16 +10,8 @@ import {
10
10
  } from "./builtins";
11
11
  import { TlaEvaluationError, TlaModuleError, TlaUnsupportedError } from "./errors";
12
12
  import { getTlcFingerprint } from "./tlc-random";
13
- import {
14
- evaluate,
15
- expectBoolean,
16
- getChildren,
17
- getDefinition,
18
- isLocallyResolved,
19
- type Builtin,
20
- type Environment,
21
- } from "./evaluate";
22
- import type { Definition, Expression } from "./ast";
13
+ import { evaluate, expectBoolean, getDefinition, type Builtin, type Environment } from "./evaluate";
14
+ import { getChildren, isLocallyResolved, type Definition, type Expression } from "./ast";
23
15
  import type { TraceStep } from "./check";
24
16
  import {
25
17
  getNamedRegisters,
@@ -111,15 +103,35 @@ const getRegister = (runtime: CheckerRuntime, key: Value) => {
111
103
  return undefined;
112
104
  };
113
105
 
114
- const setRegister = (runtime: CheckerRuntime, key: Value, value: Value) => {
106
+ // TLC's TLCSet. TLCExt's TLCGetAndSet is a TLA+ definition that calls it.
107
+ export const setTlcValue = (
108
+ runtime: CheckerRuntime,
109
+ print: (text: string) => void,
110
+ key: Value,
111
+ value: Value,
112
+ ) => {
115
113
  if (typeof key === "number" && key >= 0) {
116
114
  runtime.registers.set(key, value);
117
115
  return;
118
116
  }
117
+ if (key === "exit") {
118
+ if (value === true) runtime.isStopped = true;
119
+ return;
120
+ }
121
+ if (key === "pause") {
122
+ if (value !== true) return;
123
+ print("Press enter to resume model checking.");
124
+ runtime.pause();
125
+ return;
126
+ }
119
127
  if (typeof key === "string" && key.startsWith(NAMED_REGISTER_PREFIX)) {
120
128
  runtime.namedRegisters.set(key, value);
121
129
  return;
122
130
  }
131
+ if (typeof key === "string" && key.startsWith("-D")) {
132
+ runtime.properties.set(key.slice(2), formatValue(value));
133
+ return;
134
+ }
123
135
  throw new TlaModuleError(
124
136
  `The first argument of TLCSet should be a nonnegative integer, but instead it is:\n${formatValue(key)}`,
125
137
  );
@@ -203,7 +215,12 @@ export const createTlcExtOperators = (
203
215
  const key = getValue(args, 0, "TLCGetAndSet");
204
216
  const previous = getRegister(runtime, key) ?? getValue(args, 3, "TLCGetAndSet");
205
217
  const update = getOperator(args, 1, "TLCGetAndSet");
206
- setRegister(runtime, key, update.call([previous, getValue(args, 2, "TLCGetAndSet")]));
218
+ setTlcValue(
219
+ runtime,
220
+ print,
221
+ key,
222
+ update.call([previous, getValue(args, 2, "TLCGetAndSet")]),
223
+ );
207
224
  return previous;
208
225
  }),
209
226
  isStateLevel: true,
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
 
@@ -87,11 +87,26 @@ export const getFingerprintDistance = (
87
87
  const probability = getOptimisticProbability(distinctStates, generatedStates);
88
88
  if (probability < ACTUAL_PROBABILITY_THRESHOLD) return undefined;
89
89
  const fingerprints = getFingerprints().sort();
90
- return fingerprints.reduce((distance, fingerprint, index) => {
91
- const previous = fingerprints[index - 1];
92
- const isSameSet = index > 0 && previous < 0n === fingerprint < 0n;
93
- return isSameSet && fingerprint - previous < distance ? fingerprint - previous : distance;
94
- }, 0x7fff_ffff_ffff_ffffn);
90
+ // The low and high words of each fingerprint. A gap whose high words differ by at most 2^20 is
91
+ // below 2^53, so a number holds it exactly and only wider gaps need a BigInt.
92
+ const words = new Int32Array(fingerprints.buffer);
93
+ const nearest = { narrow: Number.POSITIVE_INFINITY, wide: 0x7fff_ffff_ffff_ffffn };
94
+ for (let index = 1; index < fingerprints.length; index++) {
95
+ const high = words[2 * index + 1];
96
+ const previousHigh = words[2 * index - 1];
97
+ if (high < 0 !== previousHigh < 0) continue;
98
+ const highGap = high - previousHigh;
99
+ if (highGap <= 0x10_0000) {
100
+ const gap = highGap * 0x1_0000_0000 + (words[2 * index] >>> 0) - (words[2 * index - 2] >>> 0);
101
+ nearest.narrow = Math.min(nearest.narrow, gap);
102
+ } else {
103
+ const gap = fingerprints[index] - fingerprints[index - 1];
104
+ if (gap < nearest.wide) nearest.wide = gap;
105
+ }
106
+ }
107
+ if (nearest.narrow === Number.POSITIVE_INFINITY) return nearest.wide;
108
+ const narrow = BigInt(nearest.narrow);
109
+ return narrow < nearest.wide ? narrow : nearest.wide;
95
110
  };
96
111
 
97
112
  export const getOutDegreeSummary = (buckets: number[]) => {
package/src/values.ts CHANGED
@@ -137,6 +137,13 @@ export const isSetValue = (value: Value) =>
137
137
  value.kind !== "Function" &&
138
138
  value.kind !== "LazyFunction";
139
139
 
140
+ export type ReducibleSet = SetValue | MixedSetValue | IntervalValue;
141
+
142
+ // TLC reduces a set enumeration or an interval eagerly, and keeps every other set lazy.
143
+ export const isReducible = (value: Value): value is ReducibleSet =>
144
+ typeof value === "object" &&
145
+ (value.kind === "Set" || value.kind === "MixedSet" || value.kind === "Interval");
146
+
140
147
  export const isFunctionValue = (value: Value): value is FunctionValue | LazyFunctionValue =>
141
148
  typeof value === "object" && (value.kind === "Function" || value.kind === "LazyFunction");
142
149
 
@@ -371,7 +378,7 @@ export const compareValues = (left: Value, right: Value): number => {
371
378
  `Attempted to compare ${describeKind(left)} ${formatValue(left)} with ${describeKind(right)} ${formatValue(right)}`,
372
379
  );
373
380
  }
374
- if (isLeftSet) return compareSets(toFiniteSet(left), toFiniteSet(right));
381
+ if (isLeftSet) return compareSets(toFiniteSet(left), toComparedSet(right));
375
382
  return compareFunctions(toFiniteFunction(left), toFiniteFunction(right));
376
383
  }
377
384
  if (typeof left === "number" && typeof right === "number") return left - right;
@@ -864,9 +871,11 @@ export const isEqualLikeTlc = (left: Value, right: Value) => {
864
871
  }
865
872
  };
866
873
 
874
+ // TLC sorts a set by comparing each element with the ones before it, so the later element converts
875
+ // a lazy set it compares and caches it.
867
876
  const isStrictlySorted = (elements: Value[]) => {
868
877
  for (let index = 1; index < elements.length; index++) {
869
- if (compareValues(elements[index - 1], elements[index]) >= 0) return false;
878
+ if (compareValues(elements[index], elements[index - 1]) <= 0) return false;
870
879
  }
871
880
  return true;
872
881
  };
@@ -1069,13 +1078,16 @@ const isTlcEnumerable = (value: Value) => isSetValue(value) && !isOverriddenSet(
1069
1078
  const formatUnion = (value: UnionValue, isStrict = false) =>
1070
1079
  `UNION(${formatValue(value.base, isStrict)})`;
1071
1080
 
1072
- const getUnionSets = (value: UnionValue) => {
1081
+ const getUnionSets = (
1082
+ value: UnionValue,
1083
+ getElements = (set: Value) => toFiniteSet(set).elements,
1084
+ ) => {
1073
1085
  if (!isTlcEnumerable(value.base)) {
1074
1086
  throw new TlaEvaluationError(
1075
1087
  `Attempted to enumerate the nonenumerable set:\n${formatUnion(value)}`,
1076
1088
  );
1077
1089
  }
1078
- return toFiniteSet(value.base).elements;
1090
+ return getElements(value.base);
1079
1091
  };
1080
1092
 
1081
1093
  const getUnionSet = (set: Value, index: number, union: UnionValue) => {
@@ -1111,7 +1123,7 @@ export const isEnumerable = (value: Value): boolean => {
1111
1123
  case "ProductSet":
1112
1124
  return value.factors.every(isEnumerable) || getEmptiness(value) === true;
1113
1125
  case "Union":
1114
- return isEnumerable(value.base) && toFiniteSet(value.base).elements.every(isEnumerable);
1126
+ return isEnumerable(value.base) && getStreamedElements(value.base).every(isEnumerable);
1115
1127
  case "SetOperation":
1116
1128
  if (value.operator === "\\cup") return isEnumerable(value.left) && isEnumerable(value.right);
1117
1129
  if (value.operator === "\\cap") return isEnumerable(value.left) || isEnumerable(value.right);
@@ -1212,9 +1224,7 @@ const enumerateSet = (value: Value): Value[] => {
1212
1224
  if (isOverriddenSet(value.base)) getCardinality(value.base);
1213
1225
  const base = toFiniteSet(value.base).elements;
1214
1226
  if (base.length > MAXIMUM_ENUMERATED_SUBSET_BASE) {
1215
- throw new TlaEvaluationError(
1216
- `SUBSET of a set with ${base.length} elements is too large to enumerate`,
1217
- );
1227
+ throw new TlaEvaluationError(describeOverflow(value));
1218
1228
  }
1219
1229
  return getSortedSubsets(base);
1220
1230
  }
@@ -1318,6 +1328,7 @@ const enumerateSet = (value: Value): Value[] => {
1318
1328
  };
1319
1329
 
1320
1330
  const finiteSets = new WeakMap<ObjectValue, SetValue>();
1331
+ const comparedSets = new WeakMap<ObjectValue, SetValue>();
1321
1332
 
1322
1333
  export const toFiniteSet = (value: Value): SetValue => {
1323
1334
  if (typeof value === "object" && value.kind === "Set") return value;
@@ -1326,6 +1337,13 @@ export const toFiniteSet = (value: Value): SetValue => {
1326
1337
  }
1327
1338
  const cached = typeof value === "object" ? finiteSets.get(value) : undefined;
1328
1339
  if (cached) return cached;
1340
+ const set =
1341
+ (typeof value === "object" ? comparedSets.get(value) : undefined) ?? enumerateFiniteSet(value);
1342
+ if (typeof value === "object") finiteSets.set(value, set);
1343
+ return set;
1344
+ };
1345
+
1346
+ const enumerateFiniteSet = (value: Value) => {
1329
1347
  const elements = enumerateSet(value);
1330
1348
  const isSorted =
1331
1349
  typeof value === "object" &&
@@ -1336,8 +1354,20 @@ export const toFiniteSet = (value: Value): SetValue => {
1336
1354
  value.kind === "ProductSet" ||
1337
1355
  value.kind === "FunctionSet" ||
1338
1356
  value.kind === "Subset");
1339
- const set = isSorted ? createSortedSet(elements) : createSet(elements);
1340
- if (typeof value === "object") finiteSets.set(value, set);
1357
+ return isSorted ? createSortedSet(elements) : createSet(elements);
1358
+ };
1359
+
1360
+ // TLC converts the set a comparison receives as its argument without caching it, so a lazy set
1361
+ // compared that way still streams the sets it combines.
1362
+ const toComparedSet = (value: Value) => {
1363
+ const isStreamed =
1364
+ typeof value === "object" &&
1365
+ (value.kind === "Union" || value.kind === "SetOperation" || value.kind === "FilteredSet");
1366
+ if (!isStreamed || finiteSets.has(value)) return toFiniteSet(value);
1367
+ const compared = comparedSets.get(value);
1368
+ if (compared) return compared;
1369
+ const set = enumerateFiniteSet(value);
1370
+ comparedSets.set(value, set);
1341
1371
  return set;
1342
1372
  };
1343
1373
 
@@ -1345,8 +1375,10 @@ export const toFiniteSet = (value: Value): SetValue => {
1345
1375
  // so an element that two of them share comes up once for each.
1346
1376
  export const getStreamedElements = (value: Value): Value[] => {
1347
1377
  if (typeof value !== "object" || finiteSets.has(value)) return toFiniteSet(value).elements;
1378
+ // TLC streams the sets of a UNION it hasn't enumerated, so a set that appears twice there yields
1379
+ // its elements twice.
1348
1380
  if (value.kind === "Union") {
1349
- return getUnionSets(value).flatMap((set, index) =>
1381
+ return getUnionSets(value, getStreamedElements).flatMap((set, index) =>
1350
1382
  getStreamedElements(getUnionSet(set, index, value)),
1351
1383
  );
1352
1384
  }
@@ -1603,7 +1635,9 @@ export const isElementOf = (element: Value, set: Value): boolean => {
1603
1635
  case "FunctionSet": {
1604
1636
  if (!isFunctionValue(element)) {
1605
1637
  if (isModelValue(element)) return false;
1606
- throw new TlaEvaluationError(describeMembership(element, set));
1638
+ throw new TlaEvaluationError(
1639
+ `Attempted to check if \n${formatValue(element)}\nwhich is not a TLC function value, is in the set of functions:\n${prettyPrint(formatValue(set))}`,
1640
+ );
1607
1641
  }
1608
1642
  const functionValue = toFiniteFunction(element);
1609
1643
  const low = getIntervalLow(functionValue.domain);
@@ -1718,10 +1752,61 @@ export const markLambdaFunction = <FunctionLike extends FunctionValue | LazyFunc
1718
1752
  return functionValue;
1719
1753
  };
1720
1754
 
1721
- const describeMissingArgument = (functionValue: Value, argument: Value) =>
1722
- typeof functionValue === "object" && lambdaFunctions.has(functionValue)
1723
- ? `In applying the function\n${prettyPrint(formatValue(functionValue))},\nthe first argument is:\n${prettyPrint(formatValue(argument))}\nwhich is not in its domain.\n`
1724
- : `Attempted to apply function ${formatValue(functionValue)} to ${formatValue(argument)}, which is not in its domain`;
1755
+ // TLC applies a tuple, a record and a function over an interval with their own classes, and each
1756
+ // reports a missing argument in its own words.
1757
+ const getFunctionClass = (functionValue: FunctionValue) => {
1758
+ const domain = functionValue.domain;
1759
+ if (domain.length === 0) return lambdaFunctions.has(functionValue) ? "FcnRcdValue" : "TupleValue";
1760
+ if (domain === intervalDomains[domain.length]) return "TupleValue";
1761
+ if (intervalArrays.has(domain)) return "IntervalFcnRcdValue";
1762
+ return domain.every((key) => typeof key === "string") ? "RecordValue" : "FcnRcdValue";
1763
+ };
1764
+
1765
+ const describeNotInDomain = (functionValue: FunctionValue, argument: Value) =>
1766
+ `Attempted to apply function:\n${prettyPrint(formatValue(functionValue))}\nto argument ${prettyPrint(formatValue(argument))}, which is not in the domain of the function.`;
1767
+
1768
+ const describeNonIntegerArgument = (argument: Value) =>
1769
+ `Attempted to apply function with integer domain to the non-integer argument ${prettyPrint(formatValue(argument))}`;
1770
+
1771
+ const describeMissingArgument = (
1772
+ functionValue: FunctionValue | LazyFunctionValue,
1773
+ argument: Value,
1774
+ ) => {
1775
+ if (lambdaFunctions.has(functionValue) || functionValue.kind === "LazyFunction")
1776
+ return `In applying the function\n${prettyPrint(formatValue(functionValue))},\nthe first argument is:\n${prettyPrint(formatValue(argument))}\nwhich is not in its domain.\n`;
1777
+ const functionClass = getFunctionClass(functionValue);
1778
+ if (functionClass === "TupleValue")
1779
+ return typeof argument === "number"
1780
+ ? `Attempted to access index ${argument} of tuple\n${prettyPrint(formatValue(functionValue))}\nwhich is out of bounds.`
1781
+ : `Attempted to access tuple at a non integral index: ${prettyPrint(formatValue(argument))}`;
1782
+ if (functionClass === "RecordValue")
1783
+ return typeof argument === "string"
1784
+ ? `Attempted to access nonexistent field '${argument}' of record\n${prettyPrint(formatValue(functionValue))}`
1785
+ : `Attempted to access record by a non-string argument: ${prettyPrint(formatValue(argument))}`;
1786
+ return functionClass === "IntervalFcnRcdValue" && typeof argument !== "number"
1787
+ ? describeNonIntegerArgument(argument)
1788
+ : describeNotInDomain(functionValue, argument);
1789
+ };
1790
+
1791
+ // TLC selects a field of a value that isn't a record from the function the value converts to,
1792
+ // which keeps a tuple's domain as an interval.
1793
+ export const describeMissingField = (functionValue: FunctionValue, field: string) =>
1794
+ getFunctionClass(functionValue) === "FcnRcdValue"
1795
+ ? describeNotInDomain(functionValue, field)
1796
+ : describeNonIntegerArgument(field);
1797
+
1798
+ export const isRecordValue = (functionValue: FunctionValue) =>
1799
+ getFunctionClass(functionValue) === "RecordValue";
1800
+
1801
+ // TLC checks the type of an argument to a tuple or a record before it looks the argument up, so
1802
+ // it never compares the argument with a key of another type.
1803
+ const isForeignKey = (domain: Value[], argument: Value) => {
1804
+ const first = domain[0];
1805
+ return typeof first === "number"
1806
+ ? typeof argument !== "number" &&
1807
+ (domain === intervalDomains[domain.length] || intervalArrays.has(domain))
1808
+ : typeof first === "string" && typeof argument !== "string";
1809
+ };
1725
1810
 
1726
1811
  const findKeyIndex = (domain: Value[], argument: Value) => {
1727
1812
  const first = domain[0];
@@ -1740,6 +1825,7 @@ export const applyFunction = (
1740
1825
  functionValue: Value,
1741
1826
  argument: Value,
1742
1827
  describeMissing?: (functionValue: FunctionValue) => string,
1828
+ describeNonFunction?: (value: Value) => string,
1743
1829
  ): Value => {
1744
1830
  if (typeof functionValue === "object" && functionValue.kind === "LazyFunction") {
1745
1831
  if (!isElementOf(argument, functionValue.domain)) {
@@ -1753,10 +1839,13 @@ export const applyFunction = (
1753
1839
  }
1754
1840
  if (typeof functionValue !== "object" || functionValue.kind !== "Function") {
1755
1841
  throw new TlaEvaluationError(
1756
- `Attempted to apply ${formatValue(functionValue)}, which is not a function`,
1842
+ describeNonFunction?.(functionValue) ??
1843
+ `Attempted to apply ${formatValue(functionValue)}, which is not a function`,
1757
1844
  );
1758
1845
  }
1759
- const position = findKeyIndex(functionValue.domain, argument);
1846
+ const position = isForeignKey(functionValue.domain, argument)
1847
+ ? -1
1848
+ : findKeyIndex(functionValue.domain, argument);
1760
1849
  if (position === -1) {
1761
1850
  throw new TlaEvaluationError(
1762
1851
  describeMissing?.(functionValue) ?? describeMissingArgument(functionValue, argument),
@@ -2101,8 +2190,11 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
2101
2190
  return `[${parameters} |-> <expression ${source.body}>]`;
2102
2191
  }
2103
2192
  const functionValue = toFiniteFunction(value);
2193
+ // TLC normalizes a lambda's domain to print it, but evaluates its body afterward.
2194
+ const formatRange = (inner: Value) =>
2195
+ formatValue(inner, isStrict, isNormalized && value.kind === "Function");
2104
2196
  if (functionValue.domain.every((key, index) => key === index + 1)) {
2105
- return `<<${functionValue.range.map(format).join(", ")}>>`;
2197
+ return `<<${functionValue.range.map(formatRange).join(", ")}>>`;
2106
2198
  }
2107
2199
  if (functionValue.domain.every((key) => typeof key === "string" && isFieldName(key))) {
2108
2200
  const isSorted =
@@ -2110,9 +2202,20 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
2110
2202
  const pairs = isSorted
2111
2203
  ? functionValue.domain.map((key, index) => [key, functionValue.range[index]])
2112
2204
  : getWrittenPairs(functionValue);
2113
- return `[${pairs.map((pair) => `${String(pair[0])} |-> ${format(pair[1])}`).join(", ")}]`;
2205
+ return `[${pairs.map((pair) => `${String(pair[0])} |-> ${formatRange(pair[1])}`).join(", ")}]`;
2114
2206
  }
2115
- return `(${functionValue.domain.map((key, index) => `${format(key)} :> ${format(functionValue.range[index])}`).join(" @@ ")})`;
2207
+ return `(${functionValue.domain.map((key, index) => `${format(key)} :> ${formatRange(functionValue.range[index])}`).join(" @@ ")})`;
2116
2208
  }
2117
2209
  }
2118
2210
  };
2211
+
2212
+ // TLC's TLCState.toString: a line per variable, as a conjunction when there are several.
2213
+ export const formatState = (state: Record<string, Value>) => {
2214
+ const entries = Object.entries(state);
2215
+ return entries
2216
+ .map(
2217
+ ([name, value]) =>
2218
+ `${entries.length === 1 ? "" : "/\\ "}${name} = ${prettyPrint(formatValue(value))}\n`,
2219
+ )
2220
+ .join("");
2221
+ };