tla-ts 0.0.3-dev.3c70a97 → 0.0.3-dev.3ff2308

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 (48) hide show
  1. package/README.md +5 -1
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +53 -22
  4. package/dist/index.d.ts +53 -22
  5. package/dist/index.js +1 -1
  6. package/dist/parallel-worker.cjs +1 -1
  7. package/dist/parallel-worker.js +2 -2
  8. package/dist/parallel.cjs +1 -1
  9. package/dist/parallel.js +2 -2
  10. package/dist/run-cli.cjs +19 -17
  11. package/dist/run-cli.js +20 -18
  12. package/dist/transfer.cjs +34 -17
  13. package/dist/transfer.js +34 -17
  14. package/package.json +1 -1
  15. package/src/ast.ts +3 -0
  16. package/src/builtins.ts +9 -3
  17. package/src/check.ts +452 -93
  18. package/src/cli-options.ts +11 -5
  19. package/src/codegen.ts +6 -3
  20. package/src/config.ts +224 -170
  21. package/src/environment.ts +111 -19
  22. package/src/errors.ts +78 -1
  23. package/src/evaluate.ts +182 -26
  24. package/src/exit-codes.ts +22 -3
  25. package/src/instances.ts +4 -4
  26. package/src/levels.ts +55 -27
  27. package/src/live-check.ts +132 -70
  28. package/src/liveness.ts +117 -22
  29. package/src/parallel-worker.ts +2 -2
  30. package/src/parallel.ts +5 -2
  31. package/src/parser.ts +21 -10
  32. package/src/resolve.ts +106 -29
  33. package/src/run-cli.ts +103 -18
  34. package/src/runtime.ts +2 -0
  35. package/src/spec-description.ts +12 -6
  36. package/src/standard-modules.ts +52 -43
  37. package/src/state-graph.ts +157 -0
  38. package/src/successors.ts +169 -33
  39. package/src/symmetry.ts +16 -6
  40. package/src/tableau.ts +51 -24
  41. package/src/tlc-ext.ts +27 -2
  42. package/src/tlc-module.ts +14 -33
  43. package/src/tlc-modules.ts +4 -0
  44. package/src/tlc-order.ts +8 -4
  45. package/src/tlc-random.ts +9 -6
  46. package/src/tlc-summary.ts +20 -5
  47. package/src/value-sources.ts +29 -0
  48. package/src/values.ts +207 -53
package/src/tlc-order.ts CHANGED
@@ -278,9 +278,13 @@ const createModuleSet = (source: string, loadModule: ModuleLoader) => {
278
278
  (name === undefined ? undefined : nestedModules.get(name)) ?? getFile(name);
279
279
  };
280
280
 
281
- // The variables in the order TLC compares them: the reverse of the root module's context
282
- // enumeration, as ModuleNode.getVariableDecls returns them.
283
- export const getTlcVariableOrder = (source: string, loadModule: ModuleLoader): string[] => {
281
+ // The constants or variables in the order of ModuleNode.getConstantDecls or getVariableDecls: the
282
+ // reverse of the root module's context enumeration. TLC compares a state's variables in this order.
283
+ export const getTlcDeclarationOrder = (
284
+ source: string,
285
+ loadModule: ModuleLoader,
286
+ kind: "constant" | "variable",
287
+ ): string[] => {
284
288
  const getParsed = createModuleSet(source, loadModule);
285
289
  const getUnits = (unit: ParsedModule) => {
286
290
  const tokens = unit.tokens;
@@ -400,7 +404,7 @@ export const getTlcVariableOrder = (source: string, loadModule: ModuleLoader): s
400
404
  };
401
405
  return getContext(undefined)
402
406
  .enumerate()
403
- .filter((entry) => entry.kind === "variable")
407
+ .filter((entry) => entry.kind === kind)
404
408
  .map((entry) => entry.name)
405
409
  .reverse();
406
410
  };
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";
@@ -137,6 +138,13 @@ export const isSetValue = (value: Value) =>
137
138
  value.kind !== "Function" &&
138
139
  value.kind !== "LazyFunction";
139
140
 
141
+ export type ReducibleSet = SetValue | MixedSetValue | IntervalValue;
142
+
143
+ // TLC reduces a set enumeration or an interval eagerly, and keeps every other set lazy.
144
+ export const isReducible = (value: Value): value is ReducibleSet =>
145
+ typeof value === "object" &&
146
+ (value.kind === "Set" || value.kind === "MixedSet" || value.kind === "Interval");
147
+
140
148
  export const isFunctionValue = (value: Value): value is FunctionValue | LazyFunctionValue =>
141
149
  typeof value === "object" && (value.kind === "Function" || value.kind === "LazyFunction");
142
150
 
@@ -371,7 +379,7 @@ export const compareValues = (left: Value, right: Value): number => {
371
379
  `Attempted to compare ${describeKind(left)} ${formatValue(left)} with ${describeKind(right)} ${formatValue(right)}`,
372
380
  );
373
381
  }
374
- if (isLeftSet) return compareSets(toFiniteSet(left), toFiniteSet(right));
382
+ if (isLeftSet) return compareSets(toFiniteSet(left), toComparedSet(right));
375
383
  return compareFunctions(toFiniteFunction(left), toFiniteFunction(right));
376
384
  }
377
385
  if (typeof left === "number" && typeof right === "number") return left - right;
@@ -726,16 +734,17 @@ const compareSetLikeTlc = (left: ObjectValue, right: Value): number => {
726
734
  );
727
735
  };
728
736
 
729
- const compareLikeTlc = (left: Value, right: Value): number => {
730
- if (typeof left !== "object") {
731
- if (typeof right === typeof left) return compareValues(left, right);
732
- if (isModelValue(right)) return compareModelValueWith(right, left);
733
- throw new TlaEvaluationError(describeScalarMismatch(left, right, false));
734
- }
735
- if (left.kind === "ModelValue") return compareModelValue(left, right);
736
- if (isFunctionValue(left)) return compareFunctionLikeTlc(left, right);
737
- return compareSetLikeTlc(left, right);
738
- };
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
+ });
739
748
 
740
749
  const equalsElementsLikeTlc = (left: Value[], right: Value[]) =>
741
750
  left.every((element, index) => equalsLikeTlc(element, right[index]));
@@ -823,16 +832,17 @@ const equalsSetLikeTlc = (left: ObjectValue, right: Value): boolean => {
823
832
  );
824
833
  };
825
834
 
826
- const equalsLikeTlc = (left: Value, right: Value): boolean => {
827
- if (typeof left !== "object") {
828
- if (typeof right === typeof left) return left === right;
829
- if (isModelValue(right)) return equalsModelValueWith(right, left);
830
- throw new TlaEvaluationError(describeScalarMismatch(left, right, true));
831
- }
832
- if (left.kind === "ModelValue") return equalsModelValue(left, right);
833
- if (isFunctionValue(left)) return equalsFunctionLikeTlc(left, right);
834
- return equalsSetLikeTlc(left, right);
835
- };
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
+ });
836
846
 
837
847
  // TLC's ValueVec.sort, which inserts each element into the sorted prefix by binary search.
838
848
  const sortLikeTlc = (elements: Value[]) => {
@@ -864,9 +874,11 @@ export const isEqualLikeTlc = (left: Value, right: Value) => {
864
874
  }
865
875
  };
866
876
 
877
+ // TLC sorts a set by comparing each element with the ones before it, so the later element converts
878
+ // a lazy set it compares and caches it.
867
879
  const isStrictlySorted = (elements: Value[]) => {
868
880
  for (let index = 1; index < elements.length; index++) {
869
- if (compareValues(elements[index - 1], elements[index]) >= 0) return false;
881
+ if (compareValues(elements[index], elements[index - 1]) <= 0) return false;
870
882
  }
871
883
  return true;
872
884
  };
@@ -1069,13 +1081,16 @@ const isTlcEnumerable = (value: Value) => isSetValue(value) && !isOverriddenSet(
1069
1081
  const formatUnion = (value: UnionValue, isStrict = false) =>
1070
1082
  `UNION(${formatValue(value.base, isStrict)})`;
1071
1083
 
1072
- const getUnionSets = (value: UnionValue) => {
1084
+ const getUnionSets = (
1085
+ value: UnionValue,
1086
+ getElements = (set: Value) => toFiniteSet(set).elements,
1087
+ ) => {
1073
1088
  if (!isTlcEnumerable(value.base)) {
1074
1089
  throw new TlaEvaluationError(
1075
1090
  `Attempted to enumerate the nonenumerable set:\n${formatUnion(value)}`,
1076
1091
  );
1077
1092
  }
1078
- return toFiniteSet(value.base).elements;
1093
+ return getElements(value.base);
1079
1094
  };
1080
1095
 
1081
1096
  const getUnionSet = (set: Value, index: number, union: UnionValue) => {
@@ -1111,7 +1126,7 @@ export const isEnumerable = (value: Value): boolean => {
1111
1126
  case "ProductSet":
1112
1127
  return value.factors.every(isEnumerable) || getEmptiness(value) === true;
1113
1128
  case "Union":
1114
- return isEnumerable(value.base) && toFiniteSet(value.base).elements.every(isEnumerable);
1129
+ return isEnumerable(value.base) && getStreamedElements(value.base).every(isEnumerable);
1115
1130
  case "SetOperation":
1116
1131
  if (value.operator === "\\cup") return isEnumerable(value.left) && isEnumerable(value.right);
1117
1132
  if (value.operator === "\\cap") return isEnumerable(value.left) || isEnumerable(value.right);
@@ -1184,6 +1199,41 @@ const advanceCombination = (indices: number[], length: number) => {
1184
1199
  return false;
1185
1200
  };
1186
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
+
1187
1237
  const getSortedSubsets = (base: Value[]) => {
1188
1238
  const subsets: Value[] = [];
1189
1239
  for (let size = 0; size <= base.length; size++) {
@@ -1212,9 +1262,7 @@ const enumerateSet = (value: Value): Value[] => {
1212
1262
  if (isOverriddenSet(value.base)) getCardinality(value.base);
1213
1263
  const base = toFiniteSet(value.base).elements;
1214
1264
  if (base.length > MAXIMUM_ENUMERATED_SUBSET_BASE) {
1215
- throw new TlaEvaluationError(
1216
- `SUBSET of a set with ${base.length} elements is too large to enumerate`,
1217
- );
1265
+ throw new TlaEvaluationError(describeOverflow(value));
1218
1266
  }
1219
1267
  return getSortedSubsets(base);
1220
1268
  }
@@ -1318,6 +1366,7 @@ const enumerateSet = (value: Value): Value[] => {
1318
1366
  };
1319
1367
 
1320
1368
  const finiteSets = new WeakMap<ObjectValue, SetValue>();
1369
+ const comparedSets = new WeakMap<ObjectValue, SetValue>();
1321
1370
 
1322
1371
  export const toFiniteSet = (value: Value): SetValue => {
1323
1372
  if (typeof value === "object" && value.kind === "Set") return value;
@@ -1326,6 +1375,16 @@ export const toFiniteSet = (value: Value): SetValue => {
1326
1375
  }
1327
1376
  const cached = typeof value === "object" ? finiteSets.get(value) : undefined;
1328
1377
  if (cached) return cached;
1378
+ const set =
1379
+ (typeof value === "object" ? comparedSets.get(value) : undefined) ??
1380
+ (valueSources.current
1381
+ ? withSource(value, () => enumerateFiniteSet(value))
1382
+ : enumerateFiniteSet(value));
1383
+ if (typeof value === "object") finiteSets.set(value, set);
1384
+ return set;
1385
+ };
1386
+
1387
+ const enumerateFiniteSet = (value: Value) => {
1329
1388
  const elements = enumerateSet(value);
1330
1389
  const isSorted =
1331
1390
  typeof value === "object" &&
@@ -1336,8 +1395,20 @@ export const toFiniteSet = (value: Value): SetValue => {
1336
1395
  value.kind === "ProductSet" ||
1337
1396
  value.kind === "FunctionSet" ||
1338
1397
  value.kind === "Subset");
1339
- const set = isSorted ? createSortedSet(elements) : createSet(elements);
1340
- if (typeof value === "object") finiteSets.set(value, set);
1398
+ return isSorted ? createSortedSet(elements) : createSet(elements);
1399
+ };
1400
+
1401
+ // TLC converts the set a comparison receives as its argument without caching it, so a lazy set
1402
+ // compared that way still streams the sets it combines.
1403
+ const toComparedSet = (value: Value) => {
1404
+ const isStreamed =
1405
+ typeof value === "object" &&
1406
+ (value.kind === "Union" || value.kind === "SetOperation" || value.kind === "FilteredSet");
1407
+ if (!isStreamed || finiteSets.has(value)) return toFiniteSet(value);
1408
+ const compared = comparedSets.get(value);
1409
+ if (compared) return compared;
1410
+ const set = enumerateFiniteSet(value);
1411
+ comparedSets.set(value, set);
1341
1412
  return set;
1342
1413
  };
1343
1414
 
@@ -1345,8 +1416,10 @@ export const toFiniteSet = (value: Value): SetValue => {
1345
1416
  // so an element that two of them share comes up once for each.
1346
1417
  export const getStreamedElements = (value: Value): Value[] => {
1347
1418
  if (typeof value !== "object" || finiteSets.has(value)) return toFiniteSet(value).elements;
1419
+ // TLC streams the sets of a UNION it hasn't enumerated, so a set that appears twice there yields
1420
+ // its elements twice.
1348
1421
  if (value.kind === "Union") {
1349
- return getUnionSets(value).flatMap((set, index) =>
1422
+ return getUnionSets(value, getStreamedElements).flatMap((set, index) =>
1350
1423
  getStreamedElements(getUnionSet(set, index, value)),
1351
1424
  );
1352
1425
  }
@@ -1565,6 +1638,12 @@ const describeNonSetMembership = (element: Value, value: Value) => {
1565
1638
  return `${prefix} function ${formatValue(value)}`;
1566
1639
  };
1567
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
+
1568
1647
  export const isElementOf = (element: Value, set: Value): boolean => {
1569
1648
  if (!isSetValue(set)) throw new TlaEvaluationError(describeNonSetMembership(element, set));
1570
1649
  switch (set.kind) {
@@ -1573,10 +1652,10 @@ export const isElementOf = (element: Value, set: Value): boolean => {
1573
1652
  return findIndex(set.elements, element) !== -1;
1574
1653
  } catch (error) {
1575
1654
  if (!(error instanceof TlaEvaluationError)) throw error;
1576
- return isElementOfLikeTlc(element, set.elements);
1655
+ return withSource(set, () => isElementOfLikeTlc(element, set.elements));
1577
1656
  }
1578
1657
  case "MixedSet":
1579
- return isElementOfLikeTlc(element, set.elements);
1658
+ return withSource(set, () => isElementOfLikeTlc(element, set.elements));
1580
1659
  case "Interval":
1581
1660
  if (typeof element === "number") return element >= set.low && element <= set.high;
1582
1661
  if (set.low <= set.high && !isModelValue(element)) {
@@ -1598,12 +1677,18 @@ export const isElementOf = (element: Value, set: Value): boolean => {
1598
1677
  return set.name !== "Nat" || (typeof element === "number" && element >= 0);
1599
1678
  }
1600
1679
  case "Subset":
1601
- if (!isSetValue(element)) throw new TlaEvaluationError(describeMembership(element, set));
1602
- 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));
1603
1686
  case "FunctionSet": {
1604
1687
  if (!isFunctionValue(element)) {
1605
1688
  if (isModelValue(element)) return false;
1606
- 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
+ );
1607
1692
  }
1608
1693
  const functionValue = toFiniteFunction(element);
1609
1694
  const low = getIntervalLow(functionValue.domain);
@@ -1614,7 +1699,7 @@ export const isElementOf = (element: Value, set: Value): boolean => {
1614
1699
  { kind: "Interval", low, high: low + functionValue.domain.length - 1 },
1615
1700
  set.domain,
1616
1701
  );
1617
- return isDomain && functionValue.range.every((item) => isElementOf(item, set.range));
1702
+ return isDomain && functionValue.range.every((item) => isElementOfSet(item, set.range));
1618
1703
  }
1619
1704
  case "RecordSet": {
1620
1705
  const functionValue = isFunctionValue(element) ? toFiniteFunction(element) : undefined;
@@ -1628,7 +1713,7 @@ export const isElementOf = (element: Value, set: Value): boolean => {
1628
1713
  functionValue.domain.length === set.names.length &&
1629
1714
  set.names.every((name, index) => {
1630
1715
  const position = findIndex(functionValue.domain, name);
1631
- return position !== -1 && isElementOf(functionValue.range[position], set.sets[index]);
1716
+ return position !== -1 && isElementOfSet(functionValue.range[position], set.sets[index]);
1632
1717
  })
1633
1718
  );
1634
1719
  }
@@ -1645,24 +1730,24 @@ export const isElementOf = (element: Value, set: Value): boolean => {
1645
1730
  }
1646
1731
  return (
1647
1732
  elements.length === set.factors.length &&
1648
- elements.every((item, index) => isElementOf(item, set.factors[index]))
1733
+ elements.every((item, index) => isElementOfSet(item, set.factors[index]))
1649
1734
  );
1650
1735
  }
1651
1736
  case "FilteredSet":
1652
- return isElementOf(element, set.base) && set.test(element);
1737
+ return isElementOfSet(element, set.base) && set.test(element);
1653
1738
  case "Union":
1654
1739
  if (!isTlcEnumerable(set.base)) {
1655
1740
  throw new TlaEvaluationError(
1656
1741
  `Attempted to check if:\n ${formatValue(element)}\nis an element of the non-enumerable set:\n ${formatUnion(set)}`,
1657
1742
  );
1658
1743
  }
1659
- return toFiniteSet(set.base).elements.some((inner) => isElementOf(element, inner));
1744
+ return toFiniteSet(set.base).elements.some((inner) => isElementOfSet(element, inner));
1660
1745
  case "SetOperation":
1661
1746
  if (set.operator === "\\cup")
1662
- return isElementOf(element, set.left) || isElementOf(element, set.right);
1747
+ return isElementOfSet(element, set.left) || isElementOfSet(element, set.right);
1663
1748
  return (
1664
- isElementOf(element, set.left) &&
1665
- isElementOf(element, set.right) === (set.operator === "\\cap")
1749
+ isElementOfSet(element, set.left) &&
1750
+ isElementOfSet(element, set.right) === (set.operator === "\\cap")
1666
1751
  );
1667
1752
  case "SequenceSet": {
1668
1753
  const elements = getSequenceElements(element);
@@ -1718,10 +1803,61 @@ export const markLambdaFunction = <FunctionLike extends FunctionValue | LazyFunc
1718
1803
  return functionValue;
1719
1804
  };
1720
1805
 
1721
- const describeMissingArgument = (functionValue: Value, argument: Value) =>
1722
- typeof functionValue === "object" && lambdaFunctions.has(functionValue)
1723
- ? `In applying the function\n${prettyPrint(formatValue(functionValue))},\nthe first argument is:\n${prettyPrint(formatValue(argument))}\nwhich is not in its domain.\n`
1724
- : `Attempted to apply function ${formatValue(functionValue)} to ${formatValue(argument)}, which is not in its domain`;
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
+ };
1725
1861
 
1726
1862
  const findKeyIndex = (domain: Value[], argument: Value) => {
1727
1863
  const first = domain[0];
@@ -1740,6 +1876,7 @@ export const applyFunction = (
1740
1876
  functionValue: Value,
1741
1877
  argument: Value,
1742
1878
  describeMissing?: (functionValue: FunctionValue) => string,
1879
+ describeNonFunction?: (value: Value) => string,
1743
1880
  ): Value => {
1744
1881
  if (typeof functionValue === "object" && functionValue.kind === "LazyFunction") {
1745
1882
  if (!isElementOf(argument, functionValue.domain)) {
@@ -1753,10 +1890,13 @@ export const applyFunction = (
1753
1890
  }
1754
1891
  if (typeof functionValue !== "object" || functionValue.kind !== "Function") {
1755
1892
  throw new TlaEvaluationError(
1756
- `Attempted to apply ${formatValue(functionValue)}, which is not a function`,
1893
+ describeNonFunction?.(functionValue) ??
1894
+ `Attempted to apply ${formatValue(functionValue)}, which is not a function`,
1757
1895
  );
1758
1896
  }
1759
- const position = findKeyIndex(functionValue.domain, argument);
1897
+ const position = isForeignKey(functionValue.domain, argument)
1898
+ ? -1
1899
+ : findKeyIndex(functionValue.domain, argument);
1760
1900
  if (position === -1) {
1761
1901
  throw new TlaEvaluationError(
1762
1902
  describeMissing?.(functionValue) ?? describeMissingArgument(functionValue, argument),
@@ -2101,8 +2241,11 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
2101
2241
  return `[${parameters} |-> <expression ${source.body}>]`;
2102
2242
  }
2103
2243
  const functionValue = toFiniteFunction(value);
2244
+ // TLC normalizes a lambda's domain to print it, but evaluates its body afterward.
2245
+ const formatRange = (inner: Value) =>
2246
+ formatValue(inner, isStrict, isNormalized && value.kind === "Function");
2104
2247
  if (functionValue.domain.every((key, index) => key === index + 1)) {
2105
- return `<<${functionValue.range.map(format).join(", ")}>>`;
2248
+ return `<<${functionValue.range.map(formatRange).join(", ")}>>`;
2106
2249
  }
2107
2250
  if (functionValue.domain.every((key) => typeof key === "string" && isFieldName(key))) {
2108
2251
  const isSorted =
@@ -2110,9 +2253,20 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
2110
2253
  const pairs = isSorted
2111
2254
  ? functionValue.domain.map((key, index) => [key, functionValue.range[index]])
2112
2255
  : getWrittenPairs(functionValue);
2113
- return `[${pairs.map((pair) => `${String(pair[0])} |-> ${format(pair[1])}`).join(", ")}]`;
2256
+ return `[${pairs.map((pair) => `${String(pair[0])} |-> ${formatRange(pair[1])}`).join(", ")}]`;
2114
2257
  }
2115
- return `(${functionValue.domain.map((key, index) => `${format(key)} :> ${format(functionValue.range[index])}`).join(" @@ ")})`;
2258
+ return `(${functionValue.domain.map((key, index) => `${format(key)} :> ${formatRange(functionValue.range[index])}`).join(" @@ ")})`;
2116
2259
  }
2117
2260
  }
2118
2261
  };
2262
+
2263
+ // TLC's TLCState.toString: a line per variable, as a conjunction when there are several.
2264
+ export const formatState = (state: Record<string, Value>) => {
2265
+ const entries = Object.entries(state);
2266
+ return entries
2267
+ .map(
2268
+ ([name, value]) =>
2269
+ `${entries.length === 1 ? "" : "/\\ "}${name} = ${prettyPrint(formatValue(value))}\n`,
2270
+ )
2271
+ .join("");
2272
+ };