tla-ts 0.0.3-dev.51ddd47 → 0.0.3-dev.598a74f

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.
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, 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,8 +89,7 @@ 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
+ const holds = (expression: Expression, context: Context, value = evaluate(expression, context)) => {
91
93
  if (typeof value === "boolean") return value;
92
94
  try {
93
95
  return expectBoolean(value, `the action at ${describeLocation(expression)}`);
@@ -292,12 +294,34 @@ const toConjunct = (
292
294
  return { kind: "Branch", expression, runner: getRunner(expression, environment, isInit) };
293
295
  };
294
296
 
297
+ // The leading guards of `\E x \in S, y \in T : P /\ Q` that read no inner bound hold for every inner
298
+ // binding alike, so they can run once for each element of the outermost bound.
299
+ const getHoistedGuards = (expression: QuantifierExpression, environment: Environment) => {
300
+ if (expression.bounds.length < 2 || expression.body.kind !== "And") return undefined;
301
+ const names = expression.bounds.flatMap((bound) =>
302
+ bound.pattern.kind === "Name" ? [bound.pattern.name] : [],
303
+ );
304
+ if (names.length !== expression.bounds.length) return undefined;
305
+ const innerNames = new Set(names.slice(0, -1));
306
+ const operands = expression.body.operands;
307
+ const index = operands.findIndex((operand) => {
308
+ if (getReadVariables(operand, environment) === undefined) return true;
309
+ if (hasBranches(operand, environment, new Set())) return true;
310
+ const readLocals = getReadLocals(operand, NO_NAMES);
311
+ return !readLocals || readLocals.some((name) => innerNames.has(name));
312
+ });
313
+ const count = index === -1 ? operands.length : index;
314
+ if (count === 0) return undefined;
315
+ return { names, guards: operands.slice(0, count), rest: operands.slice(count) };
316
+ };
317
+
295
318
  const compileConjunction = (
296
319
  operands: Expression[],
297
320
  environment: Environment,
298
321
  isInit: boolean,
299
322
  ): Runner => {
300
323
  const conjuncts = operands.map((operand) => toConjunct(operand, environment, isInit));
324
+ const evaluators: (Evaluator | undefined)[] = conjuncts.map(() => undefined);
301
325
  const runFrom = (
302
326
  start: number,
303
327
  run: Run,
@@ -320,12 +344,17 @@ const compileConjunction = (
320
344
  const conjunct = conjuncts[index];
321
345
  if (conjunct.kind === "Guard") {
322
346
  context ??= getContext(run, scope, current);
323
- if (!holds(conjunct.expression, context)) return;
347
+ const evaluator = (evaluators[index] ??= getEntryEvaluator(
348
+ conjunct.expression,
349
+ environment,
350
+ ));
351
+ if (!holds(conjunct.expression, context, evaluator(context))) return;
324
352
  continue;
325
353
  }
326
354
  if (conjunct.kind === "Assign") {
327
355
  context ??= getContext(run, scope, current);
328
- const value = evaluate(conjunct.value, context);
356
+ const evaluator = (evaluators[index] ??= getEntryEvaluator(conjunct.value, environment));
357
+ const value = evaluator(context);
329
358
  const assigned = current[conjunct.index];
330
359
  if (assigned === undefined) {
331
360
  current = assign(current, conjunct.index, value);
@@ -390,7 +419,7 @@ const compileMembership = (
390
419
  expression.operator === "\\subseteq" ? { kind: "Subset", base: evaluated } : evaluated;
391
420
  if (!isEnumerable(value)) {
392
421
  throw new TlaEvaluationError(
393
- `In computing next states, the right side of \\in is not enumerable: ${formatValue(value)} at ${describeLocation(expression)}`,
422
+ `In computing ${run.isInit ? "initial" : "next"} states, the right side of \\IN is not enumerable.\n${describeRange(expression)}`,
394
423
  );
395
424
  }
396
425
  const elements = getStreamedElements(value);
@@ -734,6 +763,33 @@ const compileAction = (
734
763
  }
735
764
  };
736
765
  }
766
+ const hoisted = isInit ? undefined : getHoistedGuards(expression, environment);
767
+ if (hoisted) {
768
+ const rest = compileConjunction(hoisted.rest, environment, isInit);
769
+ return (run, scope, partial, action, isFixed, onComplete) => {
770
+ const context = getContext(run, scope, partial);
771
+ const sets = expression.bounds.map((innerBound) =>
772
+ getEnumeratedElements(evaluate(innerBound.set, context), innerBound.set),
773
+ );
774
+ if (sets.some((elements) => elements.length === 0)) return;
775
+ const visit = (index: number, boundScope: Scope | undefined): void => {
776
+ if (index < 0) {
777
+ rest(run, boundScope, partial, action, isFixed, onComplete);
778
+ return;
779
+ }
780
+ for (const element of sets[index]) {
781
+ if (run.isStopped) return;
782
+ const elementScope = bindValue(boundScope, hoisted.names[index], element);
783
+ if (index === sets.length - 1) {
784
+ const guardContext = getContext(run, elementScope, partial);
785
+ if (!hoisted.guards.every((guard) => holds(guard, guardContext))) continue;
786
+ }
787
+ visit(index - 1, elementScope);
788
+ }
789
+ };
790
+ visit(sets.length - 1, scope);
791
+ };
792
+ }
737
793
  return (run, scope, partial, action, isFixed, onComplete) => {
738
794
  forEachBinding(expression.bounds, getContext(run, scope, partial), (boundScope) => {
739
795
  body(run, boundScope, partial, action, isFixed, onComplete);
@@ -810,7 +866,7 @@ const compileAction = (
810
866
  const body = arm?.body ?? other;
811
867
  if (!body)
812
868
  throw new TlaEvaluationError(
813
- `${UNEXPECTED_EXCEPTION}In computing next states, TLC encountered a CASE with no conditions true.\n${describeRange(expression)}`,
869
+ `In computing ${run.isInit ? "initial" : "next"} states, TLC encountered a CASE with no conditions true.\n${describeRange(expression)}`,
814
870
  );
815
871
  body(run, scope, partial, action, isFixed, onComplete);
816
872
  };
@@ -1001,7 +1057,7 @@ export const forEachSuccessor = (
1001
1057
  (partial, action) => {
1002
1058
  if (run.isStopped) return;
1003
1059
  if (!isComplete(partial)) {
1004
- throw new TlaEvaluationError(
1060
+ throw new TlaIncompleteStateError(
1005
1061
  `Successor state is not completely specified by action ${action ?? "Next"}. The following variables are not assigned: ${getMissingVariables(partial, environment).join(", ")}`,
1006
1062
  );
1007
1063
  }
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-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
  }
@@ -1718,10 +1750,61 @@ export const markLambdaFunction = <FunctionLike extends FunctionValue | LazyFunc
1718
1750
  return functionValue;
1719
1751
  };
1720
1752
 
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`;
1753
+ // TLC applies a tuple, a record and a function over an interval with their own classes, and each
1754
+ // reports a missing argument in its own words.
1755
+ const getFunctionClass = (functionValue: FunctionValue) => {
1756
+ const domain = functionValue.domain;
1757
+ if (domain.length === 0) return lambdaFunctions.has(functionValue) ? "FcnRcdValue" : "TupleValue";
1758
+ if (domain === intervalDomains[domain.length]) return "TupleValue";
1759
+ if (intervalArrays.has(domain)) return "IntervalFcnRcdValue";
1760
+ return domain.every((key) => typeof key === "string") ? "RecordValue" : "FcnRcdValue";
1761
+ };
1762
+
1763
+ const describeNotInDomain = (functionValue: FunctionValue, argument: Value) =>
1764
+ `Attempted to apply function:\n${prettyPrint(formatValue(functionValue))}\nto argument ${prettyPrint(formatValue(argument))}, which is not in the domain of the function.`;
1765
+
1766
+ const describeNonIntegerArgument = (argument: Value) =>
1767
+ `Attempted to apply function with integer domain to the non-integer argument ${prettyPrint(formatValue(argument))}`;
1768
+
1769
+ const describeMissingArgument = (
1770
+ functionValue: FunctionValue | LazyFunctionValue,
1771
+ argument: Value,
1772
+ ) => {
1773
+ if (lambdaFunctions.has(functionValue) || functionValue.kind === "LazyFunction")
1774
+ return `In applying the function\n${prettyPrint(formatValue(functionValue))},\nthe first argument is:\n${prettyPrint(formatValue(argument))}\nwhich is not in its domain.\n`;
1775
+ const functionClass = getFunctionClass(functionValue);
1776
+ if (functionClass === "TupleValue")
1777
+ return typeof argument === "number"
1778
+ ? `Attempted to access index ${argument} of tuple\n${prettyPrint(formatValue(functionValue))}\nwhich is out of bounds.`
1779
+ : `Attempted to access tuple at a non integral index: ${prettyPrint(formatValue(argument))}`;
1780
+ if (functionClass === "RecordValue")
1781
+ return typeof argument === "string"
1782
+ ? `Attempted to access nonexistent field '${argument}' of record\n${prettyPrint(formatValue(functionValue))}`
1783
+ : `Attempted to access record by a non-string argument: ${prettyPrint(formatValue(argument))}`;
1784
+ return functionClass === "IntervalFcnRcdValue" && typeof argument !== "number"
1785
+ ? describeNonIntegerArgument(argument)
1786
+ : describeNotInDomain(functionValue, argument);
1787
+ };
1788
+
1789
+ // TLC selects a field of a value that isn't a record from the function the value converts to,
1790
+ // which keeps a tuple's domain as an interval.
1791
+ export const describeMissingField = (functionValue: FunctionValue, field: string) =>
1792
+ getFunctionClass(functionValue) === "FcnRcdValue"
1793
+ ? describeNotInDomain(functionValue, field)
1794
+ : describeNonIntegerArgument(field);
1795
+
1796
+ export const isRecordValue = (functionValue: FunctionValue) =>
1797
+ getFunctionClass(functionValue) === "RecordValue";
1798
+
1799
+ // TLC checks the type of an argument to a tuple or a record before it looks the argument up, so
1800
+ // it never compares the argument with a key of another type.
1801
+ const isForeignKey = (domain: Value[], argument: Value) => {
1802
+ const first = domain[0];
1803
+ return typeof first === "number"
1804
+ ? typeof argument !== "number" &&
1805
+ (domain === intervalDomains[domain.length] || intervalArrays.has(domain))
1806
+ : typeof first === "string" && typeof argument !== "string";
1807
+ };
1725
1808
 
1726
1809
  const findKeyIndex = (domain: Value[], argument: Value) => {
1727
1810
  const first = domain[0];
@@ -1740,6 +1823,7 @@ export const applyFunction = (
1740
1823
  functionValue: Value,
1741
1824
  argument: Value,
1742
1825
  describeMissing?: (functionValue: FunctionValue) => string,
1826
+ describeNonFunction?: (value: Value) => string,
1743
1827
  ): Value => {
1744
1828
  if (typeof functionValue === "object" && functionValue.kind === "LazyFunction") {
1745
1829
  if (!isElementOf(argument, functionValue.domain)) {
@@ -1753,10 +1837,13 @@ export const applyFunction = (
1753
1837
  }
1754
1838
  if (typeof functionValue !== "object" || functionValue.kind !== "Function") {
1755
1839
  throw new TlaEvaluationError(
1756
- `Attempted to apply ${formatValue(functionValue)}, which is not a function`,
1840
+ describeNonFunction?.(functionValue) ??
1841
+ `Attempted to apply ${formatValue(functionValue)}, which is not a function`,
1757
1842
  );
1758
1843
  }
1759
- const position = findKeyIndex(functionValue.domain, argument);
1844
+ const position = isForeignKey(functionValue.domain, argument)
1845
+ ? -1
1846
+ : findKeyIndex(functionValue.domain, argument);
1760
1847
  if (position === -1) {
1761
1848
  throw new TlaEvaluationError(
1762
1849
  describeMissing?.(functionValue) ?? describeMissingArgument(functionValue, argument),
@@ -2101,8 +2188,11 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
2101
2188
  return `[${parameters} |-> <expression ${source.body}>]`;
2102
2189
  }
2103
2190
  const functionValue = toFiniteFunction(value);
2191
+ // TLC normalizes a lambda's domain to print it, but evaluates its body afterward.
2192
+ const formatRange = (inner: Value) =>
2193
+ formatValue(inner, isStrict, isNormalized && value.kind === "Function");
2104
2194
  if (functionValue.domain.every((key, index) => key === index + 1)) {
2105
- return `<<${functionValue.range.map(format).join(", ")}>>`;
2195
+ return `<<${functionValue.range.map(formatRange).join(", ")}>>`;
2106
2196
  }
2107
2197
  if (functionValue.domain.every((key) => typeof key === "string" && isFieldName(key))) {
2108
2198
  const isSorted =
@@ -2110,9 +2200,9 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
2110
2200
  const pairs = isSorted
2111
2201
  ? functionValue.domain.map((key, index) => [key, functionValue.range[index]])
2112
2202
  : getWrittenPairs(functionValue);
2113
- return `[${pairs.map((pair) => `${String(pair[0])} |-> ${format(pair[1])}`).join(", ")}]`;
2203
+ return `[${pairs.map((pair) => `${String(pair[0])} |-> ${formatRange(pair[1])}`).join(", ")}]`;
2114
2204
  }
2115
- return `(${functionValue.domain.map((key, index) => `${format(key)} :> ${format(functionValue.range[index])}`).join(" @@ ")})`;
2205
+ return `(${functionValue.domain.map((key, index) => `${format(key)} :> ${formatRange(functionValue.range[index])}`).join(" @@ ")})`;
2116
2206
  }
2117
2207
  }
2118
2208
  };