tla-ts 0.0.3-dev.bffbba3 → 0.0.3-dev.c8c988d

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/tlc-random.ts CHANGED
@@ -181,8 +181,10 @@ const createShiftTable = (length: number) => {
181
181
 
182
182
  // Extending a fingerprint by a byte is linear over GF(2), so extending it by a value's bytes
183
183
  // XORs the value's own fingerprint from zero into the fingerprint shifted by their length.
184
- // The fingerprinter caches each distinct variable value for one pass over the stored states.
185
- export const createTlcFingerprinter = () => {
184
+ // The fingerprinter caches each distinct variable value for one pass over the stored states. It
185
+ // reads a state's variables in `order` and writes each fingerprint's low and high words into
186
+ // `words`, an Int32Array over a little-endian BigInt64Array.
187
+ export const createTlcFingerprinter = (order: number[], words: Int32Array) => {
186
188
  const shiftTables = new Map<number, Int32Array>();
187
189
  const indices = new Map<Value, number>();
188
190
  const contributions: number[] = [];
@@ -204,11 +206,11 @@ export const createTlcFingerprinter = () => {
204
206
  shiftTables.set(length, table);
205
207
  return table;
206
208
  };
207
- return (state: Value[]) => {
209
+ return (state: Value[], position: number) => {
208
210
  const outer = { high, low };
209
211
  const fingerprint = { high: INITIAL_HIGH, low: INITIAL_LOW };
210
- for (const value of state) {
211
- const contribution = getContribution(value);
212
+ for (const index of order) {
213
+ const contribution = getContribution(state[index]);
212
214
  const table = getShiftTable(contributions[contribution]);
213
215
  const extended = {
214
216
  high: contributions[contribution + 1],
@@ -225,7 +227,8 @@ export const createTlcFingerprinter = () => {
225
227
  }
226
228
  high = outer.high;
227
229
  low = outer.low;
228
- return (BigInt(fingerprint.high >>> 0) << 32n) | BigInt(fingerprint.low >>> 0);
230
+ words[2 * position] = fingerprint.low;
231
+ words[2 * position + 1] = fingerprint.high;
229
232
  };
230
233
  };
231
234
 
@@ -87,11 +87,26 @@ export const getFingerprintDistance = (
87
87
  const probability = getOptimisticProbability(distinctStates, generatedStates);
88
88
  if (probability < ACTUAL_PROBABILITY_THRESHOLD) return undefined;
89
89
  const fingerprints = getFingerprints().sort();
90
- return fingerprints.reduce((distance, fingerprint, index) => {
91
- const previous = fingerprints[index - 1];
92
- const isSameSet = index > 0 && previous < 0n === fingerprint < 0n;
93
- return isSameSet && fingerprint - previous < distance ? fingerprint - previous : distance;
94
- }, 0x7fff_ffff_ffff_ffffn);
90
+ // The low and high words of each fingerprint. A gap whose high words differ by at most 2^20 is
91
+ // below 2^53, so a number holds it exactly and only wider gaps need a BigInt.
92
+ const words = new Int32Array(fingerprints.buffer);
93
+ const nearest = { narrow: Number.POSITIVE_INFINITY, wide: 0x7fff_ffff_ffff_ffffn };
94
+ for (let index = 1; index < fingerprints.length; index++) {
95
+ const high = words[2 * index + 1];
96
+ const previousHigh = words[2 * index - 1];
97
+ if (high < 0 !== previousHigh < 0) continue;
98
+ const highGap = high - previousHigh;
99
+ if (highGap <= 0x10_0000) {
100
+ const gap = highGap * 0x1_0000_0000 + (words[2 * index] >>> 0) - (words[2 * index - 2] >>> 0);
101
+ nearest.narrow = Math.min(nearest.narrow, gap);
102
+ } else {
103
+ const gap = fingerprints[index] - fingerprints[index - 1];
104
+ if (gap < nearest.wide) nearest.wide = gap;
105
+ }
106
+ }
107
+ if (nearest.narrow === Number.POSITIVE_INFINITY) return nearest.wide;
108
+ const narrow = BigInt(nearest.narrow);
109
+ return narrow < nearest.wide ? narrow : nearest.wide;
95
110
  };
96
111
 
97
112
  export const getOutDegreeSummary = (buckets: number[]) => {
@@ -0,0 +1,29 @@
1
+ import type { Expression } from "./ast";
2
+ import { TlaEvaluationError } from "./errors";
3
+ import type { Value } from "./values";
4
+
5
+ // While TLC replays a failure, it gives each set, tuple or record it builds the expression that
6
+ // built it. A method of such a value that fails prepends that expression to the error's trace, and
7
+ // TLC reports the error as one it was unable to fingerprint.
8
+ export const valueSources: { current: WeakMap<object, Expression> | undefined } = {
9
+ current: undefined,
10
+ };
11
+
12
+ const fingerprintTraces = new WeakMap<TlaEvaluationError, Expression[]>();
13
+
14
+ export const getFingerprintTrace = (error: unknown) =>
15
+ error instanceof TlaEvaluationError ? fingerprintTraces.get(error) : undefined;
16
+
17
+ export const withSource = <T>(value: Value, run: () => T): T => {
18
+ const sources = valueSources.current;
19
+ if (!sources || typeof value !== "object") return run();
20
+ try {
21
+ return run();
22
+ } catch (error) {
23
+ const source = sources.get(value);
24
+ if (source && error instanceof TlaEvaluationError) {
25
+ fingerprintTraces.set(error, [source, ...(fingerprintTraces.get(error) ?? [])]);
26
+ }
27
+ throw error;
28
+ }
29
+ };
package/src/values.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { TlaEvaluationError, TlaModuleError } from "./errors";
2
2
  import { prettyPrint } from "./pretty-print";
3
+ import { valueSources, withSource } from "./value-sources";
3
4
 
4
5
  export interface ModelValue {
5
6
  kind: "ModelValue";
@@ -733,16 +734,17 @@ const compareSetLikeTlc = (left: ObjectValue, right: Value): number => {
733
734
  );
734
735
  };
735
736
 
736
- const compareLikeTlc = (left: Value, right: Value): number => {
737
- if (typeof left !== "object") {
738
- if (typeof right === typeof left) return compareValues(left, right);
739
- if (isModelValue(right)) return compareModelValueWith(right, left);
740
- throw new TlaEvaluationError(describeScalarMismatch(left, right, false));
741
- }
742
- if (left.kind === "ModelValue") return compareModelValue(left, right);
743
- if (isFunctionValue(left)) return compareFunctionLikeTlc(left, right);
744
- return compareSetLikeTlc(left, right);
745
- };
737
+ const compareLikeTlc = (left: Value, right: Value): number =>
738
+ withSource(left, () => {
739
+ if (typeof left !== "object") {
740
+ if (typeof right === typeof left) return compareValues(left, right);
741
+ if (isModelValue(right)) return compareModelValueWith(right, left);
742
+ throw new TlaEvaluationError(describeScalarMismatch(left, right, false));
743
+ }
744
+ if (left.kind === "ModelValue") return compareModelValue(left, right);
745
+ if (isFunctionValue(left)) return compareFunctionLikeTlc(left, right);
746
+ return compareSetLikeTlc(left, right);
747
+ });
746
748
 
747
749
  const equalsElementsLikeTlc = (left: Value[], right: Value[]) =>
748
750
  left.every((element, index) => equalsLikeTlc(element, right[index]));
@@ -830,16 +832,17 @@ const equalsSetLikeTlc = (left: ObjectValue, right: Value): boolean => {
830
832
  );
831
833
  };
832
834
 
833
- const equalsLikeTlc = (left: Value, right: Value): boolean => {
834
- if (typeof left !== "object") {
835
- if (typeof right === typeof left) return left === right;
836
- if (isModelValue(right)) return equalsModelValueWith(right, left);
837
- throw new TlaEvaluationError(describeScalarMismatch(left, right, true));
838
- }
839
- if (left.kind === "ModelValue") return equalsModelValue(left, right);
840
- if (isFunctionValue(left)) return equalsFunctionLikeTlc(left, right);
841
- return equalsSetLikeTlc(left, right);
842
- };
835
+ const equalsLikeTlc = (left: Value, right: Value): boolean =>
836
+ withSource(left, () => {
837
+ if (typeof left !== "object") {
838
+ if (typeof right === typeof left) return left === right;
839
+ if (isModelValue(right)) return equalsModelValueWith(right, left);
840
+ throw new TlaEvaluationError(describeScalarMismatch(left, right, true));
841
+ }
842
+ if (left.kind === "ModelValue") return equalsModelValue(left, right);
843
+ if (isFunctionValue(left)) return equalsFunctionLikeTlc(left, right);
844
+ return equalsSetLikeTlc(left, right);
845
+ });
843
846
 
844
847
  // TLC's ValueVec.sort, which inserts each element into the sorted prefix by binary search.
845
848
  const sortLikeTlc = (elements: Value[]) => {
@@ -1196,6 +1199,41 @@ const advanceCombination = (indices: number[], length: number) => {
1196
1199
  return false;
1197
1200
  };
1198
1201
 
1202
+ // TLC enumerates SUBSET S lazily, by size and then in the order of S, so a quantifier that finds
1203
+ // its witness early never builds the rest. For a power set too large to build, the elements are
1204
+ // computed in that order as a loop reads them.
1205
+ export const getLazySubsets = (value: Value): Value[] | undefined => {
1206
+ if (typeof value !== "object" || value.kind !== "Subset" || isOverriddenSet(value.base)) {
1207
+ return undefined;
1208
+ }
1209
+ const base = toFiniteSet(value.base).elements;
1210
+ if (base.length <= MAXIMUM_ENUMERATED_SUBSET_BASE) return undefined;
1211
+ const cursor = { index: -1, indices: [0] };
1212
+ const getSubset = (index: number) => {
1213
+ if (index <= cursor.index) cursor.index = -1;
1214
+ while (cursor.index < index) {
1215
+ if (cursor.index === -1) cursor.indices = [];
1216
+ else if (!advanceCombination(cursor.indices, base.length)) {
1217
+ cursor.indices = Array.from({ length: cursor.indices.length + 1 }, (_, item) => item);
1218
+ }
1219
+ cursor.index++;
1220
+ }
1221
+ return createSortedSet(cursor.indices.map((item) => base[item]));
1222
+ };
1223
+ const length = 2 ** base.length;
1224
+ const isIndex = (property: string | symbol) =>
1225
+ typeof property === "string" && /^\d+$/.test(property) && Number(property) < length;
1226
+ return new Proxy<Value[]>([], {
1227
+ get: (target, property, receiver) => {
1228
+ if (property === "length") return length;
1229
+ return isIndex(property)
1230
+ ? getSubset(Number(property))
1231
+ : Reflect.get(target, property, receiver);
1232
+ },
1233
+ has: (target, property) => isIndex(property) || Reflect.has(target, property),
1234
+ });
1235
+ };
1236
+
1199
1237
  const getSortedSubsets = (base: Value[]) => {
1200
1238
  const subsets: Value[] = [];
1201
1239
  for (let size = 0; size <= base.length; size++) {
@@ -1224,9 +1262,7 @@ const enumerateSet = (value: Value): Value[] => {
1224
1262
  if (isOverriddenSet(value.base)) getCardinality(value.base);
1225
1263
  const base = toFiniteSet(value.base).elements;
1226
1264
  if (base.length > MAXIMUM_ENUMERATED_SUBSET_BASE) {
1227
- throw new TlaEvaluationError(
1228
- `SUBSET of a set with ${base.length} elements is too large to enumerate`,
1229
- );
1265
+ throw new TlaEvaluationError(describeOverflow(value));
1230
1266
  }
1231
1267
  return getSortedSubsets(base);
1232
1268
  }
@@ -1290,7 +1326,7 @@ const enumerateSet = (value: Value): Value[] => {
1290
1326
  case "SetOperation": {
1291
1327
  if (
1292
1328
  value.operator === "\\cup" &&
1293
- (isOverriddenSet(value.left) || isOverriddenSet(value.right))
1329
+ (!isTlcEnumerable(value.left) || !isTlcEnumerable(value.right))
1294
1330
  ) {
1295
1331
  throw new TlaEvaluationError(
1296
1332
  `Attempted to enumerate S \\cup T when S:\n${formatValue(value.left)}\nand T:\n${formatValue(value.right)}\nare not both enumerable`,
@@ -1298,14 +1334,14 @@ const enumerateSet = (value: Value): Value[] => {
1298
1334
  }
1299
1335
  if (
1300
1336
  value.operator === "\\cap" &&
1301
- isOverriddenSet(value.left) &&
1302
- isOverriddenSet(value.right)
1337
+ !isTlcEnumerable(value.left) &&
1338
+ !isTlcEnumerable(value.right)
1303
1339
  ) {
1304
1340
  throw new TlaEvaluationError(
1305
1341
  `Attempted to enumerate S \\cap T when neither S:\n${formatValue(value.left)}\nnor T:\n${formatValue(value.right)}\nis enumerable`,
1306
1342
  );
1307
1343
  }
1308
- if (value.operator === "\\" && isOverriddenSet(value.left)) {
1344
+ if (value.operator === "\\" && !isTlcEnumerable(value.left)) {
1309
1345
  throw new TlaEvaluationError(
1310
1346
  `Attempted to enumerate S \\ T when S:\n${formatValue(value.left)}\nis not enumerable.`,
1311
1347
  );
@@ -1340,7 +1376,10 @@ export const toFiniteSet = (value: Value): SetValue => {
1340
1376
  const cached = typeof value === "object" ? finiteSets.get(value) : undefined;
1341
1377
  if (cached) return cached;
1342
1378
  const set =
1343
- (typeof value === "object" ? comparedSets.get(value) : undefined) ?? enumerateFiniteSet(value);
1379
+ (typeof value === "object" ? comparedSets.get(value) : undefined) ??
1380
+ (valueSources.current
1381
+ ? withSource(value, () => enumerateFiniteSet(value))
1382
+ : enumerateFiniteSet(value));
1344
1383
  if (typeof value === "object") finiteSets.set(value, set);
1345
1384
  return set;
1346
1385
  };
@@ -1389,14 +1428,14 @@ export const getStreamedElements = (value: Value): Value[] => {
1389
1428
  }
1390
1429
  if (value.kind !== "SetOperation") return toFiniteSet(value).elements;
1391
1430
  if (value.operator === "\\cup") {
1392
- return isOverriddenSet(value.left) || isOverriddenSet(value.right)
1431
+ return !isTlcEnumerable(value.left) || !isTlcEnumerable(value.right)
1393
1432
  ? toFiniteSet(value).elements
1394
1433
  : [...getStreamedElements(value.left), ...getStreamedElements(value.right)];
1395
1434
  }
1396
1435
  const isLeftEnumerated = value.operator === "\\" || isEnumerable(value.left);
1397
1436
  const enumerated = isLeftEnumerated ? value.left : value.right;
1398
1437
  const other = isLeftEnumerated ? value.right : value.left;
1399
- if (isOverriddenSet(enumerated)) return toFiniteSet(value).elements;
1438
+ if (!isTlcEnumerable(enumerated)) return toFiniteSet(value).elements;
1400
1439
  return getStreamedElements(enumerated).filter(
1401
1440
  (element) => isElementOf(element, other) === (value.operator === "\\cap"),
1402
1441
  );
@@ -1599,6 +1638,12 @@ const describeNonSetMembership = (element: Value, value: Value) => {
1599
1638
  return `${prefix} function ${formatValue(value)}`;
1600
1639
  };
1601
1640
 
1641
+ // TLC checks membership in a set that another set holds through the inner set's own method.
1642
+ const isElementOfSet = (element: Value, set: Value) =>
1643
+ valueSources.current
1644
+ ? withSource(set, () => isElementOf(element, set))
1645
+ : isElementOf(element, set);
1646
+
1602
1647
  export const isElementOf = (element: Value, set: Value): boolean => {
1603
1648
  if (!isSetValue(set)) throw new TlaEvaluationError(describeNonSetMembership(element, set));
1604
1649
  switch (set.kind) {
@@ -1607,10 +1652,10 @@ export const isElementOf = (element: Value, set: Value): boolean => {
1607
1652
  return findIndex(set.elements, element) !== -1;
1608
1653
  } catch (error) {
1609
1654
  if (!(error instanceof TlaEvaluationError)) throw error;
1610
- return isElementOfLikeTlc(element, set.elements);
1655
+ return withSource(set, () => isElementOfLikeTlc(element, set.elements));
1611
1656
  }
1612
1657
  case "MixedSet":
1613
- return isElementOfLikeTlc(element, set.elements);
1658
+ return withSource(set, () => isElementOfLikeTlc(element, set.elements));
1614
1659
  case "Interval":
1615
1660
  if (typeof element === "number") return element >= set.low && element <= set.high;
1616
1661
  if (set.low <= set.high && !isModelValue(element)) {
@@ -1632,12 +1677,18 @@ export const isElementOf = (element: Value, set: Value): boolean => {
1632
1677
  return set.name !== "Nat" || (typeof element === "number" && element >= 0);
1633
1678
  }
1634
1679
  case "Subset":
1635
- if (!isSetValue(element)) throw new TlaEvaluationError(describeMembership(element, set));
1636
- return toFiniteSet(element).elements.every((item) => isElementOf(item, set.base));
1680
+ if (!isTlcEnumerable(element)) {
1681
+ throw new TlaEvaluationError(
1682
+ `Attempted to check if the non-enumerable value\n${prettyPrint(formatValue(element))}\nis element of\n${prettyPrint(formatValue(set))}`,
1683
+ );
1684
+ }
1685
+ return toFiniteSet(element).elements.every((item) => isElementOfSet(item, set.base));
1637
1686
  case "FunctionSet": {
1638
1687
  if (!isFunctionValue(element)) {
1639
1688
  if (isModelValue(element)) return false;
1640
- throw new TlaEvaluationError(describeMembership(element, set));
1689
+ throw new TlaEvaluationError(
1690
+ `Attempted to check if \n${formatValue(element)}\nwhich is not a TLC function value, is in the set of functions:\n${prettyPrint(formatValue(set))}`,
1691
+ );
1641
1692
  }
1642
1693
  const functionValue = toFiniteFunction(element);
1643
1694
  const low = getIntervalLow(functionValue.domain);
@@ -1648,7 +1699,7 @@ export const isElementOf = (element: Value, set: Value): boolean => {
1648
1699
  { kind: "Interval", low, high: low + functionValue.domain.length - 1 },
1649
1700
  set.domain,
1650
1701
  );
1651
- return isDomain && functionValue.range.every((item) => isElementOf(item, set.range));
1702
+ return isDomain && functionValue.range.every((item) => isElementOfSet(item, set.range));
1652
1703
  }
1653
1704
  case "RecordSet": {
1654
1705
  const functionValue = isFunctionValue(element) ? toFiniteFunction(element) : undefined;
@@ -1662,7 +1713,7 @@ export const isElementOf = (element: Value, set: Value): boolean => {
1662
1713
  functionValue.domain.length === set.names.length &&
1663
1714
  set.names.every((name, index) => {
1664
1715
  const position = findIndex(functionValue.domain, name);
1665
- return position !== -1 && isElementOf(functionValue.range[position], set.sets[index]);
1716
+ return position !== -1 && isElementOfSet(functionValue.range[position], set.sets[index]);
1666
1717
  })
1667
1718
  );
1668
1719
  }
@@ -1679,24 +1730,24 @@ export const isElementOf = (element: Value, set: Value): boolean => {
1679
1730
  }
1680
1731
  return (
1681
1732
  elements.length === set.factors.length &&
1682
- elements.every((item, index) => isElementOf(item, set.factors[index]))
1733
+ elements.every((item, index) => isElementOfSet(item, set.factors[index]))
1683
1734
  );
1684
1735
  }
1685
1736
  case "FilteredSet":
1686
- return isElementOf(element, set.base) && set.test(element);
1737
+ return isElementOfSet(element, set.base) && set.test(element);
1687
1738
  case "Union":
1688
1739
  if (!isTlcEnumerable(set.base)) {
1689
1740
  throw new TlaEvaluationError(
1690
1741
  `Attempted to check if:\n ${formatValue(element)}\nis an element of the non-enumerable set:\n ${formatUnion(set)}`,
1691
1742
  );
1692
1743
  }
1693
- return toFiniteSet(set.base).elements.some((inner) => isElementOf(element, inner));
1744
+ return toFiniteSet(set.base).elements.some((inner) => isElementOfSet(element, inner));
1694
1745
  case "SetOperation":
1695
1746
  if (set.operator === "\\cup")
1696
- return isElementOf(element, set.left) || isElementOf(element, set.right);
1747
+ return isElementOfSet(element, set.left) || isElementOfSet(element, set.right);
1697
1748
  return (
1698
- isElementOf(element, set.left) &&
1699
- isElementOf(element, set.right) === (set.operator === "\\cap")
1749
+ isElementOfSet(element, set.left) &&
1750
+ isElementOfSet(element, set.right) === (set.operator === "\\cap")
1700
1751
  );
1701
1752
  case "SequenceSet": {
1702
1753
  const elements = getSequenceElements(element);
@@ -1752,10 +1803,61 @@ export const markLambdaFunction = <FunctionLike extends FunctionValue | LazyFunc
1752
1803
  return functionValue;
1753
1804
  };
1754
1805
 
1755
- const describeMissingArgument = (functionValue: Value, argument: Value) =>
1756
- typeof functionValue === "object" && lambdaFunctions.has(functionValue)
1757
- ? `In applying the function\n${prettyPrint(formatValue(functionValue))},\nthe first argument is:\n${prettyPrint(formatValue(argument))}\nwhich is not in its domain.\n`
1758
- : `Attempted to apply function ${formatValue(functionValue)} to ${formatValue(argument)}, which is not in its domain`;
1806
+ // TLC applies a tuple, a record and a function over an interval with their own classes, and each
1807
+ // reports a missing argument in its own words.
1808
+ const getFunctionClass = (functionValue: FunctionValue) => {
1809
+ const domain = functionValue.domain;
1810
+ if (domain.length === 0) return lambdaFunctions.has(functionValue) ? "FcnRcdValue" : "TupleValue";
1811
+ if (domain === intervalDomains[domain.length]) return "TupleValue";
1812
+ if (intervalArrays.has(domain)) return "IntervalFcnRcdValue";
1813
+ return domain.every((key) => typeof key === "string") ? "RecordValue" : "FcnRcdValue";
1814
+ };
1815
+
1816
+ const describeNotInDomain = (functionValue: FunctionValue, argument: Value) =>
1817
+ `Attempted to apply function:\n${prettyPrint(formatValue(functionValue))}\nto argument ${prettyPrint(formatValue(argument))}, which is not in the domain of the function.`;
1818
+
1819
+ const describeNonIntegerArgument = (argument: Value) =>
1820
+ `Attempted to apply function with integer domain to the non-integer argument ${prettyPrint(formatValue(argument))}`;
1821
+
1822
+ const describeMissingArgument = (
1823
+ functionValue: FunctionValue | LazyFunctionValue,
1824
+ argument: Value,
1825
+ ) => {
1826
+ if (lambdaFunctions.has(functionValue) || functionValue.kind === "LazyFunction")
1827
+ return `In applying the function\n${prettyPrint(formatValue(functionValue))},\nthe first argument is:\n${prettyPrint(formatValue(argument))}\nwhich is not in its domain.\n`;
1828
+ const functionClass = getFunctionClass(functionValue);
1829
+ if (functionClass === "TupleValue")
1830
+ return typeof argument === "number"
1831
+ ? `Attempted to access index ${argument} of tuple\n${prettyPrint(formatValue(functionValue))}\nwhich is out of bounds.`
1832
+ : `Attempted to access tuple at a non integral index: ${prettyPrint(formatValue(argument))}`;
1833
+ if (functionClass === "RecordValue")
1834
+ return typeof argument === "string"
1835
+ ? `Attempted to access nonexistent field '${argument}' of record\n${prettyPrint(formatValue(functionValue))}`
1836
+ : `Attempted to access record by a non-string argument: ${prettyPrint(formatValue(argument))}`;
1837
+ return functionClass === "IntervalFcnRcdValue" && typeof argument !== "number"
1838
+ ? describeNonIntegerArgument(argument)
1839
+ : describeNotInDomain(functionValue, argument);
1840
+ };
1841
+
1842
+ // TLC selects a field of a value that isn't a record from the function the value converts to,
1843
+ // which keeps a tuple's domain as an interval.
1844
+ export const describeMissingField = (functionValue: FunctionValue, field: string) =>
1845
+ getFunctionClass(functionValue) === "FcnRcdValue"
1846
+ ? describeNotInDomain(functionValue, field)
1847
+ : describeNonIntegerArgument(field);
1848
+
1849
+ export const isRecordValue = (functionValue: FunctionValue) =>
1850
+ getFunctionClass(functionValue) === "RecordValue";
1851
+
1852
+ // TLC checks the type of an argument to a tuple or a record before it looks the argument up, so
1853
+ // it never compares the argument with a key of another type.
1854
+ const isForeignKey = (domain: Value[], argument: Value) => {
1855
+ const first = domain[0];
1856
+ return typeof first === "number"
1857
+ ? typeof argument !== "number" &&
1858
+ (domain === intervalDomains[domain.length] || intervalArrays.has(domain))
1859
+ : typeof first === "string" && typeof argument !== "string";
1860
+ };
1759
1861
 
1760
1862
  const findKeyIndex = (domain: Value[], argument: Value) => {
1761
1863
  const first = domain[0];
@@ -1774,6 +1876,7 @@ export const applyFunction = (
1774
1876
  functionValue: Value,
1775
1877
  argument: Value,
1776
1878
  describeMissing?: (functionValue: FunctionValue) => string,
1879
+ describeNonFunction?: (value: Value) => string,
1777
1880
  ): Value => {
1778
1881
  if (typeof functionValue === "object" && functionValue.kind === "LazyFunction") {
1779
1882
  if (!isElementOf(argument, functionValue.domain)) {
@@ -1787,10 +1890,13 @@ export const applyFunction = (
1787
1890
  }
1788
1891
  if (typeof functionValue !== "object" || functionValue.kind !== "Function") {
1789
1892
  throw new TlaEvaluationError(
1790
- `Attempted to apply ${formatValue(functionValue)}, which is not a function`,
1893
+ describeNonFunction?.(functionValue) ??
1894
+ `Attempted to apply ${formatValue(functionValue)}, which is not a function`,
1791
1895
  );
1792
1896
  }
1793
- const position = findKeyIndex(functionValue.domain, argument);
1897
+ const position = isForeignKey(functionValue.domain, argument)
1898
+ ? -1
1899
+ : findKeyIndex(functionValue.domain, argument);
1794
1900
  if (position === -1) {
1795
1901
  throw new TlaEvaluationError(
1796
1902
  describeMissing?.(functionValue) ?? describeMissingArgument(functionValue, argument),
@@ -1888,10 +1994,15 @@ const getElementContribution = (element: Value) =>
1888
1994
  const getEntryContribution = (key: Value, value: Value) =>
1889
1995
  finalizeHash((Math.imul(getValueHash(key), 0x27d4eb2d) + getValueHash(value)) | 0);
1890
1996
 
1997
+ const unenumeratedSets = { isHashed: false };
1998
+
1891
1999
  const computeValueHash = (value: ObjectValue) => {
1892
2000
  if (value.kind === "ModelValue") return finalizeHash(combineHash(hashString(value.name), 0x6d));
1893
2001
  if (isSetValue(value)) {
1894
- if (!isEnumerable(value)) return hashString(getValueKey(value));
2002
+ if (!isEnumerable(value)) {
2003
+ unenumeratedSets.isHashed = true;
2004
+ return hashString(getValueKey(value));
2005
+ }
1895
2006
  const elements = toFiniteSet(value).elements;
1896
2007
  let hash = SET_HASH_SEED;
1897
2008
  for (let index = 0; index < elements.length; index++) {
@@ -1923,6 +2034,25 @@ export const getValueHash = (value: Value): number => {
1923
2034
  return hash;
1924
2035
  };
1925
2036
 
2037
+ const fingerprintLikeTlc = (value: Value): void => {
2038
+ if (typeof value !== "object" || value.kind === "ModelValue") return;
2039
+ if (isOverriddenSet(value)) {
2040
+ throw new TlaEvaluationError(
2041
+ `TLC has found a state in which the value of a variable contains ${formatValue(value)}`,
2042
+ );
2043
+ }
2044
+ if (isSetValue(value)) return toFiniteSet(value).elements.forEach(fingerprintLikeTlc);
2045
+ const functionValue = toFiniteFunction(value);
2046
+ functionValue.domain.forEach(fingerprintLikeTlc);
2047
+ functionValue.range.forEach(fingerprintLikeTlc);
2048
+ };
2049
+
2050
+ // TLC enumerates every set in a state to fingerprint it, so it fails on a set it can't enumerate.
2051
+ // A state holds one only if hashing it met one, so states go unchecked until then.
2052
+ export const assertFingerprintable = (state: Value[]) => {
2053
+ if (unenumeratedSets.isHashed) state.forEach(fingerprintLikeTlc);
2054
+ };
2055
+
1926
2056
  const valueFingerprints = new WeakMap<ObjectValue, number>();
1927
2057
 
1928
2058
  const finalizeFingerprint = (hash: number) => {
@@ -1949,7 +2079,10 @@ const getEntryFingerprint = (key: Value, value: Value) =>
1949
2079
  const computeValueFingerprint = (value: ObjectValue) => {
1950
2080
  if (value.kind === "ModelValue") return finalizeFingerprint(fingerprintString(value.name) ^ 0x3c);
1951
2081
  if (isSetValue(value)) {
1952
- if (!isEnumerable(value)) return fingerprintString(getValueKey(value));
2082
+ if (!isEnumerable(value)) {
2083
+ unenumeratedSets.isHashed = true;
2084
+ return fingerprintString(getValueKey(value));
2085
+ }
1953
2086
  const elements = toFiniteSet(value).elements;
1954
2087
  let fingerprint = 0x1b873593;
1955
2088
  for (let index = 0; index < elements.length; index++) {