tla-ts 0.0.3-dev.3082068 → 0.0.3-dev.33ae522

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tla-ts",
3
- "version": "0.0.3-dev.3082068",
3
+ "version": "0.0.3-dev.33ae522",
4
4
  "description": "A TLA+ interpreter and model checker in TypeScript, 2× faster than TLC",
5
5
  "keywords": [
6
6
  "formal verification",
package/src/builtins.ts CHANGED
@@ -297,15 +297,21 @@ export const getJavaInteger = (value: Value, signature: string) => {
297
297
  return value;
298
298
  };
299
299
 
300
- export const getIntegersSignature = (method: string, result: string, arity: number) =>
301
- `public static tlc2.value.impl.${result} tlc2.module.Integers.${method}(${Array.from({ length: arity }, () => "tlc2.value.impl.IntValue").join(",")})`;
300
+ export const getArithmeticSignature = (
301
+ javaClass: "Naturals" | "Integers",
302
+ method: string,
303
+ result: string,
304
+ arity: number,
305
+ ) =>
306
+ `public static tlc2.value.impl.${result} tlc2.module.${javaClass}.${method}(${Array.from({ length: arity }, () => "tlc2.value.impl.IntValue").join(",")})`;
302
307
 
303
308
  export const defineArithmetic = (
309
+ javaClass: "Naturals" | "Integers",
304
310
  name: string,
305
311
  method: string,
306
312
  compute: (left: number, right: number) => number,
307
313
  ) => {
308
- const signature = getIntegersSignature(method, "IntValue", 2);
314
+ const signature = getArithmeticSignature(javaClass, method, "IntValue", 2);
309
315
  return defineBinary(name, (left, right) => {
310
316
  const leftNumber = getJavaInteger(left, signature);
311
317
  const rightNumber = getJavaInteger(right, signature);
package/src/check.ts CHANGED
@@ -36,6 +36,7 @@ import {
36
36
  import {
37
37
  createLivenessChecker,
38
38
  type Lasso,
39
+ type LiveGraph,
39
40
  type LivenessChecker,
40
41
  type LiveSuccessor,
41
42
  } from "./live-check";
@@ -68,6 +69,7 @@ import { createTlcFingerprinter, getTlcFingerprint } from "./tlc-random";
68
69
  import { createCanonicalizer } from "./canonical";
69
70
  import { getPossibleCounts, type CheckerRuntime } from "./runtime";
70
71
  import { createCounterExample } from "./tlc-ext";
72
+ import { getFingerprintTrace, valueSources } from "./value-sources";
71
73
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc-summary";
72
74
  import {
73
75
  combineHash,
@@ -149,6 +151,17 @@ export interface EvaluationFailure {
149
151
  export interface Replay {
150
152
  output: string[];
151
153
  callStack: string[] | undefined;
154
+ fingerprint?: Fingerprint;
155
+ // The worker that fails to check liveness replays the step at once, so TLC prints the stack
156
+ // before the error, and only when it holds a frame.
157
+ isBeforeError?: boolean;
158
+ }
159
+
160
+ // TLC reports an error from a method of a value that has a source as one it was unable to
161
+ // fingerprint. With an empty stack, it lists the sources of the values instead.
162
+ export interface Fingerprint {
163
+ sources: string[];
164
+ reason: string;
152
165
  }
153
166
 
154
167
  export interface CheckResult {
@@ -924,8 +937,8 @@ export const createSearch = (
924
937
  const withNextStateExitCode = (error: unknown) =>
925
938
  error instanceof TlaModuleError ? setExitCode(error, error.exitCode) : error;
926
939
 
927
- // TLC reports a failure of the next-state relation as an unexpected exception, unless a standard
928
- // module raised it as an EvalException.
940
+ // TLC reports a failure of the next-state relation, or of the liveness check of a step, as an
941
+ // unexpected exception, unless a standard module raised it as an EvalException.
929
942
  const toNextStateError = (error: unknown) =>
930
943
  error instanceof TlaEvaluationError &&
931
944
  !(error instanceof TlaModuleError) &&
@@ -936,15 +949,30 @@ const toNextStateError = (error: unknown) =>
936
949
  )
937
950
  : withNextStateExitCode(error);
938
951
 
952
+ const isRepeated = (frame: string, index: number, frames: string[]) =>
953
+ index > 0 && frames[index - 1] === frame;
954
+
955
+ // FingerprintException#getTrace numbers the sources from the outermost value and lists the innermost
956
+ // first.
957
+ const getSourceTrace = (sources: Expression[]) =>
958
+ sources
959
+ .flatMap((source) => (source.location.range ? [formatRange(source.location.range)] : []))
960
+ .filter((source, index, all) => !isRepeated(source, index, all))
961
+ .map((source, index) => `${index}) ${source}`)
962
+ .reverse();
963
+
939
964
  // TLC keeps the stack only when an evaluation fails, and prints each expression on it once, however
940
965
  // many times in a row it pushed it.
941
- const getReplayedCallStack = (replay: () => void, trace: Expression[]) => {
966
+ const getReplayedCallStack = (
967
+ replay: () => void,
968
+ trace: Expression[],
969
+ ): Pick<Replay, "callStack" | "fingerprint"> => {
942
970
  try {
943
971
  replay();
944
- return undefined;
972
+ return { callStack: undefined };
945
973
  } catch (error) {
946
- if (!(error instanceof TlaEvaluationError)) return [];
947
- return trace
974
+ if (!(error instanceof TlaEvaluationError)) return { callStack: [] };
975
+ const callStack = trace
948
976
  .flatMap((expression) => {
949
977
  const range = expression.location.range;
950
978
  return range
@@ -953,7 +981,12 @@ const getReplayedCallStack = (replay: () => void, trace: Expression[]) => {
953
981
  ]
954
982
  : [];
955
983
  })
956
- .filter((frame, index, frames) => index === 0 || frames[index - 1] !== frame);
984
+ .filter((frame, index, frames) => !isRepeated(frame, index, frames));
985
+ const sources = getFingerprintTrace(error);
986
+ return {
987
+ callStack,
988
+ fingerprint: sources && { sources: getSourceTrace(sources), reason: error.message },
989
+ };
957
990
  }
958
991
  };
959
992
 
@@ -1079,6 +1112,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1079
1112
  const replayFailure = (
1080
1113
  result: CheckResult,
1081
1114
  replay: (tracedSearch: Search, traced: Environment) => void,
1115
+ isBeforeError = false,
1082
1116
  ): CheckResult => {
1083
1117
  if (!result.failure) return result;
1084
1118
  const trace: Expression[] = [];
@@ -1087,9 +1121,23 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1087
1121
  if (!tracedSearch) return result;
1088
1122
  const replayed: string[] = [];
1089
1123
  output.replayed = replayed;
1090
- const callStack = getReplayedCallStack(() => replay(tracedSearch, traced), trace);
1124
+ valueSources.current = new WeakMap();
1125
+ const replayedStack = getReplayedCallStack(() => replay(tracedSearch, traced), trace);
1126
+ valueSources.current = undefined;
1091
1127
  output.replayed = undefined;
1092
- return { ...result, failure: { ...result.failure, replay: { output: replayed, callStack } } };
1128
+ return {
1129
+ ...result,
1130
+ failure: { ...result.failure, replay: { output: replayed, ...replayedStack, isBeforeError } },
1131
+ };
1132
+ };
1133
+ // TLC fingerprints a state outside CallStackTool, so a failure leaves the stack empty.
1134
+ const fingerprintReplayed = (state: Value[], traced: Environment) => {
1135
+ try {
1136
+ getStateHash(getFingerprintState(state));
1137
+ } catch (error) {
1138
+ if (traced.trace) traced.trace.length = 0;
1139
+ throw error;
1140
+ }
1093
1141
  };
1094
1142
  // TLC checks every initial state again, as when it first generated them.
1095
1143
  const replayInitialStates = (result: CheckResult) =>
@@ -1099,7 +1147,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1099
1147
  spec.init,
1100
1148
  traced,
1101
1149
  (state) => {
1102
- tracedSearch.satisfiesConstraints(state);
1150
+ if (tracedSearch.satisfiesConstraints(state)) fingerprintReplayed(state, traced);
1103
1151
  return (
1104
1152
  tracedSearch.findViolatedInvariant(state) !== undefined ||
1105
1153
  tracedSearch.findFailedInitialPredicate(state) !== undefined
@@ -1130,6 +1178,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1130
1178
  const isInModel =
1131
1179
  tracedSearch.satisfiesConstraints(successor.state) &&
1132
1180
  tracedSearch.satisfiesActionConstraints(state, successor.state);
1181
+ if (isInModel) fingerprintReplayed(successor.state, traced);
1133
1182
  return (
1134
1183
  (!isInModel && tracedSearch.findViolatedInvariant(successor.state) !== undefined) ||
1135
1184
  tracedSearch.findViolatedActionProperty(state, successor.state) !== undefined
@@ -1139,35 +1188,34 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1139
1188
  });
1140
1189
  const isReducing = config.view !== undefined || config.symmetry !== undefined;
1141
1190
  const tlcFingerprints: number[] = [];
1191
+ const liveGraph: LiveGraph = {
1192
+ getFingerprint: (index) =>
1193
+ (tlcFingerprints[index] ??= Number(BigInt.asIntN(32, runtime.getFingerprint(states[index])))),
1194
+ getSuccessors: (state) => {
1195
+ const successors: LiveSuccessor[] = [];
1196
+ if (spec.next === undefined) return successors;
1197
+ forEachSuccessor(
1198
+ spec.next,
1199
+ state,
1200
+ environment,
1201
+ (successor) => {
1202
+ canonicalizeState(successor.state);
1203
+ const isInModel =
1204
+ search.satisfiesConstraints(successor.state, state) &&
1205
+ search.satisfiesActionConstraints(state, successor.state);
1206
+ if (!isInModel) return false;
1207
+ const fingerprintState = getFingerprintState(successor.state);
1208
+ const index = findStateIndex(getStateHash(fingerprintState), fingerprintState);
1209
+ successors.push({ index, state: successor.state });
1210
+ return false;
1211
+ },
1212
+ spec.scope,
1213
+ );
1214
+ return successors;
1215
+ },
1216
+ };
1142
1217
  const liveness = withLivenessExitCode(() =>
1143
- createLivenessChecker(search.properties.liveness, spec.temporals, environment, {
1144
- getFingerprint: (index) =>
1145
- (tlcFingerprints[index] ??= Number(
1146
- BigInt.asIntN(32, runtime.getFingerprint(states[index])),
1147
- )),
1148
- getSuccessors: (state) => {
1149
- const successors: LiveSuccessor[] = [];
1150
- if (spec.next === undefined) return successors;
1151
- forEachSuccessor(
1152
- spec.next,
1153
- state,
1154
- environment,
1155
- (successor) => {
1156
- canonicalizeState(successor.state);
1157
- const isInModel =
1158
- search.satisfiesConstraints(successor.state, state) &&
1159
- search.satisfiesActionConstraints(state, successor.state);
1160
- if (!isInModel) return false;
1161
- const fingerprintState = getFingerprintState(successor.state);
1162
- const index = findStateIndex(getStateHash(fingerprintState), fingerprintState);
1163
- successors.push({ index, state: successor.state });
1164
- return false;
1165
- },
1166
- spec.scope,
1167
- );
1168
- return successors;
1169
- },
1170
- }),
1218
+ createLivenessChecker(search.properties.liveness, spec.temporals, environment, liveGraph),
1171
1219
  );
1172
1220
  const isCanonicalizedFirst = search.isSymmetric || liveness !== undefined;
1173
1221
 
@@ -1661,7 +1709,17 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1661
1709
  trace: toTrace(steps, accepted),
1662
1710
  });
1663
1711
  } catch (error) {
1664
- return toFailure(error, getStateTrace(index), undefined, getPartialOutDegrees());
1712
+ return replayFailure(
1713
+ toFailure(toNextStateError(error), getStateTrace(index), undefined, getPartialOutDegrees()),
1714
+ (_, traced) =>
1715
+ createLivenessChecker(
1716
+ search.properties.liveness,
1717
+ spec.temporals,
1718
+ traced,
1719
+ liveGraph,
1720
+ )?.addState(index, state, liveSuccessors),
1721
+ true,
1722
+ );
1665
1723
  }
1666
1724
  };
1667
1725
  // TLC names the action when the next-state relation has more than one, and prints the
@@ -266,7 +266,11 @@ export const createEnvironment = (
266
266
 
267
267
  const getStandardSymbols = (name: string) => {
268
268
  const symbols = addStandardModule(name);
269
- if (symbols) useModule(name, STANDARD_DEPENDENCIES.get(name) ?? []);
269
+ const dependencies = STANDARD_DEPENDENCIES.get(name) ?? [];
270
+ if (symbols) useModule(name, dependencies);
271
+ // TLC loads the Java class of each module a standard module uses, so one that uses Integers
272
+ // overrides the arithmetic of Naturals.
273
+ if (symbols && dependencies.includes("Integers")) addStandardModule("Integers");
270
274
  return symbols;
271
275
  };
272
276
 
package/src/errors.ts CHANGED
@@ -92,6 +92,17 @@ export class TlaModuleError extends TlaEvaluationError {
92
92
  }
93
93
  }
94
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
+
95
106
  // TLC reports a successor state that the next-state relation leaves incomplete as an error of its
96
107
  // own, not as an exception. It keeps the name TlaEvaluationError, and index.ts doesn't export it.
97
108
  export class TlaIncompleteStateError extends TlaEvaluationError {
package/src/evaluate.ts CHANGED
@@ -12,13 +12,14 @@ import {
12
12
  type RecordField,
13
13
  } from "./ast";
14
14
  import { getKindString } from "./builtins";
15
- import { formatRange, TlaEvaluationError } from "./errors";
15
+ import { formatRange, TlaEvaluationError, TlaUnassignedError } from "./errors";
16
16
  import { EXIT_STATUS, setExitCode, setOwnExitCode } from "./exit-codes";
17
17
  import { generateEvaluator } from "./codegen";
18
18
  import type { CheckerRuntime } from "./runtime";
19
19
  import { getReadVariables } from "./dependencies";
20
20
  import { contextualApplications, mapChildren, substitutedExpressions } from "./instances";
21
21
  import { isEnabled } from "./successors";
22
+ import { getFingerprintTrace, valueSources, withSource } from "./value-sources";
22
23
  import {
23
24
  applyFunction,
24
25
  combineHash,
@@ -1028,6 +1029,44 @@ const filteredSetRetracers = new WeakMap<
1028
1029
  (environment: Environment) => FilteredSetValue
1029
1030
  >();
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
+
1031
1070
  export const getEvaluator = (expression: Expression, environment: Environment): Evaluator => {
1032
1071
  const cached = environment.evaluators.get(expression);
1033
1072
  if (cached) return cached;
@@ -1039,13 +1078,17 @@ export const getEvaluator = (expression: Expression, environment: Environment):
1039
1078
  ? cacheStateValue(compiled)
1040
1079
  : compiled;
1041
1080
  const trace = environment.trace;
1081
+ const isSourcedExpression = trace !== undefined && isSourced(expression, environment);
1042
1082
  // TLC's CallStackTool pushes each expression it evaluates and keeps the stack when one fails.
1043
1083
  const evaluator: Evaluator = trace
1044
1084
  ? (context) => {
1045
1085
  const depth = trace.length;
1046
1086
  trace.push(expression);
1047
- const value = cachedEvaluator(context);
1087
+ const value = evaluateTraced(cachedEvaluator, context, trace, depth);
1048
1088
  trace.length = depth;
1089
+ if (isSourcedExpression && typeof value === "object" && value.kind !== "FilteredSet") {
1090
+ valueSources.current?.set(value, expression);
1091
+ }
1049
1092
  const retrace =
1050
1093
  typeof value === "object" && value.kind === "FilteredSet"
1051
1094
  ? filteredSetRetracers.get(value)
@@ -1169,11 +1212,32 @@ const getLazyArguments = (args: Expression[], context: Context): OperatorValue[]
1169
1212
  expression: arg,
1170
1213
  }));
1171
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
+
1172
1225
  const compileBuiltinCall = (
1173
1226
  builtin: Builtin,
1174
1227
  args: Expression[],
1175
1228
  environment: Environment,
1176
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
+ }
1177
1241
  if (builtin.isLazy) {
1178
1242
  return (context) => builtin.evaluate(getLazyArguments(args, context), context);
1179
1243
  }
@@ -1333,6 +1397,13 @@ const compileApply = (
1333
1397
  if (global?.kind === "Builtin" && global.name === "DOMAIN") {
1334
1398
  const operand = getEvaluator(args[0], environment);
1335
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
+ }
1336
1407
  return (context) => domain(operand(context));
1337
1408
  }
1338
1409
  // TLC sorts the value of a constant TLCEval argument only where no context binds a name.
@@ -1348,6 +1419,13 @@ const compileApply = (
1348
1419
  const left = getEvaluator(args[0], environment);
1349
1420
  const right = getEvaluator(args[1], environment);
1350
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
+ }
1351
1429
  return (context) => subset(left(context), right(context));
1352
1430
  }
1353
1431
  if (global?.kind === "Builtin") return compileBuiltinCall(global, args, environment);
@@ -1621,8 +1699,9 @@ export const hasDuplicateFields = (sortedFields: RecordField[]) =>
1621
1699
 
1622
1700
  export const createUnassignedError = (name: string, expression: Expression) =>
1623
1701
  setOwnExitCode(
1624
- new TlaEvaluationError(
1702
+ new TlaUnassignedError(
1625
1703
  `In evaluation, the identifier ${name} is either undefined or not an operator.\n${describeRange(expression)}`,
1704
+ name,
1626
1705
  ),
1627
1706
  EXIT_STATUS.configParseError,
1628
1707
  );
@@ -1814,6 +1893,16 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1814
1893
  const evaluateFunction = child(expression.function);
1815
1894
  const args = expression.args.map(child);
1816
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
+ }
1817
1906
  if (args.length === 1) {
1818
1907
  const argument = args[0];
1819
1908
  return (context) =>
package/src/run-cli.ts CHANGED
@@ -10,7 +10,7 @@ import {
10
10
  import { spawnSync } from "node:child_process";
11
11
  import { basename, delimiter, dirname, join, resolve } from "node:path";
12
12
  import { availableParallelism } from "node:os";
13
- import type { CheckResult, CheckStatus, TraceStep } from "./check";
13
+ import type { CheckResult, CheckStatus, Replay, TraceStep } from "./check";
14
14
  import { defineCommand, type ParsedArgs } from "./cli-options";
15
15
  import { parseConfig } from "./config";
16
16
  import {
@@ -137,22 +137,41 @@ const getTemporalHeadline = (names: string[]) =>
137
137
  ? `Error: Temporal property ${names[0]} was violated.\n`
138
138
  : `Error: Temporal properties ${names.slice(0, -1).join(", ")}${names.length > 2 ? "," : ""} and ${names[names.length - 1]} were violated.\n`;
139
139
 
140
+ const getFrames = (callStack: string[]) =>
141
+ callStack.map((frame, index) => `${index}. ${frame}\n`).join("");
142
+
143
+ const printCallStack = (frames: string) =>
144
+ console.log(
145
+ `Error: The error occurred when TLC was evaluating the nested\nexpressions at the following positions:\n${frames ? `${frames}\n` : " The error call stack is empty.\n"}`,
146
+ );
147
+
148
+ const printReplay = (replay: Replay) => {
149
+ replay.output.forEach((line) => console.log(line));
150
+ const frames = getFrames(replay.callStack ?? []);
151
+ const fingerprint = replay.fingerprint;
152
+ if (replay.isBeforeError) {
153
+ if (frames) printCallStack(frames);
154
+ } else if (replay.callStack && fingerprint) {
155
+ const sources = fingerprint.sources.map((source) => `${source}\n`).join("");
156
+ console.log(
157
+ `Error: TLC was unable to fingerprint.\n\nFingerprint Stack Trace:\n${frames ? `${frames}\n` : sources}\nReason:\n${fingerprint.reason}`,
158
+ );
159
+ } else if (replay.callStack) {
160
+ printCallStack(frames);
161
+ }
162
+ };
163
+
140
164
  const printResult = (result: CheckResult) => {
141
165
  if (result.failure) {
166
+ const replay = result.failure.replay;
167
+ if (replay?.isBeforeError) printReplay(replay);
142
168
  console.log(`Error: ${result.failure.message}`);
143
169
  if (result.failure.initialState) {
144
170
  console.log("While working on the initial state:");
145
171
  printState(result.failure.initialState);
146
172
  }
147
173
  printTrace(result.failure.trace);
148
- const replay = result.failure.replay;
149
- replay?.output.forEach((line) => console.log(line));
150
- if (replay?.callStack) {
151
- const frames = replay.callStack.map((frame, index) => `${index}. ${frame}\n`).join("");
152
- console.log(
153
- `Error: The error occurred when TLC was evaluating the nested\nexpressions at the following positions:\n${frames ? `${frames}\n` : " The error call stack is empty.\n"}`,
154
- );
155
- }
174
+ if (replay && !replay.isBeforeError) printReplay(replay);
156
175
  if (result.failure.isWithoutStatistics) return;
157
176
  } else if (result.violation) {
158
177
  const violation = result.violation;
@@ -11,7 +11,7 @@ import {
11
11
  getNumber,
12
12
  getOperator,
13
13
  getSet,
14
- getIntegersSignature,
14
+ getArithmeticSignature,
15
15
  getJavaInteger,
16
16
  getValue,
17
17
  isOutOfRange,
@@ -123,7 +123,7 @@ export const CORE_OPERATORS: Builtin[] = [
123
123
  ),
124
124
  defineOperator("\\subseteq", 2, (args) => {
125
125
  const left = getSet(args, 0, "\\subseteq");
126
- const right = getSet(args, 1, "\\subseteq");
126
+ const right = getValue(args, 1, "\\subseteq");
127
127
  const isPowerSets =
128
128
  typeof left === "object" &&
129
129
  left.kind === "Subset" &&
@@ -185,51 +185,59 @@ export const CORE_OPERATORS: Builtin[] = [
185
185
  }),
186
186
  ];
187
187
 
188
- const DOT_DOT_SIGNATURE = getIntegersSignature("DotDot", "IntervalValue", 2);
188
+ const NEG_SIGNATURE = getArithmeticSignature("Integers", "Neg", "IntValue", 1);
189
189
 
190
- const NEG_SIGNATURE = getIntegersSignature("Neg", "IntValue", 1);
190
+ // TLC overrides the operators of Naturals with the Java class of Integers when a spec loads
191
+ // Integers, which names it in their errors.
192
+ const getArithmeticOperators = (javaClass: "Naturals" | "Integers") => {
193
+ const dotDotSignature = getArithmeticSignature(javaClass, "DotDot", "IntervalValue", 2);
194
+ return [
195
+ defineArithmetic(javaClass, "+", "Plus", (left, right) => left + right),
196
+ defineArithmetic(javaClass, "-", "Minus", (left, right) => left - right),
197
+ defineArithmetic(javaClass, "*", "Times", (left, right) => left * right),
198
+ defineArithmetic(javaClass, "^", "Expt", (base, exponent) => {
199
+ if (exponent < 0) {
200
+ throw new TlaModuleError(
201
+ `The second argument of ^ should be a natural number, but instead it is:\n${exponent}`,
202
+ );
203
+ }
204
+ if (base === 0 && exponent === 0) throw new TlaModuleError("0^0 is undefined.");
205
+ return base ** exponent;
206
+ }),
207
+ defineArithmetic(javaClass, "\\div", "Divide", (left, right) => {
208
+ if (right === 0) throw new TlaModuleError("The second argument of \\div is 0.");
209
+ const quotient = Math.floor(left / right);
210
+ if (isOutOfRange(quotient)) throw createOverflowError(`${left} \\div ${right}`);
211
+ return quotient;
212
+ }),
213
+ defineArithmetic(javaClass, "%", "Mod", (left, right) => {
214
+ if (right <= 0) {
215
+ throw new TlaModuleError(
216
+ `The second argument of % should be a positive number, but instead it is:\n${right}`,
217
+ );
218
+ }
219
+ return ((left % right) + right) % right;
220
+ }),
221
+ defineOperator("..", 2, (args) => ({
222
+ kind: "Interval",
223
+ low: getJavaInteger(getValue(args, 0, ".."), dotDotSignature),
224
+ high: getJavaInteger(getValue(args, 1, ".."), dotDotSignature),
225
+ })),
226
+ ];
227
+ };
191
228
 
192
229
  const NATURALS_OPERATORS = [
193
230
  defineConstant("Nat", { kind: "InfiniteSet", name: "Nat" }),
194
- defineArithmetic("+", "Plus", (left, right) => left + right),
195
- defineArithmetic("-", "Minus", (left, right) => left - right),
196
- defineArithmetic("*", "Times", (left, right) => left * right),
197
- defineArithmetic("^", "Expt", (base, exponent) => {
198
- if (exponent < 0) {
199
- throw new TlaModuleError(
200
- `The second argument of ^ should be a natural number, but instead it is:\n${exponent}`,
201
- );
202
- }
203
- if (base === 0 && exponent === 0) throw new TlaModuleError("0^0 is undefined.");
204
- return base ** exponent;
205
- }),
206
- defineArithmetic("\\div", "Divide", (left, right) => {
207
- if (right === 0) throw new TlaModuleError("The second argument of \\div is 0.");
208
- const quotient = Math.floor(left / right);
209
- if (isOutOfRange(quotient)) throw createOverflowError(`${left} \\div ${right}`);
210
- return quotient;
211
- }),
212
- defineArithmetic("%", "Mod", (left, right) => {
213
- if (right <= 0) {
214
- throw new TlaModuleError(
215
- `The second argument of % should be a positive number, but instead it is:\n${right}`,
216
- );
217
- }
218
- return ((left % right) + right) % right;
219
- }),
231
+ ...getArithmeticOperators("Naturals"),
220
232
  defineComparison("<", (left, right) => left < right),
221
233
  defineComparison(">", (left, right) => left > right),
222
234
  defineComparison("<=", (left, right) => left <= right),
223
235
  defineComparison(">=", (left, right) => left >= right),
224
- defineOperator("..", 2, (args) => ({
225
- kind: "Interval",
226
- low: getJavaInteger(getValue(args, 0, ".."), DOT_DOT_SIGNATURE),
227
- high: getJavaInteger(getValue(args, 1, ".."), DOT_DOT_SIGNATURE),
228
- })),
229
236
  ];
230
237
 
231
238
  const INTEGERS_OPERATORS = [
232
239
  defineConstant("Int", { kind: "InfiniteSet", name: "Int" }),
240
+ ...getArithmeticOperators("Integers"),
233
241
  defineOperator("-.", 1, (args) => {
234
242
  const value = getJavaInteger(getValue(args, 0, "-"), NEG_SIGNATURE);
235
243
  if (isOutOfRange(-value)) throw createOverflowError(`-${value}`);