tla-ts 0.0.3-dev.037ac3b → 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.
@@ -12,7 +12,13 @@ import {
12
12
  import { BUNDLED_MODULES } from "./bundled-modules";
13
13
  import type { ConfigValue, ModelConfig } from "./config";
14
14
  import type { FileSystem } from "./json";
15
- import { TlaConfigError, TlaEvaluationError, TlaSyntaxError } from "./errors";
15
+ import {
16
+ createSanyError,
17
+ TlaConfigError,
18
+ TlaEvaluationError,
19
+ TlaModuleError,
20
+ TlaSyntaxError,
21
+ } from "./errors";
16
22
  import { EXIT_STATUS, setExitCode } from "./exit-codes";
17
23
  import {
18
24
  createBigNumberError,
@@ -46,7 +52,8 @@ import { createRuntime } from "./runtime";
46
52
  import { CORE_OPERATORS, getStandardModule, STANDARD_DEPENDENCIES } from "./standard-modules";
47
53
  import { resolveInstanceSubexpressions, resolveModuleSubexpressions } from "./subexpressions";
48
54
  import { checkModuleLevels, createLevelAnalyzer } from "./levels";
49
- import { checkInstances, type InstanceCheck } from "./substitution-levels";
55
+ import { createInstanceChecker, type InstanceCheck } from "./substitution-levels";
56
+ import { getTlcDeclarationOrder } from "./tlc-order";
50
57
  import {
51
58
  checkInteger,
52
59
  createModelValue,
@@ -222,6 +229,8 @@ export const createEnvironment = (
222
229
  const runtime = createRuntime(config.checkDeadlock, options.seed);
223
230
  const linkedModules = new Map<string, LinkedModule>();
224
231
  const nestedModules = new Map<string, LinkedModule>();
232
+ // Each module by name, from the time its level checks run.
233
+ const checkedModules = new Map<string, LinkedModule>();
225
234
  const linkedList: LinkedModule[] = [];
226
235
  const dependencies = new Map<string, Set<string>>();
227
236
  const loading: Set<string>[] = [];
@@ -236,7 +245,23 @@ export const createEnvironment = (
236
245
  const copyCount = { value: 0 };
237
246
  const createName = (name: string) => `${name}#${copyCount.value++}`;
238
247
  const instanceChecks: InstanceCheck[] = [];
248
+ const checkInstance = createInstanceChecker((name) => {
249
+ const linked = checkedModules.get(name) ?? getLinkedModule(name, name);
250
+ return {
251
+ constants: linked.constants,
252
+ variables: linked.variables,
253
+ definitions: [
254
+ ...new Set(
255
+ [...linked.visible.values()].flatMap((symbol) => definitions.get(symbol.key) ?? []),
256
+ ),
257
+ ],
258
+ assumptions: linked.module.assumptions.map((assumption) => assumption.expression),
259
+ theorems: linked.module.theorems,
260
+ getDefinition: (symbol) => definitions.get(linked.visible.get(symbol)?.key ?? symbol),
261
+ };
262
+ });
239
263
  const instanceActions = new Map<string, InstanceAction>();
264
+ const qualifiedNames = new Map<string, string>();
240
265
 
241
266
  const addStandardModule = (name: string): Symbols | undefined => {
242
267
  const cached = standardExports.get(name);
@@ -259,7 +284,11 @@ export const createEnvironment = (
259
284
 
260
285
  const getStandardSymbols = (name: string) => {
261
286
  const symbols = addStandardModule(name);
262
- if (symbols) useModule(name, STANDARD_DEPENDENCIES.get(name) ?? []);
287
+ const dependencies = STANDARD_DEPENDENCIES.get(name) ?? [];
288
+ if (symbols) useModule(name, dependencies);
289
+ // TLC loads the Java class of each module a standard module uses, so one that uses Integers
290
+ // overrides the arithmetic of Naturals.
291
+ if (symbols && dependencies.includes("Integers")) addStandardModule("Integers");
263
292
  return symbols;
264
293
  };
265
294
 
@@ -288,13 +317,25 @@ export const createEnvironment = (
288
317
  BUNDLED_MODULES.get(name) ??
289
318
  extractModule(options.source, name);
290
319
  if (source === undefined)
291
- throw new TlaSyntaxError(
292
- `Cannot find source file for module ${name} imported in module ${importer}.`,
320
+ throw createSanyError(
321
+ [
322
+ {
323
+ location: `In module ${importer}`,
324
+ message: `Cannot find source file for module ${name} imported in module ${importer}.`,
325
+ },
326
+ ],
327
+ true,
293
328
  );
294
329
  const module = parseModule(source);
295
330
  if (module.name !== name) {
296
- throw new TlaSyntaxError(
297
- `File name '${name}' does not match the name '${module.name}' of the top level module it contains.`,
331
+ throw createSanyError(
332
+ [
333
+ {
334
+ location: "Unknown location",
335
+ message: `File name '${name}' does not match the name '${module.name}' of the top level module it contains.`,
336
+ },
337
+ ],
338
+ true,
298
339
  );
299
340
  }
300
341
  return rejectModuleLiterals(module);
@@ -406,6 +447,7 @@ export const createEnvironment = (
406
447
  if (declarations.length > 0) {
407
448
  instanceActions.set(key, { name: `${instance.name}!${name}`, location: instance.location });
408
449
  }
450
+ qualifiedNames.set(key, `${instance.name}!${name}`);
409
451
  symbols.set(`${instance.name}!${name}`, {
410
452
  key,
411
453
  arity: symbol.arity + instance.params.length,
@@ -586,6 +628,7 @@ export const createEnvironment = (
586
628
 
587
629
  const linkModule = (unlinked: Module, scope: ModuleScope): LinkedModule => {
588
630
  const parsed = overrideDefinitions(unlinked, options.loadClass?.(unlinked.name));
631
+ const firstCheck = instanceChecks.length;
589
632
  const visible: Symbols = new Map([
590
633
  ...CORE_OPERATORS.map((operator): [string, ModuleSymbol] => [
591
634
  operator.name,
@@ -728,11 +771,6 @@ export const createEnvironment = (
728
771
  visible.set(definition.name, symbol);
729
772
  if (!definition.isLocal) exported.set(definition.name, symbol);
730
773
  });
731
- checkModuleLevels(module, {
732
- constants: new Set(constants.map((constant) => constant.name)),
733
- variables: new Set(variables),
734
- getDefinition: (symbol) => definitions.get(visible.get(symbol)?.key ?? symbol),
735
- });
736
774
  const linked = {
737
775
  module,
738
776
  constants,
@@ -743,6 +781,21 @@ export const createEnvironment = (
743
781
  modules,
744
782
  extended,
745
783
  };
784
+ if (!checkedModules.has(parsed.name)) checkedModules.set(parsed.name, linked);
785
+ // SANY checks the instances of a module with its definitions and theorems, so it reports their
786
+ // errors together.
787
+ checkModuleLevels(
788
+ module,
789
+ {
790
+ constants: new Set(constants.map((constant) => constant.name)),
791
+ variables: new Set(variables),
792
+ getDefinition: (symbol) => definitions.get(visible.get(symbol)?.key ?? symbol),
793
+ getQualifiedName: (symbol) => qualifiedNames.get(visible.get(symbol)?.key ?? symbol),
794
+ },
795
+ instanceChecks
796
+ .splice(firstCheck)
797
+ .map((check) => ({ location: check.location, check: () => checkInstance(check) })),
798
+ );
746
799
  linkedList.push(linked);
747
800
  return linked;
748
801
  };
@@ -908,11 +961,19 @@ export const createEnvironment = (
908
961
  if (symbol.key === key && name !== key) definitions.set(name, alias);
909
962
  });
910
963
  });
911
- declaredConstants.forEach((name) => {
912
- if (!constants.has(name) && !substitutions.has(name) && !operatorKeys.has(name)) {
913
- throw new TlaConfigError(`The constant ${name} is not assigned a value by the configuration`);
914
- }
915
- });
964
+ const unassigned = declaredConstants.filter(
965
+ (name) => !constants.has(name) && !substitutions.has(name) && !operatorKeys.has(name),
966
+ );
967
+ if (unassigned.length > 0) {
968
+ // TLC reports the first constant it finds unassigned in SANY's order of declarations.
969
+ const name =
970
+ getTlcDeclarationOrder(options.source, options.loadModule, "constant").find((constant) =>
971
+ unassigned.includes(constant),
972
+ ) ?? unassigned[0];
973
+ throw new TlaConfigError(
974
+ `The constant parameter ${name} is not assigned a value by the configuration file.`,
975
+ );
976
+ }
916
977
 
917
978
  const environment: Environment = {
918
979
  runtime,
@@ -929,20 +990,6 @@ export const createEnvironment = (
929
990
  constantLevels: new Map(),
930
991
  evaluators: new WeakMap(),
931
992
  };
932
- checkInstances(instanceChecks, (name) => {
933
- const linked = linkedModules.get(name) ?? nestedModules.get(name) ?? linkedRoot;
934
- return {
935
- constants: linked.constants,
936
- variables: linked.variables,
937
- definitions: [
938
- ...new Set(
939
- [...linked.visible.values()].flatMap((symbol) => definitions.get(symbol.key) ?? []),
940
- ),
941
- ],
942
- assumptions: linked.module.assumptions.map((assumption) => assumption.expression),
943
- getDefinition: (symbol) => definitions.get(linked.visible.get(symbol)?.key ?? symbol),
944
- };
945
- });
946
993
  // TLC evaluates a substitute at startup and rejects it only when that fails and the level bound it
947
994
  // computes is above constant. The bound counts the operators that TLC's Java code overrides with
948
995
  // a minimum level as state-level, so the analyzer takes them for variables.
@@ -954,26 +1001,28 @@ export const createEnvironment = (
954
1001
  ]),
955
1002
  getDefinition: (name) => getDefinition(name, environment),
956
1003
  });
957
- const isEvaluable = (body: Expression) => {
1004
+ const getEvaluationError = (body: Expression) => {
958
1005
  try {
959
1006
  evaluate(body, { environment, scope: undefined, state: undefined, next: undefined });
960
- return true;
1007
+ return undefined;
961
1008
  } catch (error) {
962
- if (error instanceof TlaEvaluationError) return false;
1009
+ if (error instanceof TlaEvaluationError) return error;
963
1010
  throw error;
964
1011
  }
965
1012
  };
966
1013
  substitutions.forEach((target, name) => {
967
1014
  const definition = definitions.get(target);
968
- if (
1015
+ const error =
969
1016
  declaredConstants.includes(name) &&
970
1017
  definition?.kind === "Operator" &&
971
1018
  definition.params.length === 0 &&
972
- analyzer.analyzeDefinition(definition, new Map()).level > 0 &&
973
- !isEvaluable(definition.body)
974
- ) {
1019
+ analyzer.analyzeDefinition(definition, new Map()).level > 0
1020
+ ? getEvaluationError(definition.body)
1021
+ : undefined;
1022
+ // TLC adds the reason unless a standard module's Java code failed.
1023
+ if (error) {
975
1024
  throw new TlaConfigError(
976
- `The configuration file substitutes constant ${name} with non-constant ${target}`,
1025
+ `The configuration file substitutes constant ${name} with non-constant ${target}${error instanceof TlaModuleError ? "" : ` - specifically: ${error.message}`}`,
977
1026
  );
978
1027
  }
979
1028
  });
package/src/errors.ts CHANGED
@@ -1,10 +1,19 @@
1
+ import type { SourceRange } from "./ast";
1
2
  import { EXIT_STATUS, getExitCode } from "./exit-codes";
3
+ import type { Value } from "./values";
2
4
 
3
5
  // How TLC reports a RuntimeException it did not expect, such as one raised while computing next
4
6
  // states.
5
7
  export const UNEXPECTED_EXCEPTION =
6
8
  "TLC threw an unexpected exception.\nThis was probably caused by an error in the spec or model.\nSee the User Output or TLC Console for clues to what happened.\nThe exception was a java.lang.RuntimeException\n: ";
7
9
 
10
+ // How TLC reports a Java StackOverflowError, which V8 raises as this RangeError.
11
+ export const STACK_OVERFLOW =
12
+ "This was a Java StackOverflowError. It was probably the result\nof an incorrect recursive function definition that caused TLC to enter\nan infinite loop when trying to compute the function or its application\nto an element in its putative domain.";
13
+
14
+ export const isStackOverflow = (error: unknown) =>
15
+ error instanceof RangeError && error.message === "Maximum call stack size exceeded";
16
+
8
17
  export class TlaError extends Error {
9
18
  constructor(message: string, cause?: unknown) {
10
19
  super(message, { cause });
@@ -19,16 +28,44 @@ export interface SyntaxFailure {
19
28
  isEnd: boolean;
20
29
  }
21
30
 
31
+ // An error SANY reports at a location, such as "In module M" or a range in a module.
32
+ export interface SanyError {
33
+ location: string;
34
+ message: string;
35
+ }
36
+
37
+ // The errors SANY reports for a spec. A fatal error stops it before semantic analysis.
38
+ export interface SanyReport {
39
+ errors: SanyError[];
40
+ isFatal: boolean;
41
+ }
42
+
22
43
  export class TlaSyntaxError extends TlaError {
23
44
  failure: SyntaxFailure | undefined;
45
+ sany: SanyReport | undefined;
24
46
 
25
- constructor(message: string, cause?: unknown, failure?: SyntaxFailure) {
47
+ constructor(message: string, cause?: unknown, failure?: SyntaxFailure, sany?: SanyReport) {
26
48
  super(message, cause);
27
49
  this.name = "TlaSyntaxError";
28
50
  this.failure = failure;
51
+ this.sany = sany;
29
52
  }
30
53
  }
31
54
 
55
+ export const createSanyError = (errors: SanyError[], isFatal = false) =>
56
+ new TlaSyntaxError(
57
+ errors.map((error) => `${error.location}\n\n${error.message}`).join("\n\n"),
58
+ undefined,
59
+ undefined,
60
+ { errors, isFatal },
61
+ );
62
+
63
+ export const formatRange = (range: SourceRange) =>
64
+ `line ${range.start.line}, col ${range.start.column} to line ${range.end.line}, col ${range.end.column} of module ${range.module}`;
65
+
66
+ export const createSemanticError = (message: string, range: SourceRange) =>
67
+ createSanyError([{ location: formatRange(range), message }]);
68
+
32
69
  export class TlaConfigError extends TlaError {
33
70
  constructor(message: string, cause?: unknown) {
34
71
  super(message, cause);
@@ -55,6 +92,46 @@ export class TlaModuleError extends TlaEvaluationError {
55
92
  }
56
93
  }
57
94
 
95
+ // A variable that a partial state leaves without a value.
96
+ export class TlaUnassignedError extends TlaEvaluationError {
97
+ variable: string;
98
+
99
+ constructor(message: string, variable: string) {
100
+ super(message);
101
+ this.name = "TlaEvaluationError";
102
+ this.variable = variable;
103
+ }
104
+ }
105
+
106
+ // TLC reports a successor state that the next-state relation leaves incomplete as an error of its
107
+ // own, not as an exception. It keeps the name TlaEvaluationError, and index.ts doesn't export it.
108
+ export class TlaIncompleteStateError extends TlaEvaluationError {
109
+ state: (Value | undefined)[];
110
+ action: string | undefined;
111
+ missing: string[];
112
+
113
+ constructor(state: (Value | undefined)[], action: string | undefined, missing: string[]) {
114
+ super(
115
+ `Successor state is not completely specified by the next-state action. The following variable${missing.length > 1 ? "s are" : " is"} not defined: ${missing.join(", ")}.\n`,
116
+ );
117
+ this.name = "TlaEvaluationError";
118
+ this.state = state;
119
+ this.action = action;
120
+ this.missing = missing;
121
+ }
122
+ }
123
+
124
+ // TLC reports an initial state that the initial predicate leaves incomplete as an illegal state.
125
+ export class TlaIllegalStateError extends TlaEvaluationError {
126
+ state: (Value | undefined)[];
127
+
128
+ constructor(state: (Value | undefined)[]) {
129
+ super("current state is not a legal state");
130
+ this.name = "TlaEvaluationError";
131
+ this.state = state;
132
+ }
133
+ }
134
+
58
135
  export interface TlapmReport {
59
136
  failure?: string;
60
137
  exception?: string;
package/src/evaluate.ts CHANGED
@@ -10,16 +10,16 @@ import {
10
10
  type NumberExpression,
11
11
  type OperatorParam,
12
12
  type RecordField,
13
- type SourceRange,
14
13
  } from "./ast";
15
14
  import { getKindString } from "./builtins";
16
- import { TlaEvaluationError } from "./errors";
17
- import { EXIT_STATUS, setExitCode } from "./exit-codes";
15
+ import { formatRange, TlaEvaluationError, TlaUnassignedError } from "./errors";
16
+ import { EXIT_STATUS, setExitCode, setOwnExitCode } from "./exit-codes";
18
17
  import { generateEvaluator } from "./codegen";
19
18
  import type { CheckerRuntime } from "./runtime";
20
19
  import { getReadVariables } from "./dependencies";
21
20
  import { contextualApplications, mapChildren, substitutedExpressions } from "./instances";
22
21
  import { isEnabled } from "./successors";
22
+ import { getFingerprintTrace, valueSources, withSource } from "./value-sources";
23
23
  import {
24
24
  applyFunction,
25
25
  combineHash,
@@ -30,14 +30,17 @@ import {
30
30
  createSortedSet,
31
31
  createWrittenRecord,
32
32
  createTuple,
33
+ describeMissingField,
33
34
  formatValue,
34
35
  getDomain,
35
36
  getFunctionDomain,
36
37
  getIntervalElements,
38
+ getLazySubsets,
37
39
  getSequenceElements,
38
40
  getValueHash,
39
41
  isFunctionValue,
40
42
  isOverriddenSet,
43
+ isRecordValue,
41
44
  isSameValue,
42
45
  markLambdaFunction,
43
46
  isReducible,
@@ -47,6 +50,8 @@ import {
47
50
  toFiniteSet,
48
51
  updateFunction,
49
52
  valuesEqual,
53
+ type FilteredSetValue,
54
+ type FunctionValue,
50
55
  type LazyFunctionSource,
51
56
  type LazyFunctionValue,
52
57
  type Value,
@@ -114,6 +119,7 @@ export interface Environment {
114
119
  definitionValues: Map<Definition, Value>;
115
120
  constantLevels: Map<Definition, boolean>;
116
121
  evaluators: WeakMap<Expression, Evaluator>;
122
+ trace?: Expression[];
117
123
  }
118
124
 
119
125
  export interface Context {
@@ -143,9 +149,6 @@ const EXCEPT_AT = "@";
143
149
  export const describeLocation = (expression: Expression) =>
144
150
  `line ${expression.location.line}, column ${expression.location.column}`;
145
151
 
146
- export const formatRange = (range: SourceRange) =>
147
- `line ${range.start.line}, col ${range.start.column} to line ${range.end.line}, col ${range.end.column} of module ${range.module}`;
148
-
149
152
  export const describeRange = (expression: Expression) => {
150
153
  const range = expression.location.range;
151
154
  return range ? formatRange(range) : describeLocation(expression);
@@ -182,8 +185,17 @@ export const getConjunctError = (
182
185
  };
183
186
 
184
187
  export const getFieldError =
185
- (expression: Expression & { kind: "FieldAccess" }) => (record: Value) =>
186
- `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)}`;
187
199
 
188
200
  export const getDomainOperator = (expression: Expression) => (value: Value) => {
189
201
  if (!isFunctionValue(value)) {
@@ -331,9 +343,8 @@ export const getEnumeratedElements = (set: Value, expression: Expression) => {
331
343
  : `TLC encountered the non-enumerable quantifier bound\n${text}\n${describeRange(expression)}\n${explanation}`,
332
344
  );
333
345
  }
334
- return typeof set === "object" && set.kind === "Interval"
335
- ? getIntervalElements(set)
336
- : toFiniteSet(set).elements;
346
+ if (typeof set === "object" && set.kind === "Interval") return getIntervalElements(set);
347
+ return getLazySubsets(set) ?? toFiniteSet(set).elements;
337
348
  };
338
349
 
339
350
  export const forEachBinding = (
@@ -1011,16 +1022,80 @@ const isStateCached = (expression: Expression, environment: Environment) =>
1011
1022
  getReadVariables(expression, environment) !== undefined &&
1012
1023
  !hasFreeLocals(expression, NO_BOUND_NAMES);
1013
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
+
1014
1070
  export const getEvaluator = (expression: Expression, environment: Environment): Evaluator => {
1015
1071
  const cached = environment.evaluators.get(expression);
1016
1072
  if (cached) return cached;
1017
1073
  const compiled = compile(expression, environment);
1018
- const evaluator =
1074
+ const cachedEvaluator =
1019
1075
  isWorthCaching(expression) && isClosedConstant(expression, environment)
1020
1076
  ? cacheFirstValue(compiled)
1021
1077
  : isStateCached(expression, environment)
1022
1078
  ? cacheStateValue(compiled)
1023
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;
1024
1099
  environment.evaluators.set(expression, evaluator);
1025
1100
  return evaluator;
1026
1101
  };
@@ -1028,6 +1103,7 @@ export const getEvaluator = (expression: Expression, environment: Environment):
1028
1103
  const entryEvaluators = new WeakMap<Expression, Evaluator>();
1029
1104
 
1030
1105
  export const getEntryEvaluator = (expression: Expression, environment: Environment) => {
1106
+ if (environment.trace) return getEvaluator(expression, environment);
1031
1107
  const cached = entryEvaluators.get(expression);
1032
1108
  if (cached) return cached;
1033
1109
  const evaluator =
@@ -1136,11 +1212,32 @@ const getLazyArguments = (args: Expression[], context: Context): OperatorValue[]
1136
1212
  expression: arg,
1137
1213
  }));
1138
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
+
1139
1225
  const compileBuiltinCall = (
1140
1226
  builtin: Builtin,
1141
1227
  args: Expression[],
1142
1228
  environment: Environment,
1143
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
+ }
1144
1241
  if (builtin.isLazy) {
1145
1242
  return (context) => builtin.evaluate(getLazyArguments(args, context), context);
1146
1243
  }
@@ -1300,6 +1397,13 @@ const compileApply = (
1300
1397
  if (global?.kind === "Builtin" && global.name === "DOMAIN") {
1301
1398
  const operand = getEvaluator(args[0], environment);
1302
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
+ }
1303
1407
  return (context) => domain(operand(context));
1304
1408
  }
1305
1409
  // TLC sorts the value of a constant TLCEval argument only where no context binds a name.
@@ -1315,6 +1419,13 @@ const compileApply = (
1315
1419
  const left = getEvaluator(args[0], environment);
1316
1420
  const right = getEvaluator(args[1], environment);
1317
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
+ }
1318
1429
  return (context) => subset(left(context), right(context));
1319
1430
  }
1320
1431
  if (global?.kind === "Builtin") return compileBuiltinCall(global, args, environment);
@@ -1325,6 +1436,11 @@ const compileApply = (
1325
1436
  if (definition?.kind === "Function") {
1326
1437
  throw new TlaEvaluationError(`${expression.operator} is a function; apply it with brackets`);
1327
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
+ }
1328
1444
  throw new TlaEvaluationError(
1329
1445
  `Unknown operator ${expression.operator} at ${describeLocation(expression)}`,
1330
1446
  );
@@ -1515,13 +1631,21 @@ const compileSetComprehension = (
1515
1631
  const pattern = expression.bound.pattern;
1516
1632
  return (context) => {
1517
1633
  const base = set(context);
1518
- const test = (element: Value) =>
1634
+ const getTest = (evaluatePredicate: Evaluator) => (element: Value) =>
1519
1635
  expectBoolean(
1520
- predicate(withScope(context, bindPattern(context.scope, pattern, element))),
1636
+ evaluatePredicate(withScope(context, bindPattern(context.scope, pattern, element))),
1521
1637
  "a set filter predicate",
1522
1638
  );
1639
+ const test = getTest(predicate);
1523
1640
  if (!isReducible(base)) {
1524
- if (isSetValue(base)) return { kind: "FilteredSet", base, test };
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
+ }
1525
1649
  throw new TlaEvaluationError(
1526
1650
  `TLC encountered a non-enumerable quantifier bound ${formatValue(base)} at ${describeLocation(expression.bound.set)}`,
1527
1651
  );
@@ -1574,7 +1698,13 @@ export const hasDuplicateFields = (sortedFields: RecordField[]) =>
1574
1698
  sortedFields.some((field, index) => index > 0 && sortedFields[index - 1].name === field.name);
1575
1699
 
1576
1700
  export const createUnassignedError = (name: string, expression: Expression) =>
1577
- new TlaEvaluationError(`The variable ${name} is not assigned at ${describeLocation(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
+ );
1578
1708
 
1579
1709
  export const createPrimeOutsideActionError = (expression: Expression) =>
1580
1710
  new TlaEvaluationError(
@@ -1762,18 +1892,41 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1762
1892
  keepLazy(expression.function);
1763
1893
  const evaluateFunction = child(expression.function);
1764
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
+ }
1765
1906
  if (args.length === 1) {
1766
1907
  const argument = args[0];
1767
- return (context) => applyFunction(evaluateFunction(context), argument(context));
1908
+ return (context) =>
1909
+ applyFunction(
1910
+ evaluateFunction(context),
1911
+ argument(context),
1912
+ undefined,
1913
+ describeNonFunction,
1914
+ );
1768
1915
  }
1769
1916
  return (context) =>
1770
- 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
+ );
1771
1923
  }
1772
1924
  case "FieldAccess": {
1773
1925
  const record = child(expression.record);
1774
1926
  const field = expression.field;
1775
1927
  const describeMissing = getFieldError(expression);
1776
- return (context) => applyFunction(record(context), field, describeMissing);
1928
+ const describeNonRecord = getNonRecordError(expression);
1929
+ return (context) => applyFunction(record(context), field, describeMissing, describeNonRecord);
1777
1930
  }
1778
1931
  case "Product": {
1779
1932
  const factors = expression.factors.map(child);