tla-ts 0.0.3-dev.ab42bab → 0.0.3-dev.ab9c809

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.ab42bab",
3
+ "version": "0.0.3-dev.ab9c809",
4
4
  "description": "A TLA+ interpreter and model checker in TypeScript, 2× faster than TLC",
5
5
  "keywords": [
6
6
  "formal verification",
package/src/ast.ts CHANGED
@@ -445,12 +445,14 @@ export type StepBody =
445
445
  | { kind: "Assert"; isSuffices: boolean; statement: Expression | AssumeProve }
446
446
  | { kind: "Qed" };
447
447
 
448
- // head is the range of the step number and its statement, without the proof.
448
+ // head is the range of the step number and its statement, without the proof, and statement is the
449
+ // range of the statement alone.
449
450
  export interface ProofStep {
450
451
  name: string | undefined;
451
452
  token: string;
452
453
  body: StepBody;
453
454
  head: SourceRange;
455
+ statement: SourceRange;
454
456
  proof: Proof | undefined;
455
457
  location: SourceLocation;
456
458
  }
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,8 +69,10 @@ 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 {
75
+ assertFingerprintable,
73
76
  combineHash,
74
77
  createModelValue,
75
78
  formatState,
@@ -149,6 +152,17 @@ export interface EvaluationFailure {
149
152
  export interface Replay {
150
153
  output: string[];
151
154
  callStack: string[] | undefined;
155
+ fingerprint?: Fingerprint;
156
+ // The worker that fails to check liveness replays the step at once, so TLC prints the stack
157
+ // before the error, and only when it holds a frame.
158
+ isBeforeError?: boolean;
159
+ }
160
+
161
+ // TLC reports an error from a method of a value that has a source as one it was unable to
162
+ // fingerprint. With an empty stack, it lists the sources of the values instead.
163
+ export interface Fingerprint {
164
+ sources: string[];
165
+ reason: string;
152
166
  }
153
167
 
154
168
  export interface CheckResult {
@@ -924,8 +938,8 @@ export const createSearch = (
924
938
  const withNextStateExitCode = (error: unknown) =>
925
939
  error instanceof TlaModuleError ? setExitCode(error, error.exitCode) : error;
926
940
 
927
- // TLC reports a failure of the next-state relation as an unexpected exception, unless a standard
928
- // module raised it as an EvalException.
941
+ // TLC reports a failure of the next-state relation, or of the liveness check of a step, as an
942
+ // unexpected exception, unless a standard module raised it as an EvalException.
929
943
  const toNextStateError = (error: unknown) =>
930
944
  error instanceof TlaEvaluationError &&
931
945
  !(error instanceof TlaModuleError) &&
@@ -936,15 +950,30 @@ const toNextStateError = (error: unknown) =>
936
950
  )
937
951
  : withNextStateExitCode(error);
938
952
 
953
+ const isRepeated = (frame: string, index: number, frames: string[]) =>
954
+ index > 0 && frames[index - 1] === frame;
955
+
956
+ // FingerprintException#getTrace numbers the sources from the outermost value and lists the innermost
957
+ // first.
958
+ const getSourceTrace = (sources: Expression[]) =>
959
+ sources
960
+ .flatMap((source) => (source.location.range ? [formatRange(source.location.range)] : []))
961
+ .filter((source, index, all) => !isRepeated(source, index, all))
962
+ .map((source, index) => `${index}) ${source}`)
963
+ .reverse();
964
+
939
965
  // TLC keeps the stack only when an evaluation fails, and prints each expression on it once, however
940
966
  // many times in a row it pushed it.
941
- const getReplayedCallStack = (replay: () => void, trace: Expression[]) => {
967
+ const getReplayedCallStack = (
968
+ replay: () => void,
969
+ trace: Expression[],
970
+ ): Pick<Replay, "callStack" | "fingerprint"> => {
942
971
  try {
943
972
  replay();
944
- return undefined;
973
+ return { callStack: undefined };
945
974
  } catch (error) {
946
- if (!(error instanceof TlaEvaluationError)) return [];
947
- return trace
975
+ if (!(error instanceof TlaEvaluationError)) return { callStack: [] };
976
+ const callStack = trace
948
977
  .flatMap((expression) => {
949
978
  const range = expression.location.range;
950
979
  return range
@@ -953,7 +982,12 @@ const getReplayedCallStack = (replay: () => void, trace: Expression[]) => {
953
982
  ]
954
983
  : [];
955
984
  })
956
- .filter((frame, index, frames) => index === 0 || frames[index - 1] !== frame);
985
+ .filter((frame, index, frames) => !isRepeated(frame, index, frames));
986
+ const sources = getFingerprintTrace(error);
987
+ return {
988
+ callStack,
989
+ fingerprint: sources && { sources: getSourceTrace(sources), reason: error.message },
990
+ };
957
991
  }
958
992
  };
959
993
 
@@ -1079,6 +1113,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1079
1113
  const replayFailure = (
1080
1114
  result: CheckResult,
1081
1115
  replay: (tracedSearch: Search, traced: Environment) => void,
1116
+ isBeforeError = false,
1082
1117
  ): CheckResult => {
1083
1118
  if (!result.failure) return result;
1084
1119
  const trace: Expression[] = [];
@@ -1087,9 +1122,24 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1087
1122
  if (!tracedSearch) return result;
1088
1123
  const replayed: string[] = [];
1089
1124
  output.replayed = replayed;
1090
- const callStack = getReplayedCallStack(() => replay(tracedSearch, traced), trace);
1125
+ valueSources.current = new WeakMap();
1126
+ const replayedStack = getReplayedCallStack(() => replay(tracedSearch, traced), trace);
1127
+ valueSources.current = undefined;
1091
1128
  output.replayed = undefined;
1092
- return { ...result, failure: { ...result.failure, replay: { output: replayed, callStack } } };
1129
+ return {
1130
+ ...result,
1131
+ failure: { ...result.failure, replay: { output: replayed, ...replayedStack, isBeforeError } },
1132
+ };
1133
+ };
1134
+ // TLC fingerprints a state outside CallStackTool, so a failure of a value with a source leaves
1135
+ // the stack empty. Any other failure keeps the stack of the initial predicate.
1136
+ const fingerprintReplayed = (state: Value[], traced: Environment) => {
1137
+ try {
1138
+ getStateHash(getFingerprintState(state));
1139
+ } catch (error) {
1140
+ if (traced.trace && getFingerprintTrace(error)) traced.trace.length = 0;
1141
+ throw error;
1142
+ }
1093
1143
  };
1094
1144
  // TLC checks every initial state again, as when it first generated them.
1095
1145
  const replayInitialStates = (result: CheckResult) =>
@@ -1099,7 +1149,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1099
1149
  spec.init,
1100
1150
  traced,
1101
1151
  (state) => {
1102
- tracedSearch.satisfiesConstraints(state);
1152
+ if (tracedSearch.satisfiesConstraints(state)) fingerprintReplayed(state, traced);
1103
1153
  return (
1104
1154
  tracedSearch.findViolatedInvariant(state) !== undefined ||
1105
1155
  tracedSearch.findFailedInitialPredicate(state) !== undefined
@@ -1130,6 +1180,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1130
1180
  const isInModel =
1131
1181
  tracedSearch.satisfiesConstraints(successor.state) &&
1132
1182
  tracedSearch.satisfiesActionConstraints(state, successor.state);
1183
+ if (isInModel) fingerprintReplayed(successor.state, traced);
1133
1184
  return (
1134
1185
  (!isInModel && tracedSearch.findViolatedInvariant(successor.state) !== undefined) ||
1135
1186
  tracedSearch.findViolatedActionProperty(state, successor.state) !== undefined
@@ -1139,35 +1190,34 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1139
1190
  });
1140
1191
  const isReducing = config.view !== undefined || config.symmetry !== undefined;
1141
1192
  const tlcFingerprints: number[] = [];
1193
+ const liveGraph: LiveGraph = {
1194
+ getFingerprint: (index) =>
1195
+ (tlcFingerprints[index] ??= Number(BigInt.asIntN(32, runtime.getFingerprint(states[index])))),
1196
+ getSuccessors: (state) => {
1197
+ const successors: LiveSuccessor[] = [];
1198
+ if (spec.next === undefined) return successors;
1199
+ forEachSuccessor(
1200
+ spec.next,
1201
+ state,
1202
+ environment,
1203
+ (successor) => {
1204
+ canonicalizeState(successor.state);
1205
+ const isInModel =
1206
+ search.satisfiesConstraints(successor.state, state) &&
1207
+ search.satisfiesActionConstraints(state, successor.state);
1208
+ if (!isInModel) return false;
1209
+ const fingerprintState = getFingerprintState(successor.state);
1210
+ const index = findStateIndex(getStateHash(fingerprintState), fingerprintState);
1211
+ successors.push({ index, state: successor.state });
1212
+ return false;
1213
+ },
1214
+ spec.scope,
1215
+ );
1216
+ return successors;
1217
+ },
1218
+ };
1142
1219
  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
- }),
1220
+ createLivenessChecker(search.properties.liveness, spec.temporals, environment, liveGraph),
1171
1221
  );
1172
1222
  const isCanonicalizedFirst = search.isSymmetric || liveness !== undefined;
1173
1223
 
@@ -1340,6 +1390,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1340
1390
  let hash = 0x811c9dc5;
1341
1391
  for (let index = 0; index < state.length; index++)
1342
1392
  hash = combineHash(hash, getValueHash(state[index]));
1393
+ assertFingerprintable(state);
1343
1394
  return hash & 0x3fffffff;
1344
1395
  };
1345
1396
  const isSameState = (stored: Value[], state: Value[]) => {
@@ -1661,7 +1712,17 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1661
1712
  trace: toTrace(steps, accepted),
1662
1713
  });
1663
1714
  } catch (error) {
1664
- return toFailure(error, getStateTrace(index), undefined, getPartialOutDegrees());
1715
+ return replayFailure(
1716
+ toFailure(toNextStateError(error), getStateTrace(index), undefined, getPartialOutDegrees()),
1717
+ (_, traced) =>
1718
+ createLivenessChecker(
1719
+ search.properties.liveness,
1720
+ spec.temporals,
1721
+ traced,
1722
+ liveGraph,
1723
+ )?.addState(index, state, liveSuccessors),
1724
+ true,
1725
+ );
1665
1726
  }
1666
1727
  };
1667
1728
  // TLC names the action when the next-state relation has more than one, and prints the
@@ -49,10 +49,11 @@ import {
49
49
  type Symbols,
50
50
  } from "./resolve";
51
51
  import { createRuntime } from "./runtime";
52
+ import { parseModuleFile } from "./sany-parse-error";
52
53
  import { CORE_OPERATORS, getStandardModule, STANDARD_DEPENDENCIES } from "./standard-modules";
53
54
  import { resolveInstanceSubexpressions, resolveModuleSubexpressions } from "./subexpressions";
54
55
  import { checkModuleLevels, createLevelAnalyzer } from "./levels";
55
- import { checkInstances, type InstanceCheck } from "./substitution-levels";
56
+ import { createInstanceChecker, type InstanceCheck } from "./substitution-levels";
56
57
  import { getTlcDeclarationOrder } from "./tlc-order";
57
58
  import {
58
59
  checkInteger,
@@ -229,6 +230,8 @@ export const createEnvironment = (
229
230
  const runtime = createRuntime(config.checkDeadlock, options.seed);
230
231
  const linkedModules = new Map<string, LinkedModule>();
231
232
  const nestedModules = new Map<string, LinkedModule>();
233
+ // Each module by name, from the time its level checks run.
234
+ const checkedModules = new Map<string, LinkedModule>();
232
235
  const linkedList: LinkedModule[] = [];
233
236
  const dependencies = new Map<string, Set<string>>();
234
237
  const loading: Set<string>[] = [];
@@ -243,7 +246,23 @@ export const createEnvironment = (
243
246
  const copyCount = { value: 0 };
244
247
  const createName = (name: string) => `${name}#${copyCount.value++}`;
245
248
  const instanceChecks: InstanceCheck[] = [];
249
+ const checkInstance = createInstanceChecker((name) => {
250
+ const linked = checkedModules.get(name) ?? getLinkedModule(name, name);
251
+ return {
252
+ constants: linked.constants,
253
+ variables: linked.variables,
254
+ definitions: [
255
+ ...new Set(
256
+ [...linked.visible.values()].flatMap((symbol) => definitions.get(symbol.key) ?? []),
257
+ ),
258
+ ],
259
+ assumptions: linked.module.assumptions.map((assumption) => assumption.expression),
260
+ theorems: linked.module.theorems,
261
+ getDefinition: (symbol) => definitions.get(linked.visible.get(symbol)?.key ?? symbol),
262
+ };
263
+ });
246
264
  const instanceActions = new Map<string, InstanceAction>();
265
+ const qualifiedNames = new Map<string, string>();
247
266
 
248
267
  const addStandardModule = (name: string): Symbols | undefined => {
249
268
  const cached = standardExports.get(name);
@@ -266,7 +285,11 @@ export const createEnvironment = (
266
285
 
267
286
  const getStandardSymbols = (name: string) => {
268
287
  const symbols = addStandardModule(name);
269
- if (symbols) useModule(name, STANDARD_DEPENDENCIES.get(name) ?? []);
288
+ const dependencies = STANDARD_DEPENDENCIES.get(name) ?? [];
289
+ if (symbols) useModule(name, dependencies);
290
+ // TLC loads the Java class of each module a standard module uses, so one that uses Integers
291
+ // overrides the arithmetic of Naturals.
292
+ if (symbols && dependencies.includes("Integers")) addStandardModule("Integers");
270
293
  return symbols;
271
294
  };
272
295
 
@@ -304,7 +327,7 @@ export const createEnvironment = (
304
327
  ],
305
328
  true,
306
329
  );
307
- const module = parseModule(source);
330
+ const module = parseModuleFile(source, name);
308
331
  if (module.name !== name) {
309
332
  throw createSanyError(
310
333
  [
@@ -425,6 +448,7 @@ export const createEnvironment = (
425
448
  if (declarations.length > 0) {
426
449
  instanceActions.set(key, { name: `${instance.name}!${name}`, location: instance.location });
427
450
  }
451
+ qualifiedNames.set(key, `${instance.name}!${name}`);
428
452
  symbols.set(`${instance.name}!${name}`, {
429
453
  key,
430
454
  arity: symbol.arity + instance.params.length,
@@ -605,6 +629,7 @@ export const createEnvironment = (
605
629
 
606
630
  const linkModule = (unlinked: Module, scope: ModuleScope): LinkedModule => {
607
631
  const parsed = overrideDefinitions(unlinked, options.loadClass?.(unlinked.name));
632
+ const firstCheck = instanceChecks.length;
608
633
  const visible: Symbols = new Map([
609
634
  ...CORE_OPERATORS.map((operator): [string, ModuleSymbol] => [
610
635
  operator.name,
@@ -747,11 +772,6 @@ export const createEnvironment = (
747
772
  visible.set(definition.name, symbol);
748
773
  if (!definition.isLocal) exported.set(definition.name, symbol);
749
774
  });
750
- checkModuleLevels(module, {
751
- constants: new Set(constants.map((constant) => constant.name)),
752
- variables: new Set(variables),
753
- getDefinition: (symbol) => definitions.get(visible.get(symbol)?.key ?? symbol),
754
- });
755
775
  const linked = {
756
776
  module,
757
777
  constants,
@@ -762,6 +782,21 @@ export const createEnvironment = (
762
782
  modules,
763
783
  extended,
764
784
  };
785
+ if (!checkedModules.has(parsed.name)) checkedModules.set(parsed.name, linked);
786
+ // SANY checks the instances of a module with its definitions and theorems, so it reports their
787
+ // errors together.
788
+ checkModuleLevels(
789
+ module,
790
+ {
791
+ constants: new Set(constants.map((constant) => constant.name)),
792
+ variables: new Set(variables),
793
+ getDefinition: (symbol) => definitions.get(visible.get(symbol)?.key ?? symbol),
794
+ getQualifiedName: (symbol) => qualifiedNames.get(visible.get(symbol)?.key ?? symbol),
795
+ },
796
+ instanceChecks
797
+ .splice(firstCheck)
798
+ .map((check) => ({ location: check.location, check: () => checkInstance(check) })),
799
+ );
765
800
  linkedList.push(linked);
766
801
  return linked;
767
802
  };
@@ -956,20 +991,6 @@ export const createEnvironment = (
956
991
  constantLevels: new Map(),
957
992
  evaluators: new WeakMap(),
958
993
  };
959
- checkInstances(instanceChecks, (name) => {
960
- const linked = linkedModules.get(name) ?? nestedModules.get(name) ?? linkedRoot;
961
- return {
962
- constants: linked.constants,
963
- variables: linked.variables,
964
- definitions: [
965
- ...new Set(
966
- [...linked.visible.values()].flatMap((symbol) => definitions.get(symbol.key) ?? []),
967
- ),
968
- ],
969
- assumptions: linked.module.assumptions.map((assumption) => assumption.expression),
970
- getDefinition: (symbol) => definitions.get(linked.visible.get(symbol)?.key ?? symbol),
971
- };
972
- });
973
994
  // TLC evaluates a substitute at startup and rejects it only when that fails and the level bound it
974
995
  // computes is above constant. The bound counts the operators that TLC's Java code overrides with
975
996
  // a minimum level as state-level, so the analyzer takes them for variables.
package/src/errors.ts CHANGED
@@ -34,10 +34,12 @@ export interface SanyError {
34
34
  message: string;
35
35
  }
36
36
 
37
- // The errors SANY reports for a spec. A fatal error stops it before semantic analysis.
37
+ // The errors SANY reports for a spec. A fatal error stops it before semantic analysis. SANY's
38
+ // parser prints its message for a module it rejects before the report.
38
39
  export interface SanyReport {
39
40
  errors: SanyError[];
40
41
  isFatal: boolean;
42
+ parseError?: string;
41
43
  }
42
44
 
43
45
  export class TlaSyntaxError extends TlaError {
@@ -52,14 +54,23 @@ export class TlaSyntaxError extends TlaError {
52
54
  }
53
55
  }
54
56
 
55
- export const createSanyError = (errors: SanyError[], isFatal = false) =>
57
+ export const createSanyError = (errors: SanyError[], isFatal = false, parseError?: string) =>
56
58
  new TlaSyntaxError(
57
59
  errors.map((error) => `${error.location}\n\n${error.message}`).join("\n\n"),
58
60
  undefined,
59
61
  undefined,
60
- { errors, isFatal },
62
+ { errors, isFatal, parseError },
61
63
  );
62
64
 
65
+ // SANY's message for a module its parser rejects, such as a "***Parse Error***" with the
66
+ // productions it was in.
67
+ export class TlaParseError extends TlaError {
68
+ constructor(message: string) {
69
+ super(message);
70
+ this.name = "TlaParseError";
71
+ }
72
+ }
73
+
63
74
  export const formatRange = (range: SourceRange) =>
64
75
  `line ${range.start.line}, col ${range.start.column} to line ${range.end.line}, col ${range.end.column} of module ${range.module}`;
65
76
 
@@ -92,6 +103,17 @@ export class TlaModuleError extends TlaEvaluationError {
92
103
  }
93
104
  }
94
105
 
106
+ // A variable that a partial state leaves without a value.
107
+ export class TlaUnassignedError extends TlaEvaluationError {
108
+ variable: string;
109
+
110
+ constructor(message: string, variable: string) {
111
+ super(message);
112
+ this.name = "TlaEvaluationError";
113
+ this.variable = variable;
114
+ }
115
+ }
116
+
95
117
  // TLC reports a successor state that the next-state relation leaves incomplete as an error of its
96
118
  // own, not as an exception. It keeps the name TlaEvaluationError, and index.ts doesn't export it.
97
119
  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,
@@ -34,6 +35,7 @@ import {
34
35
  getDomain,
35
36
  getFunctionDomain,
36
37
  getIntervalElements,
38
+ getLazySubsets,
37
39
  getSequenceElements,
38
40
  getValueHash,
39
41
  isFunctionValue,
@@ -341,9 +343,8 @@ export const getEnumeratedElements = (set: Value, expression: Expression) => {
341
343
  : `TLC encountered the non-enumerable quantifier bound\n${text}\n${describeRange(expression)}\n${explanation}`,
342
344
  );
343
345
  }
344
- return typeof set === "object" && set.kind === "Interval"
345
- ? getIntervalElements(set)
346
- : toFiniteSet(set).elements;
346
+ if (typeof set === "object" && set.kind === "Interval") return getIntervalElements(set);
347
+ return getLazySubsets(set) ?? toFiniteSet(set).elements;
347
348
  };
348
349
 
349
350
  export const forEachBinding = (
@@ -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) =>
@@ -1,4 +1,4 @@
1
- import { getValueFingerprint, getValueHash, type Value } from "./values";
1
+ import { assertFingerprintable, getValueFingerprint, getValueHash, type Value } from "./values";
2
2
 
3
3
  const EMPTY = 0;
4
4
  const INITIAL_CAPACITY = 1 << 12;
@@ -20,6 +20,7 @@ export const writeStateFingerprint = (state: Value[], fingerprint: Int32Array) =
20
20
  first = Math.imul(first ^ getValueHash(state[index]), 0x01000193);
21
21
  second = Math.imul(second ^ getValueFingerprint(state[index]), 0x5bd1e995);
22
22
  }
23
+ assertFingerprintable(state);
23
24
  fingerprint[0] = mix(first) || 1;
24
25
  fingerprint[1] = mix(second);
25
26
  };