tla-ts 0.0.3 → 0.0.4-dev.2be6058

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