tla-ts 0.0.3-dev.e927a09 → 0.0.3-dev.e9c5857

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 (47) hide show
  1. package/README.md +5 -1
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +52 -22
  4. package/dist/index.d.ts +52 -22
  5. package/dist/index.js +1 -1
  6. package/dist/parallel-worker.cjs +1 -1
  7. package/dist/parallel-worker.js +2 -2
  8. package/dist/parallel.cjs +1 -1
  9. package/dist/parallel.js +2 -2
  10. package/dist/run-cli.cjs +19 -17
  11. package/dist/run-cli.js +20 -18
  12. package/dist/transfer.cjs +32 -15
  13. package/dist/transfer.js +32 -15
  14. package/package.json +1 -1
  15. package/src/ast.ts +3 -0
  16. package/src/check.ts +419 -68
  17. package/src/cli-options.ts +11 -5
  18. package/src/codegen.ts +6 -3
  19. package/src/config.ts +224 -170
  20. package/src/environment.ts +106 -18
  21. package/src/errors.ts +71 -3
  22. package/src/evaluate.ts +178 -23
  23. package/src/exit-codes.ts +21 -14
  24. package/src/instances.ts +4 -4
  25. package/src/levels.ts +55 -27
  26. package/src/live-check.ts +132 -70
  27. package/src/liveness.ts +117 -22
  28. package/src/parallel-worker.ts +2 -2
  29. package/src/parallel.ts +5 -2
  30. package/src/parser.ts +21 -10
  31. package/src/resolve.ts +106 -29
  32. package/src/run-cli.ts +90 -17
  33. package/src/runtime.ts +2 -0
  34. package/src/spec-description.ts +12 -6
  35. package/src/standard-modules.ts +10 -9
  36. package/src/state-graph.ts +157 -0
  37. package/src/successors.ts +131 -28
  38. package/src/symmetry.ts +16 -6
  39. package/src/tableau.ts +51 -24
  40. package/src/tlc-ext.ts +27 -2
  41. package/src/tlc-module.ts +14 -33
  42. package/src/tlc-modules.ts +4 -0
  43. package/src/tlc-order.ts +8 -4
  44. package/src/tlc-random.ts +9 -6
  45. package/src/tlc-summary.ts +20 -5
  46. package/src/value-sources.ts +29 -0
  47. package/src/values.ts +172 -53
@@ -12,12 +12,19 @@ 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,
19
25
  createRealNumberError,
20
- isConstantLevel,
26
+ evaluate,
27
+ getDefinition,
21
28
  isTlcInteger,
22
29
  type Builtin,
23
30
  type Environment,
@@ -44,8 +51,9 @@ import {
44
51
  import { createRuntime } from "./runtime";
45
52
  import { CORE_OPERATORS, getStandardModule, STANDARD_DEPENDENCIES } from "./standard-modules";
46
53
  import { resolveInstanceSubexpressions, resolveModuleSubexpressions } from "./subexpressions";
47
- import { checkModuleLevels } from "./levels";
54
+ import { checkModuleLevels, createLevelAnalyzer } from "./levels";
48
55
  import { checkInstances, type InstanceCheck } from "./substitution-levels";
56
+ import { getTlcDeclarationOrder } from "./tlc-order";
49
57
  import {
50
58
  checkInteger,
51
59
  createModelValue,
@@ -212,6 +220,8 @@ export const createEnvironment = (
212
220
  const root = parseModule(options.source);
213
221
  const definitions = new Map<string, Definition>();
214
222
  const parameterized = new Map<string, boolean>();
223
+ // The definition each instance copy came from, and the instance parameters the copy adds.
224
+ const copySources = new Map<string, { source: string; prefix: number }>();
215
225
  const builtins = new Map<string, Builtin>(
216
226
  CORE_OPERATORS.map((operator) => [operator.name, operator]),
217
227
  );
@@ -285,13 +295,25 @@ export const createEnvironment = (
285
295
  BUNDLED_MODULES.get(name) ??
286
296
  extractModule(options.source, name);
287
297
  if (source === undefined)
288
- throw new TlaSyntaxError(
289
- `Cannot find source file for module ${name} imported in module ${importer}.`,
298
+ throw createSanyError(
299
+ [
300
+ {
301
+ location: `In module ${importer}`,
302
+ message: `Cannot find source file for module ${name} imported in module ${importer}.`,
303
+ },
304
+ ],
305
+ true,
290
306
  );
291
307
  const module = parseModule(source);
292
308
  if (module.name !== name) {
293
- throw new TlaSyntaxError(
294
- `File name '${name}' does not match the name '${module.name}' of the top level module it contains.`,
309
+ throw createSanyError(
310
+ [
311
+ {
312
+ location: "Unknown location",
313
+ message: `File name '${name}' does not match the name '${module.name}' of the top level module it contains.`,
314
+ },
315
+ ],
316
+ true,
295
317
  );
296
318
  }
297
319
  return rejectModuleLiterals(module);
@@ -379,10 +401,11 @@ export const createEnvironment = (
379
401
  variables: new Set(linked.variables),
380
402
  getDefinition: (key) => definitions.get(key),
381
403
  isParameterized: (key) => parameterized.get(key) === true,
382
- addDefinition: (name, create) => {
404
+ addDefinition: (source, name, create) => {
383
405
  const key = createName(`${name}@${module.name}`);
384
406
  definitions.set(key, create(key));
385
407
  parameterized.set(key, !isParameterFree);
408
+ copySources.set(key, { source, prefix: instance.params.length });
386
409
  return key;
387
410
  },
388
411
  createName,
@@ -544,7 +567,7 @@ export const createEnvironment = (
544
567
  variables: new Set(linked.variables),
545
568
  getDefinition: (key) => definitions.get(key),
546
569
  isParameterized: (key) => parameterized.get(key) === true,
547
- addDefinition: (name, create) => {
570
+ addDefinition: (_source, name, create) => {
548
571
  const key = `${name}${KEY_SEPARATOR}${instance.module}${suffix}.${copies.length}`;
549
572
  const definition = create(key);
550
573
  copies.push(
@@ -872,11 +895,51 @@ export const createEnvironment = (
872
895
  );
873
896
  }
874
897
  });
875
- declaredConstants.forEach((name) => {
876
- if (!constants.has(name) && !substitutions.has(name) && !operatorKeys.has(name)) {
877
- throw new TlaConfigError(`The constant ${name} is not assigned a value by the configuration`);
878
- }
898
+ // TLC sets a module-scoped entry on the body of the module's definition, which every instance of
899
+ // the module shares.
900
+ const scopedKeys = new Set(
901
+ [...config.constants, ...config.substitutions]
902
+ .filter((item) => item.module !== undefined)
903
+ .flatMap(getScopedKeys),
904
+ );
905
+ const getOverride = (
906
+ key: string,
907
+ prefix: number,
908
+ ): { key: string; prefix: number } | undefined => {
909
+ if (scopedKeys.has(key)) return { key, prefix };
910
+ const copy = copySources.get(key);
911
+ return copy && getOverride(copy.source, prefix + copy.prefix);
912
+ };
913
+ copySources.forEach((copy, key) => {
914
+ const override = getOverride(copy.source, copy.prefix);
915
+ const definition = definitions.get(key);
916
+ if (!override || !definition) return;
917
+ const params = definition.kind === "Operator" ? definition.params : [];
918
+ const alias = createLocalAlias(
919
+ key,
920
+ override.key,
921
+ params,
922
+ params.slice(override.prefix),
923
+ definition.location,
924
+ );
925
+ definitions.set(key, alias);
926
+ linkedRoot.visible.forEach((symbol, name) => {
927
+ if (symbol.key === key && name !== key) definitions.set(name, alias);
928
+ });
879
929
  });
930
+ const unassigned = declaredConstants.filter(
931
+ (name) => !constants.has(name) && !substitutions.has(name) && !operatorKeys.has(name),
932
+ );
933
+ if (unassigned.length > 0) {
934
+ // TLC reports the first constant it finds unassigned in SANY's order of declarations.
935
+ const name =
936
+ getTlcDeclarationOrder(options.source, options.loadModule, "constant").find((constant) =>
937
+ unassigned.includes(constant),
938
+ ) ?? unassigned[0];
939
+ throw new TlaConfigError(
940
+ `The constant parameter ${name} is not assigned a value by the configuration file.`,
941
+ );
942
+ }
880
943
 
881
944
  const environment: Environment = {
882
945
  runtime,
@@ -907,18 +970,43 @@ export const createEnvironment = (
907
970
  getDefinition: (symbol) => definitions.get(linked.visible.get(symbol)?.key ?? symbol),
908
971
  };
909
972
  });
973
+ // TLC evaluates a substitute at startup and rejects it only when that fails and the level bound it
974
+ // computes is above constant. The bound counts the operators that TLC's Java code overrides with
975
+ // a minimum level as state-level, so the analyzer takes them for variables.
976
+ const analyzer = createLevelAnalyzer({
977
+ constants: new Set(constants.keys()),
978
+ variables: new Set([
979
+ ...variables,
980
+ ...["TLCGet", "Trace", "CounterExample"].filter((name) => builtins.has(name)),
981
+ ]),
982
+ getDefinition: (name) => getDefinition(name, environment),
983
+ });
984
+ const getEvaluationError = (body: Expression) => {
985
+ try {
986
+ evaluate(body, { environment, scope: undefined, state: undefined, next: undefined });
987
+ return undefined;
988
+ } catch (error) {
989
+ if (error instanceof TlaEvaluationError) return error;
990
+ throw error;
991
+ }
992
+ };
910
993
  substitutions.forEach((target, name) => {
911
994
  const definition = definitions.get(target);
912
- if (
995
+ const error =
913
996
  declaredConstants.includes(name) &&
914
- definition &&
915
- !isConstantLevel(definition, environment)
916
- ) {
997
+ definition?.kind === "Operator" &&
998
+ definition.params.length === 0 &&
999
+ analyzer.analyzeDefinition(definition, new Map()).level > 0
1000
+ ? getEvaluationError(definition.body)
1001
+ : undefined;
1002
+ // TLC adds the reason unless a standard module's Java code failed.
1003
+ if (error) {
917
1004
  throw new TlaConfigError(
918
- `The configuration file substitutes constant ${name} with non-constant ${target}`,
1005
+ `The configuration file substitutes constant ${name} with non-constant ${target}${error instanceof TlaModuleError ? "" : ` - specifically: ${error.message}`}`,
919
1006
  );
920
1007
  }
921
1008
  });
1009
+ runtime.isStarted = true;
922
1010
  return {
923
1011
  environment,
924
1012
  assumptions,
package/src/errors.ts CHANGED
@@ -1,10 +1,19 @@
1
- import { EXIT_STATUS, getExitCode, setModuleExitCode } from "./exit-codes";
1
+ import type { SourceRange } from "./ast";
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);
@@ -46,10 +83,41 @@ export class TlaEvaluationError extends TlaError {
46
83
  // An evaluation error that TLC raises as an EvalException from a standard module's Java code. It
47
84
  // keeps the name TlaEvaluationError, and index.ts doesn't export it.
48
85
  export class TlaModuleError extends TlaEvaluationError {
86
+ exitCode: number;
87
+
49
88
  constructor(message: string, exitCode: number = EXIT_STATUS.error) {
50
89
  super(message);
51
90
  this.name = "TlaEvaluationError";
52
- setModuleExitCode(this, exitCode);
91
+ this.exitCode = exitCode;
92
+ }
93
+ }
94
+
95
+ // TLC reports a successor state that the next-state relation leaves incomplete as an error of its
96
+ // own, not as an exception. It keeps the name TlaEvaluationError, and index.ts doesn't export it.
97
+ export class TlaIncompleteStateError extends TlaEvaluationError {
98
+ state: (Value | undefined)[];
99
+ action: string | undefined;
100
+ missing: string[];
101
+
102
+ constructor(state: (Value | undefined)[], action: string | undefined, missing: string[]) {
103
+ super(
104
+ `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`,
105
+ );
106
+ this.name = "TlaEvaluationError";
107
+ this.state = state;
108
+ this.action = action;
109
+ this.missing = missing;
110
+ }
111
+ }
112
+
113
+ // TLC reports an initial state that the initial predicate leaves incomplete as an illegal state.
114
+ export class TlaIllegalStateError extends TlaEvaluationError {
115
+ state: (Value | undefined)[];
116
+
117
+ constructor(state: (Value | undefined)[]) {
118
+ super("current state is not a legal state");
119
+ this.name = "TlaEvaluationError";
120
+ this.state = state;
53
121
  }
54
122
  }
55
123
 
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 } 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,23 +30,27 @@ import {
30
30
  createSortedSet,
31
31
  createWrittenRecord,
32
32
  createTuple,
33
+ describeMissingField,
33
34
  formatValue,
34
35
  getDomain,
35
36
  getFunctionDomain,
36
37
  getIntervalElements,
37
38
  getSequenceElements,
38
39
  getValueHash,
39
- isEnumerable,
40
40
  isFunctionValue,
41
41
  isOverriddenSet,
42
+ isRecordValue,
42
43
  isSameValue,
43
44
  markLambdaFunction,
45
+ isReducible,
44
46
  isSetValue,
45
47
  MAXIMUM_INTEGER,
46
48
  MINIMUM_INTEGER,
47
49
  toFiniteSet,
48
50
  updateFunction,
49
51
  valuesEqual,
52
+ type FilteredSetValue,
53
+ type FunctionValue,
50
54
  type LazyFunctionSource,
51
55
  type LazyFunctionValue,
52
56
  type Value,
@@ -114,6 +118,7 @@ export interface Environment {
114
118
  definitionValues: Map<Definition, Value>;
115
119
  constantLevels: Map<Definition, boolean>;
116
120
  evaluators: WeakMap<Expression, Evaluator>;
121
+ trace?: Expression[];
117
122
  }
118
123
 
119
124
  export interface Context {
@@ -143,9 +148,6 @@ const EXCEPT_AT = "@";
143
148
  export const describeLocation = (expression: Expression) =>
144
149
  `line ${expression.location.line}, column ${expression.location.column}`;
145
150
 
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
151
  export const describeRange = (expression: Expression) => {
150
152
  const range = expression.location.range;
151
153
  return range ? formatRange(range) : describeLocation(expression);
@@ -182,8 +184,17 @@ export const getConjunctError = (
182
184
  };
183
185
 
184
186
  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)}`;
187
+ (expression: Expression & { kind: "FieldAccess" }) => (record: FunctionValue) =>
188
+ isRecordValue(record)
189
+ ? `Attempted to select nonexistent field "${expression.field}" from the record\n${formatValue(record)}\n${describeRange(expression)}`
190
+ : describeMissingField(record, expression.field);
191
+
192
+ export const getNonFunctionError = (expression: Expression) => (value: Value) =>
193
+ `A non-function (${getKindString(value)}) was applied as a function.\n${describeRange(expression)}`;
194
+
195
+ export const getNonRecordError =
196
+ (expression: Expression & { kind: "FieldAccess" }) => (value: Value) =>
197
+ `Attempted to select field "${expression.field}" from a non-record value ${formatValue(value)}\n${describeRange(expression)}`;
187
198
 
188
199
  export const getDomainOperator = (expression: Expression) => (value: Value) => {
189
200
  if (!isFunctionValue(value)) {
@@ -1011,23 +1022,88 @@ 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
  };
1027
1102
 
1028
1103
  const entryEvaluators = new WeakMap<Expression, Evaluator>();
1029
1104
 
1030
- const getEntryEvaluator = (expression: Expression, environment: Environment) => {
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
  );
@@ -1420,7 +1536,13 @@ const compileFunctionConstruction = (
1420
1536
  const set = getEvaluator(bound.set, environment);
1421
1537
  return (context) => {
1422
1538
  const domain = isSingleName ? set(context) : getBoundsDomain(bounds, context);
1423
- 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)) {
1424
1546
  const functionValue = createLazyFunction(
1425
1547
  domain,
1426
1548
  (argument) => body(withScope(context, bindArgument(bounds, context.scope, argument))),
@@ -1509,16 +1631,21 @@ const compileSetComprehension = (
1509
1631
  const pattern = expression.bound.pattern;
1510
1632
  return (context) => {
1511
1633
  const base = set(context);
1512
- const test = (element: Value) =>
1634
+ const getTest = (evaluatePredicate: Evaluator) => (element: Value) =>
1513
1635
  expectBoolean(
1514
- predicate(withScope(context, bindPattern(context.scope, pattern, element))),
1636
+ evaluatePredicate(withScope(context, bindPattern(context.scope, pattern, element))),
1515
1637
  "a set filter predicate",
1516
1638
  );
1517
- const isReducible =
1518
- typeof base === "object" &&
1519
- (base.kind === "Set" || base.kind === "MixedSet" || base.kind === "Interval");
1520
- if (!isReducible) {
1521
- 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
+ }
1522
1649
  throw new TlaEvaluationError(
1523
1650
  `TLC encountered a non-enumerable quantifier bound ${formatValue(base)} at ${describeLocation(expression.bound.set)}`,
1524
1651
  );
@@ -1571,7 +1698,12 @@ export const hasDuplicateFields = (sortedFields: RecordField[]) =>
1571
1698
  sortedFields.some((field, index) => index > 0 && sortedFields[index - 1].name === field.name);
1572
1699
 
1573
1700
  export const createUnassignedError = (name: string, expression: Expression) =>
1574
- new TlaEvaluationError(`The variable ${name} is not assigned at ${describeLocation(expression)}`);
1701
+ setOwnExitCode(
1702
+ new TlaEvaluationError(
1703
+ `In evaluation, the identifier ${name} is either undefined or not an operator.\n${describeRange(expression)}`,
1704
+ ),
1705
+ EXIT_STATUS.configParseError,
1706
+ );
1575
1707
 
1576
1708
  export const createPrimeOutsideActionError = (expression: Expression) =>
1577
1709
  new TlaEvaluationError(
@@ -1759,18 +1891,41 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1759
1891
  keepLazy(expression.function);
1760
1892
  const evaluateFunction = child(expression.function);
1761
1893
  const args = expression.args.map(child);
1894
+ const describeNonFunction = getNonFunctionError(expression);
1895
+ if (args.length === 1 && environment.trace) {
1896
+ const argument = args[0];
1897
+ return (context) => {
1898
+ const functionValue = evaluateFunction(context);
1899
+ const argumentValue = argument(context);
1900
+ const apply = () =>
1901
+ applyFunction(functionValue, argumentValue, undefined, describeNonFunction);
1902
+ return isFunctionValue(functionValue) ? withSource(functionValue, apply) : apply();
1903
+ };
1904
+ }
1762
1905
  if (args.length === 1) {
1763
1906
  const argument = args[0];
1764
- return (context) => applyFunction(evaluateFunction(context), argument(context));
1907
+ return (context) =>
1908
+ applyFunction(
1909
+ evaluateFunction(context),
1910
+ argument(context),
1911
+ undefined,
1912
+ describeNonFunction,
1913
+ );
1765
1914
  }
1766
1915
  return (context) =>
1767
- applyFunction(evaluateFunction(context), createTuple(args.map((arg) => arg(context))));
1916
+ applyFunction(
1917
+ evaluateFunction(context),
1918
+ createTuple(args.map((arg) => arg(context))),
1919
+ undefined,
1920
+ describeNonFunction,
1921
+ );
1768
1922
  }
1769
1923
  case "FieldAccess": {
1770
1924
  const record = child(expression.record);
1771
1925
  const field = expression.field;
1772
1926
  const describeMissing = getFieldError(expression);
1773
- return (context) => applyFunction(record(context), field, describeMissing);
1927
+ const describeNonRecord = getNonRecordError(expression);
1928
+ return (context) => applyFunction(record(context), field, describeMissing, describeNonRecord);
1774
1929
  }
1775
1930
  case "Product": {
1776
1931
  const factors = expression.factors.map(child);