tla-ts 0.0.3-dev.e9d8347 → 0.0.3-dev.eed6eb1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/dist/cli.cjs +1 -1
  2. package/dist/cli.js +1 -1
  3. package/dist/index.cjs +1 -1
  4. package/dist/index.d.cts +150 -8
  5. package/dist/index.d.ts +150 -8
  6. package/dist/index.js +1 -1
  7. package/dist/parallel-worker.cjs +1 -1
  8. package/dist/parallel-worker.js +2 -2
  9. package/dist/parallel.cjs +1 -1
  10. package/dist/parallel.js +2 -2
  11. package/dist/run-cli.cjs +1351 -20
  12. package/dist/run-cli.js +1351 -20
  13. package/dist/transfer.cjs +86 -28
  14. package/dist/transfer.js +86 -28
  15. package/package.json +5 -1
  16. package/src/ast.ts +57 -6
  17. package/src/bags.ts +4 -7
  18. package/src/builtins.ts +29 -11
  19. package/src/bundled-modules.ts +3 -3
  20. package/src/canonical.ts +4 -3
  21. package/src/check.ts +1348 -227
  22. package/src/cli.ts +8 -1
  23. package/src/codegen.ts +68 -21
  24. package/src/config.ts +254 -181
  25. package/src/environment.ts +437 -123
  26. package/src/errors.ts +210 -5
  27. package/src/evaluate.ts +716 -141
  28. package/src/exit-codes.ts +5 -4
  29. package/src/index.ts +1 -0
  30. package/src/instances.ts +4 -2
  31. package/src/java-overrides.ts +104 -25
  32. package/src/levels.ts +183 -37
  33. package/src/lexer.ts +122 -29
  34. package/src/live-check.ts +204 -146
  35. package/src/liveness.ts +192 -65
  36. package/src/obligation-expression.ts +2 -2
  37. package/src/obligation-source.ts +2 -0
  38. package/src/parallel-worker.ts +6 -1
  39. package/src/parallel.ts +57 -6
  40. package/src/parser.ts +445 -147
  41. package/src/pcal-ast.ts +770 -0
  42. package/src/pcal-parse.ts +1523 -0
  43. package/src/pcal-tokenize.ts +516 -0
  44. package/src/pcal-translate.ts +1230 -0
  45. package/src/pcal-validate.ts +454 -0
  46. package/src/randomization.ts +24 -7
  47. package/src/resolve.ts +1465 -411
  48. package/src/run-cli.ts +1179 -155
  49. package/src/runtime.ts +16 -0
  50. package/src/sany-builtins.ts +147 -0
  51. package/src/sany-generator.ts +3128 -0
  52. package/src/sany-levels.ts +1208 -0
  53. package/src/sany-lexer.ts +545 -0
  54. package/src/sany-linter.ts +122 -0
  55. package/src/sany-modules.ts +1398 -0
  56. package/src/sany-nodes.ts +463 -0
  57. package/src/sany-parse-error.ts +2161 -0
  58. package/src/sany-report.ts +356 -0
  59. package/src/sany-selectors.ts +738 -0
  60. package/src/sany-source.ts +248 -0
  61. package/src/sany-xml.ts +1017 -0
  62. package/src/spec-description.ts +26 -7
  63. package/src/standard-modules.ts +203 -146
  64. package/src/standard-ranges.ts +116 -0
  65. package/src/state-graph.ts +29 -6
  66. package/src/subexpressions.ts +221 -161
  67. package/src/substitution-levels.ts +38 -17
  68. package/src/successors.ts +162 -114
  69. package/src/symmetry.ts +168 -50
  70. package/src/tableau.ts +3 -1
  71. package/src/tlc-ext.ts +13 -17
  72. package/src/tlc-messages.ts +329 -0
  73. package/src/tlc-module.ts +49 -21
  74. package/src/tlc-modules.ts +0 -4
  75. package/src/tlc-order.ts +55 -9
  76. package/src/tlc-random.ts +28 -3
  77. package/src/tlc-replay.ts +655 -0
  78. package/src/tlc-version.ts +18 -0
  79. package/src/transfer.ts +15 -3
  80. package/src/value-sources.ts +29 -0
  81. package/src/values.ts +699 -256
package/src/values.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { TlaEvaluationError, TlaModuleError } from "./errors";
2
2
  import { prettyPrint } from "./pretty-print";
3
+ import type { TlcVersion } from "./tlc-version";
3
4
 
4
5
  export interface ModelValue {
5
6
  kind: "ModelValue";
@@ -29,6 +30,7 @@ export interface FunctionValue {
29
30
  hash: number;
30
31
  fingerprint: number;
31
32
  writtenKeys: Value[] | undefined;
33
+ functionClass: FunctionClass | undefined;
32
34
  }
33
35
 
34
36
  export interface IntervalValue {
@@ -76,10 +78,17 @@ export interface SetOperationValue {
76
78
  right: Value;
77
79
  }
78
80
 
81
+ // TLC prints a set filter as its bound names and the location of its predicate.
82
+ interface FilteredSetSource {
83
+ names: string;
84
+ predicate: string;
85
+ }
86
+
79
87
  export interface FilteredSetValue {
80
88
  kind: "FilteredSet";
81
89
  base: Value;
82
90
  test: (element: Value) => boolean;
91
+ source?: FilteredSetSource;
83
92
  }
84
93
 
85
94
  // UNION S when some element of S isn't a set enumeration. TLC enumerates it only when it has to.
@@ -103,6 +112,7 @@ export interface LazyFunctionValue {
103
112
  domain: Value;
104
113
  apply: (argument: Value) => Value;
105
114
  source?: LazyFunctionSource;
115
+ functionClass?: FunctionClass;
106
116
  }
107
117
 
108
118
  export type Value =
@@ -137,10 +147,9 @@ export const isSetValue = (value: Value) =>
137
147
  value.kind !== "Function" &&
138
148
  value.kind !== "LazyFunction";
139
149
 
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 =>
150
+ // TLC's Reducible values, SetEnumValue and IntervalValue, which combine with another set element by
151
+ // element.
152
+ export const isReducibleSet = (value: Value): value is SetValue | MixedSetValue | IntervalValue =>
144
153
  typeof value === "object" &&
145
154
  (value.kind === "Set" || value.kind === "MixedSet" || value.kind === "Interval");
146
155
 
@@ -182,7 +191,7 @@ export const getWrittenPairs = (functionValue: FunctionValue): [Value, Value][]
182
191
  };
183
192
 
184
193
  export const createWrittenRecord = (names: Value[], range: Value[], writtenNames: Value[]) =>
185
- setWrittenOrder(createSortedFunction(names, range), writtenNames);
194
+ setWrittenOrder(createSortedRecord(names, range), writtenNames);
186
195
 
187
196
  // TLC sorts a value it compares even with itself, and every value inside it, so a value it has
188
197
  // hashed or fingerprinted is already sorted.
@@ -267,7 +276,10 @@ const checkModelValueTypes = (left: Value, right: Value, isEquality: boolean) =>
267
276
 
268
277
  // TLC orders strings and model value names by when it first interned the text, so every
269
278
  // check sets the order of its spec's strings before it builds any value.
270
- const stringOrder = { ranks: Object.create(null) as Record<string, number>, size: 0 };
279
+ const stringOrder: { ranks: Record<string, number>; size: number } = {
280
+ ranks: Object.create(null),
281
+ size: 0,
282
+ };
271
283
 
272
284
  export const setStringOrder = (texts: Iterable<string>) => {
273
285
  stringOrder.ranks = Object.create(null);
@@ -276,6 +288,14 @@ export const setStringOrder = (texts: Iterable<string>) => {
276
288
  for (const text of texts) rankString(text);
277
289
  };
278
290
 
291
+ // TLC 1.7.4 prints an empty function that isn't a tuple with a space between its brackets, and
292
+ // looks a key up in a function differently, so every check also sets the version its values follow.
293
+ const valueVersion = { is174: false };
294
+
295
+ export const setValueVersion = (version: TlcVersion | undefined) => {
296
+ valueVersion.is174 = version === "1.7.4";
297
+ };
298
+
279
299
  export const rankString = (text: string) => {
280
300
  if (stringOrder.ranks[text] === undefined) stringOrder.ranks[text] = stringOrder.size++;
281
301
  return text;
@@ -378,7 +398,7 @@ export const compareValues = (left: Value, right: Value): number => {
378
398
  `Attempted to compare ${describeKind(left)} ${formatValue(left)} with ${describeKind(right)} ${formatValue(right)}`,
379
399
  );
380
400
  }
381
- if (isLeftSet) return compareSets(toFiniteSet(left), toComparedSet(right));
401
+ if (isLeftSet) return compareSets(toFiniteSet(left), toFiniteSet(right));
382
402
  return compareFunctions(toFiniteFunction(left), toFiniteFunction(right));
383
403
  }
384
404
  if (typeof left === "number" && typeof right === "number") return left - right;
@@ -422,9 +442,101 @@ export const createSortedFunction = (domain: Value[], range: Value[]): FunctionV
422
442
  hash: 0,
423
443
  fingerprint: 0,
424
444
  writtenKeys: undefined,
445
+ functionClass: undefined,
425
446
  });
426
447
 
448
+ // TLC words a failed function application by the Java class of the function: FcnLambdaValue for
449
+ // [x \in S |-> e], TupleValue for <<...>> and what the sequence operators build, RecordValue for
450
+ // [a |-> e], and FcnRcdValue for any other function.
451
+ export type FunctionClass = "lambda" | "tuple" | "record";
452
+
453
+ // Whether a lambda exists for markFingerprinted to find, so that a spec without one skips the walk.
454
+ const lambdaPresence = { isPresent: false };
455
+
456
+ export const setFunctionClass = <FunctionLike extends FunctionValue | LazyFunctionValue>(
457
+ functionValue: FunctionLike,
458
+ functionClass: FunctionClass | undefined,
459
+ ) => {
460
+ if (functionClass === "lambda") lambdaPresence.isPresent = true;
461
+ if (functionClass !== undefined) functionValue.functionClass = functionClass;
462
+ return functionValue;
463
+ };
464
+
465
+ export const getFunctionClass = (value: Value) =>
466
+ typeof value === "object" && (value.kind === "Function" || value.kind === "LazyFunction")
467
+ ? value.functionClass
468
+ : undefined;
469
+
470
+ export const markLambdaFunction = <FunctionLike extends FunctionValue | LazyFunctionValue>(
471
+ functionValue: FunctionLike,
472
+ ) => setFunctionClass(functionValue, "lambda");
473
+
474
+ const fingerprintedValues = new WeakSet<ObjectValue>();
475
+
476
+ // The lazy sets TLC has cached the elements of. TLC caches a set as the receiver of compareTo,
477
+ // equals, size, and fingerPrint, not as their argument, and enumerates the sets an uncached one
478
+ // combines, duplicates and all.
479
+ const cachedSets = new WeakSet<ObjectValue>();
480
+
481
+ // Whether the spec has built a UNION or \cup set, the sets that stream duplicates, so that a spec
482
+ // without one skips tracking what TLC caches.
483
+ const streamedSetPresence = { isPresent: false };
484
+
485
+ export const markStreamedSet = <Streamed extends UnionValue | SetOperationValue>(
486
+ value: Streamed,
487
+ ) => {
488
+ streamedSetPresence.isPresent = true;
489
+ return value;
490
+ };
491
+
492
+ // The sets that stream their elements apart from the normalized set until TLC caches them.
493
+ const STREAMING_KINDS = new Set<ObjectValue["kind"]>([
494
+ "Union",
495
+ "SetOperation",
496
+ "FilteredSet",
497
+ "ProductSet",
498
+ "RecordSet",
499
+ "FunctionSet",
500
+ ]);
501
+
502
+ const cacheSet = (value: Value) => {
503
+ if (
504
+ streamedSetPresence.isPresent &&
505
+ typeof value === "object" &&
506
+ STREAMING_KINDS.has(value.kind)
507
+ ) {
508
+ cachedSets.add(value);
509
+ }
510
+ };
511
+
512
+ // FcnLambdaValue#fingerPrint caches the FcnRcdValue the function enumerates to, which applies it
513
+ // from then on, so a function TLC has fingerprinted is no longer a lambda.
514
+ export const markFingerprinted = (value: Value): void => {
515
+ if (
516
+ (!lambdaPresence.isPresent && !streamedSetPresence.isPresent) ||
517
+ typeof value !== "object" ||
518
+ fingerprintedValues.has(value)
519
+ ) {
520
+ return;
521
+ }
522
+ fingerprintedValues.add(value);
523
+ if (value.kind === "Function") {
524
+ if (value.functionClass === "lambda") value.functionClass = undefined;
525
+ value.domain.forEach(markFingerprinted);
526
+ value.range.forEach(markFingerprinted);
527
+ } else if (value.kind === "Set" || value.kind === "MixedSet") {
528
+ value.elements.forEach(markFingerprinted);
529
+ } else if (isSetValue(value) && isEnumerable(value)) {
530
+ cacheSet(value);
531
+ toFiniteSet(value).elements.forEach(markFingerprinted);
532
+ }
533
+ };
534
+
535
+ export const createSortedRecord = (names: Value[], range: Value[]) =>
536
+ setFunctionClass(createSortedFunction(names, range), "record");
537
+
427
538
  export const valuesEqual = (left: Value, right: Value): boolean => {
539
+ cacheSet(left);
428
540
  if (left === right) {
429
541
  if (writtenOrderUse.isUsed) forgetWrittenOrder(left);
430
542
  return left !== ANY_SET || compareAny(left);
@@ -498,28 +610,36 @@ export const valuesEqual = (left: Value, right: Value): boolean => {
498
610
  return compareValues(left, right) === 0;
499
611
  };
500
612
 
501
- const areSameValues = (left: Value[], right: Value[]) =>
502
- left === right ||
503
- (left.length === right.length &&
504
- left.every((element, index) => isSameValue(element, right[index])));
505
-
506
- export const isSameValue = (left: Value, right: Value): boolean => {
507
- if (left === right) return true;
508
- if (typeof left !== "object" || typeof right !== "object") return false;
509
- if (left.kind === "Set" && right.kind === "Set")
510
- return (
511
- (left.hash === 0 || right.hash === 0 || left.hash === right.hash) &&
512
- areSameValues(left.elements, right.elements)
513
- );
514
- if (left.kind === "Function" && right.kind === "Function")
515
- return (
516
- (left.hash === 0 || right.hash === 0 || left.hash === right.hash) &&
517
- areSameValues(left.domain, right.domain) &&
518
- areSameValues(left.range, right.range)
519
- );
520
- return getValueKey(left) === getValueKey(right);
613
+ // TLC prints and words errors about an equal function by its Java class, so a value can stand for
614
+ // another in a state only if each function in it has the same class.
615
+ const createSameValueCheck = (isClassSensitive: boolean) => {
616
+ const areSameValues = (left: Value[], right: Value[]) =>
617
+ left === right ||
618
+ (left.length === right.length && left.every((element, index) => isSame(element, right[index])));
619
+ const isSame = (left: Value, right: Value): boolean => {
620
+ if (left === right) return true;
621
+ if (typeof left !== "object" || typeof right !== "object") return false;
622
+ if (left.kind === "Set" && right.kind === "Set")
623
+ return (
624
+ (left.hash === 0 || right.hash === 0 || left.hash === right.hash) &&
625
+ areSameValues(left.elements, right.elements)
626
+ );
627
+ if (left.kind === "Function" && right.kind === "Function")
628
+ return (
629
+ (!isClassSensitive || left.functionClass === right.functionClass) &&
630
+ (left.hash === 0 || right.hash === 0 || left.hash === right.hash) &&
631
+ areSameValues(left.domain, right.domain) &&
632
+ areSameValues(left.range, right.range)
633
+ );
634
+ return getValueKey(left) === getValueKey(right);
635
+ };
636
+ return isSame;
521
637
  };
522
638
 
639
+ export const isSameValue = createSameValueCheck(false);
640
+
641
+ export const isInterchangeableValue = createSameValueCheck(true);
642
+
523
643
  // The comparisons above fail with their own messages. These follow the compareTo and equals
524
644
  // methods of TLC's Java value classes, which word a failure by the class of the left operand, so a
525
645
  // failed comparison runs again through them to fail as TLC does.
@@ -675,7 +795,7 @@ const compareFunctionLikeTlc = (left: FunctionValue | LazyFunctionValue, right:
675
795
  compareElementsLikeTlc(functionValue.range, tuple)
676
796
  );
677
797
  }
678
- if (left.kind === "Function" && functionValue.domain.every((key) => typeof key === "string")) {
798
+ if (getFunctionClass(left) === "record") {
679
799
  const record = toTlcRecord(right);
680
800
  if (!record) {
681
801
  if (isModelValue(right)) return compareModelValueWith(right, left);
@@ -793,7 +913,7 @@ const equalsFunctionLikeTlc = (left: FunctionValue | LazyFunctionValue, right: V
793
913
  equalsElementsLikeTlc(functionValue.range, tuple)
794
914
  );
795
915
  }
796
- if (left.kind === "Function" && functionValue.domain.every((key) => typeof key === "string")) {
916
+ if (getFunctionClass(left) === "record") {
797
917
  const record = toTlcRecord(right);
798
918
  if (!record) {
799
919
  if (isModelValue(right)) return equalsModelValueWith(right, left);
@@ -845,42 +965,75 @@ const equalsLikeTlc = (left: Value, right: Value): boolean => {
845
965
  const sortLikeTlc = (elements: Value[]) => {
846
966
  const sorted: Value[] = [];
847
967
  for (const element of elements) {
848
- const bounds = { low: 0, high: sorted.length, comparison: 1 };
849
- while (bounds.low < bounds.high) {
850
- const middle = bounds.low + ((bounds.high - bounds.low) >> 1);
851
- bounds.comparison = compareLikeTlc(element, sorted[middle]);
852
- if (bounds.comparison === 0) break;
853
- if (bounds.comparison < 0) bounds.high = middle;
854
- else bounds.low = middle + 1;
855
- }
856
- if (bounds.comparison !== 0) sorted.splice(bounds.low, 0, element);
968
+ const found = searchLikeTlc(element, sorted);
969
+ if (!found.isFound) sorted.splice(found.index, 0, element);
857
970
  }
858
971
  return sorted;
859
972
  };
860
973
 
861
- // TLC checks membership in a set enumeration it hasn't sorted element by element.
974
+ // Calls a method of a value as TLC does, whose failure the value heads when it has a source.
975
+ const callTracedMethod = <Result>(receiver: Value, method: () => Result) => {
976
+ const sets = setTrace.sets;
977
+ if (sets === undefined) return method();
978
+ sets.push(receiver);
979
+ const result = method();
980
+ sets.pop();
981
+ return result;
982
+ };
983
+
984
+ // ValueVec.search on sorted elements: a binary search with compareTo, which ends where the element
985
+ // is or would go.
986
+ const searchLikeTlc = (element: Value, sorted: Value[]) => {
987
+ const bounds = { low: 0, high: sorted.length };
988
+ while (bounds.low < bounds.high) {
989
+ const middle = bounds.low + ((bounds.high - bounds.low) >> 1);
990
+ const comparison = callTracedMethod(element, () => compareLikeTlc(element, sorted[middle]));
991
+ if (comparison === 0) return { index: middle, isFound: true };
992
+ if (comparison < 0) bounds.high = middle;
993
+ else bounds.low = middle + 1;
994
+ }
995
+ return { index: bounds.low, isFound: false };
996
+ };
997
+
998
+ // TLC checks membership in a set enumeration it hasn't sorted element by element, with the equals
999
+ // method of each member.
862
1000
  const isElementOfLikeTlc = (element: Value, elements: Value[]) =>
863
- elements.some((member) => equalsLikeTlc(member, element));
1001
+ elements.some((member) => callTracedMethod(member, () => equalsLikeTlc(member, element)));
864
1002
 
865
- export const isEqualLikeTlc = (left: Value, right: Value) => {
866
- try {
867
- return valuesEqual(left, right);
868
- } catch (error) {
869
- if (!(error instanceof TlaEvaluationError)) throw error;
870
- return equalsLikeTlc(left, right);
1003
+ // The sets TLC has normalized, whose membership ValueVec.search checks by binary search with
1004
+ // compareTo instead of element by element.
1005
+ const normalizedSets = new WeakSet<SetValue>();
1006
+
1007
+ // IValue.deepNormalize, which TLC applies to the constants of the config and the constant
1008
+ // definitions it computes as it starts.
1009
+ export const markNormalized = (value: Value): void => {
1010
+ if (typeof value !== "object") return;
1011
+ if (value.kind === "Set") {
1012
+ normalizedSets.add(value);
1013
+ value.elements.forEach(markNormalized);
1014
+ }
1015
+ if (value.kind === "Function") {
1016
+ value.domain.forEach(markNormalized);
1017
+ value.range.forEach(markNormalized);
871
1018
  }
872
1019
  };
873
1020
 
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.
1021
+ export const isEqualLikeTlc = (left: Value, right: Value) =>
1022
+ computeLikeTlcOnFailure(
1023
+ () => valuesEqual(left, right),
1024
+ () => equalsLikeTlc(left, right),
1025
+ );
1026
+
876
1027
  const isStrictlySorted = (elements: Value[]) => {
877
1028
  for (let index = 1; index < elements.length; index++) {
878
- if (compareValues(elements[index], elements[index - 1]) <= 0) return false;
1029
+ if (compareValues(elements[index - 1], elements[index]) >= 0) return false;
879
1030
  }
880
1031
  return true;
881
1032
  };
882
1033
 
883
1034
  export const createSet = (elements: Value[]): SetValue => {
1035
+ // ValueVec.sort compares each element after the first with those before it.
1036
+ for (let index = 1; index < elements.length; index++) cacheSet(elements[index]);
884
1037
  if (elements.length < 2 || isStrictlySorted(elements)) return createSortedSet(elements);
885
1038
  const sorted = [...elements].sort(compareValues);
886
1039
  const unique = [sorted[0]];
@@ -892,14 +1045,11 @@ export const createSet = (elements: Value[]): SetValue => {
892
1045
 
893
1046
  // TLC builds a set enumeration without sorting it, so one whose elements it can't compare still
894
1047
  // evaluates.
895
- export const createEnumeratedSet = (elements: Value[]): SetValue | MixedSetValue => {
896
- try {
897
- return createSet(elements);
898
- } catch (error) {
899
- if (!(error instanceof TlaEvaluationError)) throw error;
900
- return { kind: "MixedSet", elements };
901
- }
902
- };
1048
+ export const createEnumeratedSet = (elements: Value[]): SetValue | MixedSetValue =>
1049
+ computeLikeTlcOnFailure<SetValue | MixedSetValue>(
1050
+ () => createSet(elements),
1051
+ () => ({ kind: "MixedSet", elements }),
1052
+ );
903
1053
 
904
1054
  export const EMPTY_SET = createSortedSet([]);
905
1055
 
@@ -978,12 +1128,15 @@ export const unionSorted = (left: SetValue, right: SetValue): SetValue => {
978
1128
  }
979
1129
  if (added.length === 0) return left;
980
1130
  const union = createSortedSet(merged);
981
- if (left.hash !== 0) {
1131
+ if (left.hash !== 0 && left.hash !== UNFINGERPRINTABLE_HASH) {
982
1132
  let hash = left.hash;
983
- for (let index = 0; index < added.length; index++) {
984
- hash = (hash + getElementContribution(added[index])) | 0;
1133
+ let index = 0;
1134
+ for (; index < added.length; index++) {
1135
+ const elementHash = getValueHash(added[index]);
1136
+ if (elementHash === UNFINGERPRINTABLE_HASH) break;
1137
+ hash = (hash + getElementContribution(elementHash)) | 0;
985
1138
  }
986
- union.hash = hash;
1139
+ if (index === added.length) union.hash = hash;
987
1140
  }
988
1141
  if (left.fingerprint !== 0) {
989
1142
  let fingerprint = left.fingerprint;
@@ -1068,12 +1221,13 @@ const getIntervalValue = (high: number): IntervalValue => {
1068
1221
  };
1069
1222
 
1070
1223
  export const createTuple = (elements: Value[]): FunctionValue =>
1071
- createSortedFunction(getIntervalDomain(elements.length), elements);
1224
+ setFunctionClass(createSortedFunction(getIntervalDomain(elements.length), elements), "tuple");
1072
1225
 
1073
- export const createRecord = (fields: [string, Value][]): FunctionValue => createFunction(fields);
1226
+ export const createRecord = (fields: [string, Value][]): FunctionValue =>
1227
+ setFunctionClass(createFunction(fields), "record");
1074
1228
 
1075
1229
  // TLC's Enumerable classes: every set except the ones it implements in Java.
1076
- const isTlcEnumerable = (value: Value) => isSetValue(value) && !isOverriddenSet(value);
1230
+ export const isTlcEnumerable = (value: Value) => isSetValue(value) && !isOverriddenSet(value);
1077
1231
 
1078
1232
  const formatUnion = (value: UnionValue, isStrict = false) =>
1079
1233
  `UNION(${formatValue(value.base, isStrict)})`;
@@ -1196,6 +1350,41 @@ const advanceCombination = (indices: number[], length: number) => {
1196
1350
  return false;
1197
1351
  };
1198
1352
 
1353
+ // TLC enumerates SUBSET S lazily, by size and then in the order of S, so a quantifier that finds
1354
+ // its witness early never builds the rest. For a power set too large to build, the elements are
1355
+ // computed in that order as a loop reads them.
1356
+ export const getLazySubsets = (value: Value): Value[] | undefined => {
1357
+ if (typeof value !== "object" || value.kind !== "Subset" || isOverriddenSet(value.base)) {
1358
+ return undefined;
1359
+ }
1360
+ const base = toFiniteSet(value.base).elements;
1361
+ if (base.length <= MAXIMUM_ENUMERATED_SUBSET_BASE) return undefined;
1362
+ const cursor = { index: -1, indices: [0] };
1363
+ const getSubset = (index: number) => {
1364
+ if (index <= cursor.index) cursor.index = -1;
1365
+ while (cursor.index < index) {
1366
+ if (cursor.index === -1) cursor.indices = [];
1367
+ else if (!advanceCombination(cursor.indices, base.length)) {
1368
+ cursor.indices = Array.from({ length: cursor.indices.length + 1 }, (_, item) => item);
1369
+ }
1370
+ cursor.index++;
1371
+ }
1372
+ return createSortedSet(cursor.indices.map((item) => base[item]));
1373
+ };
1374
+ const length = 2 ** base.length;
1375
+ const isIndex = (property: string | symbol) =>
1376
+ typeof property === "string" && /^\d+$/.test(property) && Number(property) < length;
1377
+ return new Proxy<Value[]>([], {
1378
+ get: (target, property, receiver) => {
1379
+ if (property === "length") return length;
1380
+ return isIndex(property)
1381
+ ? getSubset(Number(property))
1382
+ : Reflect.get(target, property, receiver);
1383
+ },
1384
+ has: (target, property) => isIndex(property) || Reflect.has(target, property),
1385
+ });
1386
+ };
1387
+
1199
1388
  const getSortedSubsets = (base: Value[]) => {
1200
1389
  const subsets: Value[] = [];
1201
1390
  for (let size = 0; size <= base.length; size++) {
@@ -1207,7 +1396,30 @@ const getSortedSubsets = (base: Value[]) => {
1207
1396
  return subsets;
1208
1397
  };
1209
1398
 
1210
- const enumerateSet = (value: Value): Value[] => {
1399
+ // The Enumerator of a set of records or tuples enumerates its sets in turn and stops at the first
1400
+ // empty one, which leaves the product empty. Later versions of TLC decide that the set is empty
1401
+ // before they enumerate it.
1402
+ const getComponentElements = (
1403
+ sets: Value[],
1404
+ getElements: (set: Value) => Value[],
1405
+ describeUnenumerable: (set: Value, index: number) => string,
1406
+ ) => {
1407
+ const lists: Value[][] = [];
1408
+ for (let index = 0; index < sets.length; index++) {
1409
+ const set = sets[index];
1410
+ if (isOverriddenSet(set)) throw new TlaEvaluationError(describeUnenumerable(set, index));
1411
+ const elements = getElements(set);
1412
+ if (elements.length === 0) return [[]];
1413
+ lists.push(elements);
1414
+ }
1415
+ return lists;
1416
+ };
1417
+
1418
+ // getElements enumerates the sets a set of functions, records, or tuples combines.
1419
+ const enumerateSet = (
1420
+ value: Value,
1421
+ getElements = (set: Value) => toFiniteSet(set).elements,
1422
+ ): Value[] => {
1211
1423
  if (typeof value !== "object")
1212
1424
  throw new TlaEvaluationError(`Expected a set but found ${formatValue(value)}`);
1213
1425
  switch (value.kind) {
@@ -1221,7 +1433,14 @@ const enumerateSet = (value: Value): Value[] => {
1221
1433
  return elements;
1222
1434
  }
1223
1435
  case "Subset": {
1224
- if (isOverriddenSet(value.base)) getCardinality(value.base);
1436
+ // SubsetValue.toSetEnum sizes the set before it enumerates it, and enumerates only the empty
1437
+ // set of a value of size 0, a function with an empty domain among them.
1438
+ if (getCardinality(value.base) === 0) return getSortedSubsets([]);
1439
+ if (!isSetValue(value.base)) {
1440
+ throw new TlaEvaluationError(
1441
+ `Attempted to compute the value of an expression of form\nSUBSET S, but S is a non-enumerable value:\n${prettyPrint(formatValue(value.base))}`,
1442
+ );
1443
+ }
1225
1444
  const base = toFiniteSet(value.base).elements;
1226
1445
  if (base.length > MAXIMUM_ENUMERATED_SUBSET_BASE) {
1227
1446
  throw new TlaEvaluationError(describeOverflow(value));
@@ -1229,51 +1448,48 @@ const enumerateSet = (value: Value): Value[] => {
1229
1448
  return getSortedSubsets(base);
1230
1449
  }
1231
1450
  case "FunctionSet": {
1232
- if (isEmptySet(value)) return [];
1451
+ if (!valueVersion.is174 && isEmptySet(value)) return [];
1233
1452
  if (isOverriddenSet(value.domain)) {
1234
1453
  throw new TlaEvaluationError(
1235
1454
  `Attempted to enumerate a set of the form [D -> R],but the domain D:\n${formatValue(value.domain)}\ncannot be enumerated.`,
1236
1455
  );
1237
1456
  }
1238
1457
  const domain = getFunctionDomain(value.domain);
1239
- if (domain.length > 0 && isOverriddenSet(value.range)) {
1458
+ // TLC 1.7.4 requires an enumerable range even of an empty domain.
1459
+ if ((domain.length > 0 || valueVersion.is174) && isOverriddenSet(value.range)) {
1240
1460
  throw new TlaEvaluationError(
1241
1461
  `Attempted to enumerate a set of the form [D -> R],but the range R:\n${formatValue(value.range)}\ncannot be enumerated.`,
1242
1462
  );
1243
1463
  }
1244
- const range = domain.length === 0 ? [] : toFiniteSet(value.range).elements;
1464
+ const range = domain.length === 0 ? [] : getElements(value.range);
1245
1465
  return getCartesianProduct(domain.map(() => range)).map((combination): Value =>
1246
1466
  createSortedFunction(domain, combination),
1247
1467
  );
1248
1468
  }
1249
1469
  case "RecordSet": {
1250
- if (isEmptySet(value)) return [];
1251
- const fields = value.sets.map((set, index) => {
1252
- if (isOverriddenSet(set)) {
1253
- throw new TlaEvaluationError(
1254
- `Attempted to enumerate a set of the form [l1 : v1, ..., ln : vn],\nbut can't enumerate the value of the \`${value.names[index]}' field:\n${formatValue(set)}`,
1255
- );
1256
- }
1257
- return toFiniteSet(set).elements;
1258
- });
1470
+ if (!valueVersion.is174 && isEmptySet(value)) return [];
1471
+ const fields = getComponentElements(
1472
+ value.sets,
1473
+ getElements,
1474
+ (set, index) =>
1475
+ `Attempted to enumerate a set of the form [l1 : v1, ..., ln : vn],\nbut can't enumerate the value of the \`${value.names[index]}' field:\n${formatValue(set)}`,
1476
+ );
1259
1477
  return getCartesianProduct(fields).map((combination) =>
1260
1478
  createRecord(value.names.map((name, index): [string, Value] => [name, combination[index]])),
1261
1479
  );
1262
1480
  }
1263
1481
  case "ProductSet": {
1264
- if (isEmptySet(value)) return [];
1265
- const factors = value.factors.map((factor, index) => {
1266
- if (isOverriddenSet(factor)) {
1267
- throw new TlaEvaluationError(
1268
- `Attempted to enumerate a set of the form s1 \\X s2 ... \\X sn,\nbut can't enumerate s${index}:\n${formatValue(factor)}`,
1269
- );
1270
- }
1271
- return toFiniteSet(factor).elements;
1272
- });
1482
+ if (!valueVersion.is174 && isEmptySet(value)) return [];
1483
+ const factors = getComponentElements(
1484
+ value.factors,
1485
+ getElements,
1486
+ (factor, index) =>
1487
+ `Attempted to enumerate a set of the form s1 \\X s2 ... \\X sn,\nbut can't enumerate s${index}:\n${formatValue(factor)}`,
1488
+ );
1273
1489
  return getCartesianProduct(factors).map(createTuple);
1274
1490
  }
1275
1491
  case "FilteredSet":
1276
- if (isOverriddenSet(value.base)) {
1492
+ if (!isSetValue(value.base) || isOverriddenSet(value.base)) {
1277
1493
  throw new TlaEvaluationError(
1278
1494
  `Attempted to enumerate { x \\in S : p(x) } when S:\n${formatValue(value.base)}\nis not enumerable`,
1279
1495
  );
@@ -1288,7 +1504,7 @@ const enumerateSet = (value: Value): Value[] => {
1288
1504
  case "SetOperation": {
1289
1505
  if (
1290
1506
  value.operator === "\\cup" &&
1291
- (isOverriddenSet(value.left) || isOverriddenSet(value.right))
1507
+ (!isTlcEnumerable(value.left) || !isTlcEnumerable(value.right))
1292
1508
  ) {
1293
1509
  throw new TlaEvaluationError(
1294
1510
  `Attempted to enumerate S \\cup T when S:\n${formatValue(value.left)}\nand T:\n${formatValue(value.right)}\nare not both enumerable`,
@@ -1296,21 +1512,21 @@ const enumerateSet = (value: Value): Value[] => {
1296
1512
  }
1297
1513
  if (
1298
1514
  value.operator === "\\cap" &&
1299
- isOverriddenSet(value.left) &&
1300
- isOverriddenSet(value.right)
1515
+ !isTlcEnumerable(value.left) &&
1516
+ !isTlcEnumerable(value.right)
1301
1517
  ) {
1302
1518
  throw new TlaEvaluationError(
1303
1519
  `Attempted to enumerate S \\cap T when neither S:\n${formatValue(value.left)}\nnor T:\n${formatValue(value.right)}\nis enumerable`,
1304
1520
  );
1305
1521
  }
1306
- if (value.operator === "\\" && isOverriddenSet(value.left)) {
1522
+ if (value.operator === "\\" && !isTlcEnumerable(value.left)) {
1307
1523
  throw new TlaEvaluationError(
1308
1524
  `Attempted to enumerate S \\ T when S:\n${formatValue(value.left)}\nis not enumerable.`,
1309
1525
  );
1310
1526
  }
1311
1527
  if (value.operator === "\\cup")
1312
1528
  return unionSorted(toFiniteSet(value.left), toFiniteSet(value.right)).elements;
1313
- const isLeftEnumerated = value.operator === "\\" || isEnumerable(value.left);
1529
+ const isLeftEnumerated = value.operator === "\\" || isTlcEnumerable(value.left);
1314
1530
  const enumerated = isLeftEnumerated ? value.left : value.right;
1315
1531
  const other = isLeftEnumerated ? value.right : value.left;
1316
1532
  return toFiniteSet(enumerated).elements.filter(
@@ -1328,7 +1544,6 @@ const enumerateSet = (value: Value): Value[] => {
1328
1544
  };
1329
1545
 
1330
1546
  const finiteSets = new WeakMap<ObjectValue, SetValue>();
1331
- const comparedSets = new WeakMap<ObjectValue, SetValue>();
1332
1547
 
1333
1548
  export const toFiniteSet = (value: Value): SetValue => {
1334
1549
  if (typeof value === "object" && value.kind === "Set") return value;
@@ -1337,14 +1552,10 @@ export const toFiniteSet = (value: Value): SetValue => {
1337
1552
  }
1338
1553
  const cached = typeof value === "object" ? finiteSets.get(value) : undefined;
1339
1554
  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) => {
1555
+ const sets = setTrace.sets;
1556
+ sets?.push(value);
1347
1557
  const elements = enumerateSet(value);
1558
+ sets?.pop();
1348
1559
  const isSorted =
1349
1560
  typeof value === "object" &&
1350
1561
  (value.kind === "MixedSet" ||
@@ -1354,27 +1565,46 @@ const enumerateFiniteSet = (value: Value) => {
1354
1565
  value.kind === "ProductSet" ||
1355
1566
  value.kind === "FunctionSet" ||
1356
1567
  value.kind === "Subset");
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);
1568
+ const set = isSorted ? createSortedSet(elements) : createSet(elements);
1569
+ if (typeof value === "object") finiteSets.set(value, set);
1371
1570
  return set;
1372
1571
  };
1373
1572
 
1374
1573
  // TLC's Enumerator for a lazy set streams the sets it combines until the set caches its elements,
1375
1574
  // so an element that two of them share comes up once for each.
1376
1575
  export const getStreamedElements = (value: Value): Value[] => {
1377
- if (typeof value !== "object" || finiteSets.has(value)) return toFiniteSet(value).elements;
1576
+ if (typeof value !== "object" || cachedSets.has(value)) return toFiniteSet(value).elements;
1577
+ const sets = setTrace.sets;
1578
+ sets?.push(value);
1579
+ const elements = streamElements(value);
1580
+ sets?.pop();
1581
+ return elements;
1582
+ };
1583
+
1584
+ const getCombinedSets = (value: ObjectValue) =>
1585
+ value.kind === "ProductSet"
1586
+ ? value.factors
1587
+ : value.kind === "RecordSet"
1588
+ ? value.sets
1589
+ : value.kind === "FunctionSet"
1590
+ ? [value.range]
1591
+ : undefined;
1592
+
1593
+ // Whether a set streams its elements in another order than the normalized set, so that a set of
1594
+ // tuples, records, or functions it is a component of has to stream too.
1595
+ const isStreamedApart = (value: Value): boolean => {
1596
+ if (typeof value !== "object" || cachedSets.has(value)) return false;
1597
+ if (value.kind === "Union") return true;
1598
+ if (value.kind === "FilteredSet") return isStreamedApart(value.base);
1599
+ if (value.kind === "SetOperation") {
1600
+ return (
1601
+ value.operator === "\\cup" || isStreamedApart(value.left) || isStreamedApart(value.right)
1602
+ );
1603
+ }
1604
+ return getCombinedSets(value)?.some(isStreamedApart) ?? false;
1605
+ };
1606
+
1607
+ const streamElements = (value: ObjectValue): Value[] => {
1378
1608
  // TLC streams the sets of a UNION it hasn't enumerated, so a set that appears twice there yields
1379
1609
  // its elements twice.
1380
1610
  if (value.kind === "Union") {
@@ -1385,16 +1615,18 @@ export const getStreamedElements = (value: Value): Value[] => {
1385
1615
  if (value.kind === "FilteredSet" && !isOverriddenSet(value.base)) {
1386
1616
  return getStreamedElements(value.base).filter(value.test);
1387
1617
  }
1618
+ const components = getCombinedSets(value);
1619
+ if (components?.some(isStreamedApart)) return enumerateSet(value, getStreamedElements);
1388
1620
  if (value.kind !== "SetOperation") return toFiniteSet(value).elements;
1389
1621
  if (value.operator === "\\cup") {
1390
- return isOverriddenSet(value.left) || isOverriddenSet(value.right)
1622
+ return !isTlcEnumerable(value.left) || !isTlcEnumerable(value.right)
1391
1623
  ? toFiniteSet(value).elements
1392
1624
  : [...getStreamedElements(value.left), ...getStreamedElements(value.right)];
1393
1625
  }
1394
- const isLeftEnumerated = value.operator === "\\" || isEnumerable(value.left);
1626
+ const isLeftEnumerated = value.operator === "\\" || isTlcEnumerable(value.left);
1395
1627
  const enumerated = isLeftEnumerated ? value.left : value.right;
1396
1628
  const other = isLeftEnumerated ? value.right : value.left;
1397
- if (isOverriddenSet(enumerated)) return toFiniteSet(value).elements;
1629
+ if (!isTlcEnumerable(enumerated)) return toFiniteSet(value).elements;
1398
1630
  return getStreamedElements(enumerated).filter(
1399
1631
  (element) => isElementOf(element, other) === (value.operator === "\\cap"),
1400
1632
  );
@@ -1431,9 +1663,13 @@ export const isEmptySet = (value: Value): boolean => {
1431
1663
  }
1432
1664
  };
1433
1665
 
1434
- const getProductCardinality = (sets: Value[], describe: () => string) =>
1666
+ const getProductCardinality = (
1667
+ sets: Value[],
1668
+ version: TlcVersion | undefined,
1669
+ describe: () => string,
1670
+ ) =>
1435
1671
  sets.reduce<number>((product, set) => {
1436
- const size = product * getCardinality(set);
1672
+ const size = product * getCardinality(set, version);
1437
1673
  if (size > MAXIMUM_INTEGER) throw new TlaEvaluationError(describe());
1438
1674
  return size;
1439
1675
  }, 1);
@@ -1441,9 +1677,25 @@ const getProductCardinality = (sets: Value[], describe: () => string) =>
1441
1677
  const describeOverflow = (value: Value) =>
1442
1678
  `Overflow when computing the number of elements in:\n${formatValue(value)}`;
1443
1679
 
1444
- export const getCardinality = (value: Value): number => {
1445
- if (typeof value !== "object") return toFiniteSet(value).elements.length;
1680
+ // TLC 1.7.4 sizes every component of a set of functions, records, or tuples without first
1681
+ // checking whether one is empty, so an infinite component fails even beside an empty one.
1682
+ export const getCardinality = (value: Value, version?: TlcVersion): number => {
1683
+ if (typeof value !== "object") {
1684
+ const kind =
1685
+ typeof value === "number" ? "integer" : typeof value === "string" ? "string" : "boolean";
1686
+ throw new TlaEvaluationError(
1687
+ `Attempted to compute the number of elements in the ${kind} ${formatValue(value)}.`,
1688
+ );
1689
+ }
1446
1690
  switch (value.kind) {
1691
+ case "ModelValue":
1692
+ throw new TlaEvaluationError(
1693
+ `Attempted to compute the number of elements in the model value ${formatValue(value)}.`,
1694
+ );
1695
+ case "Function":
1696
+ return value.domain.length;
1697
+ case "LazyFunction":
1698
+ return getCardinality(value.domain, version);
1447
1699
  case "Interval": {
1448
1700
  const size = Math.max(0, value.high - value.low + 1);
1449
1701
  if (size > MAXIMUM_INTEGER) {
@@ -1459,16 +1711,19 @@ export const getCardinality = (value: Value): number => {
1459
1711
  `Attempted to compute the number of elements in the overridden value ${formatValue(value)}.`,
1460
1712
  );
1461
1713
  case "Subset": {
1462
- const size = getCardinality(value.base);
1714
+ const size = getCardinality(value.base, version);
1463
1715
  if (size >= 31) throw new TlaEvaluationError(describeOverflow(value));
1464
1716
  return 2 ** size;
1465
1717
  }
1466
1718
  case "FunctionSet": {
1467
- if (isEmptySet(value.domain)) return 1;
1468
- if (isEmptySet(value.range)) return 0;
1469
- const rangeSize = getCardinality(value.range);
1470
- if (rangeSize === 1) return 1;
1471
- const domainSize = getCardinality(value.domain);
1719
+ if (version !== "1.7.4") {
1720
+ if (isEmptySet(value.domain)) return 1;
1721
+ if (isEmptySet(value.range)) return 0;
1722
+ if (getCardinality(value.range, version) === 1) return 1;
1723
+ }
1724
+ const domainSize = getCardinality(value.domain, version);
1725
+ const rangeSize = getCardinality(value.range, version);
1726
+ if (rangeSize <= 1) return domainSize === 0 ? 1 : rangeSize;
1472
1727
  const size = { value: 1 };
1473
1728
  for (let index = 0; index < domainSize; index++) {
1474
1729
  size.value *= rangeSize;
@@ -1477,15 +1732,17 @@ export const getCardinality = (value: Value): number => {
1477
1732
  return size.value;
1478
1733
  }
1479
1734
  case "RecordSet":
1480
- if (isEmptySet(value)) return 0;
1481
- return getProductCardinality(value.sets, () => describeOverflow(value));
1735
+ if (version !== "1.7.4" && isEmptySet(value)) return 0;
1736
+ return getProductCardinality(value.sets, version, () => describeOverflow(value));
1482
1737
  case "ProductSet":
1483
- if (isEmptySet(value)) return 0;
1738
+ if (version !== "1.7.4" && isEmptySet(value)) return 0;
1484
1739
  return getProductCardinality(
1485
1740
  value.factors,
1741
+ version,
1486
1742
  () => `Overflow when computing the number of elements in ${formatValue(value)}`,
1487
1743
  );
1488
1744
  default:
1745
+ cacheSet(value);
1489
1746
  return toFiniteSet(value).elements.length;
1490
1747
  }
1491
1748
  };
@@ -1560,11 +1817,11 @@ export const isFiniteSet = (value: Value): boolean => {
1560
1817
  }
1561
1818
  };
1562
1819
 
1563
- const findIndex = (sortedValues: Value[], target: Value) => {
1820
+ const findIndex = (sortedValues: Value[], target: Value, compare = compareValues) => {
1564
1821
  const bounds = { low: 0, high: sortedValues.length - 1 };
1565
1822
  while (bounds.low <= bounds.high) {
1566
1823
  const middle = (bounds.low + bounds.high) >> 1;
1567
- const comparison = compareValues(sortedValues[middle], target);
1824
+ const comparison = compare(sortedValues[middle], target);
1568
1825
  if (comparison === 0) return middle;
1569
1826
  if (comparison < 0) bounds.low = middle + 1;
1570
1827
  else bounds.high = middle - 1;
@@ -1580,33 +1837,78 @@ export const getSequenceElements = (value: Value): Value[] | undefined => {
1580
1837
  : undefined;
1581
1838
  };
1582
1839
 
1583
- const describeMembership = (element: Value, set: Value) =>
1584
- `Attempted to check if the value ${formatValue(element)} is an element of ${formatValue(set)}`;
1585
-
1586
1840
  const describeNonSetMembership = (element: Value, value: Value) => {
1587
1841
  const prefix = `Attempted to check if the value:\n${formatValue(element)}\nis an element of the`;
1588
1842
  if (!isFunctionValue(value)) return `${prefix} ${describeKind(value)} ${formatValue(value)}`;
1589
- const domain =
1590
- value.kind === "Function" || isEnumerable(value.domain) ? toFiniteFunction(value).domain : [];
1591
- if (domain.length > 0 && domain.every((key) => typeof key === "string")) {
1843
+ const functionClass = getFunctionClass(value);
1844
+ if (functionClass === "record") {
1592
1845
  return `Attempted to check if element:\n${formatValue(element)}\nis in the record:\n${formatValue(value)}`;
1593
1846
  }
1594
- if (domain.every((key, index) => key === index + 1)) {
1595
- return "Attempted to check set membership in a tuple value.";
1596
- }
1847
+ if (functionClass === "tuple") return "Attempted to check set membership in a tuple value.";
1597
1848
  return `${prefix} function ${formatValue(value)}`;
1598
1849
  };
1599
1850
 
1851
+ // The call stack of the replay, which a failed fast path leaves frozen.
1852
+ interface TracedCallStack {
1853
+ expressions: unknown[];
1854
+ isFrozen: boolean;
1855
+ fingerprint?: unknown;
1856
+ }
1857
+
1858
+ // The sets whose membership is being checked or whose elements are being enumerated, and the
1859
+ // members being compared, outermost first, while TLC's CallStackTool replays a computation. A failed
1860
+ // check or enumeration leaves the values it was in, each of which TLC adds to the
1861
+ // FingerprintException when it has a source.
1862
+ export const setTrace: { sets: Value[] | undefined; callStack?: TracedCallStack } = {
1863
+ sets: undefined,
1864
+ };
1865
+
1866
+ // Takes a fast path, and computes as TLC does where it fails. TLC never takes the fast path, so
1867
+ // the failure's leftovers in the replay's trace go first.
1868
+ export const computeLikeTlcOnFailure = <Result>(
1869
+ compute: () => Result,
1870
+ computeLikeTlc: (error: TlaEvaluationError) => Result,
1871
+ ): Result => {
1872
+ const sets = setTrace.sets;
1873
+ const callStack = setTrace.callStack;
1874
+ const depth = sets?.length ?? 0;
1875
+ const trace = callStack && { ...callStack, length: callStack.expressions.length };
1876
+ try {
1877
+ return compute();
1878
+ } catch (error) {
1879
+ if (!(error instanceof TlaEvaluationError)) throw error;
1880
+ if (sets) sets.length = depth;
1881
+ if (callStack && trace) {
1882
+ callStack.expressions.length = trace.length;
1883
+ callStack.isFrozen = trace.isFrozen;
1884
+ callStack.fingerprint = trace.fingerprint;
1885
+ }
1886
+ return computeLikeTlc(error);
1887
+ }
1888
+ };
1889
+
1600
1890
  export const isElementOf = (element: Value, set: Value): boolean => {
1891
+ const sets = setTrace.sets;
1892
+ if (sets === undefined) return isElementOfSet(element, set);
1893
+ sets.push(set);
1894
+ const isElement = isElementOfSet(element, set);
1895
+ sets.pop();
1896
+ return isElement;
1897
+ };
1898
+
1899
+ const isElementOfSet = (element: Value, set: Value): boolean => {
1601
1900
  if (!isSetValue(set)) throw new TlaEvaluationError(describeNonSetMembership(element, set));
1602
1901
  switch (set.kind) {
1603
1902
  case "Set":
1604
- try {
1605
- return findIndex(set.elements, element) !== -1;
1606
- } catch (error) {
1607
- if (!(error instanceof TlaEvaluationError)) throw error;
1608
- return isElementOfLikeTlc(element, set.elements);
1609
- }
1903
+ // SetEnumValue.member compares the element with the set's.
1904
+ cacheSet(element);
1905
+ return computeLikeTlcOnFailure(
1906
+ () => findIndex(set.elements, element) !== -1,
1907
+ () =>
1908
+ normalizedSets.has(set)
1909
+ ? searchLikeTlc(element, set.elements).isFound
1910
+ : isElementOfLikeTlc(element, set.elements),
1911
+ );
1610
1912
  case "MixedSet":
1611
1913
  return isElementOfLikeTlc(element, set.elements);
1612
1914
  case "Interval":
@@ -1630,12 +1932,21 @@ export const isElementOf = (element: Value, set: Value): boolean => {
1630
1932
  return set.name !== "Nat" || (typeof element === "number" && element >= 0);
1631
1933
  }
1632
1934
  case "Subset":
1633
- if (!isSetValue(element)) throw new TlaEvaluationError(describeMembership(element, set));
1935
+ // SubsetValue.member fails on any value that is not Enumerable, model values and the sets a
1936
+ // Java class overrides included.
1937
+ if (!isSetValue(element) || isOverriddenSet(element)) {
1938
+ throw new TlaEvaluationError(
1939
+ `Attempted to check if the non-enumerable value\n${prettyPrint(formatValue(element))}\nis element of\n${prettyPrint(formatValue(set))}`,
1940
+ );
1941
+ }
1634
1942
  return toFiniteSet(element).elements.every((item) => isElementOf(item, set.base));
1635
1943
  case "FunctionSet": {
1636
1944
  if (!isFunctionValue(element)) {
1637
1945
  if (isModelValue(element)) return false;
1638
- throw new TlaEvaluationError(describeMembership(element, set));
1946
+ // SetOfFcnsValue.member prints the element without Values.ppr.
1947
+ throw new TlaEvaluationError(
1948
+ `Attempted to check if \n${formatValue(element)}\nwhich is not a TLC function value, is in the set of functions:\n${prettyPrint(formatValue(set))}`,
1949
+ );
1639
1950
  }
1640
1951
  const functionValue = toFiniteFunction(element);
1641
1952
  const low = getIntervalLow(functionValue.domain);
@@ -1700,7 +2011,10 @@ export const isElementOf = (element: Value, set: Value): boolean => {
1700
2011
  const elements = getSequenceElements(element);
1701
2012
  if (elements === undefined) {
1702
2013
  if (isModelValue(element)) return false;
1703
- throw new TlaEvaluationError(describeMembership(element, set));
2014
+ // Sequences.member raises TLC_MODULE_CHECK_MEMBER_OF.
2015
+ throw new TlaEvaluationError(
2016
+ `Attempted to check if the value:\n${prettyPrint(formatValue(element))}\nis an element of ${prettyPrint(formatValue(set))}.`,
2017
+ );
1704
2018
  }
1705
2019
  return elements.every((item) => isElementOf(item, set.base));
1706
2020
  }
@@ -1733,77 +2047,58 @@ export const toFiniteFunction = (value: Value): FunctionValue => {
1733
2047
  if (typeof value === "object" && value.kind === "LazyFunction") {
1734
2048
  if (!isEnumerable(value.domain)) getCardinality(value.domain);
1735
2049
  const domain = getFunctionDomain(value.domain);
1736
- return createSortedFunction(
1737
- domain,
1738
- domain.map((key) => value.apply(key)),
2050
+ return setFunctionClass(
2051
+ createSortedFunction(
2052
+ domain,
2053
+ domain.map((key) => value.apply(key)),
2054
+ ),
2055
+ getFunctionClass(value),
1739
2056
  );
1740
2057
  }
1741
2058
  throw new TlaEvaluationError(`Expected a function but found ${formatValue(value)}`);
1742
2059
  };
1743
2060
 
1744
- const lambdaFunctions = new WeakSet<ObjectValue>();
1745
-
1746
- export const markLambdaFunction = <FunctionLike extends FunctionValue | LazyFunctionValue>(
1747
- functionValue: FunctionLike,
2061
+ export const describeMissingArgument = (
2062
+ functionValue: Value,
2063
+ argument: Value,
2064
+ version?: TlcVersion,
1748
2065
  ) => {
1749
- lambdaFunctions.add(functionValue);
1750
- return functionValue;
1751
- };
1752
-
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";
2066
+ const shown = prettyPrint(formatValue(functionValue));
2067
+ const shownArgument = prettyPrint(formatValue(argument));
2068
+ const is174 = version === "1.7.4";
2069
+ switch (getFunctionClass(functionValue)) {
2070
+ case "lambda":
2071
+ return `In applying the function\n${shown},\nthe first argument is:\n${shownArgument}\nwhich is not in its domain.\n`;
2072
+ case "tuple":
2073
+ if (typeof argument !== "number") {
2074
+ return is174
2075
+ ? "Attempted to apply tuple to a non-integer argument."
2076
+ : `Attempted to access tuple at a non integral index: ${shownArgument}`;
2077
+ }
2078
+ return is174
2079
+ ? `Attempted to apply tuple\n${shown}\nto integer ${argument} which is out of domain.`
2080
+ : `Attempted to access index ${argument} of tuple\n${shown}\nwhich is out of bounds.`;
2081
+ case "record":
2082
+ if (typeof argument !== "string") {
2083
+ return is174
2084
+ ? `Attempted to apply record to a non-string value ${shownArgument}.`
2085
+ : `Attempted to access record by a non-string argument: ${shownArgument}`;
2086
+ }
2087
+ return is174
2088
+ ? `Attempted to apply the record\n${shown}\nto nonexistent record field ${argument}.`
2089
+ : `Attempted to access nonexistent field '${argument}' of record\n${shown}`;
2090
+ default:
2091
+ return `Attempted to apply function:\n${shown}\nto argument ${shownArgument}, which is not in the domain of the function.`;
2092
+ }
1761
2093
  };
1762
2094
 
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";
2095
+ // TLC 1.7.4 words a key of the wrong type in an EXCEPT, which selects rather than applies, apart.
2096
+ const describeExceptKey = (functionValue: FunctionValue, argument: Value) => {
2097
+ if (!valueVersion.is174) return describeMissingArgument(functionValue, argument);
2098
+ const shown = prettyPrint(formatValue(argument));
2099
+ return getFunctionClass(functionValue) === "tuple"
2100
+ ? `Attempted to apply tuple to a non-integer argument ${shown}.`
2101
+ : `Attempted to apply record to a non-string argument ${shown}.`;
1807
2102
  };
1808
2103
 
1809
2104
  const findKeyIndex = (domain: Value[], argument: Value) => {
@@ -1819,16 +2114,57 @@ const findKeyIndex = (domain: Value[], argument: Value) => {
1819
2114
  return findIndex(domain, argument);
1820
2115
  };
1821
2116
 
2117
+ export const createNonIntegerKeyError = (argument: Value) =>
2118
+ new TlaEvaluationError(
2119
+ `Attempted to apply function with integer domain to the non-integer argument ${prettyPrint(formatValue(argument))}`,
2120
+ );
2121
+
2122
+ // TLC's FcnRcdValue searches a domain this small linearly with equals, and a larger normalized one by
2123
+ // binary search with compareTo.
2124
+ const LINEAR_SEARCH_LIMIT = 32;
2125
+
2126
+ // TLC looks a key up by the Java class of the function: a tuple or a record rejects a key of the
2127
+ // wrong type, and another function rejects a non-integer for a domain it keeps as an interval, which
2128
+ // TLC 1.7.4 doesn't. A key of another type than the domain's keys otherwise fails TLC's comparison.
2129
+ const findKeyIndexLikeTlc = (
2130
+ functionValue: FunctionValue,
2131
+ argument: Value,
2132
+ describeWrongKey: (functionValue: FunctionValue, argument: Value) => string,
2133
+ ) => {
2134
+ const domain = functionValue.domain;
2135
+ if (typeof argument !== typeof domain[0]) {
2136
+ const functionClass = getFunctionClass(functionValue);
2137
+ const keyType =
2138
+ functionClass === "tuple" ? "number" : functionClass === "record" ? "string" : undefined;
2139
+ if (keyType !== undefined && typeof argument !== keyType) {
2140
+ throw new TlaEvaluationError(describeWrongKey(functionValue, argument));
2141
+ }
2142
+ if (keyType === undefined && !valueVersion.is174 && isIntervalDomain(domain)) {
2143
+ throw createNonIntegerKeyError(argument);
2144
+ }
2145
+ }
2146
+ return computeLikeTlcOnFailure(
2147
+ () => findKeyIndex(domain, argument),
2148
+ (error) => {
2149
+ if (valueVersion.is174 || domain.length < LINEAR_SEARCH_LIMIT) {
2150
+ domain.forEach((key) => equalsLikeTlc(key, argument));
2151
+ } else {
2152
+ findIndex(domain, argument, compareLikeTlc);
2153
+ }
2154
+ throw error;
2155
+ },
2156
+ );
2157
+ };
2158
+
1822
2159
  export const applyFunction = (
1823
2160
  functionValue: Value,
1824
2161
  argument: Value,
1825
- describeMissing?: (functionValue: FunctionValue) => string,
1826
- describeNonFunction?: (value: Value) => string,
2162
+ describeMissing?: (functionValue: FunctionValue, argument: Value) => string,
1827
2163
  ): Value => {
1828
2164
  if (typeof functionValue === "object" && functionValue.kind === "LazyFunction") {
1829
2165
  if (!isElementOf(argument, functionValue.domain)) {
1830
2166
  throw new TlaEvaluationError(
1831
- lambdaFunctions.has(functionValue)
2167
+ getFunctionClass(functionValue) === "lambda"
1832
2168
  ? describeMissingArgument(functionValue, argument)
1833
2169
  : `Attempted to apply a function to ${formatValue(argument)}, which is not in its domain`,
1834
2170
  );
@@ -1837,18 +2173,12 @@ export const applyFunction = (
1837
2173
  }
1838
2174
  if (typeof functionValue !== "object" || functionValue.kind !== "Function") {
1839
2175
  throw new TlaEvaluationError(
1840
- describeNonFunction?.(functionValue) ??
1841
- `Attempted to apply ${formatValue(functionValue)}, which is not a function`,
1842
- );
1843
- }
1844
- const position = isForeignKey(functionValue.domain, argument)
1845
- ? -1
1846
- : findKeyIndex(functionValue.domain, argument);
1847
- if (position === -1) {
1848
- throw new TlaEvaluationError(
1849
- describeMissing?.(functionValue) ?? describeMissingArgument(functionValue, argument),
2176
+ `Attempted to apply ${formatValue(functionValue)}, which is not a function`,
1850
2177
  );
1851
2178
  }
2179
+ const describe = describeMissing ?? describeMissingArgument;
2180
+ const position = findKeyIndexLikeTlc(functionValue, argument, describe);
2181
+ if (position === -1) throw new TlaEvaluationError(describe(functionValue, argument));
1852
2182
  return functionValue.range[position];
1853
2183
  };
1854
2184
 
@@ -1877,28 +2207,45 @@ export const updateFunction = (
1877
2207
  if (isLazy) {
1878
2208
  if (!isElementOf(argument, functionValue.domain)) return functionValue;
1879
2209
  const updated = update(functionValue.apply(argument));
1880
- return {
1881
- kind: "LazyFunction",
1882
- domain: functionValue.domain,
1883
- apply: (key) => (isEqualLikeTlc(argument, key) ? updated : functionValue.apply(key)),
1884
- source: functionValue.source,
1885
- };
2210
+ return setFunctionClass<LazyFunctionValue>(
2211
+ {
2212
+ kind: "LazyFunction",
2213
+ domain: functionValue.domain,
2214
+ apply: (key) => (isEqualLikeTlc(argument, key) ? updated : functionValue.apply(key)),
2215
+ source: functionValue.source,
2216
+ },
2217
+ getFunctionClass(functionValue),
2218
+ );
2219
+ }
2220
+ if (!isFunctionValue(functionValue)) {
2221
+ throw new TlaEvaluationError(
2222
+ `Attempted to apply EXCEPT construct to the value ${prettyPrint(formatValue(functionValue))}.`,
2223
+ );
1886
2224
  }
1887
2225
  const finite = toFiniteFunction(functionValue);
1888
- const position = findKeyIndex(finite.domain, argument);
2226
+ const position = findKeyIndexLikeTlc(finite, argument, describeExceptKey);
1889
2227
  if (position === -1) return finite;
1890
2228
  const range = [...finite.range];
1891
2229
  const previous = finite.range[position];
1892
2230
  const next = update(previous);
1893
2231
  range[position] = next;
1894
- const updated = createSortedFunction(finite.domain, range);
2232
+ const updated = setFunctionClass(
2233
+ createSortedFunction(finite.domain, range),
2234
+ getFunctionClass(finite),
2235
+ );
1895
2236
  updated.writtenKeys = finite.writtenKeys;
1896
- if (finite.hash !== 0) {
1897
- const key = finite.domain[position];
1898
- updated.hash =
1899
- previous === next
1900
- ? finite.hash
1901
- : (finite.hash - getEntryContribution(key, previous) + getEntryContribution(key, next)) | 0;
2237
+ if (finite.hash !== 0 && finite.hash !== UNFINGERPRINTABLE_HASH) {
2238
+ const nextHash = getValueHash(next);
2239
+ if (nextHash !== UNFINGERPRINTABLE_HASH) {
2240
+ const keyHash = getValueHash(finite.domain[position]);
2241
+ updated.hash =
2242
+ previous === next
2243
+ ? finite.hash
2244
+ : (finite.hash -
2245
+ getEntryContribution(keyHash, getValueHash(previous)) +
2246
+ getEntryContribution(keyHash, nextHash)) |
2247
+ 0;
2248
+ }
1902
2249
  }
1903
2250
  if (finite.fingerprint !== 0) {
1904
2251
  const key = finite.domain[position];
@@ -1935,32 +2282,103 @@ const hashString = (value: string) => {
1935
2282
  const SET_HASH_SEED = 0x73a5c3e1;
1936
2283
  const FUNCTION_HASH_SEED = 0x66d1b4f7;
1937
2284
 
1938
- const getElementContribution = (element: Value) =>
1939
- finalizeHash((getValueHash(element) + 0x9e3779b9) | 0);
2285
+ const getElementContribution = (elementHash: number) =>
2286
+ finalizeHash((elementHash + 0x9e3779b9) | 0);
2287
+
2288
+ const getEntryContribution = (keyHash: number, valueHash: number) =>
2289
+ finalizeHash((Math.imul(keyHash, 0x27d4eb2d) + valueHash) | 0);
1940
2290
 
1941
- const getEntryContribution = (key: Value, value: Value) =>
1942
- finalizeHash((Math.imul(getValueHash(key), 0x27d4eb2d) + getValueHash(value)) | 0);
2291
+ // The hash of each value that TLC fails to fingerprint, such as Nat or a set that holds it. Calls
2292
+ // with such a value as an argument still share their result, and a state that holds one fails
2293
+ // when TLC fingerprints it.
2294
+ const UNFINGERPRINTABLE_HASH = 0x2f6b1c4d;
1943
2295
 
1944
2296
  const computeValueHash = (value: ObjectValue) => {
1945
2297
  if (value.kind === "ModelValue") return finalizeHash(combineHash(hashString(value.name), 0x6d));
1946
2298
  if (isSetValue(value)) {
1947
- if (!isEnumerable(value)) return hashString(getValueKey(value));
2299
+ if (!isEnumerable(value)) return UNFINGERPRINTABLE_HASH;
1948
2300
  const elements = toFiniteSet(value).elements;
1949
2301
  let hash = SET_HASH_SEED;
1950
2302
  for (let index = 0; index < elements.length; index++) {
1951
- hash = (hash + getElementContribution(elements[index])) | 0;
2303
+ const elementHash = getValueHash(elements[index]);
2304
+ if (elementHash === UNFINGERPRINTABLE_HASH) return UNFINGERPRINTABLE_HASH;
2305
+ hash = (hash + getElementContribution(elementHash)) | 0;
1952
2306
  }
1953
2307
  return hash;
1954
2308
  }
2309
+ if (value.kind === "LazyFunction" && !isEnumerable(value.domain)) return UNFINGERPRINTABLE_HASH;
1955
2310
  const functionValue = toFiniteFunction(value);
1956
2311
  let hash = FUNCTION_HASH_SEED;
1957
2312
  for (let index = 0; index < functionValue.domain.length; index++) {
1958
- hash =
1959
- (hash + getEntryContribution(functionValue.domain[index], functionValue.range[index])) | 0;
2313
+ const keyHash = getValueHash(functionValue.domain[index]);
2314
+ const itemHash = getValueHash(functionValue.range[index]);
2315
+ if (keyHash === UNFINGERPRINTABLE_HASH || itemHash === UNFINGERPRINTABLE_HASH) {
2316
+ return UNFINGERPRINTABLE_HASH;
2317
+ }
2318
+ hash = (hash + getEntryContribution(keyHash, itemHash)) | 0;
1960
2319
  }
1961
2320
  return hash;
1962
2321
  };
1963
2322
 
2323
+ // TLC's fingerPrint enumerates each set and function a value holds, and fails on Nat, Seq(S) and
2324
+ // the like, which it never enumerates.
2325
+ const fingerprintValue = (value: Value): void => {
2326
+ if (typeof value !== "object" || value.kind === "ModelValue") return;
2327
+ if (value.kind === "InfiniteSet" || value.kind === "SequenceSet") {
2328
+ throw new TlaEvaluationError(
2329
+ `TLC has found a state in which the value of a variable contains ${formatValue(value)}`,
2330
+ );
2331
+ }
2332
+ if (isSetValue(value)) {
2333
+ toFiniteSet(value).elements.forEach(fingerprintValue);
2334
+ return;
2335
+ }
2336
+ const functionValue = toFiniteFunction(value);
2337
+ functionValue.domain.forEach(fingerprintValue);
2338
+ functionValue.range.forEach(fingerprintValue);
2339
+ };
2340
+
2341
+ // The error TLC raises as it fingerprints a value: one that hashing the value raises, as for a set
2342
+ // too large to enumerate, or one of a value with the hash of the values TLC fails on.
2343
+ export const getFingerprintError = (value: Value) => {
2344
+ if (typeof value !== "object" || value.kind === "ModelValue") return undefined;
2345
+ try {
2346
+ if (getValueHash(value) === UNFINGERPRINTABLE_HASH) fingerprintValue(value);
2347
+ return undefined;
2348
+ } catch (error) {
2349
+ if (!(error instanceof TlaEvaluationError)) throw error;
2350
+ return error;
2351
+ }
2352
+ };
2353
+
2354
+ // The values a value holds, which TLC fingerprints as it fingerprints the value.
2355
+ export const getHeldValues = (value: ObjectValue): Value[] => {
2356
+ switch (value.kind) {
2357
+ case "Set":
2358
+ case "MixedSet":
2359
+ return value.elements;
2360
+ case "Function":
2361
+ return [...value.domain, ...value.range];
2362
+ case "Subset":
2363
+ case "SequenceSet":
2364
+ case "FilteredSet":
2365
+ case "Union":
2366
+ return [value.base];
2367
+ case "FunctionSet":
2368
+ return [value.domain, value.range];
2369
+ case "RecordSet":
2370
+ return value.sets;
2371
+ case "ProductSet":
2372
+ return value.factors;
2373
+ case "SetOperation":
2374
+ return [value.left, value.right];
2375
+ case "LazyFunction":
2376
+ return [value.domain];
2377
+ default:
2378
+ return [];
2379
+ }
2380
+ };
2381
+
1964
2382
  export const getValueHash = (value: Value): number => {
1965
2383
  if (typeof value === "number") return finalizeHash(value ^ 0x5bd1e995);
1966
2384
  if (typeof value === "boolean") return value ? 0x2b7e1516 : 0x28aed2a6;
@@ -2135,7 +2553,9 @@ const formatLazySet = (value: LazySetValue, isStrict: boolean): string => {
2135
2553
  case "SetOperation":
2136
2554
  return `${format(value.left)} ${value.operator} ${format(value.right)}`;
2137
2555
  case "FilteredSet":
2138
- return `{x \\in ${format(value.base)} : ...}`;
2556
+ return value.source
2557
+ ? `{${value.source.names} \\in ${format(value.base)} : <expression ${value.source.predicate}> }`
2558
+ : `{x \\in ${format(value.base)} : ...}`;
2139
2559
  case "Union":
2140
2560
  return formatUnion(value, isStrict);
2141
2561
  }
@@ -2148,6 +2568,17 @@ const isFieldName = (name: string) =>
2148
2568
  /\p{L}/u.test(name) &&
2149
2569
  (name.length < 4 || !/^[WS]F_/.test(name));
2150
2570
 
2571
+ // FcnLambdaValue#toString prints a function it fails to enumerate as its parameters and body.
2572
+ const toPrintedFunction = (value: LazyFunctionValue) => {
2573
+ if (!isEnumerable(value.domain)) return undefined;
2574
+ try {
2575
+ return toFiniteFunction(value);
2576
+ } catch (error) {
2577
+ if (error instanceof TlaEvaluationError) return undefined;
2578
+ throw error;
2579
+ }
2580
+ };
2581
+
2151
2582
  export const formatValue = (value: Value, isStrict = false, isNormalized = false): string => {
2152
2583
  const format = (inner: Value) => formatValue(inner, isStrict, isNormalized);
2153
2584
  if (typeof value === "boolean") return value ? "TRUE" : "FALSE";
@@ -2179,22 +2610,34 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
2179
2610
  return `Seq(${format(value.base)})`;
2180
2611
  case "Function":
2181
2612
  case "LazyFunction": {
2182
- if (value.kind === "LazyFunction" && !isEnumerable(value.domain)) {
2183
- const source = value.source;
2613
+ const functionValue = value.kind === "LazyFunction" ? toPrintedFunction(value) : value;
2614
+ if (functionValue === undefined) {
2615
+ const source = value.kind === "LazyFunction" ? value.source : undefined;
2184
2616
  if (!source) return "<function>";
2185
2617
  const parameters = source.parameters
2186
2618
  .map((parameter) => `${parameter.name} \\in ${formatValue(parameter.domain)}`)
2187
2619
  .join(", ");
2188
2620
  return `[${parameters} |-> <expression ${source.body}>]`;
2189
2621
  }
2190
- const functionValue = toFiniteFunction(value);
2622
+ if (
2623
+ functionValue.domain.length === 0 &&
2624
+ valueVersion.is174 &&
2625
+ getFunctionClass(value) !== "tuple"
2626
+ ) {
2627
+ return "<< >>";
2628
+ }
2191
2629
  // TLC normalizes a lambda's domain to print it, but evaluates its body afterward.
2192
2630
  const formatRange = (inner: Value) =>
2193
- formatValue(inner, isStrict, isNormalized && value.kind === "Function");
2631
+ formatValue(inner, isStrict, isNormalized && getFunctionClass(value) !== "lambda");
2194
2632
  if (functionValue.domain.every((key, index) => key === index + 1)) {
2195
2633
  return `<<${functionValue.range.map(formatRange).join(", ")}>>`;
2196
2634
  }
2197
- if (functionValue.domain.every((key) => typeof key === "string" && isFieldName(key))) {
2635
+ // A RecordValue prints as a record whatever its fields, and a FcnRcdValue only if each key
2636
+ // is a name.
2637
+ if (
2638
+ getFunctionClass(value) === "record" ||
2639
+ functionValue.domain.every((key) => typeof key === "string" && isFieldName(key))
2640
+ ) {
2198
2641
  const isSorted =
2199
2642
  isNormalized || functionValue.hash !== 0 || functionValue.fingerprint !== 0;
2200
2643
  const pairs = isSorted