tla-ts 0.0.2 → 0.0.3-dev.07eab97

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/README.md +78 -12
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +98 -15
  4. package/dist/index.d.ts +98 -15
  5. package/dist/index.js +1 -1
  6. package/dist/parallel-worker.cjs +2 -2
  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 +23 -2
  11. package/dist/run-cli.js +23 -2
  12. package/dist/transfer.cjs +36 -16
  13. package/dist/transfer.js +36 -16
  14. package/package.json +3 -1
  15. package/src/ast.ts +139 -4
  16. package/src/builtins.ts +9 -3
  17. package/src/check.ts +555 -107
  18. package/src/cli-options.ts +64 -0
  19. package/src/codegen.ts +15 -22
  20. package/src/config.ts +224 -170
  21. package/src/dependencies.ts +2 -2
  22. package/src/environment.ts +156 -48
  23. package/src/errors.ts +123 -3
  24. package/src/evaluate.ts +258 -160
  25. package/src/exit-codes.ts +39 -42
  26. package/src/fingerprints.ts +48 -12
  27. package/src/instances.ts +16 -15
  28. package/src/levels.ts +181 -45
  29. package/src/lexer.ts +11 -2
  30. package/src/live-check.ts +772 -0
  31. package/src/liveness.ts +120 -543
  32. package/src/obligation-action.ts +384 -0
  33. package/src/obligation-anon.ts +575 -0
  34. package/src/obligation-deref.ts +637 -0
  35. package/src/obligation-expression.ts +1060 -0
  36. package/src/obligation-format.ts +406 -0
  37. package/src/obligation-generate.ts +1074 -0
  38. package/src/obligation-levels.ts +329 -0
  39. package/src/obligation-module.ts +1042 -0
  40. package/src/obligation-printer.ts +889 -0
  41. package/src/obligation-proof.ts +76 -0
  42. package/src/obligation-source.ts +1084 -0
  43. package/src/obligation-tuples.ts +184 -0
  44. package/src/obligations.ts +316 -0
  45. package/src/parallel-worker.ts +168 -212
  46. package/src/parallel.ts +78 -37
  47. package/src/parser.ts +350 -63
  48. package/src/resolve.ts +124 -44
  49. package/src/run-cli.ts +405 -45
  50. package/src/runtime.ts +3 -1
  51. package/src/spec-description.ts +19 -8
  52. package/src/standard-levels.ts +3 -3
  53. package/src/standard-modules.ts +54 -45
  54. package/src/state-graph.ts +157 -0
  55. package/src/subexpressions.ts +10 -10
  56. package/src/substitution-levels.ts +38 -17
  57. package/src/successors.ts +183 -39
  58. package/src/symmetry.ts +30 -8
  59. package/src/tableau.ts +51 -24
  60. package/src/tlc-ext.ts +29 -12
  61. package/src/tlc-module.ts +14 -33
  62. package/src/tlc-modules.ts +4 -0
  63. package/src/tlc-order.ts +25 -7
  64. package/src/tlc-random.ts +9 -6
  65. package/src/tlc-summary.ts +20 -5
  66. package/src/transfer.ts +22 -1
  67. package/src/value-sources.ts +29 -0
  68. package/src/values.ts +300 -83
package/src/values.ts CHANGED
@@ -1,9 +1,12 @@
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";
6
7
  name: string;
8
+ type: string | undefined;
9
+ rank: number;
7
10
  }
8
11
 
9
12
  export interface SetValue {
@@ -135,6 +138,13 @@ export const isSetValue = (value: Value) =>
135
138
  value.kind !== "Function" &&
136
139
  value.kind !== "LazyFunction";
137
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
+
138
148
  export const isFunctionValue = (value: Value): value is FunctionValue | LazyFunctionValue =>
139
149
  typeof value === "object" && (value.kind === "Function" || value.kind === "LazyFunction");
140
150
 
@@ -233,8 +243,7 @@ const compareSets = (left: SetValue, right: SetValue) => {
233
243
  return 0;
234
244
  };
235
245
 
236
- const getModelValueType = (value: Value) =>
237
- isModelValue(value) && value.name.length > 2 && value.name[1] === "_" ? value.name[0] : undefined;
246
+ const getModelValueType = (value: Value) => (isModelValue(value) ? value.type : undefined);
238
247
 
239
248
  const checkModelValueTypes = (left: Value, right: Value, isEquality: boolean) => {
240
249
  const leftType = getModelValueType(left);
@@ -264,6 +273,7 @@ const stringOrder = { ranks: Object.create(null) as Record<string, number>, size
264
273
  export const setStringOrder = (texts: Iterable<string>) => {
265
274
  stringOrder.ranks = Object.create(null);
266
275
  stringOrder.size = 0;
276
+ modelValues.clear();
267
277
  for (const text of texts) rankString(text);
268
278
  };
269
279
 
@@ -349,11 +359,14 @@ export const compareValues = (left: Value, right: Value): number => {
349
359
  const otherSize = Math.max(0, right.high - right.low + 1);
350
360
  return size !== otherSize || size === 0 ? size - otherSize : left.low - right.low;
351
361
  }
362
+ if (leftKind === "ModelValue" && rightKind === "ModelValue") {
363
+ if (left.type !== undefined && right.type !== undefined) {
364
+ checkModelValueTypes(left, right, false);
365
+ }
366
+ return left.rank - right.rank;
367
+ }
352
368
  if (leftKind === "ModelValue" || rightKind === "ModelValue") {
353
369
  checkModelValueTypes(left, right, false);
354
- if (leftKind === "ModelValue" && rightKind === "ModelValue") {
355
- return compareStrings(left.name, right.name);
356
- }
357
370
  return leftKind === "ModelValue" ? -1 : 1;
358
371
  }
359
372
  if (left === ANY_SET || right === ANY_SET) return compareAny(left === ANY_SET ? right : left);
@@ -366,7 +379,7 @@ export const compareValues = (left: Value, right: Value): number => {
366
379
  `Attempted to compare ${describeKind(left)} ${formatValue(left)} with ${describeKind(right)} ${formatValue(right)}`,
367
380
  );
368
381
  }
369
- if (isLeftSet) return compareSets(toFiniteSet(left), toFiniteSet(right));
382
+ if (isLeftSet) return compareSets(toFiniteSet(left), toComparedSet(right));
370
383
  return compareFunctions(toFiniteFunction(left), toFiniteFunction(right));
371
384
  }
372
385
  if (typeof left === "number" && typeof right === "number") return left - right;
@@ -382,11 +395,16 @@ export const compareValues = (left: Value, right: Value): number => {
382
395
 
383
396
  const modelValues = new Map<string, ModelValue>();
384
397
 
398
+ // A check ranks every model value's name when it creates the value, and creates its own values.
385
399
  export const createModelValue = (name: string): ModelValue => {
386
- rankString(name);
387
400
  const known = modelValues.get(name);
388
401
  if (known) return known;
389
- const value: ModelValue = { kind: "ModelValue", name };
402
+ const value: ModelValue = {
403
+ kind: "ModelValue",
404
+ name,
405
+ type: name.length > 2 && name[1] === "_" ? name[0] : undefined,
406
+ rank: getStringRank(name),
407
+ };
390
408
  modelValues.set(name, value);
391
409
  return value;
392
410
  };
@@ -555,7 +573,7 @@ const equalsModelValueWith = (modelValue: ModelValue, other: Value) => {
555
573
 
556
574
  const compareModelValue = (left: ModelValue, right: Value) => {
557
575
  const type = getModelValueType(left);
558
- if (type === undefined) return isModelValue(right) ? compareStrings(left.name, right.name) : -1;
576
+ if (type === undefined) return isModelValue(right) ? left.rank - right.rank : -1;
559
577
  if (!isModelValue(right)) {
560
578
  throw new TlaEvaluationError(
561
579
  `Attempted to compare the typed model value ${formatValue(left)} and non-model value\n${formatValue(right)}`,
@@ -567,7 +585,7 @@ const compareModelValue = (left: ModelValue, right: Value) => {
567
585
  `Attempted to compare the differently-typed model values ${formatValue(left)} and ${formatValue(right)}`,
568
586
  );
569
587
  }
570
- return compareStrings(left.name, right.name);
588
+ return left.rank - right.rank;
571
589
  };
572
590
 
573
591
  const equalsModelValue = (left: ModelValue, right: Value) => {
@@ -716,16 +734,17 @@ const compareSetLikeTlc = (left: ObjectValue, right: Value): number => {
716
734
  );
717
735
  };
718
736
 
719
- const compareLikeTlc = (left: Value, right: Value): number => {
720
- if (typeof left !== "object") {
721
- if (typeof right === typeof left) return compareValues(left, right);
722
- if (isModelValue(right)) return compareModelValueWith(right, left);
723
- throw new TlaEvaluationError(describeScalarMismatch(left, right, false));
724
- }
725
- if (left.kind === "ModelValue") return compareModelValue(left, right);
726
- if (isFunctionValue(left)) return compareFunctionLikeTlc(left, right);
727
- return compareSetLikeTlc(left, right);
728
- };
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
+ });
729
748
 
730
749
  const equalsElementsLikeTlc = (left: Value[], right: Value[]) =>
731
750
  left.every((element, index) => equalsLikeTlc(element, right[index]));
@@ -813,16 +832,17 @@ const equalsSetLikeTlc = (left: ObjectValue, right: Value): boolean => {
813
832
  );
814
833
  };
815
834
 
816
- const equalsLikeTlc = (left: Value, right: Value): boolean => {
817
- if (typeof left !== "object") {
818
- if (typeof right === typeof left) return left === right;
819
- if (isModelValue(right)) return equalsModelValueWith(right, left);
820
- throw new TlaEvaluationError(describeScalarMismatch(left, right, true));
821
- }
822
- if (left.kind === "ModelValue") return equalsModelValue(left, right);
823
- if (isFunctionValue(left)) return equalsFunctionLikeTlc(left, right);
824
- return equalsSetLikeTlc(left, right);
825
- };
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
+ });
826
846
 
827
847
  // TLC's ValueVec.sort, which inserts each element into the sorted prefix by binary search.
828
848
  const sortLikeTlc = (elements: Value[]) => {
@@ -854,9 +874,11 @@ export const isEqualLikeTlc = (left: Value, right: Value) => {
854
874
  }
855
875
  };
856
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.
857
879
  const isStrictlySorted = (elements: Value[]) => {
858
880
  for (let index = 1; index < elements.length; index++) {
859
- if (compareValues(elements[index - 1], elements[index]) >= 0) return false;
881
+ if (compareValues(elements[index], elements[index - 1]) <= 0) return false;
860
882
  }
861
883
  return true;
862
884
  };
@@ -1059,13 +1081,16 @@ const isTlcEnumerable = (value: Value) => isSetValue(value) && !isOverriddenSet(
1059
1081
  const formatUnion = (value: UnionValue, isStrict = false) =>
1060
1082
  `UNION(${formatValue(value.base, isStrict)})`;
1061
1083
 
1062
- const getUnionSets = (value: UnionValue) => {
1084
+ const getUnionSets = (
1085
+ value: UnionValue,
1086
+ getElements = (set: Value) => toFiniteSet(set).elements,
1087
+ ) => {
1063
1088
  if (!isTlcEnumerable(value.base)) {
1064
1089
  throw new TlaEvaluationError(
1065
1090
  `Attempted to enumerate the nonenumerable set:\n${formatUnion(value)}`,
1066
1091
  );
1067
1092
  }
1068
- return toFiniteSet(value.base).elements;
1093
+ return getElements(value.base);
1069
1094
  };
1070
1095
 
1071
1096
  const getUnionSet = (set: Value, index: number, union: UnionValue) => {
@@ -1101,7 +1126,7 @@ export const isEnumerable = (value: Value): boolean => {
1101
1126
  case "ProductSet":
1102
1127
  return value.factors.every(isEnumerable) || getEmptiness(value) === true;
1103
1128
  case "Union":
1104
- return isEnumerable(value.base) && toFiniteSet(value.base).elements.every(isEnumerable);
1129
+ return isEnumerable(value.base) && getStreamedElements(value.base).every(isEnumerable);
1105
1130
  case "SetOperation":
1106
1131
  if (value.operator === "\\cup") return isEnumerable(value.left) && isEnumerable(value.right);
1107
1132
  if (value.operator === "\\cap") return isEnumerable(value.left) || isEnumerable(value.right);
@@ -1174,6 +1199,41 @@ const advanceCombination = (indices: number[], length: number) => {
1174
1199
  return false;
1175
1200
  };
1176
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
+
1177
1237
  const getSortedSubsets = (base: Value[]) => {
1178
1238
  const subsets: Value[] = [];
1179
1239
  for (let size = 0; size <= base.length; size++) {
@@ -1202,9 +1262,7 @@ const enumerateSet = (value: Value): Value[] => {
1202
1262
  if (isOverriddenSet(value.base)) getCardinality(value.base);
1203
1263
  const base = toFiniteSet(value.base).elements;
1204
1264
  if (base.length > MAXIMUM_ENUMERATED_SUBSET_BASE) {
1205
- throw new TlaEvaluationError(
1206
- `SUBSET of a set with ${base.length} elements is too large to enumerate`,
1207
- );
1265
+ throw new TlaEvaluationError(describeOverflow(value));
1208
1266
  }
1209
1267
  return getSortedSubsets(base);
1210
1268
  }
@@ -1268,7 +1326,7 @@ const enumerateSet = (value: Value): Value[] => {
1268
1326
  case "SetOperation": {
1269
1327
  if (
1270
1328
  value.operator === "\\cup" &&
1271
- (isOverriddenSet(value.left) || isOverriddenSet(value.right))
1329
+ (!isTlcEnumerable(value.left) || !isTlcEnumerable(value.right))
1272
1330
  ) {
1273
1331
  throw new TlaEvaluationError(
1274
1332
  `Attempted to enumerate S \\cup T when S:\n${formatValue(value.left)}\nand T:\n${formatValue(value.right)}\nare not both enumerable`,
@@ -1276,14 +1334,14 @@ const enumerateSet = (value: Value): Value[] => {
1276
1334
  }
1277
1335
  if (
1278
1336
  value.operator === "\\cap" &&
1279
- isOverriddenSet(value.left) &&
1280
- isOverriddenSet(value.right)
1337
+ !isTlcEnumerable(value.left) &&
1338
+ !isTlcEnumerable(value.right)
1281
1339
  ) {
1282
1340
  throw new TlaEvaluationError(
1283
1341
  `Attempted to enumerate S \\cap T when neither S:\n${formatValue(value.left)}\nnor T:\n${formatValue(value.right)}\nis enumerable`,
1284
1342
  );
1285
1343
  }
1286
- if (value.operator === "\\" && isOverriddenSet(value.left)) {
1344
+ if (value.operator === "\\" && !isTlcEnumerable(value.left)) {
1287
1345
  throw new TlaEvaluationError(
1288
1346
  `Attempted to enumerate S \\ T when S:\n${formatValue(value.left)}\nis not enumerable.`,
1289
1347
  );
@@ -1308,6 +1366,7 @@ const enumerateSet = (value: Value): Value[] => {
1308
1366
  };
1309
1367
 
1310
1368
  const finiteSets = new WeakMap<ObjectValue, SetValue>();
1369
+ const comparedSets = new WeakMap<ObjectValue, SetValue>();
1311
1370
 
1312
1371
  export const toFiniteSet = (value: Value): SetValue => {
1313
1372
  if (typeof value === "object" && value.kind === "Set") return value;
@@ -1316,6 +1375,16 @@ export const toFiniteSet = (value: Value): SetValue => {
1316
1375
  }
1317
1376
  const cached = typeof value === "object" ? finiteSets.get(value) : undefined;
1318
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) => {
1319
1388
  const elements = enumerateSet(value);
1320
1389
  const isSorted =
1321
1390
  typeof value === "object" &&
@@ -1326,8 +1395,20 @@ export const toFiniteSet = (value: Value): SetValue => {
1326
1395
  value.kind === "ProductSet" ||
1327
1396
  value.kind === "FunctionSet" ||
1328
1397
  value.kind === "Subset");
1329
- const set = isSorted ? createSortedSet(elements) : createSet(elements);
1330
- 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);
1331
1412
  return set;
1332
1413
  };
1333
1414
 
@@ -1335,8 +1416,10 @@ export const toFiniteSet = (value: Value): SetValue => {
1335
1416
  // so an element that two of them share comes up once for each.
1336
1417
  export const getStreamedElements = (value: Value): Value[] => {
1337
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.
1338
1421
  if (value.kind === "Union") {
1339
- return getUnionSets(value).flatMap((set, index) =>
1422
+ return getUnionSets(value, getStreamedElements).flatMap((set, index) =>
1340
1423
  getStreamedElements(getUnionSet(set, index, value)),
1341
1424
  );
1342
1425
  }
@@ -1345,14 +1428,14 @@ export const getStreamedElements = (value: Value): Value[] => {
1345
1428
  }
1346
1429
  if (value.kind !== "SetOperation") return toFiniteSet(value).elements;
1347
1430
  if (value.operator === "\\cup") {
1348
- return isOverriddenSet(value.left) || isOverriddenSet(value.right)
1431
+ return !isTlcEnumerable(value.left) || !isTlcEnumerable(value.right)
1349
1432
  ? toFiniteSet(value).elements
1350
1433
  : [...getStreamedElements(value.left), ...getStreamedElements(value.right)];
1351
1434
  }
1352
1435
  const isLeftEnumerated = value.operator === "\\" || isEnumerable(value.left);
1353
1436
  const enumerated = isLeftEnumerated ? value.left : value.right;
1354
1437
  const other = isLeftEnumerated ? value.right : value.left;
1355
- if (isOverriddenSet(enumerated)) return toFiniteSet(value).elements;
1438
+ if (!isTlcEnumerable(enumerated)) return toFiniteSet(value).elements;
1356
1439
  return getStreamedElements(enumerated).filter(
1357
1440
  (element) => isElementOf(element, other) === (value.operator === "\\cap"),
1358
1441
  );
@@ -1555,6 +1638,12 @@ const describeNonSetMembership = (element: Value, value: Value) => {
1555
1638
  return `${prefix} function ${formatValue(value)}`;
1556
1639
  };
1557
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
+
1558
1647
  export const isElementOf = (element: Value, set: Value): boolean => {
1559
1648
  if (!isSetValue(set)) throw new TlaEvaluationError(describeNonSetMembership(element, set));
1560
1649
  switch (set.kind) {
@@ -1563,10 +1652,10 @@ export const isElementOf = (element: Value, set: Value): boolean => {
1563
1652
  return findIndex(set.elements, element) !== -1;
1564
1653
  } catch (error) {
1565
1654
  if (!(error instanceof TlaEvaluationError)) throw error;
1566
- return isElementOfLikeTlc(element, set.elements);
1655
+ return withSource(set, () => isElementOfLikeTlc(element, set.elements));
1567
1656
  }
1568
1657
  case "MixedSet":
1569
- return isElementOfLikeTlc(element, set.elements);
1658
+ return withSource(set, () => isElementOfLikeTlc(element, set.elements));
1570
1659
  case "Interval":
1571
1660
  if (typeof element === "number") return element >= set.low && element <= set.high;
1572
1661
  if (set.low <= set.high && !isModelValue(element)) {
@@ -1588,12 +1677,18 @@ export const isElementOf = (element: Value, set: Value): boolean => {
1588
1677
  return set.name !== "Nat" || (typeof element === "number" && element >= 0);
1589
1678
  }
1590
1679
  case "Subset":
1591
- if (!isSetValue(element)) throw new TlaEvaluationError(describeMembership(element, set));
1592
- 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));
1593
1686
  case "FunctionSet": {
1594
1687
  if (!isFunctionValue(element)) {
1595
1688
  if (isModelValue(element)) return false;
1596
- 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
+ );
1597
1692
  }
1598
1693
  const functionValue = toFiniteFunction(element);
1599
1694
  const low = getIntervalLow(functionValue.domain);
@@ -1604,7 +1699,7 @@ export const isElementOf = (element: Value, set: Value): boolean => {
1604
1699
  { kind: "Interval", low, high: low + functionValue.domain.length - 1 },
1605
1700
  set.domain,
1606
1701
  );
1607
- return isDomain && functionValue.range.every((item) => isElementOf(item, set.range));
1702
+ return isDomain && functionValue.range.every((item) => isElementOfSet(item, set.range));
1608
1703
  }
1609
1704
  case "RecordSet": {
1610
1705
  const functionValue = isFunctionValue(element) ? toFiniteFunction(element) : undefined;
@@ -1618,7 +1713,7 @@ export const isElementOf = (element: Value, set: Value): boolean => {
1618
1713
  functionValue.domain.length === set.names.length &&
1619
1714
  set.names.every((name, index) => {
1620
1715
  const position = findIndex(functionValue.domain, name);
1621
- return position !== -1 && isElementOf(functionValue.range[position], set.sets[index]);
1716
+ return position !== -1 && isElementOfSet(functionValue.range[position], set.sets[index]);
1622
1717
  })
1623
1718
  );
1624
1719
  }
@@ -1635,24 +1730,24 @@ export const isElementOf = (element: Value, set: Value): boolean => {
1635
1730
  }
1636
1731
  return (
1637
1732
  elements.length === set.factors.length &&
1638
- elements.every((item, index) => isElementOf(item, set.factors[index]))
1733
+ elements.every((item, index) => isElementOfSet(item, set.factors[index]))
1639
1734
  );
1640
1735
  }
1641
1736
  case "FilteredSet":
1642
- return isElementOf(element, set.base) && set.test(element);
1737
+ return isElementOfSet(element, set.base) && set.test(element);
1643
1738
  case "Union":
1644
1739
  if (!isTlcEnumerable(set.base)) {
1645
1740
  throw new TlaEvaluationError(
1646
1741
  `Attempted to check if:\n ${formatValue(element)}\nis an element of the non-enumerable set:\n ${formatUnion(set)}`,
1647
1742
  );
1648
1743
  }
1649
- return toFiniteSet(set.base).elements.some((inner) => isElementOf(element, inner));
1744
+ return toFiniteSet(set.base).elements.some((inner) => isElementOfSet(element, inner));
1650
1745
  case "SetOperation":
1651
1746
  if (set.operator === "\\cup")
1652
- return isElementOf(element, set.left) || isElementOf(element, set.right);
1747
+ return isElementOfSet(element, set.left) || isElementOfSet(element, set.right);
1653
1748
  return (
1654
- isElementOf(element, set.left) &&
1655
- isElementOf(element, set.right) === (set.operator === "\\cap")
1749
+ isElementOfSet(element, set.left) &&
1750
+ isElementOfSet(element, set.right) === (set.operator === "\\cap")
1656
1751
  );
1657
1752
  case "SequenceSet": {
1658
1753
  const elements = getSequenceElements(element);
@@ -1667,6 +1762,25 @@ export const isElementOf = (element: Value, set: Value): boolean => {
1667
1762
  }
1668
1763
  };
1669
1764
 
1765
+ // A function that agrees with a member of a function set outside some entries is a member when
1766
+ // those entries are.
1767
+ export const isUpdatedElementOf = (element: Value, member: Value, set: Value): boolean => {
1768
+ if (element === member) return true;
1769
+ if (
1770
+ typeof element !== "object" ||
1771
+ typeof member !== "object" ||
1772
+ typeof set !== "object" ||
1773
+ element.kind !== "Function" ||
1774
+ member.kind !== "Function" ||
1775
+ set.kind !== "FunctionSet" ||
1776
+ element.domain !== member.domain
1777
+ )
1778
+ return isElementOf(element, set);
1779
+ return element.range.every((item, index) =>
1780
+ isUpdatedElementOf(item, member.range[index], set.range),
1781
+ );
1782
+ };
1783
+
1670
1784
  export const toFiniteFunction = (value: Value): FunctionValue => {
1671
1785
  if (typeof value === "object" && value.kind === "Function") return value;
1672
1786
  if (typeof value === "object" && value.kind === "LazyFunction") {
@@ -1689,15 +1803,80 @@ export const markLambdaFunction = <FunctionLike extends FunctionValue | LazyFunc
1689
1803
  return functionValue;
1690
1804
  };
1691
1805
 
1692
- const describeMissingArgument = (functionValue: Value, argument: Value) =>
1693
- typeof functionValue === "object" && lambdaFunctions.has(functionValue)
1694
- ? `In applying the function\n${prettyPrint(formatValue(functionValue))},\nthe first argument is:\n${prettyPrint(formatValue(argument))}\nwhich is not in its domain.\n`
1695
- : `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
+ };
1861
+
1862
+ const findKeyIndex = (domain: Value[], argument: Value) => {
1863
+ const first = domain[0];
1864
+ if (typeof argument === "number" && typeof first === "number") {
1865
+ const offset = argument - first;
1866
+ if (domain[offset] === argument) return offset;
1867
+ }
1868
+ if (domain.length <= 8) {
1869
+ for (let index = 0; index < domain.length; index++)
1870
+ if (domain[index] === argument) return index;
1871
+ }
1872
+ return findIndex(domain, argument);
1873
+ };
1696
1874
 
1697
1875
  export const applyFunction = (
1698
1876
  functionValue: Value,
1699
1877
  argument: Value,
1700
1878
  describeMissing?: (functionValue: FunctionValue) => string,
1879
+ describeNonFunction?: (value: Value) => string,
1701
1880
  ): Value => {
1702
1881
  if (typeof functionValue === "object" && functionValue.kind === "LazyFunction") {
1703
1882
  if (!isElementOf(argument, functionValue.domain)) {
@@ -1711,20 +1890,13 @@ export const applyFunction = (
1711
1890
  }
1712
1891
  if (typeof functionValue !== "object" || functionValue.kind !== "Function") {
1713
1892
  throw new TlaEvaluationError(
1714
- `Attempted to apply ${formatValue(functionValue)}, which is not a function`,
1893
+ describeNonFunction?.(functionValue) ??
1894
+ `Attempted to apply ${formatValue(functionValue)}, which is not a function`,
1715
1895
  );
1716
1896
  }
1717
- const domain = functionValue.domain;
1718
- const first = domain[0];
1719
- if (typeof argument === "number" && typeof first === "number") {
1720
- const offset = argument - first;
1721
- if (domain[offset] === argument) return functionValue.range[offset];
1722
- }
1723
- if (domain.length <= 8) {
1724
- for (let index = 0; index < domain.length; index++)
1725
- if (domain[index] === argument) return functionValue.range[index];
1726
- }
1727
- const position = findIndex(domain, argument);
1897
+ const position = isForeignKey(functionValue.domain, argument)
1898
+ ? -1
1899
+ : findKeyIndex(functionValue.domain, argument);
1728
1900
  if (position === -1) {
1729
1901
  throw new TlaEvaluationError(
1730
1902
  describeMissing?.(functionValue) ?? describeMissingArgument(functionValue, argument),
@@ -1733,12 +1905,16 @@ export const applyFunction = (
1733
1905
  return functionValue.range[position];
1734
1906
  };
1735
1907
 
1908
+ export const getDomainInterval = (domain: Value[]) =>
1909
+ isIntervalDomain(domain)
1910
+ ? (intervalArrays.get(domain) ?? getIntervalValue(domain.length))
1911
+ : undefined;
1912
+
1736
1913
  export const getDomain = (functionValue: Value): Value => {
1737
1914
  if (typeof functionValue === "object" && functionValue.kind === "LazyFunction")
1738
1915
  return functionValue.domain;
1739
1916
  const domain = toFiniteFunction(functionValue).domain;
1740
- if (!isIntervalDomain(domain)) return createSortedSet(domain);
1741
- return intervalArrays.get(domain) ?? getIntervalValue(domain.length);
1917
+ return getDomainInterval(domain) ?? createSortedSet(domain);
1742
1918
  };
1743
1919
 
1744
1920
  export const updateFunction = (
@@ -1762,7 +1938,7 @@ export const updateFunction = (
1762
1938
  };
1763
1939
  }
1764
1940
  const finite = toFiniteFunction(functionValue);
1765
- const position = findIndex(finite.domain, argument);
1941
+ const position = findKeyIndex(finite.domain, argument);
1766
1942
  if (position === -1) return finite;
1767
1943
  const range = [...finite.range];
1768
1944
  const previous = finite.range[position];
@@ -1818,10 +1994,15 @@ const getElementContribution = (element: Value) =>
1818
1994
  const getEntryContribution = (key: Value, value: Value) =>
1819
1995
  finalizeHash((Math.imul(getValueHash(key), 0x27d4eb2d) + getValueHash(value)) | 0);
1820
1996
 
1997
+ const unenumeratedSets = { isHashed: false };
1998
+
1821
1999
  const computeValueHash = (value: ObjectValue) => {
1822
2000
  if (value.kind === "ModelValue") return finalizeHash(combineHash(hashString(value.name), 0x6d));
1823
2001
  if (isSetValue(value)) {
1824
- if (!isEnumerable(value)) return hashString(getValueKey(value));
2002
+ if (!isEnumerable(value)) {
2003
+ unenumeratedSets.isHashed = true;
2004
+ return hashString(getValueKey(value));
2005
+ }
1825
2006
  const elements = toFiniteSet(value).elements;
1826
2007
  let hash = SET_HASH_SEED;
1827
2008
  for (let index = 0; index < elements.length; index++) {
@@ -1853,6 +2034,25 @@ export const getValueHash = (value: Value): number => {
1853
2034
  return hash;
1854
2035
  };
1855
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
+
1856
2056
  const valueFingerprints = new WeakMap<ObjectValue, number>();
1857
2057
 
1858
2058
  const finalizeFingerprint = (hash: number) => {
@@ -1879,7 +2079,10 @@ const getEntryFingerprint = (key: Value, value: Value) =>
1879
2079
  const computeValueFingerprint = (value: ObjectValue) => {
1880
2080
  if (value.kind === "ModelValue") return finalizeFingerprint(fingerprintString(value.name) ^ 0x3c);
1881
2081
  if (isSetValue(value)) {
1882
- if (!isEnumerable(value)) return fingerprintString(getValueKey(value));
2082
+ if (!isEnumerable(value)) {
2083
+ unenumeratedSets.isHashed = true;
2084
+ return fingerprintString(getValueKey(value));
2085
+ }
1883
2086
  const elements = toFiniteSet(value).elements;
1884
2087
  let fingerprint = 0x1b873593;
1885
2088
  for (let index = 0; index < elements.length; index++) {
@@ -2065,8 +2268,11 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
2065
2268
  return `[${parameters} |-> <expression ${source.body}>]`;
2066
2269
  }
2067
2270
  const functionValue = toFiniteFunction(value);
2271
+ // TLC normalizes a lambda's domain to print it, but evaluates its body afterward.
2272
+ const formatRange = (inner: Value) =>
2273
+ formatValue(inner, isStrict, isNormalized && value.kind === "Function");
2068
2274
  if (functionValue.domain.every((key, index) => key === index + 1)) {
2069
- return `<<${functionValue.range.map(format).join(", ")}>>`;
2275
+ return `<<${functionValue.range.map(formatRange).join(", ")}>>`;
2070
2276
  }
2071
2277
  if (functionValue.domain.every((key) => typeof key === "string" && isFieldName(key))) {
2072
2278
  const isSorted =
@@ -2074,9 +2280,20 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
2074
2280
  const pairs = isSorted
2075
2281
  ? functionValue.domain.map((key, index) => [key, functionValue.range[index]])
2076
2282
  : getWrittenPairs(functionValue);
2077
- return `[${pairs.map((pair) => `${String(pair[0])} |-> ${format(pair[1])}`).join(", ")}]`;
2283
+ return `[${pairs.map((pair) => `${String(pair[0])} |-> ${formatRange(pair[1])}`).join(", ")}]`;
2078
2284
  }
2079
- return `(${functionValue.domain.map((key, index) => `${format(key)} :> ${format(functionValue.range[index])}`).join(" @@ ")})`;
2285
+ return `(${functionValue.domain.map((key, index) => `${format(key)} :> ${formatRange(functionValue.range[index])}`).join(" @@ ")})`;
2080
2286
  }
2081
2287
  }
2082
2288
  };
2289
+
2290
+ // TLC's TLCState.toString: a line per variable, as a conjunction when there are several.
2291
+ export const formatState = (state: Record<string, Value>) => {
2292
+ const entries = Object.entries(state);
2293
+ return entries
2294
+ .map(
2295
+ ([name, value]) =>
2296
+ `${entries.length === 1 ? "" : "/\\ "}${name} = ${prettyPrint(formatValue(value))}\n`,
2297
+ )
2298
+ .join("");
2299
+ };