tla-ts 0.0.10-dev.28c823e4b → 0.0.10-dev.b4a856304

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 (68) hide show
  1. package/dist/index.cjs +1 -1
  2. package/dist/index.d.cts +0 -34
  3. package/dist/index.d.ts +0 -34
  4. package/dist/index.js +1 -1
  5. package/dist/parallel-worker.cjs +1 -1
  6. package/dist/parallel-worker.js +1 -1
  7. package/dist/prove.cjs +43 -43
  8. package/dist/prove.js +47 -47
  9. package/dist/run.cjs +30 -30
  10. package/dist/run.js +33 -33
  11. package/dist/transfer.cjs +38 -38
  12. package/dist/transfer.js +39 -39
  13. package/package.json +1 -1
  14. package/src/ast.ts +5 -0
  15. package/src/bags.ts +5 -2
  16. package/src/builtins.ts +8 -1
  17. package/src/check.ts +193 -128
  18. package/src/cli/run.ts +2 -0
  19. package/src/cli/runtime-invariants.ts +7 -8
  20. package/src/cli/shared.ts +4 -0
  21. package/src/cli/tlc-arguments.ts +30 -24
  22. package/src/cli/tlc-usage.ts +3 -2
  23. package/src/evaluate.ts +102 -26
  24. package/src/java-overrides.ts +9 -4
  25. package/src/json-reader.ts +2 -1
  26. package/src/json.ts +11 -4
  27. package/src/levels.ts +15 -7
  28. package/src/lexer.ts +83 -72
  29. package/src/liveness-checker.ts +106 -77
  30. package/src/liveness.ts +34 -10
  31. package/src/parallel.ts +33 -26
  32. package/src/parser.ts +226 -163
  33. package/src/pcal/ast.ts +65 -53
  34. package/src/pcal/parse.ts +191 -144
  35. package/src/pcal/tokenize.ts +115 -91
  36. package/src/pcal/translate.ts +98 -83
  37. package/src/pcal/validate.ts +50 -48
  38. package/src/pretty-print.ts +6 -6
  39. package/src/randomization.ts +4 -1
  40. package/src/resolve.ts +70 -12
  41. package/src/runtime.ts +18 -11
  42. package/src/sany/builtins.ts +3 -1
  43. package/src/sany/generator.ts +127 -74
  44. package/src/sany/levels.ts +9 -5
  45. package/src/sany/lexer.ts +44 -40
  46. package/src/sany/linter.ts +1 -0
  47. package/src/search.ts +1 -1
  48. package/src/simulate.ts +59 -50
  49. package/src/spec-description.ts +34 -23
  50. package/src/standard-definitions.ts +3 -0
  51. package/src/standard-modules.ts +12 -1
  52. package/src/state-graph.ts +8 -1
  53. package/src/subexpressions.ts +47 -38
  54. package/src/successors.ts +35 -14
  55. package/src/symmetry.ts +19 -4
  56. package/src/tlc/fingerprint.ts +21 -15
  57. package/src/tlc/jar-data.ts +1 -0
  58. package/src/tlc/messages.ts +21 -2
  59. package/src/tlc/order.ts +38 -20
  60. package/src/tlc/random.ts +30 -18
  61. package/src/tlc/replay.ts +33 -13
  62. package/src/tlc/summary.ts +45 -36
  63. package/src/tlc/tlc-operators.ts +14 -4
  64. package/src/tlc/tlcext-operators.ts +15 -11
  65. package/src/tlc/trace-spec.ts +4 -0
  66. package/src/tlc/value-stream.ts +13 -9
  67. package/src/tlc/version.ts +1 -0
  68. package/src/values.ts +181 -74
package/src/values.ts CHANGED
@@ -28,13 +28,16 @@ interface LazySet {
28
28
  export interface SetValue {
29
29
  kind: "Set";
30
30
  elements: Value[];
31
+ // A set enumeration's unsorted elements, duplicates included, until TLC normalizes it.
31
32
  writtenElements: Value[] | undefined;
33
+ // Once normalized, TLC checks membership by binary search with compareTo, not with equals.
32
34
  isNormalized: boolean;
33
35
  hash: number;
34
36
  fingerprint: number;
35
37
  isFingerprinted: boolean;
36
38
  }
37
39
 
40
+ // TLC sorts a set enumeration only when it has to, so it checks membership element by element.
38
41
  export interface MixedSetValue extends LazySet {
39
42
  kind: "MixedSet";
40
43
  elements: Value[];
@@ -48,6 +51,7 @@ export interface FunctionValue {
48
51
  fingerprint: number;
49
52
  writtenKeys: Value[] | undefined;
50
53
  functionClass: FunctionClass | undefined;
54
+ // The set a lambda ranges over, which TLC's DOMAIN returns until it builds the function.
51
55
  lambdaDomain: Value | undefined;
52
56
  isFingerprinted: boolean;
53
57
  }
@@ -97,6 +101,7 @@ export interface SetOperationValue extends LazySet {
97
101
  right: Value;
98
102
  }
99
103
 
104
+ // TLC prints a set filter as its bound names and the location of its predicate.
100
105
  interface FilteredSetSource {
101
106
  names: string;
102
107
  predicate: string;
@@ -109,6 +114,7 @@ export interface FilteredSetValue extends LazySet {
109
114
  source?: FilteredSetSource;
110
115
  }
111
116
 
117
+ // UNION S when some element of S isn't a set enumeration. TLC enumerates it only when it has to.
112
118
  export interface UnionValue extends LazySet {
113
119
  kind: "Union";
114
120
  base: Value;
@@ -124,10 +130,12 @@ export interface LazyFunctionSource {
124
130
  body: string;
125
131
  }
126
132
 
133
+ // enumerated is the FcnRcdValue TLC converts the function to once it compares or fingerprints it.
127
134
  export interface LazyFunctionValue {
128
135
  kind: "LazyFunction";
129
136
  domain: Value;
130
137
  apply: (argument: Value) => Value;
138
+ // The length of each bound's tuple pattern, or undefined for a name.
131
139
  boundTupleLengths?: (number | undefined)[];
132
140
  source?: LazyFunctionSource;
133
141
  functionClass?: FunctionClass;
@@ -181,14 +189,16 @@ export const MAXIMUM_INTEGER = 2147483647;
181
189
  const DEFAULT_SET_BOUND = 1000000;
182
190
  const VALUE_VEC_CAPACITY = 10;
183
191
 
184
- let setBound = DEFAULT_SET_BOUND;
192
+ const setBound = { size: DEFAULT_SET_BOUND };
185
193
 
186
- export const getSetBound = () => setBound;
194
+ export const getSetBound = () => setBound.size;
187
195
 
188
- export const getMaximumSetSize = () => Math.max(setBound, VALUE_VEC_CAPACITY);
196
+ // A ValueVec that TLC grows one element at a time starts with room for 10, and fails to grow once
197
+ // its room reaches the bound.
198
+ export const getMaximumSetSize = () => Math.max(setBound.size, VALUE_VEC_CAPACITY);
189
199
 
190
200
  export const getSetBoundMessage = () =>
191
- `Attempted to construct a set with too many elements (>${setBound}).`;
201
+ `Attempted to construct a set with too many elements (>${setBound.size}).`;
192
202
 
193
203
  export const addBoundedElement = (elements: Value[], element: Value) => {
194
204
  if (elements.length === getMaximumSetSize()) throw new TlaSetBoundError(getSetBoundMessage());
@@ -200,6 +210,7 @@ export const isBeyondSetBound = (value: Value): value is IntervalValue =>
200
210
  value.kind === "Interval" &&
201
211
  value.high - value.low >= getMaximumSetSize();
202
212
 
213
+ // TLC steps through an interval without building its elements.
203
214
  export const forEachElement = (
204
215
  elements: IntervalValue | Value[],
205
216
  visit: (element: Value) => void,
@@ -241,10 +252,13 @@ export const describeKind = (value: Value) => {
241
252
  export const isTlcInteger = (value: number) =>
242
253
  Number.isInteger(value) && value <= MAXIMUM_INTEGER && value >= MINIMUM_INTEGER;
243
254
 
244
- let isWrittenOrderUsed = false;
255
+ // TLC keeps a record, or a function @@ builds, in written order until it sorts it to compare or
256
+ // fingerprint it. It searches the function in that order, and ToString, Assert, and error
257
+ // messages show it, unless every key is an integer.
258
+ const writtenOrderUse = { isUsed: false };
245
259
 
246
260
  const setWrittenOrder = (functionValue: FunctionValue, keys: Value[]) => {
247
- isWrittenOrderUsed = true;
261
+ writtenOrderUse.isUsed = true;
248
262
  functionValue.writtenKeys = keys;
249
263
  return functionValue;
250
264
  };
@@ -260,6 +274,7 @@ export const getWrittenPairs = (functionValue: FunctionValue): [Value, Value][]
260
274
  functionValue.range[functionValue.domain.indexOf(key)],
261
275
  ]);
262
276
 
277
+ // TLC sorts a function whose keys are all integers to check whether it is a tuple.
263
278
  export const getPrintedPairs = (functionValue: FunctionValue): [Value, Value][] =>
264
279
  functionValue.domain.every((key) => typeof key === "number")
265
280
  ? functionValue.domain.map((key, index) => [key, functionValue.range[index]])
@@ -268,6 +283,7 @@ export const getPrintedPairs = (functionValue: FunctionValue): [Value, Value][]
268
283
  export const createWrittenRecord = (names: Value[], range: Value[], writtenNames: Value[]) =>
269
284
  setWrittenOrder(createSortedRecord(names, range), writtenNames);
270
285
 
286
+ // TLC sorts a value it compares, even with itself, so a hashed or fingerprinted value is sorted.
271
287
  const forgetWrittenOrder = (value: Value): void => {
272
288
  if (typeof value !== "object" || (value.kind !== "Function" && value.kind !== "Set")) return;
273
289
  if (value.hash !== 0 || value.fingerprint !== 0) return;
@@ -278,11 +294,12 @@ const forgetWrittenOrder = (value: Value): void => {
278
294
 
279
295
  const isRecordDomain = (domain: Value[]) => domain.every((key) => typeof key === "string");
280
296
 
297
+ // TLC compares a record only with a record, so this can fail before the sizes decide.
281
298
  const isRecordMismatch = (left: Value[], right: Value[]) =>
282
299
  left.length > 0 && right.length > 0 && isRecordDomain(left) !== isRecordDomain(right);
283
300
 
284
301
  const compareFunctions = (left: FunctionValue, right: FunctionValue) => {
285
- if (isWrittenOrderUsed) {
302
+ if (writtenOrderUse.isUsed) {
286
303
  left.writtenKeys = undefined;
287
304
  right.writtenKeys = undefined;
288
305
  }
@@ -354,10 +371,13 @@ const checkModelValueTypes = (left: Value, right: Value, isEquality: boolean) =>
354
371
  interface StringOrder {
355
372
  ranks: Record<string, number>;
356
373
  size: number;
374
+ // A parallel search's workers rank the strings they create in different orders, so the search
375
+ // notes the first string it orders against another string ranked from this rank on.
357
376
  searchRank: number | undefined;
358
377
  unorderedString: string | undefined;
359
378
  }
360
379
 
380
+ // TLC orders strings and model values by first interning, so each check sets its order first.
361
381
  const stringOrder: StringOrder = {
362
382
  ranks: Object.create(null),
363
383
  size: 0,
@@ -380,7 +400,8 @@ export const freezeStringOrder = () => {
380
400
 
381
401
  export const getUnorderedString = () => stringOrder.unorderedString;
382
402
 
383
- let isVersion174 = false;
403
+ // TLC 1.7.4 prints and looks keys up in functions differently, so each check sets the version.
404
+ const valueVersion = { is174: false };
384
405
 
385
406
  const printing = { isExpanded: true, isViewPrinted: false };
386
407
 
@@ -392,12 +413,13 @@ export interface ValueOptions {
392
413
  }
393
414
 
394
415
  export const setValueOptions = (options: ValueOptions) => {
395
- isVersion174 = options.version === "1.7.4";
396
- setBound = options.maxSetSize ?? DEFAULT_SET_BOUND;
416
+ valueVersion.is174 = options.version === "1.7.4";
417
+ setBound.size = options.maxSetSize ?? DEFAULT_SET_BOUND;
397
418
  printing.isExpanded = options.isLazyValueExpanded ?? true;
398
419
  printing.isViewPrinted = options.isViewPrinted ?? false;
399
420
  };
400
421
 
422
+ // TLC evaluates the VIEW of a state it prints as it prints it.
401
423
  const viewTexts = new WeakMap<Record<string, Value>, () => string>();
402
424
 
403
425
  export const setViewText = (state: Record<string, Value>, getText: () => string) => {
@@ -405,6 +427,7 @@ export const setViewText = (state: Record<string, Value>, getText: () => string)
405
427
  return state;
406
428
  };
407
429
 
430
+ // TLC prints by its _format only the state an ALIAS gives.
408
431
  const aliasNames = new WeakMap<Record<string, Value>, string>();
409
432
 
410
433
  export const setAliasName = (state: Record<string, Value>, alias: string) => {
@@ -457,6 +480,8 @@ const createComparisonError = (left: Value, right: Value) =>
457
480
  : `Attempted to compare ${describeKind(left)} ${formatValue(left)} with ${describeKind(right)} ${formatValue(right)}`,
458
481
  );
459
482
 
483
+ // TLC's Nat, Int, STRING, Seq(S), and Any compare only with each other and with model values,
484
+ // and fail with any other set, worded by the class of the left operand.
460
485
  const compareOverriddenSets = (
461
486
  left: Value,
462
487
  right: Value,
@@ -485,8 +510,9 @@ const compareAny = (other: Value): never => {
485
510
  throw new TlaModuleError(`Attempted to compare ANY with the value\n${formatValue(other)}`);
486
511
  };
487
512
 
513
+ // TLC enumerates a lambda to compare it, even with itself.
488
514
  const compareWithItself = (value: Value) => {
489
- if (isWrittenOrderUsed) forgetWrittenOrder(value);
515
+ if (writtenOrderUse.isUsed) forgetWrittenOrder(value);
490
516
  if (value === ANY_SET) compareAny(value);
491
517
  if (typeof value === "object" && value.kind === "LazyFunction") toFiniteFunction(value);
492
518
  };
@@ -524,6 +550,7 @@ export const compareValues = (left: Value, right: Value): number => {
524
550
  if (isLeftSet !== isSetValue(right)) {
525
551
  throw createComparisonError(left, right);
526
552
  }
553
+ // The sizes decide first, so an interval of another size never needs its elements.
527
554
  if (leftKind === "Interval" && rightKind === "Set") {
528
555
  const difference = getCardinality(left) - right.elements.length;
529
556
  if (difference !== 0) return difference;
@@ -546,8 +573,10 @@ export const compareValues = (left: Value, right: Value): number => {
546
573
 
547
574
  const modelValues = new Map<string, ModelValue>();
548
575
 
576
+ // ModelValue's index is a short.
549
577
  const MAXIMUM_MODEL_VALUES = 32768;
550
578
 
579
+ // setStringOrder clears the model values, so each check ranks and creates its own.
551
580
  export const createModelValue = (name: string): ModelValue => {
552
581
  const known = modelValues.get(name);
553
582
  if (known) return known;
@@ -598,15 +627,18 @@ export const createSortedFunction = (domain: Value[], range: Value[]): FunctionV
598
627
  isFingerprinted: false,
599
628
  });
600
629
 
630
+ // TLC words a failed application by the function's Java class: FcnLambdaValue, TupleValue,
631
+ // RecordValue, or FcnRcdValue.
601
632
  export type FunctionClass = "lambda" | "tuple" | "record";
602
633
 
603
- let hasLambda = false;
634
+ // Whether a lambda exists for markFingerprinted to find, so that a spec without one skips the walk.
635
+ const lambdaPresence = { isPresent: false };
604
636
 
605
637
  export const setFunctionClass = <FunctionLike extends FunctionValue | LazyFunctionValue>(
606
638
  functionValue: FunctionLike,
607
639
  functionClass: FunctionClass | undefined,
608
640
  ) => {
609
- if (functionClass === "lambda") hasLambda = true;
641
+ if (functionClass === "lambda") lambdaPresence.isPresent = true;
610
642
  if (functionClass !== undefined) functionValue.functionClass = functionClass;
611
643
  return functionValue;
612
644
  };
@@ -620,14 +652,17 @@ export const markLambdaFunction = <FunctionLike extends FunctionValue | LazyFunc
620
652
  functionValue: FunctionLike,
621
653
  ) => setFunctionClass(functionValue, "lambda");
622
654
 
655
+ // TLC caches a lazy set as the receiver of compareTo, equals, size, and fingerPrint, not as
656
+ // their argument, and enumerates the sets an uncached one combines, duplicates and all.
623
657
  const isCachedSet = (value: ObjectValue) => isLazySet(value) && value.isCached === true;
624
658
 
625
- let hasStreamedSet = false;
659
+ // Lets a spec without a UNION or \cup set, which stream duplicates, skip tracking TLC's caches.
660
+ const streamedSetPresence = { isPresent: false };
626
661
 
627
662
  export const markStreamedSet = <Streamed extends UnionValue | SetOperationValue>(
628
663
  value: Streamed,
629
664
  ) => {
630
- hasStreamedSet = true;
665
+ streamedSetPresence.isPresent = true;
631
666
  return value;
632
667
  };
633
668
 
@@ -642,7 +677,7 @@ const STREAMING_KINDS = new Set<ObjectValue["kind"]>([
642
677
 
643
678
  const cacheSet = (value: Value) => {
644
679
  if (
645
- hasStreamedSet &&
680
+ streamedSetPresence.isPresent &&
646
681
  typeof value === "object" &&
647
682
  isLazySet(value) &&
648
683
  STREAMING_KINDS.has(value.kind)
@@ -651,8 +686,11 @@ const cacheSet = (value: Value) => {
651
686
  }
652
687
  };
653
688
 
689
+ // Fingerprinting caches the FcnRcdValue a lambda enumerates to, so it is no longer a lambda.
654
690
  export const markFingerprinted = (value: Value): void => {
655
- if ((!hasLambda && !hasStreamedSet) || typeof value !== "object") return;
691
+ if ((!lambdaPresence.isPresent && !streamedSetPresence.isPresent) || typeof value !== "object") {
692
+ return;
693
+ }
656
694
  if (value.kind === "ModelValue" || value.kind === "Interval" || value.kind === "InfiniteSet") {
657
695
  return;
658
696
  }
@@ -686,6 +724,7 @@ export const valuesEqual = (left: Value, right: Value): boolean => {
686
724
  if (left.kind === "Function" && right.kind === "Function")
687
725
  return compareFunctions(left, right) === 0;
688
726
  if (left.kind === "Set" && right.kind === "Set") return compareSets(left, right) === 0;
727
+ // The sizes decide first, so an interval of another size never needs its elements.
689
728
  if (left.kind === "Interval" && right.kind === "Set") {
690
729
  if (getCardinality(left) !== right.elements.length) return false;
691
730
  }
@@ -693,6 +732,7 @@ export const valuesEqual = (left: Value, right: Value): boolean => {
693
732
  if (left.elements.length !== getCardinality(right)) return false;
694
733
  }
695
734
  if (isModelValue(left) || isModelValue(right)) {
735
+ // TLC enumerates a lambda, which can fail, before it compares it.
696
736
  if (left.kind === "LazyFunction") toFiniteFunction(left);
697
737
  checkModelValueTypes(left, right, true);
698
738
  return isModelValue(left) && isModelValue(right) && left.name === right.name;
@@ -746,6 +786,7 @@ export const valuesEqual = (left: Value, right: Value): boolean => {
746
786
  return compareValues(left, right) === 0;
747
787
  };
748
788
 
789
+ // TLC words errors by each function's Java class, so a stand-in must match each function's class.
749
790
  const createSameValueCheck = (isClassSensitive: boolean) => {
750
791
  const areSameValues = (left: Value[], right: Value[]) => {
751
792
  if (left === right) return true;
@@ -785,6 +826,7 @@ const canonicalizeElements = (elements: Value[], canonicalize: (value: Value) =>
785
826
  }
786
827
  };
787
828
 
829
+ // So that the states it keeps share their values.
788
830
  export const createCanonicalizer = () => {
789
831
  const canonicalValues = new Map<number, Value | Value[]>();
790
832
  const canonicalize = (value: Value): Value => {
@@ -818,12 +860,15 @@ export const createCanonicalizer = () => {
818
860
  };
819
861
  };
820
862
 
863
+ // These follow TLC's compareTo and equals, which word a failure by the left operand's class,
864
+ // so a failed comparison above runs again through them to fail as TLC does.
821
865
  interface TlcFunction {
822
866
  domain: Value[];
823
867
  range: Value[];
824
868
  low: number | undefined;
825
869
  }
826
870
 
871
+ // TLC compares a domain it keeps as an interval apart from one it keeps as an array.
827
872
  const getIntervalLow = (value: Value, domain: Value[]) =>
828
873
  domain.length === 0 || getFunctionClass(value) === "tuple" ? 1 : getDomainInterval(domain)?.low;
829
874
 
@@ -840,9 +885,10 @@ const toTlcFunction = (value: Value) => {
840
885
  const toTlcRecord = (value: Value) => {
841
886
  if (!isFunctionValue(value)) return undefined;
842
887
  const functionValue = toFiniteFunction(value);
843
- return isRecordDomain(functionValue.domain) ? functionValue : undefined;
888
+ return functionValue.domain.every((key) => typeof key === "string") ? functionValue : undefined;
844
889
  };
845
890
 
891
+ // A model value compared with a value of another kind. The other value is never a model value.
846
892
  const compareModelValueWith = (modelValue: ModelValue, other: Value) => {
847
893
  checkModelValueTypes(other, modelValue, false);
848
894
  return 1;
@@ -954,6 +1000,7 @@ const compareFunctionLikeTlc = (left: FunctionValue | LazyFunctionValue, right:
954
1000
  );
955
1001
  };
956
1002
 
1003
+ // TLC compares a lazy or Java-overridden set through its own class before it compares elements.
957
1004
  const isComparedByClass = (left: ObjectValue, right: Value) =>
958
1005
  isOverriddenSet(left) ||
959
1006
  isOverriddenSet(right) ||
@@ -1093,6 +1140,7 @@ const equalsLikeTlc = (left: Value, right: Value): boolean => {
1093
1140
  return equalsSetLikeTlc(left, right);
1094
1141
  };
1095
1142
 
1143
+ // TLC's ValueVec.sort, which inserts each element into the sorted prefix by binary search.
1096
1144
  const sortLikeTlc = (elements: Value[]) => {
1097
1145
  const sorted: Value[] = [];
1098
1146
  for (const element of elements) {
@@ -1111,17 +1159,17 @@ const callTracedMethod = <Result>(receiver: Value, method: () => Result) => {
1111
1159
  return result;
1112
1160
  };
1113
1161
 
1162
+ // A binary search with compareTo, which ends where the element is or would go.
1114
1163
  const searchLikeTlc = (element: Value, sorted: Value[]) => {
1115
- let low = 0;
1116
- let high = sorted.length;
1117
- while (low < high) {
1118
- const middle = low + ((high - low) >> 1);
1164
+ const bounds = { low: 0, high: sorted.length };
1165
+ while (bounds.low < bounds.high) {
1166
+ const middle = bounds.low + ((bounds.high - bounds.low) >> 1);
1119
1167
  const comparison = callTracedMethod(element, () => compareLikeTlc(element, sorted[middle]));
1120
1168
  if (comparison === 0) return { index: middle, isFound: true };
1121
- if (comparison < 0) high = middle;
1122
- else low = middle + 1;
1169
+ if (comparison < 0) bounds.high = middle;
1170
+ else bounds.low = middle + 1;
1123
1171
  }
1124
- return { index: low, isFound: false };
1172
+ return { index: bounds.low, isFound: false };
1125
1173
  };
1126
1174
 
1127
1175
  const isElementOfLikeTlc = (element: Value, elements: Value[]) =>
@@ -1144,6 +1192,7 @@ export const markNormalized = (value: Value): void => {
1144
1192
  }
1145
1193
  };
1146
1194
 
1195
+ // TLC's Value.normalize sorts a set enumeration, and the sets a lazy set it hasn't cached combines.
1147
1196
  export const normalizeShallowly = (value: Value): void => {
1148
1197
  if (typeof value !== "object" || isCachedSet(value)) return;
1149
1198
  switch (value.kind) {
@@ -1192,6 +1241,7 @@ const isAscendingIntegers = (elements: Value[]) => {
1192
1241
  };
1193
1242
 
1194
1243
  export const createSet = (elements: Value[]): SetValue => {
1244
+ // TLC's sort compares each element after the first with those before it.
1195
1245
  for (let index = 1; index < elements.length; index++) cacheSet(elements[index]);
1196
1246
  if (elements.length < 2 || isStrictlySorted(elements)) return createSortedSet(elements);
1197
1247
  const sorted = [...elements].sort(compareValues);
@@ -1202,6 +1252,7 @@ export const createSet = (elements: Value[]): SetValue => {
1202
1252
  return createSortedSet(unique);
1203
1253
  };
1204
1254
 
1255
+ // TLC builds a set enumeration unsorted, so one whose elements it can't compare still evaluates.
1205
1256
  export const createEnumeratedSet = (elements: Value[]): SetValue | MixedSetValue => {
1206
1257
  if (isAscendingIntegers(elements)) return createSortedSet(elements);
1207
1258
  const set = computeLikeTlcOnFailure<Value[], undefined, SetValue | MixedSetValue>(
@@ -1343,15 +1394,20 @@ const longIntervalDomains = new Map<number, WeakRef<Value[]>>();
1343
1394
  const intervalValues: IntervalValue[] = [];
1344
1395
  const intervalArrays = new WeakMap<Value[], IntervalValue>();
1345
1396
 
1397
+ // Every function over 1..n shares one domain array per length, so the array's identity records
1398
+ // the interval. Callers must not mutate the returned array. Longer domains are held weakly: a
1399
+ // sequence that grows one element at a time would otherwise keep an array of every length it
1400
+ // passed through, n * n / 2 numbers in all.
1346
1401
  const getIntervalDomain = (length: number): Value[] => {
1347
1402
  const cached = intervalDomains[length] ?? longIntervalDomains.get(length)?.deref();
1348
1403
  if (cached) return cached;
1349
- const domain = Array.from({ length }, (_value, index) => index + 1);
1404
+ const domain = Array.from({ length }, (_, index) => index + 1);
1350
1405
  if (length > MAX_SHARED_INTERVAL_LENGTH) longIntervalDomains.set(length, new WeakRef(domain));
1351
1406
  else intervalDomains[length] = domain;
1352
1407
  return domain;
1353
1408
  };
1354
1409
 
1410
+ // The caller only iterates the elements, so they need not record the interval for DOMAIN.
1355
1411
  export const getIntervalElements = (value: IntervalValue): Value[] => {
1356
1412
  getCardinality(value);
1357
1413
  if (value.low === 1 && value.high >= 1) return getIntervalDomain(value.high);
@@ -1366,6 +1422,7 @@ const isIntervalDomain = (domain: Value[]) =>
1366
1422
  domain === longIntervalDomains.get(domain.length)?.deref())) ||
1367
1423
  intervalArrays.has(domain);
1368
1424
 
1425
+ // A set such as (1..2) \cap S, whose elements are the shared array, gets a copy.
1369
1426
  export const getFunctionDomain = (set: Value): Value[] => {
1370
1427
  const elements = toFiniteSet(set).elements;
1371
1428
  return isIntervalDomain(elements) && !(typeof set === "object" && set.kind === "Interval")
@@ -1519,24 +1576,25 @@ const advanceCombination = (indices: number[], length: number) => {
1519
1576
  return false;
1520
1577
  };
1521
1578
 
1579
+ // TLC enumerates SUBSET S lazily, by size and then in the order of S, so a quantifier that
1580
+ // finds its witness early never builds the rest.
1522
1581
  export const getLazySubsets = (value: Value): Value[] | undefined => {
1523
1582
  if (typeof value !== "object" || value.kind !== "Subset" || isOverriddenSet(value.base)) {
1524
1583
  return undefined;
1525
1584
  }
1526
1585
  const base = toFiniteSet(value.base).elements;
1527
1586
  if (base.length <= MAXIMUM_BUILT_SUBSET_BASE) return undefined;
1528
- let cursorIndex = -1;
1529
- let indices = [0];
1587
+ const cursor = { index: -1, indices: [0] };
1530
1588
  const getSubset = (index: number) => {
1531
- if (index <= cursorIndex) cursorIndex = -1;
1532
- while (cursorIndex < index) {
1533
- if (cursorIndex === -1) indices = [];
1534
- else if (!advanceCombination(indices, base.length)) {
1535
- indices = Array.from({ length: indices.length + 1 }, (_value, position) => position);
1589
+ if (index <= cursor.index) cursor.index = -1;
1590
+ while (cursor.index < index) {
1591
+ if (cursor.index === -1) cursor.indices = [];
1592
+ else if (!advanceCombination(cursor.indices, base.length)) {
1593
+ cursor.indices = Array.from({ length: cursor.indices.length + 1 }, (_, item) => item);
1536
1594
  }
1537
- cursorIndex++;
1595
+ cursor.index++;
1538
1596
  }
1539
- return createSortedSet(indices.map((baseIndex) => base[baseIndex]));
1597
+ return createSortedSet(cursor.indices.map((item) => base[item]));
1540
1598
  };
1541
1599
  const length = 2 ** base.length;
1542
1600
  const isIndex = (property: string | symbol) =>
@@ -1555,7 +1613,7 @@ export const getLazySubsets = (value: Value): Value[] | undefined => {
1555
1613
  const getSortedSubsets = (base: Value[]) => {
1556
1614
  const subsets: Value[] = [];
1557
1615
  for (let size = 0; size <= base.length; size++) {
1558
- const indices = Array.from({ length: size }, (_value, index) => index);
1616
+ const indices = Array.from({ length: size }, (_, index) => index);
1559
1617
  do {
1560
1618
  subsets.push(createSortedSet(indices.map((index) => base[index])));
1561
1619
  } while (advanceCombination(indices, base.length));
@@ -1563,6 +1621,8 @@ const getSortedSubsets = (base: Value[]) => {
1563
1621
  return subsets;
1564
1622
  };
1565
1623
 
1624
+ // TLC enumerates the sets in turn and stops at the first empty one. Later versions decide
1625
+ // that the set is empty before they enumerate it.
1566
1626
  const getComponentElements = (
1567
1627
  sets: Value[],
1568
1628
  getElements: (set: Value) => Value[],
@@ -1596,6 +1656,7 @@ const enumerateSet = (
1596
1656
  return elements;
1597
1657
  }
1598
1658
  case "Subset": {
1659
+ // TLC sizes the set before it enumerates it, and enumerates a set of size 0 as {{}}.
1599
1660
  if (getCardinality(value.base) === 0) return getSortedSubsets([]);
1600
1661
  if (!isSetValue(value.base)) {
1601
1662
  throw new TlaEvaluationError(
@@ -1609,14 +1670,15 @@ const enumerateSet = (
1609
1670
  return getSortedSubsets(base);
1610
1671
  }
1611
1672
  case "FunctionSet": {
1612
- if (!isVersion174 && isEmptySet(value)) return [];
1673
+ if (!valueVersion.is174 && isEmptySet(value)) return [];
1613
1674
  if (isOverriddenSet(value.domain)) {
1614
1675
  throw new TlaEvaluationError(
1615
1676
  `Attempted to enumerate a set of the form [D -> R],but the domain D:\n${formatValue(value.domain)}\ncannot be enumerated.`,
1616
1677
  );
1617
1678
  }
1618
1679
  const domain = getFunctionDomain(value.domain);
1619
- if ((domain.length > 0 || isVersion174) && isOverriddenSet(value.range)) {
1680
+ // TLC 1.7.4 requires an enumerable range even of an empty domain.
1681
+ if ((domain.length > 0 || valueVersion.is174) && isOverriddenSet(value.range)) {
1620
1682
  throw new TlaEvaluationError(
1621
1683
  `Attempted to enumerate a set of the form [D -> R],but the range R:\n${formatValue(value.range)}\ncannot be enumerated.`,
1622
1684
  );
@@ -1627,7 +1689,7 @@ const enumerateSet = (
1627
1689
  );
1628
1690
  }
1629
1691
  case "RecordSet": {
1630
- if (!isVersion174 && isEmptySet(value)) return [];
1692
+ if (!valueVersion.is174 && isEmptySet(value)) return [];
1631
1693
  const fields = getComponentElements(
1632
1694
  value.sets,
1633
1695
  getElements,
@@ -1639,7 +1701,7 @@ const enumerateSet = (
1639
1701
  );
1640
1702
  }
1641
1703
  case "ProductSet": {
1642
- if (!isVersion174 && isEmptySet(value)) return [];
1704
+ if (!valueVersion.is174 && isEmptySet(value)) return [];
1643
1705
  const factors = getComponentElements(
1644
1706
  value.factors,
1645
1707
  getElements,
@@ -1737,6 +1799,8 @@ export const toFiniteSet = (value: Value): SetValue => {
1737
1799
  return set;
1738
1800
  };
1739
1801
 
1802
+ // TLC's enumerator of a set sorts the set enumerations it streams, and fails on a set it can't
1803
+ // enumerate, before it yields an element, so S \cup T fails on T before it streams S.
1740
1804
  const openStream = (value: Value): void => {
1741
1805
  if (typeof value !== "object" || isCachedSet(value)) return;
1742
1806
  switch (value.kind) {
@@ -1785,6 +1849,8 @@ const listUnionLikeTlc = (union: SetOperationValue) => {
1785
1849
  return [...left, ...right];
1786
1850
  };
1787
1851
 
1852
+ // EnumerableValue#elements(NORMALIZED) sorts a union outside its methods, so a failed comparison
1853
+ // isn't a fingerprint failure.
1788
1854
  export const getNormalizedSetElements = (value: Value) => {
1789
1855
  if (
1790
1856
  typeof value !== "object" ||
@@ -1800,6 +1866,8 @@ export const getNormalizedSetElements = (value: Value) => {
1800
1866
  return elements;
1801
1867
  };
1802
1868
 
1869
+ // TLC streams the sets a lazy set combines until it caches it, so a shared element repeats. Like
1870
+ // its enumerators, the stream stops at the first element visit accepts.
1803
1871
  export const someStreamedElement = (value: Value, visit: (element: Value) => boolean): boolean => {
1804
1872
  if (typeof value !== "object" || isCachedSet(value)) {
1805
1873
  return toFiniteSet(value).elements.some(visit);
@@ -1807,6 +1875,7 @@ export const someStreamedElement = (value: Value, visit: (element: Value) => boo
1807
1875
  const sets = setTrace.sets;
1808
1876
  sets?.push(value);
1809
1877
  openStream(value);
1878
+ // The set is enumerated only while it computes an element, not while visit looks at one.
1810
1879
  const isFound = someElementOfStream(value, (element) => {
1811
1880
  sets?.pop();
1812
1881
  const isAccepted = visit(element);
@@ -1835,6 +1904,9 @@ const getCombinedSets = (value: ObjectValue) =>
1835
1904
  ? [value.range]
1836
1905
  : undefined;
1837
1906
 
1907
+ // Whether one evaluation can stand for the next: no UNION or \cup, which streams until TLC
1908
+ // caches it, no lambda, which fingerprinting turns into a record, and no record a
1909
+ // comparison reorders.
1838
1910
  export const isSettledValue = (value: Value): boolean => {
1839
1911
  if (typeof value !== "object") return true;
1840
1912
  switch (value.kind) {
@@ -1863,6 +1935,7 @@ export const isSettledValue = (value: Value): boolean => {
1863
1935
  }
1864
1936
  };
1865
1937
 
1938
+ // A set of tuples, records, or functions with such a component has to stream too.
1866
1939
  const isStreamedApart = (value: Value): boolean => {
1867
1940
  if (typeof value !== "object" || isCachedSet(value)) return false;
1868
1941
  if (value.kind === "Union") return true;
@@ -1876,6 +1949,7 @@ const isStreamedApart = (value: Value): boolean => {
1876
1949
  };
1877
1950
 
1878
1951
  const someElementOfStream = (value: ObjectValue, visit: (element: Value) => boolean): boolean => {
1952
+ // TLC streams the sets of a UNION it hasn't enumerated, so a repeated set yields them twice.
1879
1953
  if (value.kind === "Union") {
1880
1954
  return getUnionSets(value, getStreamedElements).some((set, index) =>
1881
1955
  someStreamedElement(getUnionSet(set, index, value), visit),
@@ -1952,6 +2026,7 @@ const getProductCardinality = (
1952
2026
  const describeOverflow = (value: Value) =>
1953
2027
  `Overflow when computing the number of elements in:\n${formatValue(value)}`;
1954
2028
 
2029
+ // TLC 1.7.4 sizes every component without checking for an empty one, so an infinite one fails.
1955
2030
  export const getCardinality = (value: Value, version?: TlcVersion): number => {
1956
2031
  if (typeof value !== "object") {
1957
2032
  throw new TlaEvaluationError(
@@ -1995,12 +2070,12 @@ export const getCardinality = (value: Value, version?: TlcVersion): number => {
1995
2070
  const domainSize = getCardinality(value.domain, version);
1996
2071
  const rangeSize = getCardinality(value.range, version);
1997
2072
  if (rangeSize <= 1) return domainSize === 0 ? 1 : rangeSize;
1998
- let size = 1;
2073
+ const size = { value: 1 };
1999
2074
  for (let index = 0; index < domainSize; index++) {
2000
- size *= rangeSize;
2001
- if (size > MAXIMUM_INTEGER) throw new TlaEvaluationError(describeOverflow(value));
2075
+ size.value *= rangeSize;
2076
+ if (size.value > MAXIMUM_INTEGER) throw new TlaEvaluationError(describeOverflow(value));
2002
2077
  }
2003
- return size;
2078
+ return size.value;
2004
2079
  }
2005
2080
  case "RecordSet":
2006
2081
  if (version !== "1.7.4" && isEmptySet(value)) return 0;
@@ -2053,12 +2128,12 @@ export const isFiniteSet = (value: Value): boolean => {
2053
2128
  case "RecordSet":
2054
2129
  case "ProductSet": {
2055
2130
  const parts = value.kind === "RecordSet" ? value.sets : value.factors;
2056
- let isAllFinite = true;
2131
+ const finiteness = { isAllFinite: true };
2057
2132
  for (const part of parts) {
2058
- if (!isFiniteSet(part)) isAllFinite = false;
2133
+ if (!isFiniteSet(part)) finiteness.isAllFinite = false;
2059
2134
  else if (isEmptySet(part)) return true;
2060
2135
  }
2061
- return isAllFinite;
2136
+ return finiteness.isAllFinite;
2062
2137
  }
2063
2138
  case "Union":
2064
2139
  if (!isTlcEnumerable(value.base)) {
@@ -2089,18 +2164,18 @@ export const isFiniteSet = (value: Value): boolean => {
2089
2164
  };
2090
2165
 
2091
2166
  const findSortedIndex = (sortedValues: Value[], target: Value, compare = compareValues) => {
2092
- let low = 0;
2093
- let high = sortedValues.length - 1;
2094
- while (low <= high) {
2095
- const middle = (low + high) >> 1;
2167
+ const bounds = { low: 0, high: sortedValues.length - 1 };
2168
+ while (bounds.low <= bounds.high) {
2169
+ const middle = (bounds.low + bounds.high) >> 1;
2096
2170
  const comparison = compare(sortedValues[middle], target);
2097
2171
  if (comparison === 0) return middle;
2098
- if (comparison < 0) low = middle + 1;
2099
- else high = middle - 1;
2172
+ if (comparison < 0) bounds.low = middle + 1;
2173
+ else bounds.high = middle - 1;
2100
2174
  }
2101
2175
  return -1;
2102
2176
  };
2103
2177
 
2178
+ // A sorted set as TLC builds it unsorted, by adding each element it doesn't hold yet.
2104
2179
  export const createUnsortedCopy = (set: SetValue, added: Value[]): SetValue => {
2105
2180
  const elements = set.elements;
2106
2181
  if (elements.length > getMaximumSetSize()) throw new TlaSetBoundError(getSetBoundMessage());
@@ -2152,10 +2227,14 @@ interface TracedCallStack {
2152
2227
  fingerprint?: unknown;
2153
2228
  }
2154
2229
 
2230
+ // The values being checked or enumerated, outermost first, as TLC's CallStackTool replays a
2231
+ // computation. TLC adds each one with a source to the FingerprintException.
2155
2232
  export const setTrace: { sets: Value[] | undefined; callStack?: TracedCallStack } = {
2156
2233
  sets: undefined,
2157
2234
  };
2158
2235
 
2236
+ // TLC never takes the fast path, so the failure's leftovers in the replay's trace go first.
2237
+ // The operands are arguments so that a hot caller passes functions it doesn't allocate.
2159
2238
  export const computeLikeTlcOnFailure = <Left, Right, Result>(
2160
2239
  compute: (left: Left, right: Right) => Result,
2161
2240
  computeLikeTlc: (left: Left, right: Right, error: TlaEvaluationError) => Result,
@@ -2194,17 +2273,17 @@ export const isElementOf = (element: Value, set: Value): boolean => {
2194
2273
  return isElement;
2195
2274
  };
2196
2275
 
2276
+ // Integers compare by subtraction, so a search that meets only integers needs no other comparison.
2197
2277
  const isIntegerInSortedSet = (element: number, set: SetValue) => {
2198
2278
  const elements = set.elements;
2199
- let low = 0;
2200
- let high = elements.length - 1;
2201
- while (low <= high) {
2202
- const middle = (low + high) >> 1;
2279
+ const bounds = { low: 0, high: elements.length - 1 };
2280
+ while (bounds.low <= bounds.high) {
2281
+ const middle = (bounds.low + bounds.high) >> 1;
2203
2282
  const probe = elements[middle];
2204
2283
  if (typeof probe !== "number") return undefined;
2205
2284
  if (probe === element) return true;
2206
- if (probe < element) low = middle + 1;
2207
- else high = middle - 1;
2285
+ if (probe < element) bounds.low = middle + 1;
2286
+ else bounds.high = middle - 1;
2208
2287
  }
2209
2288
  return false;
2210
2289
  };
@@ -2240,6 +2319,7 @@ const isElementOfAnySet = (element: Value, set: Value): boolean => {
2240
2319
  if (!isSetValue(set)) throw new TlaEvaluationError(describeNonSetMembership(element, set));
2241
2320
  switch (set.kind) {
2242
2321
  case "Set":
2322
+ // TLC compares the element with the set's.
2243
2323
  cacheSet(element);
2244
2324
  return computeLikeTlcOnFailure(isInSortedSet, isInSortedSetLikeTlc, element, set);
2245
2325
  case "MixedSet":
@@ -2265,6 +2345,7 @@ const isElementOfAnySet = (element: Value, set: Value): boolean => {
2265
2345
  return set.name !== "Nat" || (typeof element === "number" && element >= 0);
2266
2346
  }
2267
2347
  case "Subset":
2348
+ // TLC fails on a value that isn't Enumerable, model values and Java-overridden sets included.
2268
2349
  if (!isSetValue(element) || isOverriddenSet(element)) {
2269
2350
  throw new TlaEvaluationError(
2270
2351
  `Attempted to check if the non-enumerable value\n${prettyPrint(formatValue(element))}\nis element of\n${prettyPrint(formatValue(set))}`,
@@ -2274,6 +2355,7 @@ const isElementOfAnySet = (element: Value, set: Value): boolean => {
2274
2355
  case "FunctionSet": {
2275
2356
  if (!isFunctionValue(element)) {
2276
2357
  if (isModelValue(element)) return isModelValueMember(element, set);
2358
+ // TLC prints the element without Values.ppr.
2277
2359
  throw new TlaEvaluationError(
2278
2360
  `Attempted to check if \n${formatValue(element)}\nwhich is not a TLC function value, is in the set of functions:\n${prettyPrint(formatValue(set))}`,
2279
2361
  );
@@ -2338,6 +2420,7 @@ const isElementOfAnySet = (element: Value, set: Value): boolean => {
2338
2420
  );
2339
2421
  }
2340
2422
  const sets = toFiniteSet(set.base).elements;
2423
+ // TLC sorts the sets to enumerate them, and comparing two sets normalizes both.
2341
2424
  if (sets.length > 1) {
2342
2425
  sets.forEach((inner) => {
2343
2426
  if (typeof inner === "object" && inner.kind === "Set") inner.isNormalized = true;
@@ -2356,6 +2439,7 @@ const isElementOfAnySet = (element: Value, set: Value): boolean => {
2356
2439
  const elements = getSequenceElements(element);
2357
2440
  if (elements === undefined) {
2358
2441
  if (isModelValue(element)) return isModelValueMember(element, set);
2442
+ // TLC raises TLC_MODULE_CHECK_MEMBER_OF.
2359
2443
  throw new TlaModuleError(
2360
2444
  `Attempted to check if the value:\n${prettyPrint(formatValue(element))}\nis an element of ${prettyPrint(formatValue(set))}.`,
2361
2445
  );
@@ -2439,14 +2523,16 @@ export const describeMissingArgument = (
2439
2523
  }
2440
2524
  };
2441
2525
 
2526
+ // TLC 1.7.4 words a key of the wrong type in an EXCEPT, which selects rather than applies, apart.
2442
2527
  const describeExceptKey = (functionValue: FunctionValue, argument: Value) => {
2443
- if (!isVersion174) return describeMissingArgument(functionValue, argument);
2528
+ if (!valueVersion.is174) return describeMissingArgument(functionValue, argument);
2444
2529
  const shown = prettyPrint(formatValue(argument));
2445
2530
  return getFunctionClass(functionValue) === "tuple"
2446
2531
  ? `Attempted to apply tuple to a non-integer argument ${shown}.`
2447
2532
  : `Attempted to apply record to a non-string argument ${shown}.`;
2448
2533
  };
2449
2534
 
2535
+ // A key the domain holds itself, which TLC finds without a comparison that can fail.
2450
2536
  const findIdenticalKey = (domain: Value[], argument: Value) => {
2451
2537
  const first = domain[0];
2452
2538
  if (typeof argument === "number" && typeof first === "number") {
@@ -2461,18 +2547,20 @@ export const createNonIntegerKeyError = (argument: Value) =>
2461
2547
  `Attempted to apply function with integer domain to the non-integer argument ${prettyPrint(formatValue(argument))}`,
2462
2548
  );
2463
2549
 
2550
+ // TLC searches a domain this small linearly with equals, and a larger one with compareTo.
2464
2551
  const LINEAR_SEARCH_LIMIT = 32;
2465
2552
 
2466
2553
  const findDomainIndex = (functionValue: FunctionValue, argument: Value) =>
2467
2554
  findSortedIndex(functionValue.domain, argument);
2468
2555
 
2556
+ // TLC searches a function it hasn't normalized linearly, in the order its keys were written.
2469
2557
  const failKeyLikeTlc = (
2470
2558
  functionValue: FunctionValue,
2471
2559
  argument: Value,
2472
2560
  error: TlaEvaluationError,
2473
2561
  ): never => {
2474
2562
  const keys = getWrittenKeys(functionValue);
2475
- if (isVersion174 || keys !== functionValue.domain || keys.length < LINEAR_SEARCH_LIMIT) {
2563
+ if (valueVersion.is174 || keys !== functionValue.domain || keys.length < LINEAR_SEARCH_LIMIT) {
2476
2564
  keys.forEach((key) => equalsLikeTlc(key, argument));
2477
2565
  } else {
2478
2566
  findSortedIndex(keys, argument, compareLikeTlc);
@@ -2480,6 +2568,8 @@ const failKeyLikeTlc = (
2480
2568
  throw error;
2481
2569
  };
2482
2570
 
2571
+ // A tuple or a record rejects a key of the wrong type, and another function a non-integer for
2572
+ // an interval domain, which TLC 1.7.4 doesn't. Any other key type fails TLC's comparison.
2483
2573
  const findKeyIndexLikeTlc = (
2484
2574
  functionValue: FunctionValue,
2485
2575
  argument: Value,
@@ -2495,7 +2585,7 @@ const findKeyIndexLikeTlc = (
2495
2585
  }
2496
2586
  if (
2497
2587
  keyType === undefined &&
2498
- !isVersion174 &&
2588
+ !valueVersion.is174 &&
2499
2589
  typeof argument !== "number" &&
2500
2590
  isIntervalDomain(domain)
2501
2591
  ) {
@@ -2507,7 +2597,8 @@ const findKeyIndexLikeTlc = (
2507
2597
  return computeLikeTlcOnFailure(findDomainIndex, failKeyLikeTlc, functionValue, argument);
2508
2598
  };
2509
2599
 
2510
- // Deviation from TLC: FcnLambdaValue#apply indexes past an argument tuple shorter than the bounds and ignores a longer one, where this rejects the list.
2600
+ // TLC checks each argument against its bound in turn. FcnLambdaValue#apply then indexes past an
2601
+ // argument tuple shorter than the bounds and ignores one longer, where this rejects the list.
2511
2602
  const checkBoundArguments = (
2512
2603
  functionValue: LazyFunctionValue,
2513
2604
  tupleLengths: (number | undefined)[],
@@ -2551,6 +2642,8 @@ const checkBoundArguments = (
2551
2642
  if (elements.length > tupleLengths.length) throw createListError();
2552
2643
  };
2553
2644
 
2645
+ // TLC checks that a FcnLambdaValue's domain holds the argument, and searches only the FcnRcdValue
2646
+ // it converts the lambda to when it fingerprints it.
2554
2647
  const isOutsideLambdaDomain = (functionValue: FunctionValue, argument: Value) =>
2555
2648
  functionValue.lambdaDomain !== undefined &&
2556
2649
  functionValue.hash === 0 &&
@@ -2607,6 +2700,7 @@ export const getDomain = (functionValue: Value): Value => {
2607
2700
  const interval = getDomainInterval(finite.domain);
2608
2701
  if (interval) return interval;
2609
2702
  const set = createSortedSet(finite.domain);
2703
+ // TLC keeps a record's domain in written order and sorts any other function's.
2610
2704
  if (finite.functionClass === "record") {
2611
2705
  if (finite.writtenKeys) set.writtenElements = finite.writtenKeys;
2612
2706
  return set;
@@ -2710,6 +2804,8 @@ const getElementContribution = (elementHash: number) =>
2710
2804
  const getEntryContribution = (keyHash: number, valueHash: number) =>
2711
2805
  finalizeHash((Math.imul(keyHash, 0x27d4eb2d) + valueHash) | 0);
2712
2806
 
2807
+ // The hash of a value TLC fails to fingerprint, such as Nat. Calls with one as an argument still
2808
+ // share their result, and a state that holds one fails when TLC fingerprints it.
2713
2809
  const UNFINGERPRINTABLE_HASH = 0x2f6b1c4d;
2714
2810
 
2715
2811
  const computeValueHash = (value: SetValue | FunctionValue) => {
@@ -2735,6 +2831,7 @@ const computeValueHash = (value: SetValue | FunctionValue) => {
2735
2831
  return hash;
2736
2832
  };
2737
2833
 
2834
+ // TLC enumerates each set and function, and fails on Nat, Seq(S) and the like.
2738
2835
  const fingerprintValue = (value: Value): void => {
2739
2836
  if (typeof value !== "object" || value.kind === "ModelValue") return;
2740
2837
  if (value.kind === "InfiniteSet" || value.kind === "SequenceSet") {
@@ -2751,6 +2848,7 @@ const fingerprintValue = (value: Value): void => {
2751
2848
  functionValue.range.forEach(fingerprintValue);
2752
2849
  };
2753
2850
 
2851
+ // Hashing can fail, as for a set too large to enumerate, and so can a value TLC fails on.
2754
2852
  export const getFingerprintError = (value: Value) => {
2755
2853
  if (typeof value !== "object" || value.kind === "ModelValue") return undefined;
2756
2854
  try {
@@ -2918,6 +3016,7 @@ const expandLazySet = (value: LazySetValue) => {
2918
3016
  if (value.kind === "SetOperation" || value.kind === "FilteredSet" || value.kind === "Union") {
2919
3017
  return toFiniteSet(value);
2920
3018
  }
3019
+ // TLC asks whether the domain is empty before it sizes it.
2921
3020
  if (value.kind === "FunctionSet") {
2922
3021
  const domainSize = isEmptySet(value.domain) ? 0 : getCardinality(value.domain);
2923
3022
  const size = domainSize === 0 ? 1 : getCardinality(value.range) ** domainSize;
@@ -2928,7 +3027,9 @@ const expandLazySet = (value: LazySetValue) => {
2928
3027
  };
2929
3028
 
2930
3029
  const getExpandedLazySet = (value: LazySetValue, isStrict: boolean) => {
3030
+ // UnionValue alone of TLC's lazy sets doesn't swallow the failure to enumerate itself.
2931
3031
  if (isStrict || value.kind === "Union") return expandLazySet(value);
3032
+ // TLC sizes the base of SUBSET before it enumerates it, and only a failure to size it is quiet.
2932
3033
  if (
2933
3034
  value.kind === "Subset" &&
2934
3035
  isFunctionValue(value.base) &&
@@ -2936,6 +3037,7 @@ const getExpandedLazySet = (value: LazySetValue, isStrict: boolean) => {
2936
3037
  ) {
2937
3038
  return expandLazySet(value);
2938
3039
  }
3040
+ // TLC prints a set it can't enumerate symbolically, except in Print, PrintT, and ToString.
2939
3041
  if (!isEnumerable(value)) return undefined;
2940
3042
  try {
2941
3043
  return expandLazySet(value);
@@ -2969,6 +3071,7 @@ const formatLazySet = (value: LazySetValue, isStrict: boolean): string => {
2969
3071
  }
2970
3072
  };
2971
3073
 
3074
+ // TLC prints a record when every key is letters, digits, and underscores, with a letter.
2972
3075
  const isFieldName = (name: string) =>
2973
3076
  /^[\p{L}\p{Nd}_]*$/u.test(name) &&
2974
3077
  /\p{L}/u.test(name) &&
@@ -2984,6 +3087,7 @@ const toPrintedFunction = (value: LazyFunctionValue) => {
2984
3087
  }
2985
3088
  };
2986
3089
 
3090
+ // TLC prints normalized copies, so the printed values themselves stay unnormalized.
2987
3091
  export const formatNormalizedCopies = (values: Value[]) => {
2988
3092
  const markedSets: SetValue[] = [];
2989
3093
  const normalize = (value: Value): void => {
@@ -3086,11 +3190,12 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
3086
3190
  }
3087
3191
  if (
3088
3192
  functionValue.domain.length === 0 &&
3089
- isVersion174 &&
3193
+ valueVersion.is174 &&
3090
3194
  getFunctionClass(value) !== "tuple"
3091
3195
  ) {
3092
3196
  return "<< >>";
3093
3197
  }
3198
+ // TLC normalizes a lambda's domain to print it, but evaluates its body afterward.
3094
3199
  const formatRange = (inner: Value) =>
3095
3200
  formatValue(inner, isStrict, isNormalized && getFunctionClass(value) !== "lambda");
3096
3201
  if (functionValue.domain.length === 0 && getFunctionClass(value) === "record") return "[]";
@@ -3100,6 +3205,7 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
3100
3205
  const pairs = isNormalized
3101
3206
  ? functionValue.domain.map((key, index) => [key, functionValue.range[index]])
3102
3207
  : getPrintedPairs(functionValue);
3208
+ // A RecordValue always prints as a record, a FcnRcdValue only if its keys are names.
3103
3209
  if (
3104
3210
  getFunctionClass(value) === "record" ||
3105
3211
  functionValue.domain.every((key) => typeof key === "string" && isFieldName(key))
@@ -3111,6 +3217,7 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
3111
3217
  }
3112
3218
  };
3113
3219
 
3220
+ // TLC counts a value it can't compare with the previous one as changed.
3114
3221
  const isUnchanged = (previous: Value | undefined, value: Value) => {
3115
3222
  if (previous === undefined) return false;
3116
3223
  try {
@@ -3124,15 +3231,14 @@ const isUnchanged = (previous: Value | undefined, value: Value) => {
3124
3231
  const JAVA_FORMAT_SPECIFIER = /%(\d+\$)?([-#+ 0,(<]*)(\d+)?(\.\d+)?(.?)/gs;
3125
3232
 
3126
3233
  const getJavaHashCode = (text: string) =>
3127
- Array.from({ length: text.length }, (_value, index) => text.charCodeAt(index)).reduce(
3234
+ Array.from({ length: text.length }, (_, index) => text.charCodeAt(index)).reduce(
3128
3235
  (hash, unit) => (Math.imul(hash, 31) + unit) | 0,
3129
3236
  0,
3130
3237
  );
3131
3238
 
3132
3239
  const formatJava = (format: string, args: string[]) => {
3133
- let nextIndex = 0;
3134
- let lastIndex = -1;
3135
- let isFitting = true;
3240
+ const indices = { next: 0, last: -1 };
3241
+ const isFitting = { value: true };
3136
3242
  const text = format.replace(
3137
3243
  JAVA_FORMAT_SPECIFIER,
3138
3244
  (match, explicit?: string, flags = "", width?: string, precision?: string, conversion = "") => {
@@ -3142,15 +3248,15 @@ const formatJava = (format: string, args: string[]) => {
3142
3248
  const otherFlags = flags.replace("<", "");
3143
3249
  if (conversion === "n" && match === "%n") return "\n";
3144
3250
  if (conversion === "%" && precision === undefined && /^-?$/.test(otherFlags)) {
3145
- if (otherFlags === "-" && width === undefined) isFitting = false;
3251
+ if (otherFlags === "-" && width === undefined) isFitting.value = false;
3146
3252
  return pad("%");
3147
3253
  }
3148
3254
  const index = isRelative
3149
- ? lastIndex
3255
+ ? indices.last
3150
3256
  : explicit === undefined
3151
- ? nextIndex++
3257
+ ? indices.next++
3152
3258
  : Number(explicit.slice(0, -1)) - 1;
3153
- lastIndex = index;
3259
+ indices.last = index;
3154
3260
  const arg = args[index];
3155
3261
  if (
3156
3262
  !"sSbBhH".includes(conversion) ||
@@ -3159,7 +3265,7 @@ const formatJava = (format: string, args: string[]) => {
3159
3265
  (otherFlags === "-" && width === undefined) ||
3160
3266
  arg === undefined
3161
3267
  ) {
3162
- isFitting = false;
3268
+ isFitting.value = false;
3163
3269
  return match;
3164
3270
  }
3165
3271
  const lower = conversion.toLowerCase();
@@ -3171,9 +3277,10 @@ const formatJava = (format: string, args: string[]) => {
3171
3277
  return conversion === lower ? shown : shown.toUpperCase();
3172
3278
  },
3173
3279
  );
3174
- return isFitting ? text : undefined;
3280
+ return isFitting.value ? text : undefined;
3175
3281
  };
3176
3282
 
3283
+ // TLC prints the VIEW of a state, but not of one it prints as a difference from the previous.
3177
3284
  export const formatState = (state: Record<string, Value>, previous?: Record<string, Value>) => {
3178
3285
  const getViewText = previous ? undefined : viewTexts.get(state);
3179
3286
  if (getViewText) return getViewText();