tla-ts 0.0.3-dev.51ddd47 → 0.0.3-dev.596cd91

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 (83) hide show
  1. package/README.md +12 -12
  2. package/dist/cli.cjs +1 -1
  3. package/dist/cli.js +1 -1
  4. package/dist/index.cjs +1 -1
  5. package/dist/index.d.cts +150 -8
  6. package/dist/index.d.ts +150 -8
  7. package/dist/index.js +1 -1
  8. package/dist/parallel-worker.cjs +1 -1
  9. package/dist/parallel-worker.js +2 -2
  10. package/dist/parallel.cjs +1 -1
  11. package/dist/parallel.js +2 -2
  12. package/dist/run-cli.cjs +45 -19
  13. package/dist/run-cli.js +45 -19
  14. package/dist/transfer.cjs +1391 -28
  15. package/dist/transfer.js +1391 -28
  16. package/package.json +5 -1
  17. package/src/ast.ts +57 -6
  18. package/src/bags.ts +4 -7
  19. package/src/builtins.ts +29 -11
  20. package/src/bundled-modules.ts +3 -3
  21. package/src/canonical.ts +4 -3
  22. package/src/check.ts +1393 -226
  23. package/src/cli.ts +8 -1
  24. package/src/codegen.ts +68 -18
  25. package/src/config.ts +254 -181
  26. package/src/environment.ts +473 -132
  27. package/src/errors.ts +217 -3
  28. package/src/evaluate.ts +722 -112
  29. package/src/exit-codes.ts +5 -4
  30. package/src/index.ts +1 -0
  31. package/src/instances.ts +4 -2
  32. package/src/java-overrides.ts +104 -25
  33. package/src/levels.ts +183 -37
  34. package/src/lexer.ts +122 -29
  35. package/src/live-check.ts +220 -102
  36. package/src/liveness.ts +216 -52
  37. package/src/obligation-expression.ts +2 -2
  38. package/src/obligation-source.ts +2 -0
  39. package/src/parallel-worker.ts +8 -3
  40. package/src/parallel.ts +56 -5
  41. package/src/parser.ts +445 -147
  42. package/src/pcal-ast.ts +770 -0
  43. package/src/pcal-parse.ts +1523 -0
  44. package/src/pcal-tokenize.ts +516 -0
  45. package/src/pcal-translate.ts +1230 -0
  46. package/src/pcal-validate.ts +454 -0
  47. package/src/randomization.ts +24 -7
  48. package/src/resolve.ts +1465 -411
  49. package/src/run-cli.ts +1179 -155
  50. package/src/runtime.ts +16 -0
  51. package/src/sany-builtins.ts +147 -0
  52. package/src/sany-generator.ts +3128 -0
  53. package/src/sany-levels.ts +1208 -0
  54. package/src/sany-lexer.ts +545 -0
  55. package/src/sany-linter.ts +122 -0
  56. package/src/sany-modules.ts +1398 -0
  57. package/src/sany-nodes.ts +463 -0
  58. package/src/sany-parse-error.ts +2161 -0
  59. package/src/sany-report.ts +356 -0
  60. package/src/sany-selectors.ts +738 -0
  61. package/src/sany-source.ts +248 -0
  62. package/src/sany-xml.ts +1017 -0
  63. package/src/spec-description.ts +26 -7
  64. package/src/standard-modules.ts +200 -148
  65. package/src/standard-ranges.ts +116 -0
  66. package/src/state-graph.ts +29 -6
  67. package/src/subexpressions.ts +221 -161
  68. package/src/substitution-levels.ts +38 -17
  69. package/src/successors.ts +207 -103
  70. package/src/symmetry.ts +180 -52
  71. package/src/tableau.ts +54 -25
  72. package/src/tlc-ext.ts +13 -17
  73. package/src/tlc-messages.ts +329 -0
  74. package/src/tlc-module.ts +46 -18
  75. package/src/tlc-modules.ts +4 -0
  76. package/src/tlc-order.ts +61 -7
  77. package/src/tlc-random.ts +37 -9
  78. package/src/tlc-replay.ts +655 -0
  79. package/src/tlc-summary.ts +20 -5
  80. package/src/tlc-version.ts +18 -0
  81. package/src/transfer.ts +15 -3
  82. package/src/value-sources.ts +29 -0
  83. package/src/values.ts +713 -180
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,6 +147,12 @@ export const isSetValue = (value: Value) =>
137
147
  value.kind !== "Function" &&
138
148
  value.kind !== "LazyFunction";
139
149
 
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 =>
153
+ typeof value === "object" &&
154
+ (value.kind === "Set" || value.kind === "MixedSet" || value.kind === "Interval");
155
+
140
156
  export const isFunctionValue = (value: Value): value is FunctionValue | LazyFunctionValue =>
141
157
  typeof value === "object" && (value.kind === "Function" || value.kind === "LazyFunction");
142
158
 
@@ -175,7 +191,7 @@ export const getWrittenPairs = (functionValue: FunctionValue): [Value, Value][]
175
191
  };
176
192
 
177
193
  export const createWrittenRecord = (names: Value[], range: Value[], writtenNames: Value[]) =>
178
- setWrittenOrder(createSortedFunction(names, range), writtenNames);
194
+ setWrittenOrder(createSortedRecord(names, range), writtenNames);
179
195
 
180
196
  // TLC sorts a value it compares even with itself, and every value inside it, so a value it has
181
197
  // hashed or fingerprinted is already sorted.
@@ -260,7 +276,10 @@ const checkModelValueTypes = (left: Value, right: Value, isEquality: boolean) =>
260
276
 
261
277
  // TLC orders strings and model value names by when it first interned the text, so every
262
278
  // check sets the order of its spec's strings before it builds any value.
263
- 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
+ };
264
283
 
265
284
  export const setStringOrder = (texts: Iterable<string>) => {
266
285
  stringOrder.ranks = Object.create(null);
@@ -269,6 +288,14 @@ export const setStringOrder = (texts: Iterable<string>) => {
269
288
  for (const text of texts) rankString(text);
270
289
  };
271
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
+
272
299
  export const rankString = (text: string) => {
273
300
  if (stringOrder.ranks[text] === undefined) stringOrder.ranks[text] = stringOrder.size++;
274
301
  return text;
@@ -415,9 +442,101 @@ export const createSortedFunction = (domain: Value[], range: Value[]): FunctionV
415
442
  hash: 0,
416
443
  fingerprint: 0,
417
444
  writtenKeys: undefined,
445
+ functionClass: undefined,
418
446
  });
419
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
+
420
538
  export const valuesEqual = (left: Value, right: Value): boolean => {
539
+ cacheSet(left);
421
540
  if (left === right) {
422
541
  if (writtenOrderUse.isUsed) forgetWrittenOrder(left);
423
542
  return left !== ANY_SET || compareAny(left);
@@ -491,28 +610,36 @@ export const valuesEqual = (left: Value, right: Value): boolean => {
491
610
  return compareValues(left, right) === 0;
492
611
  };
493
612
 
494
- const areSameValues = (left: Value[], right: Value[]) =>
495
- left === right ||
496
- (left.length === right.length &&
497
- left.every((element, index) => isSameValue(element, right[index])));
498
-
499
- export const isSameValue = (left: Value, right: Value): boolean => {
500
- if (left === right) return true;
501
- if (typeof left !== "object" || typeof right !== "object") return false;
502
- if (left.kind === "Set" && right.kind === "Set")
503
- return (
504
- (left.hash === 0 || right.hash === 0 || left.hash === right.hash) &&
505
- areSameValues(left.elements, right.elements)
506
- );
507
- if (left.kind === "Function" && right.kind === "Function")
508
- return (
509
- (left.hash === 0 || right.hash === 0 || left.hash === right.hash) &&
510
- areSameValues(left.domain, right.domain) &&
511
- areSameValues(left.range, right.range)
512
- );
513
- 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;
514
637
  };
515
638
 
639
+ export const isSameValue = createSameValueCheck(false);
640
+
641
+ export const isInterchangeableValue = createSameValueCheck(true);
642
+
516
643
  // The comparisons above fail with their own messages. These follow the compareTo and equals
517
644
  // methods of TLC's Java value classes, which word a failure by the class of the left operand, so a
518
645
  // failed comparison runs again through them to fail as TLC does.
@@ -668,7 +795,7 @@ const compareFunctionLikeTlc = (left: FunctionValue | LazyFunctionValue, right:
668
795
  compareElementsLikeTlc(functionValue.range, tuple)
669
796
  );
670
797
  }
671
- if (left.kind === "Function" && functionValue.domain.every((key) => typeof key === "string")) {
798
+ if (getFunctionClass(left) === "record") {
672
799
  const record = toTlcRecord(right);
673
800
  if (!record) {
674
801
  if (isModelValue(right)) return compareModelValueWith(right, left);
@@ -786,7 +913,7 @@ const equalsFunctionLikeTlc = (left: FunctionValue | LazyFunctionValue, right: V
786
913
  equalsElementsLikeTlc(functionValue.range, tuple)
787
914
  );
788
915
  }
789
- if (left.kind === "Function" && functionValue.domain.every((key) => typeof key === "string")) {
916
+ if (getFunctionClass(left) === "record") {
790
917
  const record = toTlcRecord(right);
791
918
  if (!record) {
792
919
  if (isModelValue(right)) return equalsModelValueWith(right, left);
@@ -838,32 +965,65 @@ const equalsLikeTlc = (left: Value, right: Value): boolean => {
838
965
  const sortLikeTlc = (elements: Value[]) => {
839
966
  const sorted: Value[] = [];
840
967
  for (const element of elements) {
841
- const bounds = { low: 0, high: sorted.length, comparison: 1 };
842
- while (bounds.low < bounds.high) {
843
- const middle = bounds.low + ((bounds.high - bounds.low) >> 1);
844
- bounds.comparison = compareLikeTlc(element, sorted[middle]);
845
- if (bounds.comparison === 0) break;
846
- if (bounds.comparison < 0) bounds.high = middle;
847
- else bounds.low = middle + 1;
848
- }
849
- 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);
850
970
  }
851
971
  return sorted;
852
972
  };
853
973
 
854
- // 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.
855
1000
  const isElementOfLikeTlc = (element: Value, elements: Value[]) =>
856
- elements.some((member) => equalsLikeTlc(member, element));
1001
+ elements.some((member) => callTracedMethod(member, () => equalsLikeTlc(member, element)));
857
1002
 
858
- export const isEqualLikeTlc = (left: Value, right: Value) => {
859
- try {
860
- return valuesEqual(left, right);
861
- } catch (error) {
862
- if (!(error instanceof TlaEvaluationError)) throw error;
863
- 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);
864
1018
  }
865
1019
  };
866
1020
 
1021
+ export const isEqualLikeTlc = (left: Value, right: Value) =>
1022
+ computeLikeTlcOnFailure(
1023
+ () => valuesEqual(left, right),
1024
+ () => equalsLikeTlc(left, right),
1025
+ );
1026
+
867
1027
  const isStrictlySorted = (elements: Value[]) => {
868
1028
  for (let index = 1; index < elements.length; index++) {
869
1029
  if (compareValues(elements[index - 1], elements[index]) >= 0) return false;
@@ -872,6 +1032,8 @@ const isStrictlySorted = (elements: Value[]) => {
872
1032
  };
873
1033
 
874
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]);
875
1037
  if (elements.length < 2 || isStrictlySorted(elements)) return createSortedSet(elements);
876
1038
  const sorted = [...elements].sort(compareValues);
877
1039
  const unique = [sorted[0]];
@@ -883,14 +1045,11 @@ export const createSet = (elements: Value[]): SetValue => {
883
1045
 
884
1046
  // TLC builds a set enumeration without sorting it, so one whose elements it can't compare still
885
1047
  // evaluates.
886
- export const createEnumeratedSet = (elements: Value[]): SetValue | MixedSetValue => {
887
- try {
888
- return createSet(elements);
889
- } catch (error) {
890
- if (!(error instanceof TlaEvaluationError)) throw error;
891
- return { kind: "MixedSet", elements };
892
- }
893
- };
1048
+ export const createEnumeratedSet = (elements: Value[]): SetValue | MixedSetValue =>
1049
+ computeLikeTlcOnFailure<SetValue | MixedSetValue>(
1050
+ () => createSet(elements),
1051
+ () => ({ kind: "MixedSet", elements }),
1052
+ );
894
1053
 
895
1054
  export const EMPTY_SET = createSortedSet([]);
896
1055
 
@@ -969,12 +1128,15 @@ export const unionSorted = (left: SetValue, right: SetValue): SetValue => {
969
1128
  }
970
1129
  if (added.length === 0) return left;
971
1130
  const union = createSortedSet(merged);
972
- if (left.hash !== 0) {
1131
+ if (left.hash !== 0 && left.hash !== UNFINGERPRINTABLE_HASH) {
973
1132
  let hash = left.hash;
974
- for (let index = 0; index < added.length; index++) {
975
- 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;
976
1138
  }
977
- union.hash = hash;
1139
+ if (index === added.length) union.hash = hash;
978
1140
  }
979
1141
  if (left.fingerprint !== 0) {
980
1142
  let fingerprint = left.fingerprint;
@@ -1059,23 +1221,27 @@ const getIntervalValue = (high: number): IntervalValue => {
1059
1221
  };
1060
1222
 
1061
1223
  export const createTuple = (elements: Value[]): FunctionValue =>
1062
- createSortedFunction(getIntervalDomain(elements.length), elements);
1224
+ setFunctionClass(createSortedFunction(getIntervalDomain(elements.length), elements), "tuple");
1063
1225
 
1064
- export const createRecord = (fields: [string, Value][]): FunctionValue => createFunction(fields);
1226
+ export const createRecord = (fields: [string, Value][]): FunctionValue =>
1227
+ setFunctionClass(createFunction(fields), "record");
1065
1228
 
1066
1229
  // TLC's Enumerable classes: every set except the ones it implements in Java.
1067
- const isTlcEnumerable = (value: Value) => isSetValue(value) && !isOverriddenSet(value);
1230
+ export const isTlcEnumerable = (value: Value) => isSetValue(value) && !isOverriddenSet(value);
1068
1231
 
1069
1232
  const formatUnion = (value: UnionValue, isStrict = false) =>
1070
1233
  `UNION(${formatValue(value.base, isStrict)})`;
1071
1234
 
1072
- const getUnionSets = (value: UnionValue) => {
1235
+ const getUnionSets = (
1236
+ value: UnionValue,
1237
+ getElements = (set: Value) => toFiniteSet(set).elements,
1238
+ ) => {
1073
1239
  if (!isTlcEnumerable(value.base)) {
1074
1240
  throw new TlaEvaluationError(
1075
1241
  `Attempted to enumerate the nonenumerable set:\n${formatUnion(value)}`,
1076
1242
  );
1077
1243
  }
1078
- return toFiniteSet(value.base).elements;
1244
+ return getElements(value.base);
1079
1245
  };
1080
1246
 
1081
1247
  const getUnionSet = (set: Value, index: number, union: UnionValue) => {
@@ -1111,7 +1277,7 @@ export const isEnumerable = (value: Value): boolean => {
1111
1277
  case "ProductSet":
1112
1278
  return value.factors.every(isEnumerable) || getEmptiness(value) === true;
1113
1279
  case "Union":
1114
- return isEnumerable(value.base) && toFiniteSet(value.base).elements.every(isEnumerable);
1280
+ return isEnumerable(value.base) && getStreamedElements(value.base).every(isEnumerable);
1115
1281
  case "SetOperation":
1116
1282
  if (value.operator === "\\cup") return isEnumerable(value.left) && isEnumerable(value.right);
1117
1283
  if (value.operator === "\\cap") return isEnumerable(value.left) || isEnumerable(value.right);
@@ -1184,6 +1350,41 @@ const advanceCombination = (indices: number[], length: number) => {
1184
1350
  return false;
1185
1351
  };
1186
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
+
1187
1388
  const getSortedSubsets = (base: Value[]) => {
1188
1389
  const subsets: Value[] = [];
1189
1390
  for (let size = 0; size <= base.length; size++) {
@@ -1195,7 +1396,30 @@ const getSortedSubsets = (base: Value[]) => {
1195
1396
  return subsets;
1196
1397
  };
1197
1398
 
1198
- 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[] => {
1199
1423
  if (typeof value !== "object")
1200
1424
  throw new TlaEvaluationError(`Expected a set but found ${formatValue(value)}`);
1201
1425
  switch (value.kind) {
@@ -1209,61 +1433,63 @@ const enumerateSet = (value: Value): Value[] => {
1209
1433
  return elements;
1210
1434
  }
1211
1435
  case "Subset": {
1212
- if (isOverriddenSet(value.base)) getCardinality(value.base);
1213
- const base = toFiniteSet(value.base).elements;
1214
- if (base.length > MAXIMUM_ENUMERATED_SUBSET_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)) {
1215
1440
  throw new TlaEvaluationError(
1216
- `SUBSET of a set with ${base.length} elements is too large to enumerate`,
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))}`,
1217
1442
  );
1218
1443
  }
1444
+ const base = toFiniteSet(value.base).elements;
1445
+ if (base.length > MAXIMUM_ENUMERATED_SUBSET_BASE) {
1446
+ throw new TlaEvaluationError(describeOverflow(value));
1447
+ }
1219
1448
  return getSortedSubsets(base);
1220
1449
  }
1221
1450
  case "FunctionSet": {
1222
- if (isEmptySet(value)) return [];
1451
+ if (!valueVersion.is174 && isEmptySet(value)) return [];
1223
1452
  if (isOverriddenSet(value.domain)) {
1224
1453
  throw new TlaEvaluationError(
1225
1454
  `Attempted to enumerate a set of the form [D -> R],but the domain D:\n${formatValue(value.domain)}\ncannot be enumerated.`,
1226
1455
  );
1227
1456
  }
1228
1457
  const domain = getFunctionDomain(value.domain);
1229
- 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)) {
1230
1460
  throw new TlaEvaluationError(
1231
1461
  `Attempted to enumerate a set of the form [D -> R],but the range R:\n${formatValue(value.range)}\ncannot be enumerated.`,
1232
1462
  );
1233
1463
  }
1234
- const range = domain.length === 0 ? [] : toFiniteSet(value.range).elements;
1464
+ const range = domain.length === 0 ? [] : getElements(value.range);
1235
1465
  return getCartesianProduct(domain.map(() => range)).map((combination): Value =>
1236
1466
  createSortedFunction(domain, combination),
1237
1467
  );
1238
1468
  }
1239
1469
  case "RecordSet": {
1240
- if (isEmptySet(value)) return [];
1241
- const fields = value.sets.map((set, index) => {
1242
- if (isOverriddenSet(set)) {
1243
- throw new TlaEvaluationError(
1244
- `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)}`,
1245
- );
1246
- }
1247
- return toFiniteSet(set).elements;
1248
- });
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
+ );
1249
1477
  return getCartesianProduct(fields).map((combination) =>
1250
1478
  createRecord(value.names.map((name, index): [string, Value] => [name, combination[index]])),
1251
1479
  );
1252
1480
  }
1253
1481
  case "ProductSet": {
1254
- if (isEmptySet(value)) return [];
1255
- const factors = value.factors.map((factor, index) => {
1256
- if (isOverriddenSet(factor)) {
1257
- throw new TlaEvaluationError(
1258
- `Attempted to enumerate a set of the form s1 \\X s2 ... \\X sn,\nbut can't enumerate s${index}:\n${formatValue(factor)}`,
1259
- );
1260
- }
1261
- return toFiniteSet(factor).elements;
1262
- });
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
+ );
1263
1489
  return getCartesianProduct(factors).map(createTuple);
1264
1490
  }
1265
1491
  case "FilteredSet":
1266
- if (isOverriddenSet(value.base)) {
1492
+ if (!isSetValue(value.base) || isOverriddenSet(value.base)) {
1267
1493
  throw new TlaEvaluationError(
1268
1494
  `Attempted to enumerate { x \\in S : p(x) } when S:\n${formatValue(value.base)}\nis not enumerable`,
1269
1495
  );
@@ -1278,7 +1504,7 @@ const enumerateSet = (value: Value): Value[] => {
1278
1504
  case "SetOperation": {
1279
1505
  if (
1280
1506
  value.operator === "\\cup" &&
1281
- (isOverriddenSet(value.left) || isOverriddenSet(value.right))
1507
+ (!isTlcEnumerable(value.left) || !isTlcEnumerable(value.right))
1282
1508
  ) {
1283
1509
  throw new TlaEvaluationError(
1284
1510
  `Attempted to enumerate S \\cup T when S:\n${formatValue(value.left)}\nand T:\n${formatValue(value.right)}\nare not both enumerable`,
@@ -1286,21 +1512,21 @@ const enumerateSet = (value: Value): Value[] => {
1286
1512
  }
1287
1513
  if (
1288
1514
  value.operator === "\\cap" &&
1289
- isOverriddenSet(value.left) &&
1290
- isOverriddenSet(value.right)
1515
+ !isTlcEnumerable(value.left) &&
1516
+ !isTlcEnumerable(value.right)
1291
1517
  ) {
1292
1518
  throw new TlaEvaluationError(
1293
1519
  `Attempted to enumerate S \\cap T when neither S:\n${formatValue(value.left)}\nnor T:\n${formatValue(value.right)}\nis enumerable`,
1294
1520
  );
1295
1521
  }
1296
- if (value.operator === "\\" && isOverriddenSet(value.left)) {
1522
+ if (value.operator === "\\" && !isTlcEnumerable(value.left)) {
1297
1523
  throw new TlaEvaluationError(
1298
1524
  `Attempted to enumerate S \\ T when S:\n${formatValue(value.left)}\nis not enumerable.`,
1299
1525
  );
1300
1526
  }
1301
1527
  if (value.operator === "\\cup")
1302
1528
  return unionSorted(toFiniteSet(value.left), toFiniteSet(value.right)).elements;
1303
- const isLeftEnumerated = value.operator === "\\" || isEnumerable(value.left);
1529
+ const isLeftEnumerated = value.operator === "\\" || isTlcEnumerable(value.left);
1304
1530
  const enumerated = isLeftEnumerated ? value.left : value.right;
1305
1531
  const other = isLeftEnumerated ? value.right : value.left;
1306
1532
  return toFiniteSet(enumerated).elements.filter(
@@ -1326,7 +1552,10 @@ export const toFiniteSet = (value: Value): SetValue => {
1326
1552
  }
1327
1553
  const cached = typeof value === "object" ? finiteSets.get(value) : undefined;
1328
1554
  if (cached) return cached;
1555
+ const sets = setTrace.sets;
1556
+ sets?.push(value);
1329
1557
  const elements = enumerateSet(value);
1558
+ sets?.pop();
1330
1559
  const isSorted =
1331
1560
  typeof value === "object" &&
1332
1561
  (value.kind === "MixedSet" ||
@@ -1344,25 +1573,60 @@ export const toFiniteSet = (value: Value): SetValue => {
1344
1573
  // TLC's Enumerator for a lazy set streams the sets it combines until the set caches its elements,
1345
1574
  // so an element that two of them share comes up once for each.
1346
1575
  export const getStreamedElements = (value: Value): Value[] => {
1347
- 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[] => {
1608
+ // TLC streams the sets of a UNION it hasn't enumerated, so a set that appears twice there yields
1609
+ // its elements twice.
1348
1610
  if (value.kind === "Union") {
1349
- return getUnionSets(value).flatMap((set, index) =>
1611
+ return getUnionSets(value, getStreamedElements).flatMap((set, index) =>
1350
1612
  getStreamedElements(getUnionSet(set, index, value)),
1351
1613
  );
1352
1614
  }
1353
1615
  if (value.kind === "FilteredSet" && !isOverriddenSet(value.base)) {
1354
1616
  return getStreamedElements(value.base).filter(value.test);
1355
1617
  }
1618
+ const components = getCombinedSets(value);
1619
+ if (components?.some(isStreamedApart)) return enumerateSet(value, getStreamedElements);
1356
1620
  if (value.kind !== "SetOperation") return toFiniteSet(value).elements;
1357
1621
  if (value.operator === "\\cup") {
1358
- return isOverriddenSet(value.left) || isOverriddenSet(value.right)
1622
+ return !isTlcEnumerable(value.left) || !isTlcEnumerable(value.right)
1359
1623
  ? toFiniteSet(value).elements
1360
1624
  : [...getStreamedElements(value.left), ...getStreamedElements(value.right)];
1361
1625
  }
1362
- const isLeftEnumerated = value.operator === "\\" || isEnumerable(value.left);
1626
+ const isLeftEnumerated = value.operator === "\\" || isTlcEnumerable(value.left);
1363
1627
  const enumerated = isLeftEnumerated ? value.left : value.right;
1364
1628
  const other = isLeftEnumerated ? value.right : value.left;
1365
- if (isOverriddenSet(enumerated)) return toFiniteSet(value).elements;
1629
+ if (!isTlcEnumerable(enumerated)) return toFiniteSet(value).elements;
1366
1630
  return getStreamedElements(enumerated).filter(
1367
1631
  (element) => isElementOf(element, other) === (value.operator === "\\cap"),
1368
1632
  );
@@ -1399,9 +1663,13 @@ export const isEmptySet = (value: Value): boolean => {
1399
1663
  }
1400
1664
  };
1401
1665
 
1402
- const getProductCardinality = (sets: Value[], describe: () => string) =>
1666
+ const getProductCardinality = (
1667
+ sets: Value[],
1668
+ version: TlcVersion | undefined,
1669
+ describe: () => string,
1670
+ ) =>
1403
1671
  sets.reduce<number>((product, set) => {
1404
- const size = product * getCardinality(set);
1672
+ const size = product * getCardinality(set, version);
1405
1673
  if (size > MAXIMUM_INTEGER) throw new TlaEvaluationError(describe());
1406
1674
  return size;
1407
1675
  }, 1);
@@ -1409,9 +1677,25 @@ const getProductCardinality = (sets: Value[], describe: () => string) =>
1409
1677
  const describeOverflow = (value: Value) =>
1410
1678
  `Overflow when computing the number of elements in:\n${formatValue(value)}`;
1411
1679
 
1412
- export const getCardinality = (value: Value): number => {
1413
- 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
+ }
1414
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);
1415
1699
  case "Interval": {
1416
1700
  const size = Math.max(0, value.high - value.low + 1);
1417
1701
  if (size > MAXIMUM_INTEGER) {
@@ -1427,16 +1711,19 @@ export const getCardinality = (value: Value): number => {
1427
1711
  `Attempted to compute the number of elements in the overridden value ${formatValue(value)}.`,
1428
1712
  );
1429
1713
  case "Subset": {
1430
- const size = getCardinality(value.base);
1714
+ const size = getCardinality(value.base, version);
1431
1715
  if (size >= 31) throw new TlaEvaluationError(describeOverflow(value));
1432
1716
  return 2 ** size;
1433
1717
  }
1434
1718
  case "FunctionSet": {
1435
- if (isEmptySet(value.domain)) return 1;
1436
- if (isEmptySet(value.range)) return 0;
1437
- const rangeSize = getCardinality(value.range);
1438
- if (rangeSize === 1) return 1;
1439
- 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;
1440
1727
  const size = { value: 1 };
1441
1728
  for (let index = 0; index < domainSize; index++) {
1442
1729
  size.value *= rangeSize;
@@ -1445,15 +1732,17 @@ export const getCardinality = (value: Value): number => {
1445
1732
  return size.value;
1446
1733
  }
1447
1734
  case "RecordSet":
1448
- if (isEmptySet(value)) return 0;
1449
- return getProductCardinality(value.sets, () => describeOverflow(value));
1735
+ if (version !== "1.7.4" && isEmptySet(value)) return 0;
1736
+ return getProductCardinality(value.sets, version, () => describeOverflow(value));
1450
1737
  case "ProductSet":
1451
- if (isEmptySet(value)) return 0;
1738
+ if (version !== "1.7.4" && isEmptySet(value)) return 0;
1452
1739
  return getProductCardinality(
1453
1740
  value.factors,
1741
+ version,
1454
1742
  () => `Overflow when computing the number of elements in ${formatValue(value)}`,
1455
1743
  );
1456
1744
  default:
1745
+ cacheSet(value);
1457
1746
  return toFiniteSet(value).elements.length;
1458
1747
  }
1459
1748
  };
@@ -1528,11 +1817,11 @@ export const isFiniteSet = (value: Value): boolean => {
1528
1817
  }
1529
1818
  };
1530
1819
 
1531
- const findIndex = (sortedValues: Value[], target: Value) => {
1820
+ const findIndex = (sortedValues: Value[], target: Value, compare = compareValues) => {
1532
1821
  const bounds = { low: 0, high: sortedValues.length - 1 };
1533
1822
  while (bounds.low <= bounds.high) {
1534
1823
  const middle = (bounds.low + bounds.high) >> 1;
1535
- const comparison = compareValues(sortedValues[middle], target);
1824
+ const comparison = compare(sortedValues[middle], target);
1536
1825
  if (comparison === 0) return middle;
1537
1826
  if (comparison < 0) bounds.low = middle + 1;
1538
1827
  else bounds.high = middle - 1;
@@ -1548,33 +1837,78 @@ export const getSequenceElements = (value: Value): Value[] | undefined => {
1548
1837
  : undefined;
1549
1838
  };
1550
1839
 
1551
- const describeMembership = (element: Value, set: Value) =>
1552
- `Attempted to check if the value ${formatValue(element)} is an element of ${formatValue(set)}`;
1553
-
1554
1840
  const describeNonSetMembership = (element: Value, value: Value) => {
1555
1841
  const prefix = `Attempted to check if the value:\n${formatValue(element)}\nis an element of the`;
1556
1842
  if (!isFunctionValue(value)) return `${prefix} ${describeKind(value)} ${formatValue(value)}`;
1557
- const domain =
1558
- value.kind === "Function" || isEnumerable(value.domain) ? toFiniteFunction(value).domain : [];
1559
- if (domain.length > 0 && domain.every((key) => typeof key === "string")) {
1843
+ const functionClass = getFunctionClass(value);
1844
+ if (functionClass === "record") {
1560
1845
  return `Attempted to check if element:\n${formatValue(element)}\nis in the record:\n${formatValue(value)}`;
1561
1846
  }
1562
- if (domain.every((key, index) => key === index + 1)) {
1563
- return "Attempted to check set membership in a tuple value.";
1564
- }
1847
+ if (functionClass === "tuple") return "Attempted to check set membership in a tuple value.";
1565
1848
  return `${prefix} function ${formatValue(value)}`;
1566
1849
  };
1567
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
+
1568
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 => {
1569
1900
  if (!isSetValue(set)) throw new TlaEvaluationError(describeNonSetMembership(element, set));
1570
1901
  switch (set.kind) {
1571
1902
  case "Set":
1572
- try {
1573
- return findIndex(set.elements, element) !== -1;
1574
- } catch (error) {
1575
- if (!(error instanceof TlaEvaluationError)) throw error;
1576
- return isElementOfLikeTlc(element, set.elements);
1577
- }
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
+ );
1578
1912
  case "MixedSet":
1579
1913
  return isElementOfLikeTlc(element, set.elements);
1580
1914
  case "Interval":
@@ -1598,12 +1932,21 @@ export const isElementOf = (element: Value, set: Value): boolean => {
1598
1932
  return set.name !== "Nat" || (typeof element === "number" && element >= 0);
1599
1933
  }
1600
1934
  case "Subset":
1601
- 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
+ }
1602
1942
  return toFiniteSet(element).elements.every((item) => isElementOf(item, set.base));
1603
1943
  case "FunctionSet": {
1604
1944
  if (!isFunctionValue(element)) {
1605
1945
  if (isModelValue(element)) return false;
1606
- 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
+ );
1607
1950
  }
1608
1951
  const functionValue = toFiniteFunction(element);
1609
1952
  const low = getIntervalLow(functionValue.domain);
@@ -1668,7 +2011,10 @@ export const isElementOf = (element: Value, set: Value): boolean => {
1668
2011
  const elements = getSequenceElements(element);
1669
2012
  if (elements === undefined) {
1670
2013
  if (isModelValue(element)) return false;
1671
- 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
+ );
1672
2018
  }
1673
2019
  return elements.every((item) => isElementOf(item, set.base));
1674
2020
  }
@@ -1701,27 +2047,59 @@ export const toFiniteFunction = (value: Value): FunctionValue => {
1701
2047
  if (typeof value === "object" && value.kind === "LazyFunction") {
1702
2048
  if (!isEnumerable(value.domain)) getCardinality(value.domain);
1703
2049
  const domain = getFunctionDomain(value.domain);
1704
- return createSortedFunction(
1705
- domain,
1706
- domain.map((key) => value.apply(key)),
2050
+ return setFunctionClass(
2051
+ createSortedFunction(
2052
+ domain,
2053
+ domain.map((key) => value.apply(key)),
2054
+ ),
2055
+ getFunctionClass(value),
1707
2056
  );
1708
2057
  }
1709
2058
  throw new TlaEvaluationError(`Expected a function but found ${formatValue(value)}`);
1710
2059
  };
1711
2060
 
1712
- const lambdaFunctions = new WeakSet<ObjectValue>();
1713
-
1714
- export const markLambdaFunction = <FunctionLike extends FunctionValue | LazyFunctionValue>(
1715
- functionValue: FunctionLike,
2061
+ export const describeMissingArgument = (
2062
+ functionValue: Value,
2063
+ argument: Value,
2064
+ version?: TlcVersion,
1716
2065
  ) => {
1717
- lambdaFunctions.add(functionValue);
1718
- return functionValue;
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
+ }
1719
2093
  };
1720
2094
 
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`;
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}.`;
2102
+ };
1725
2103
 
1726
2104
  const findKeyIndex = (domain: Value[], argument: Value) => {
1727
2105
  const first = domain[0];
@@ -1736,15 +2114,57 @@ const findKeyIndex = (domain: Value[], argument: Value) => {
1736
2114
  return findIndex(domain, argument);
1737
2115
  };
1738
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
+
1739
2159
  export const applyFunction = (
1740
2160
  functionValue: Value,
1741
2161
  argument: Value,
1742
- describeMissing?: (functionValue: FunctionValue) => string,
2162
+ describeMissing?: (functionValue: FunctionValue, argument: Value) => string,
1743
2163
  ): Value => {
1744
2164
  if (typeof functionValue === "object" && functionValue.kind === "LazyFunction") {
1745
2165
  if (!isElementOf(argument, functionValue.domain)) {
1746
2166
  throw new TlaEvaluationError(
1747
- lambdaFunctions.has(functionValue)
2167
+ getFunctionClass(functionValue) === "lambda"
1748
2168
  ? describeMissingArgument(functionValue, argument)
1749
2169
  : `Attempted to apply a function to ${formatValue(argument)}, which is not in its domain`,
1750
2170
  );
@@ -1756,12 +2176,9 @@ export const applyFunction = (
1756
2176
  `Attempted to apply ${formatValue(functionValue)}, which is not a function`,
1757
2177
  );
1758
2178
  }
1759
- const position = findKeyIndex(functionValue.domain, argument);
1760
- if (position === -1) {
1761
- throw new TlaEvaluationError(
1762
- describeMissing?.(functionValue) ?? describeMissingArgument(functionValue, argument),
1763
- );
1764
- }
2179
+ const describe = describeMissing ?? describeMissingArgument;
2180
+ const position = findKeyIndexLikeTlc(functionValue, argument, describe);
2181
+ if (position === -1) throw new TlaEvaluationError(describe(functionValue, argument));
1765
2182
  return functionValue.range[position];
1766
2183
  };
1767
2184
 
@@ -1790,28 +2207,45 @@ export const updateFunction = (
1790
2207
  if (isLazy) {
1791
2208
  if (!isElementOf(argument, functionValue.domain)) return functionValue;
1792
2209
  const updated = update(functionValue.apply(argument));
1793
- return {
1794
- kind: "LazyFunction",
1795
- domain: functionValue.domain,
1796
- apply: (key) => (isEqualLikeTlc(argument, key) ? updated : functionValue.apply(key)),
1797
- source: functionValue.source,
1798
- };
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
+ );
1799
2224
  }
1800
2225
  const finite = toFiniteFunction(functionValue);
1801
- const position = findKeyIndex(finite.domain, argument);
2226
+ const position = findKeyIndexLikeTlc(finite, argument, describeExceptKey);
1802
2227
  if (position === -1) return finite;
1803
2228
  const range = [...finite.range];
1804
2229
  const previous = finite.range[position];
1805
2230
  const next = update(previous);
1806
2231
  range[position] = next;
1807
- const updated = createSortedFunction(finite.domain, range);
2232
+ const updated = setFunctionClass(
2233
+ createSortedFunction(finite.domain, range),
2234
+ getFunctionClass(finite),
2235
+ );
1808
2236
  updated.writtenKeys = finite.writtenKeys;
1809
- if (finite.hash !== 0) {
1810
- const key = finite.domain[position];
1811
- updated.hash =
1812
- previous === next
1813
- ? finite.hash
1814
- : (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
+ }
1815
2249
  }
1816
2250
  if (finite.fingerprint !== 0) {
1817
2251
  const key = finite.domain[position];
@@ -1848,32 +2282,103 @@ const hashString = (value: string) => {
1848
2282
  const SET_HASH_SEED = 0x73a5c3e1;
1849
2283
  const FUNCTION_HASH_SEED = 0x66d1b4f7;
1850
2284
 
1851
- const getElementContribution = (element: Value) =>
1852
- 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);
1853
2290
 
1854
- const getEntryContribution = (key: Value, value: Value) =>
1855
- 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;
1856
2295
 
1857
2296
  const computeValueHash = (value: ObjectValue) => {
1858
2297
  if (value.kind === "ModelValue") return finalizeHash(combineHash(hashString(value.name), 0x6d));
1859
2298
  if (isSetValue(value)) {
1860
- if (!isEnumerable(value)) return hashString(getValueKey(value));
2299
+ if (!isEnumerable(value)) return UNFINGERPRINTABLE_HASH;
1861
2300
  const elements = toFiniteSet(value).elements;
1862
2301
  let hash = SET_HASH_SEED;
1863
2302
  for (let index = 0; index < elements.length; index++) {
1864
- 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;
1865
2306
  }
1866
2307
  return hash;
1867
2308
  }
2309
+ if (value.kind === "LazyFunction" && !isEnumerable(value.domain)) return UNFINGERPRINTABLE_HASH;
1868
2310
  const functionValue = toFiniteFunction(value);
1869
2311
  let hash = FUNCTION_HASH_SEED;
1870
2312
  for (let index = 0; index < functionValue.domain.length; index++) {
1871
- hash =
1872
- (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;
1873
2319
  }
1874
2320
  return hash;
1875
2321
  };
1876
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
+
1877
2382
  export const getValueHash = (value: Value): number => {
1878
2383
  if (typeof value === "number") return finalizeHash(value ^ 0x5bd1e995);
1879
2384
  if (typeof value === "boolean") return value ? 0x2b7e1516 : 0x28aed2a6;
@@ -2048,7 +2553,9 @@ const formatLazySet = (value: LazySetValue, isStrict: boolean): string => {
2048
2553
  case "SetOperation":
2049
2554
  return `${format(value.left)} ${value.operator} ${format(value.right)}`;
2050
2555
  case "FilteredSet":
2051
- 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)} : ...}`;
2052
2559
  case "Union":
2053
2560
  return formatUnion(value, isStrict);
2054
2561
  }
@@ -2061,6 +2568,17 @@ const isFieldName = (name: string) =>
2061
2568
  /\p{L}/u.test(name) &&
2062
2569
  (name.length < 4 || !/^[WS]F_/.test(name));
2063
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
+
2064
2582
  export const formatValue = (value: Value, isStrict = false, isNormalized = false): string => {
2065
2583
  const format = (inner: Value) => formatValue(inner, isStrict, isNormalized);
2066
2584
  if (typeof value === "boolean") return value ? "TRUE" : "FALSE";
@@ -2092,27 +2610,42 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
2092
2610
  return `Seq(${format(value.base)})`;
2093
2611
  case "Function":
2094
2612
  case "LazyFunction": {
2095
- if (value.kind === "LazyFunction" && !isEnumerable(value.domain)) {
2096
- 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;
2097
2616
  if (!source) return "<function>";
2098
2617
  const parameters = source.parameters
2099
2618
  .map((parameter) => `${parameter.name} \\in ${formatValue(parameter.domain)}`)
2100
2619
  .join(", ");
2101
2620
  return `[${parameters} |-> <expression ${source.body}>]`;
2102
2621
  }
2103
- const functionValue = toFiniteFunction(value);
2622
+ if (
2623
+ functionValue.domain.length === 0 &&
2624
+ valueVersion.is174 &&
2625
+ getFunctionClass(value) !== "tuple"
2626
+ ) {
2627
+ return "<< >>";
2628
+ }
2629
+ // TLC normalizes a lambda's domain to print it, but evaluates its body afterward.
2630
+ const formatRange = (inner: Value) =>
2631
+ formatValue(inner, isStrict, isNormalized && getFunctionClass(value) !== "lambda");
2104
2632
  if (functionValue.domain.every((key, index) => key === index + 1)) {
2105
- return `<<${functionValue.range.map(format).join(", ")}>>`;
2633
+ return `<<${functionValue.range.map(formatRange).join(", ")}>>`;
2106
2634
  }
2107
- 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
+ ) {
2108
2641
  const isSorted =
2109
2642
  isNormalized || functionValue.hash !== 0 || functionValue.fingerprint !== 0;
2110
2643
  const pairs = isSorted
2111
2644
  ? functionValue.domain.map((key, index) => [key, functionValue.range[index]])
2112
2645
  : getWrittenPairs(functionValue);
2113
- return `[${pairs.map((pair) => `${String(pair[0])} |-> ${format(pair[1])}`).join(", ")}]`;
2646
+ return `[${pairs.map((pair) => `${String(pair[0])} |-> ${formatRange(pair[1])}`).join(", ")}]`;
2114
2647
  }
2115
- return `(${functionValue.domain.map((key, index) => `${format(key)} :> ${format(functionValue.range[index])}`).join(" @@ ")})`;
2648
+ return `(${functionValue.domain.map((key, index) => `${format(key)} :> ${formatRange(functionValue.range[index])}`).join(" @@ ")})`;
2116
2649
  }
2117
2650
  }
2118
2651
  };