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/evaluate.ts CHANGED
@@ -1,23 +1,25 @@
1
- import type {
2
- Bound,
3
- BoundPattern,
4
- DecimalExpression,
5
- Definition,
6
- Expression,
7
- FunctionDefinition,
8
- NumberExpression,
9
- OperatorParam,
10
- RecordField,
11
- SourceRange,
1
+ import {
2
+ getChildren,
3
+ isLocallyResolved,
4
+ type Bound,
5
+ type BoundPattern,
6
+ type DecimalExpression,
7
+ type Definition,
8
+ type Expression,
9
+ type FunctionDefinition,
10
+ type NumberExpression,
11
+ type OperatorParam,
12
+ type RecordField,
12
13
  } from "./ast";
13
14
  import { getKindString } from "./builtins";
14
- import { TlaEvaluationError } from "./errors";
15
- import { EXIT_STATUS, setExitCode } from "./exit-codes";
15
+ import { formatRange, TlaEvaluationError, TlaUnassignedError } from "./errors";
16
+ import { EXIT_STATUS, setExitCode, setOwnExitCode } from "./exit-codes";
16
17
  import { generateEvaluator } from "./codegen";
17
18
  import type { CheckerRuntime } from "./runtime";
18
19
  import { getReadVariables } from "./dependencies";
19
20
  import { contextualApplications, mapChildren, substitutedExpressions } from "./instances";
20
21
  import { isEnabled } from "./successors";
22
+ import { getFingerprintTrace, valueSources, withSource } from "./value-sources";
21
23
  import {
22
24
  applyFunction,
23
25
  combineHash,
@@ -28,23 +30,28 @@ import {
28
30
  createSortedSet,
29
31
  createWrittenRecord,
30
32
  createTuple,
33
+ describeMissingField,
31
34
  formatValue,
32
35
  getDomain,
33
36
  getFunctionDomain,
34
37
  getIntervalElements,
38
+ getLazySubsets,
35
39
  getSequenceElements,
36
40
  getValueHash,
37
- isEnumerable,
38
41
  isFunctionValue,
39
42
  isOverriddenSet,
43
+ isRecordValue,
40
44
  isSameValue,
41
45
  markLambdaFunction,
46
+ isReducible,
42
47
  isSetValue,
43
48
  MAXIMUM_INTEGER,
44
49
  MINIMUM_INTEGER,
45
50
  toFiniteSet,
46
51
  updateFunction,
47
52
  valuesEqual,
53
+ type FilteredSetValue,
54
+ type FunctionValue,
48
55
  type LazyFunctionSource,
49
56
  type LazyFunctionValue,
50
57
  type Value,
@@ -112,6 +119,7 @@ export interface Environment {
112
119
  definitionValues: Map<Definition, Value>;
113
120
  constantLevels: Map<Definition, boolean>;
114
121
  evaluators: WeakMap<Expression, Evaluator>;
122
+ trace?: Expression[];
115
123
  }
116
124
 
117
125
  export interface Context {
@@ -141,9 +149,6 @@ const EXCEPT_AT = "@";
141
149
  export const describeLocation = (expression: Expression) =>
142
150
  `line ${expression.location.line}, column ${expression.location.column}`;
143
151
 
144
- export const formatRange = (range: SourceRange) =>
145
- `line ${range.start.line}, col ${range.start.column} to line ${range.end.line}, col ${range.end.column} of module ${range.module}`;
146
-
147
152
  export const describeRange = (expression: Expression) => {
148
153
  const range = expression.location.range;
149
154
  return range ? formatRange(range) : describeLocation(expression);
@@ -180,8 +185,17 @@ export const getConjunctError = (
180
185
  };
181
186
 
182
187
  export const getFieldError =
183
- (expression: Expression & { kind: "FieldAccess" }) => (record: Value) =>
184
- `Attempted to select nonexistent field "${expression.field}" from the record\n${formatValue(record)}\n${describeRange(expression)}`;
188
+ (expression: Expression & { kind: "FieldAccess" }) => (record: FunctionValue) =>
189
+ isRecordValue(record)
190
+ ? `Attempted to select nonexistent field "${expression.field}" from the record\n${formatValue(record)}\n${describeRange(expression)}`
191
+ : describeMissingField(record, expression.field);
192
+
193
+ export const getNonFunctionError = (expression: Expression) => (value: Value) =>
194
+ `A non-function (${getKindString(value)}) was applied as a function.\n${describeRange(expression)}`;
195
+
196
+ export const getNonRecordError =
197
+ (expression: Expression & { kind: "FieldAccess" }) => (value: Value) =>
198
+ `Attempted to select field "${expression.field}" from a non-record value ${formatValue(value)}\n${describeRange(expression)}`;
185
199
 
186
200
  export const getDomainOperator = (expression: Expression) => (value: Value) => {
187
201
  if (!isFunctionValue(value)) {
@@ -262,96 +276,6 @@ export const expectBoolean = (value: Value, description: string) => {
262
276
  return value;
263
277
  };
264
278
 
265
- export const getChildren = (expression: Expression): Expression[] => {
266
- switch (expression.kind) {
267
- case "Number":
268
- case "Decimal":
269
- case "String":
270
- case "Identifier":
271
- case "OperatorReference":
272
- case "ExceptAt":
273
- return [];
274
- case "Apply":
275
- return expression.args;
276
- case "Lambda":
277
- return [expression.body];
278
- case "And":
279
- case "Or":
280
- return expression.operands;
281
- case "Prime":
282
- case "Unchanged":
283
- case "Enabled":
284
- case "Always":
285
- case "Eventually":
286
- return [expression.expression];
287
- case "If":
288
- return [expression.condition, expression.consequent, expression.alternative];
289
- case "Case":
290
- return [
291
- ...expression.arms.flatMap((arm) => [arm.condition, arm.body]),
292
- ...(expression.other ? [expression.other] : []),
293
- ];
294
- case "Let":
295
- return [
296
- ...expression.definitions.flatMap((definition) =>
297
- definition.kind === "Function"
298
- ? [...definition.bounds.map((bound) => bound.set), definition.body]
299
- : [definition.body],
300
- ),
301
- expression.body,
302
- ];
303
- case "Forall":
304
- case "Exists":
305
- return [...expression.bounds.map((bound) => bound.set), expression.body];
306
- case "UnboundedQuantifier":
307
- return [expression.body];
308
- case "Choose":
309
- return [...(expression.set ? [expression.set] : []), expression.body];
310
- case "SetEnumeration":
311
- case "Tuple":
312
- return expression.elements;
313
- case "SetFilter":
314
- return [expression.bound.set, expression.predicate];
315
- case "SetMap":
316
- return [expression.expression, ...expression.bounds.map((bound) => bound.set)];
317
- case "FunctionConstruction":
318
- return [...expression.bounds.map((bound) => bound.set), expression.body];
319
- case "FunctionSet":
320
- return [expression.domain, expression.range];
321
- case "Record":
322
- case "RecordSet":
323
- return expression.fields.map((field) => field.value);
324
- case "Except":
325
- return [
326
- expression.function,
327
- ...expression.updates.flatMap((update) => [
328
- ...update.path.flatMap((step) => (step.kind === "Index" ? step.args : [])),
329
- update.value,
330
- ]),
331
- ];
332
- case "FunctionApplication":
333
- return [expression.function, ...expression.args];
334
- case "FieldAccess":
335
- return [expression.record];
336
- case "Product":
337
- return expression.factors;
338
- case "BoxAction":
339
- case "AngleAction":
340
- return [expression.action, expression.subscript];
341
- case "WeakFairness":
342
- case "StrongFairness":
343
- return [expression.subscript, expression.action];
344
- case "Label":
345
- return [expression.body];
346
- case "Subexpression":
347
- return expression.selectors.flatMap((selector) => ("args" in selector ? selector.args : []));
348
- }
349
- };
350
-
351
- export const isLocallyResolved = (expression: Expression) =>
352
- (expression.kind === "Identifier" || expression.kind === "Apply") &&
353
- expression.resolution?.kind === "Local";
354
-
355
279
  export const getDefinition = (name: string, environment: Environment) =>
356
280
  environment.definitions.get(environment.substitutions.get(name) ?? name);
357
281
 
@@ -419,9 +343,8 @@ export const getEnumeratedElements = (set: Value, expression: Expression) => {
419
343
  : `TLC encountered the non-enumerable quantifier bound\n${text}\n${describeRange(expression)}\n${explanation}`,
420
344
  );
421
345
  }
422
- return typeof set === "object" && set.kind === "Interval"
423
- ? getIntervalElements(set)
424
- : toFiniteSet(set).elements;
346
+ if (typeof set === "object" && set.kind === "Interval") return getIntervalElements(set);
347
+ return getLazySubsets(set) ?? toFiniteSet(set).elements;
425
348
  };
426
349
 
427
350
  export const forEachBinding = (
@@ -734,7 +657,9 @@ const compileArgumentBinder = (argument: Expression, environment: Environment):
734
657
  if (global === undefined) {
735
658
  return (context) => {
736
659
  const binding = lookupScope(context.scope, argument.name);
737
- return binding?.kind === "Value" ? binding : createThunk(argument, context);
660
+ return binding?.kind === "Value" || binding?.kind === "Thunk"
661
+ ? binding
662
+ : createThunk(argument, context);
738
663
  };
739
664
  }
740
665
  }
@@ -857,11 +782,7 @@ const evaluateLocalIdentifier = (name: string, expression: Expression, context:
857
782
  const global = findGlobalName(name, context.environment);
858
783
  if (global?.kind === "Variable") {
859
784
  const value = context.state?.[global.index];
860
- if (value === undefined) {
861
- throw new TlaEvaluationError(
862
- `The variable ${name} is not assigned at ${describeLocation(expression)}`,
863
- );
864
- }
785
+ if (value === undefined) throw createUnassignedError(name, expression);
865
786
  return value;
866
787
  }
867
788
  if (global?.kind === "Value") return global.value;
@@ -887,14 +808,29 @@ const IMPURE_BUILTINS = new Set([
887
808
  export const isImpureBuiltin = (name: string, environment: Environment) =>
888
809
  IMPURE_BUILTINS.has(name) || environment.builtins.get(name)?.isStateLevel === true;
889
810
 
890
- const impureDefinitions = new WeakMap<Definition, boolean>();
811
+ interface Impurity {
812
+ builtins: Set<string>;
813
+ definitions: WeakMap<Definition, boolean>;
814
+ }
815
+
816
+ const ANY_EFFECT: Impurity = { builtins: IMPURE_BUILTINS, definitions: new WeakMap() };
817
+
818
+ // An Assert that held holds again, so evaluating it twice looks the same as evaluating it once.
819
+ const REPEATED_EFFECT: Impurity = {
820
+ builtins: new Set([...IMPURE_BUILTINS].filter((name) => name !== "Assert")),
821
+ definitions: new WeakMap(),
822
+ };
891
823
 
892
824
  const isEvaluatedOnce = (definition: Definition, environment: Environment) =>
893
825
  definition.kind === "Operator" &&
894
826
  definition.params.length === 0 &&
895
827
  isConstantLevel(definition, environment);
896
828
 
897
- const callsImpureBuiltin = (expression: Expression, environment: Environment): boolean => {
829
+ const callsImpureBuiltin = (
830
+ expression: Expression,
831
+ environment: Environment,
832
+ impurity: Impurity,
833
+ ): boolean => {
898
834
  const name =
899
835
  expression.kind === "Identifier"
900
836
  ? expression.name
@@ -903,29 +839,35 @@ const callsImpureBuiltin = (expression: Expression, environment: Environment): b
903
839
  : undefined;
904
840
  if (name !== undefined && !isLocallyResolved(expression)) {
905
841
  const definition = getDefinition(name, environment);
906
- if (!definition && isImpureBuiltin(name, environment)) return true;
842
+ const isImpureCall =
843
+ impurity.builtins.has(name) || environment.builtins.get(name)?.isStateLevel === true;
844
+ if (!definition && isImpureCall) return true;
907
845
  if (
908
846
  definition &&
909
847
  !isEvaluatedOnce(definition, environment) &&
910
- isImpureDefinition(definition, environment)
848
+ isImpureDefinition(definition, environment, impurity)
911
849
  ) {
912
850
  return true;
913
851
  }
914
852
  }
915
- return getChildren(expression).some((child) => callsImpureBuiltin(child, environment));
853
+ return getChildren(expression).some((child) => callsImpureBuiltin(child, environment, impurity));
916
854
  };
917
855
 
918
856
  // TLC evaluates a constant definition without parameters once, so only other definitions pass
919
857
  // on the side effects and random choices of the builtins they call.
920
- const isImpureDefinition = (definition: Definition, environment: Environment): boolean => {
921
- const cached = impureDefinitions.get(definition);
858
+ const isImpureDefinition = (
859
+ definition: Definition,
860
+ environment: Environment,
861
+ impurity = ANY_EFFECT,
862
+ ): boolean => {
863
+ const cached = impurity.definitions.get(definition);
922
864
  if (cached !== undefined) return cached;
923
- impureDefinitions.set(definition, false);
865
+ impurity.definitions.set(definition, false);
924
866
  const isImpure =
925
- callsImpureBuiltin(definition.body, environment) ||
867
+ callsImpureBuiltin(definition.body, environment, impurity) ||
926
868
  (definition.kind === "Function" &&
927
- definition.bounds.some((bound) => callsImpureBuiltin(bound.set, environment)));
928
- impureDefinitions.set(definition, isImpure);
869
+ definition.bounds.some((bound) => callsImpureBuiltin(bound.set, environment, impurity)));
870
+ impurity.definitions.set(definition, isImpure);
929
871
  return isImpure;
930
872
  };
931
873
 
@@ -939,6 +881,12 @@ export const isImpure = (environment: Environment) =>
939
881
  isImpureDefinition(definition, environment),
940
882
  );
941
883
 
884
+ // Whether evaluating a definition again can show, such as by printing twice.
885
+ export const hasRepeatedEffects = (environment: Environment) =>
886
+ [...environment.definitions.values()].some((definition) =>
887
+ isImpureDefinition(definition, environment, REPEATED_EFFECT),
888
+ );
889
+
942
890
  const closedConstants = new WeakMap<Expression, boolean>();
943
891
 
944
892
  export const isClosedConstant = (expression: Expression, environment: Environment): boolean => {
@@ -1074,23 +1022,88 @@ const isStateCached = (expression: Expression, environment: Environment) =>
1074
1022
  getReadVariables(expression, environment) !== undefined &&
1075
1023
  !hasFreeLocals(expression, NO_BOUND_NAMES);
1076
1024
 
1025
+ // CallStackTool also evaluates the predicate of a lazy set filter it returns, even one that TLC
1026
+ // made before the replay.
1027
+ const filteredSetRetracers = new WeakMap<
1028
+ FilteredSetValue,
1029
+ (environment: Environment) => FilteredSetValue
1030
+ >();
1031
+
1032
+ const SOURCED_KINDS = new Set<Expression["kind"]>([
1033
+ "SetEnumeration",
1034
+ "SetMap",
1035
+ "SetFilter",
1036
+ "Tuple",
1037
+ "Record",
1038
+ "RecordSet",
1039
+ "FunctionSet",
1040
+ "Product",
1041
+ ]);
1042
+
1043
+ const SOURCED_OPERATORS = new Set(["SUBSET", "UNION", "DOMAIN", "\\cup", "\\cap", "\\"]);
1044
+
1045
+ // CallStackTool gives a set, tuple or record it builds the expression as its source, but not a lazy
1046
+ // set filter, which it returns as a copy.
1047
+ const isSourced = (expression: Expression, environment: Environment) =>
1048
+ SOURCED_KINDS.has(expression.kind) ||
1049
+ (expression.kind === "Apply" &&
1050
+ SOURCED_OPERATORS.has(expression.operator) &&
1051
+ !isLocallyResolved(expression) &&
1052
+ resolveGlobalOperator(expression.operator, environment)?.kind === "Builtin");
1053
+
1054
+ // When an evaluation fails, CallStackTool freezes the stack at the innermost expression and pushes
1055
+ // the source of each value whose method failed.
1056
+ const evaluateTraced = (
1057
+ evaluator: Evaluator,
1058
+ context: Context,
1059
+ trace: Expression[],
1060
+ depth: number,
1061
+ ) => {
1062
+ try {
1063
+ return evaluator(context);
1064
+ } catch (error) {
1065
+ if (trace.length === depth + 1) trace.push(...(getFingerprintTrace(error) ?? []));
1066
+ throw error;
1067
+ }
1068
+ };
1069
+
1077
1070
  export const getEvaluator = (expression: Expression, environment: Environment): Evaluator => {
1078
1071
  const cached = environment.evaluators.get(expression);
1079
1072
  if (cached) return cached;
1080
1073
  const compiled = compile(expression, environment);
1081
- const evaluator =
1074
+ const cachedEvaluator =
1082
1075
  isWorthCaching(expression) && isClosedConstant(expression, environment)
1083
1076
  ? cacheFirstValue(compiled)
1084
1077
  : isStateCached(expression, environment)
1085
1078
  ? cacheStateValue(compiled)
1086
1079
  : compiled;
1080
+ const trace = environment.trace;
1081
+ const isSourcedExpression = trace !== undefined && isSourced(expression, environment);
1082
+ // TLC's CallStackTool pushes each expression it evaluates and keeps the stack when one fails.
1083
+ const evaluator: Evaluator = trace
1084
+ ? (context) => {
1085
+ const depth = trace.length;
1086
+ trace.push(expression);
1087
+ const value = evaluateTraced(cachedEvaluator, context, trace, depth);
1088
+ trace.length = depth;
1089
+ if (isSourcedExpression && typeof value === "object" && value.kind !== "FilteredSet") {
1090
+ valueSources.current?.set(value, expression);
1091
+ }
1092
+ const retrace =
1093
+ typeof value === "object" && value.kind === "FilteredSet"
1094
+ ? filteredSetRetracers.get(value)
1095
+ : undefined;
1096
+ return retrace ? retrace(environment) : value;
1097
+ }
1098
+ : cachedEvaluator;
1087
1099
  environment.evaluators.set(expression, evaluator);
1088
1100
  return evaluator;
1089
1101
  };
1090
1102
 
1091
1103
  const entryEvaluators = new WeakMap<Expression, Evaluator>();
1092
1104
 
1093
- const getEntryEvaluator = (expression: Expression, environment: Environment) => {
1105
+ export const getEntryEvaluator = (expression: Expression, environment: Environment) => {
1106
+ if (environment.trace) return getEvaluator(expression, environment);
1094
1107
  const cached = entryEvaluators.get(expression);
1095
1108
  if (cached) return cached;
1096
1109
  const evaluator =
@@ -1114,11 +1127,7 @@ const compileIdentifier = (
1114
1127
  const index = global.index;
1115
1128
  return (context) => {
1116
1129
  const value = context.state?.[index];
1117
- if (value === undefined) {
1118
- throw new TlaEvaluationError(
1119
- `The variable ${name} is not assigned at ${describeLocation(expression)}`,
1120
- );
1121
- }
1130
+ if (value === undefined) throw createUnassignedError(name, expression);
1122
1131
  return value;
1123
1132
  };
1124
1133
  }
@@ -1203,11 +1212,32 @@ const getLazyArguments = (args: Expression[], context: Context): OperatorValue[]
1203
1212
  expression: arg,
1204
1213
  }));
1205
1214
 
1215
+ const RECEIVING_OPERATORS = new Set(["=", "#", "\\in", "\\notin", "\\cup", "\\cap", "\\"]);
1216
+
1217
+ // The argument whose method TLC calls to apply a built-in operator.
1218
+ const getReceiver = (name: string, left: Value, right: Value) =>
1219
+ name === "\\in" ||
1220
+ name === "\\notin" ||
1221
+ ((name === "\\cup" || name === "\\cap") && !isReducible(left))
1222
+ ? right
1223
+ : left;
1224
+
1206
1225
  const compileBuiltinCall = (
1207
1226
  builtin: Builtin,
1208
1227
  args: Expression[],
1209
1228
  environment: Environment,
1210
1229
  ): Evaluator => {
1230
+ if (environment.trace && RECEIVING_OPERATORS.has(builtin.name) && args.length === 2) {
1231
+ const evaluateLeft = getEvaluator(args[0], environment);
1232
+ const evaluateRight = getEvaluator(args[1], environment);
1233
+ return (context) => {
1234
+ const left = evaluateLeft(context);
1235
+ const right = evaluateRight(context);
1236
+ return withSource(getReceiver(builtin.name, left, right), () =>
1237
+ builtin.evaluate([left, right], context),
1238
+ );
1239
+ };
1240
+ }
1211
1241
  if (builtin.isLazy) {
1212
1242
  return (context) => builtin.evaluate(getLazyArguments(args, context), context);
1213
1243
  }
@@ -1367,6 +1397,13 @@ const compileApply = (
1367
1397
  if (global?.kind === "Builtin" && global.name === "DOMAIN") {
1368
1398
  const operand = getEvaluator(args[0], environment);
1369
1399
  const domain = getDomainOperator(expression);
1400
+ // TLC builds a new interval for the domain of a tuple, so the source it gives one stays its own.
1401
+ if (environment.trace) {
1402
+ return (context) => {
1403
+ const value = domain(operand(context));
1404
+ return typeof value === "object" && value.kind === "Interval" ? { ...value } : value;
1405
+ };
1406
+ }
1370
1407
  return (context) => domain(operand(context));
1371
1408
  }
1372
1409
  // TLC sorts the value of a constant TLCEval argument only where no context binds a name.
@@ -1382,6 +1419,13 @@ const compileApply = (
1382
1419
  const left = getEvaluator(args[0], environment);
1383
1420
  const right = getEvaluator(args[1], environment);
1384
1421
  const subset = getSubsetOperator(expression, global);
1422
+ if (environment.trace) {
1423
+ return (context) => {
1424
+ const subsetValue = left(context);
1425
+ const superset = right(context);
1426
+ return withSource(subsetValue, () => subset(subsetValue, superset));
1427
+ };
1428
+ }
1385
1429
  return (context) => subset(left(context), right(context));
1386
1430
  }
1387
1431
  if (global?.kind === "Builtin") return compileBuiltinCall(global, args, environment);
@@ -1392,6 +1436,11 @@ const compileApply = (
1392
1436
  if (definition?.kind === "Function") {
1393
1437
  throw new TlaEvaluationError(`${expression.operator} is a function; apply it with brackets`);
1394
1438
  }
1439
+ if (expression.operator === "\\cdot") {
1440
+ throw new TlaEvaluationError(
1441
+ "The current version of TLC does not support action composition. An incomplete implementation can be enabled via the tlc2.tool.impl.Tool.cdot=true java property.",
1442
+ );
1443
+ }
1395
1444
  throw new TlaEvaluationError(
1396
1445
  `Unknown operator ${expression.operator} at ${describeLocation(expression)}`,
1397
1446
  );
@@ -1487,7 +1536,13 @@ const compileFunctionConstruction = (
1487
1536
  const set = getEvaluator(bound.set, environment);
1488
1537
  return (context) => {
1489
1538
  const domain = isSingleName ? set(context) : getBoundsDomain(bounds, context);
1490
- if (expression.isRecursive || isKeptLazy || !isEnumerable(domain)) {
1539
+ // TLC builds the function only when it reduces every domain, and evaluates the body lazily
1540
+ // otherwise.
1541
+ const domains =
1542
+ typeof domain === "object" && domain.kind === "ProductSet" && bounds.length > 1
1543
+ ? domain.factors
1544
+ : [domain];
1545
+ if (expression.isRecursive || isKeptLazy || !domains.every(isReducible)) {
1491
1546
  const functionValue = createLazyFunction(
1492
1547
  domain,
1493
1548
  (argument) => body(withScope(context, bindArgument(bounds, context.scope, argument))),
@@ -1576,16 +1631,21 @@ const compileSetComprehension = (
1576
1631
  const pattern = expression.bound.pattern;
1577
1632
  return (context) => {
1578
1633
  const base = set(context);
1579
- const test = (element: Value) =>
1634
+ const getTest = (evaluatePredicate: Evaluator) => (element: Value) =>
1580
1635
  expectBoolean(
1581
- predicate(withScope(context, bindPattern(context.scope, pattern, element))),
1636
+ evaluatePredicate(withScope(context, bindPattern(context.scope, pattern, element))),
1582
1637
  "a set filter predicate",
1583
1638
  );
1584
- const isReducible =
1585
- typeof base === "object" &&
1586
- (base.kind === "Set" || base.kind === "MixedSet" || base.kind === "Interval");
1587
- if (!isReducible) {
1588
- if (isSetValue(base)) return { kind: "FilteredSet", base, test };
1639
+ const test = getTest(predicate);
1640
+ if (!isReducible(base)) {
1641
+ if (isSetValue(base)) {
1642
+ const filtered: FilteredSetValue = { kind: "FilteredSet", base, test };
1643
+ filteredSetRetracers.set(filtered, (traced) => ({
1644
+ ...filtered,
1645
+ test: getTest(getEvaluator(expression.predicate, traced)),
1646
+ }));
1647
+ return filtered;
1648
+ }
1589
1649
  throw new TlaEvaluationError(
1590
1650
  `TLC encountered a non-enumerable quantifier bound ${formatValue(base)} at ${describeLocation(expression.bound.set)}`,
1591
1651
  );
@@ -1630,11 +1690,30 @@ const compileSetComprehension = (
1630
1690
  };
1631
1691
  };
1632
1692
 
1633
- const compileRecord = (recordFields: RecordField[], environment: Environment): Evaluator => {
1634
- const fields = [...recordFields].sort((left, right) => compareValues(left.name, right.name));
1635
- const hasDuplicates = fields.some(
1636
- (field, index) => index > 0 && fields[index - 1].name === field.name,
1693
+ // TLC orders a record's fields by name.
1694
+ export const getSortedFields = (fields: RecordField[]) =>
1695
+ [...fields].sort((left, right) => compareValues(left.name, right.name));
1696
+
1697
+ export const hasDuplicateFields = (sortedFields: RecordField[]) =>
1698
+ sortedFields.some((field, index) => index > 0 && sortedFields[index - 1].name === field.name);
1699
+
1700
+ export const createUnassignedError = (name: string, expression: Expression) =>
1701
+ setOwnExitCode(
1702
+ new TlaUnassignedError(
1703
+ `In evaluation, the identifier ${name} is either undefined or not an operator.\n${describeRange(expression)}`,
1704
+ name,
1705
+ ),
1706
+ EXIT_STATUS.configParseError,
1707
+ );
1708
+
1709
+ export const createPrimeOutsideActionError = (expression: Expression) =>
1710
+ new TlaEvaluationError(
1711
+ `A primed expression appears outside an action at ${describeLocation(expression)}`,
1637
1712
  );
1713
+
1714
+ const compileRecord = (recordFields: RecordField[], environment: Environment): Evaluator => {
1715
+ const fields = getSortedFields(recordFields);
1716
+ const hasDuplicates = hasDuplicateFields(fields);
1638
1717
  const values = fields.map((field) => getEvaluator(field.value, environment));
1639
1718
  if (hasDuplicates) {
1640
1719
  return (context) =>
@@ -1712,11 +1791,7 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1712
1791
  case "Prime": {
1713
1792
  const inner = child(expression.expression);
1714
1793
  return (context) => {
1715
- if (!context.next) {
1716
- throw new TlaEvaluationError(
1717
- `A primed expression appears outside an action at ${describeLocation(expression)}`,
1718
- );
1719
- }
1794
+ if (!context.next) throw createPrimeOutsideActionError(expression);
1720
1795
  return inner({
1721
1796
  environment: context.environment,
1722
1797
  scope: context.scope,
@@ -1755,7 +1830,9 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1755
1830
  if (expectBoolean(arm.condition(context), "a CASE guard")) return arm.body(context);
1756
1831
  }
1757
1832
  if (other) return other(context);
1758
- throw new TlaEvaluationError(`No CASE guard is true at ${describeLocation(expression)}`);
1833
+ throw new TlaEvaluationError(
1834
+ `Attempted to evaluate a CASE with no conditions true.\n${describeRange(expression)}`,
1835
+ );
1759
1836
  };
1760
1837
  }
1761
1838
  case "Let": {
@@ -1794,9 +1871,7 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1794
1871
  case "Record":
1795
1872
  return compileRecord(expression.fields, environment);
1796
1873
  case "RecordSet": {
1797
- const fields = [...expression.fields].sort((left, right) =>
1798
- compareValues(left.name, right.name),
1799
- );
1874
+ const fields = getSortedFields(expression.fields);
1800
1875
  const names = fields.map((field) => field.name);
1801
1876
  const sets = fields.map((field) => child(field.value));
1802
1877
  return (context) => ({ kind: "RecordSet", names, sets: sets.map((set) => set(context)) });
@@ -1817,18 +1892,41 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1817
1892
  keepLazy(expression.function);
1818
1893
  const evaluateFunction = child(expression.function);
1819
1894
  const args = expression.args.map(child);
1895
+ const describeNonFunction = getNonFunctionError(expression);
1896
+ if (args.length === 1 && environment.trace) {
1897
+ const argument = args[0];
1898
+ return (context) => {
1899
+ const functionValue = evaluateFunction(context);
1900
+ const argumentValue = argument(context);
1901
+ const apply = () =>
1902
+ applyFunction(functionValue, argumentValue, undefined, describeNonFunction);
1903
+ return isFunctionValue(functionValue) ? withSource(functionValue, apply) : apply();
1904
+ };
1905
+ }
1820
1906
  if (args.length === 1) {
1821
1907
  const argument = args[0];
1822
- return (context) => applyFunction(evaluateFunction(context), argument(context));
1908
+ return (context) =>
1909
+ applyFunction(
1910
+ evaluateFunction(context),
1911
+ argument(context),
1912
+ undefined,
1913
+ describeNonFunction,
1914
+ );
1823
1915
  }
1824
1916
  return (context) =>
1825
- applyFunction(evaluateFunction(context), createTuple(args.map((arg) => arg(context))));
1917
+ applyFunction(
1918
+ evaluateFunction(context),
1919
+ createTuple(args.map((arg) => arg(context))),
1920
+ undefined,
1921
+ describeNonFunction,
1922
+ );
1826
1923
  }
1827
1924
  case "FieldAccess": {
1828
1925
  const record = child(expression.record);
1829
1926
  const field = expression.field;
1830
1927
  const describeMissing = getFieldError(expression);
1831
- return (context) => applyFunction(record(context), field, describeMissing);
1928
+ const describeNonRecord = getNonRecordError(expression);
1929
+ return (context) => applyFunction(record(context), field, describeMissing, describeNonRecord);
1832
1930
  }
1833
1931
  case "Product": {
1834
1932
  const factors = expression.factors.map(child);