tla-ts 0.0.3-dev.c949d82 → 0.0.3-dev.cfd469d

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.
@@ -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" &&
@@ -135,8 +135,8 @@ export const CORE_OPERATORS: Builtin[] = [
135
135
  }),
136
136
  ...SET_OPERATORS.map((operator) =>
137
137
  defineOperator(operator, 2, (args) => {
138
- const left = getSet(args, 0, operator);
139
- const right = getSet(args, 1, operator);
138
+ const left = getValue(args, 0, operator);
139
+ const right = getValue(args, 1, operator);
140
140
  if (isReducible(left) && isReducible(right) && !isMixedSet(left) && !isMixedSet(right)) {
141
141
  if (operator === "\\cup" && isEmptySet(left)) return right;
142
142
  const merge =
@@ -145,7 +145,13 @@ export const CORE_OPERATORS: Builtin[] = [
145
145
  : operator === "\\cap"
146
146
  ? intersectSorted
147
147
  : differenceSorted;
148
- return merge(toFiniteSet(left), toFiniteSet(right));
148
+ // Merging compares elements across the sets. Where that fails, TLC's element-by-element
149
+ // membership test fails or succeeds on its own.
150
+ try {
151
+ return merge(toFiniteSet(left), toFiniteSet(right));
152
+ } catch (error) {
153
+ if (!(error instanceof TlaEvaluationError)) throw error;
154
+ }
149
155
  }
150
156
  if (isReducible(left)) return combineReducible(operator, left, right);
151
157
  if (operator !== "\\" && isReducible(right)) return combineReducible(operator, right, left);
@@ -179,51 +185,59 @@ export const CORE_OPERATORS: Builtin[] = [
179
185
  }),
180
186
  ];
181
187
 
182
- const DOT_DOT_SIGNATURE = getIntegersSignature("DotDot", "IntervalValue", 2);
188
+ const NEG_SIGNATURE = getArithmeticSignature("Integers", "Neg", "IntValue", 1);
183
189
 
184
- 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
+ };
185
228
 
186
229
  const NATURALS_OPERATORS = [
187
230
  defineConstant("Nat", { kind: "InfiniteSet", name: "Nat" }),
188
- defineArithmetic("+", "Plus", (left, right) => left + right),
189
- defineArithmetic("-", "Minus", (left, right) => left - right),
190
- defineArithmetic("*", "Times", (left, right) => left * right),
191
- defineArithmetic("^", "Expt", (base, exponent) => {
192
- if (exponent < 0) {
193
- throw new TlaModuleError(
194
- `The second argument of ^ should be a natural number, but instead it is:\n${exponent}`,
195
- );
196
- }
197
- if (base === 0 && exponent === 0) throw new TlaModuleError("0^0 is undefined.");
198
- return base ** exponent;
199
- }),
200
- defineArithmetic("\\div", "Divide", (left, right) => {
201
- if (right === 0) throw new TlaModuleError("The second argument of \\div is 0.");
202
- const quotient = Math.floor(left / right);
203
- if (isOutOfRange(quotient)) throw createOverflowError(`${left} \\div ${right}`);
204
- return quotient;
205
- }),
206
- defineArithmetic("%", "Mod", (left, right) => {
207
- if (right <= 0) {
208
- throw new TlaModuleError(
209
- `The second argument of % should be a positive number, but instead it is:\n${right}`,
210
- );
211
- }
212
- return ((left % right) + right) % right;
213
- }),
231
+ ...getArithmeticOperators("Naturals"),
214
232
  defineComparison("<", (left, right) => left < right),
215
233
  defineComparison(">", (left, right) => left > right),
216
234
  defineComparison("<=", (left, right) => left <= right),
217
235
  defineComparison(">=", (left, right) => left >= right),
218
- defineOperator("..", 2, (args) => ({
219
- kind: "Interval",
220
- low: getJavaInteger(getValue(args, 0, ".."), DOT_DOT_SIGNATURE),
221
- high: getJavaInteger(getValue(args, 1, ".."), DOT_DOT_SIGNATURE),
222
- })),
223
236
  ];
224
237
 
225
238
  const INTEGERS_OPERATORS = [
226
239
  defineConstant("Int", { kind: "InfiniteSet", name: "Int" }),
240
+ ...getArithmeticOperators("Integers"),
227
241
  defineOperator("-.", 1, (args) => {
228
242
  const value = getJavaInteger(getValue(args, 0, "-"), NEG_SIGNATURE);
229
243
  if (isOutOfRange(-value)) throw createOverflowError(`-${value}`);
@@ -0,0 +1,116 @@
1
+ import type { SourceRange } from "./ast";
2
+
3
+ // Where the modules in TLC's tla2sany/StandardModules define the operators that tla-ts implements
4
+ // natively, which SANY reports when a spec defines one of them again.
5
+ const RANGES: Record<string, Record<string, [number, number, number, number]>> = {
6
+ Naturals: {
7
+ Nat: [14, 1, 14, 16],
8
+ "+": [15, 1, 15, 19],
9
+ "-": [17, 1, 17, 33],
10
+ "*": [18, 1, 18, 17],
11
+ "^": [19, 1, 19, 19],
12
+ "<": [20, 1, 20, 19],
13
+ ">": [21, 1, 21, 19],
14
+ "<=": [22, 1, 22, 19],
15
+ ">=": [23, 1, 23, 19],
16
+ "%": [33, 1, 33, 20],
17
+ "\\div": [34, 1, 34, 20],
18
+ "..": [35, 1, 35, 20],
19
+ },
20
+ Integers: {
21
+ Int: [18, 1, 18, 12],
22
+ "-.": [22, 1, 22, 13],
23
+ },
24
+ Sequences: {
25
+ Seq: [20, 1, 20, 41],
26
+ Len: [25, 1, 25, 44],
27
+ "\\o": [30, 1, 31, 76],
28
+ Append: [36, 1, 36, 26],
29
+ Head: [41, 1, 41, 15],
30
+ Tail: [42, 1, 42, 61],
31
+ SubSeq: [48, 1, 48, 50],
32
+ SelectSeq: [53, 1, 65, 14],
33
+ },
34
+ FiniteSets: {
35
+ IsFiniteSet: [14, 1, 19, 68],
36
+ Cardinality: [21, 1, 27, 11],
37
+ },
38
+ Bags: {
39
+ IsABag: [20, 1, 24, 41],
40
+ BagToSet: [26, 1, 26, 23],
41
+ SetToBag: [31, 1, 31, 30],
42
+ BagIn: [36, 1, 36, 31],
43
+ EmptyBag: [41, 1, 41, 24],
44
+ "\\oplus": [43, 1, 49, 46],
45
+ "\\ominus": [51, 1, 60, 50],
46
+ BagUnion: [74, 1, 79, 58],
47
+ "\\sqsubseteq": [81, 1, 87, 42],
48
+ SubBag: [89, 1, 110, 11],
49
+ BagOfAll: [122, 1, 130, 66],
50
+ BagCardinality: [132, 1, 138, 8],
51
+ CopiesIn: [140, 1, 145, 33],
52
+ },
53
+ TLC: {
54
+ Print: [17, 1, 17, 22],
55
+ PrintT: [18, 1, 18, 19],
56
+ Assert: [24, 1, 25, 54],
57
+ JavaTime: [26, 1, 26, 32],
58
+ TLCGet: [75, 1, 75, 28],
59
+ TLCSet: [76, 1, 76, 20],
60
+ ":>": [78, 1, 78, 27],
61
+ "@@": [79, 1, 80, 50],
62
+ Permutations: [81, 1, 82, 54],
63
+ SortSeq: [88, 1, 92, 40],
64
+ RandomElement: [110, 1, 110, 41],
65
+ Any: [119, 1, 119, 22],
66
+ ToString: [121, 1, 121, 58],
67
+ TLCEval: [145, 1, 145, 15],
68
+ },
69
+ TLCExt: {
70
+ AssertEq: [14, 1, 20, 14],
71
+ AssertError: [23, 1, 26, 72],
72
+ TLCGetOrDefault: [30, 1, 31, 17],
73
+ TLCGetAndSet: [33, 1, 35, 57],
74
+ Trace: [41, 1, 57, 6],
75
+ CounterExample: [61, 1, 75, 8],
76
+ ToTrace: [77, 1, 87, 12],
77
+ TLCModelValue: [91, 1, 120, 29],
78
+ TLCDefer: [122, 1, 134, 6],
79
+ TLCNoOp: [138, 1, 145, 5],
80
+ PickSuccessor: [148, 1, 162, 37],
81
+ TLCCache: [166, 1, 173, 12],
82
+ TLCFP: [175, 1, 181, 24],
83
+ TLCEvalDefinition: [185, 1, 190, 6],
84
+ },
85
+ Randomization: {
86
+ RandomSubset: [30, 1, 30, 64],
87
+ RandomSetOfSubsets: [48, 1, 49, 67],
88
+ TestRandomSetOfSubsets: [61, 1, 62, 71],
89
+ },
90
+ Json: {
91
+ ToJson: [46, 1, 55, 37],
92
+ ToJsonArray: [57, 1, 64, 42],
93
+ ToJsonObject: [66, 1, 73, 43],
94
+ JsonSerialize: [75, 1, 80, 6],
95
+ JsonDeserialize: [82, 1, 87, 19],
96
+ ndJsonSerialize: [89, 1, 95, 6],
97
+ ndJsonDeserialize: [97, 1, 103, 19],
98
+ },
99
+ _Possible: {
100
+ _Track: [10, 1, 17, 38],
101
+ _Counts: [24, 1, 30, 14],
102
+ _CheckName: [32, 1, 35, 35],
103
+ _PrintCounts: [37, 1, 37, 31],
104
+ },
105
+ };
106
+
107
+ export const getStandardRange = (module: string, name: string): SourceRange | undefined => {
108
+ const range = RANGES[module]?.[name];
109
+ return (
110
+ range && {
111
+ module,
112
+ start: { line: range[0], column: range[1] },
113
+ end: { line: range[2], column: range[3] },
114
+ }
115
+ );
116
+ };
@@ -11,7 +11,13 @@ import {
11
11
  } from "./ast";
12
12
  import { TlaSyntaxError } from "./errors";
13
13
  import { getSourceName, mapChildren, mapDefinition } from "./instances";
14
- import { getArity, getBoundNames, getPatternNames, LOCAL_RESOLUTION } from "./resolve";
14
+ import {
15
+ getArity,
16
+ getBoundNames,
17
+ getOperandIndex,
18
+ getPatternNames,
19
+ LOCAL_RESOLUTION,
20
+ } from "./resolve";
15
21
 
16
22
  type Lookup = (name: string) => Definition | undefined;
17
23
 
@@ -37,12 +43,6 @@ const getBoundSets = (bounds: Bound[]) =>
37
43
  .filter((bound, index) => index === 0 || bounds[index - 1].set !== bound.set)
38
44
  .map((bound) => bound.set);
39
45
 
40
- const getOperandIndex = (operand: number | "<<" | ">>", count: number) => {
41
- if (typeof operand === "number") return operand >= 1 && operand <= count ? operand - 1 : -1;
42
- if (operand === "<<") return count > 0 ? 0 : -1;
43
- return count === 2 ? 1 : -1;
44
- };
45
-
46
46
  const getOperands = (expression: Expression): Expression[] | undefined => {
47
47
  switch (expression.kind) {
48
48
  case "Apply":
@@ -393,15 +393,22 @@ const containsReference = (expression: Expression): boolean =>
393
393
  (expression.kind === "Apply" && expression.operator.includes("!")) ||
394
394
  getChildren(expression).some(containsReference);
395
395
 
396
- const resolveSubexpressions = (expression: Expression, lookup: Lookup): Expression => {
396
+ // A reference into a theorem whose statement is an ASSUME/PROVE stays for name resolution to check.
397
+ const resolveSubexpressions = (
398
+ expression: Expression,
399
+ lookup: Lookup,
400
+ goals: ReadonlySet<string>,
401
+ ): Expression => {
397
402
  if (!containsReference(expression)) return expression;
398
403
  if (expression.kind === "Let") {
399
404
  const local: Lookup = (name) =>
400
405
  expression.definitions.find((definition) => definition.name === name) ?? lookup(name);
401
- return mapChildren(expression, (child) => resolveSubexpressions(child, local));
406
+ return mapChildren(expression, (child) => resolveSubexpressions(child, local, goals));
402
407
  }
403
- const mapped = mapChildren(expression, (child) => resolveSubexpressions(child, lookup));
408
+ const mapped = mapChildren(expression, (child) => resolveSubexpressions(child, lookup, goals));
404
409
  if (mapped.kind === "Subexpression") {
410
+ const first = mapped.selectors[0];
411
+ if (first.kind === "Name" && goals.has(first.name)) return mapped;
405
412
  return selectSubexpression(mapped.selectors, lookup, mapped.location, []);
406
413
  }
407
414
  const name =
@@ -424,8 +431,8 @@ export const resolveInstanceSubexpressions = (instance: Instance, module: Module
424
431
  return {
425
432
  ...instance,
426
433
  substitutions: instance.substitutions.map((substitution) => ({
427
- name: substitution.name,
428
- expression: resolveSubexpressions(substitution.expression, lookup),
434
+ ...substitution,
435
+ expression: resolveSubexpressions(substitution.expression, lookup, new Set()),
429
436
  })),
430
437
  };
431
438
  };
@@ -436,14 +443,19 @@ export const resolveModuleSubexpressions = (module: Module, available: Definitio
436
443
  module.definitions.some((definition) => containsReference(definition.body)) ||
437
444
  module.assumptions.some((assumption) => containsReference(assumption.expression));
438
445
  if (!hasReferences) return module;
446
+ const goals = new Set(
447
+ module.theorems.flatMap((theorem) =>
448
+ theorem.name !== undefined && theorem.statement.kind === "AssumeProve" ? [theorem.name] : [],
449
+ ),
450
+ );
439
451
  return {
440
452
  ...module,
441
453
  definitions: module.definitions.map((definition) =>
442
- mapDefinition(definition, (child) => resolveSubexpressions(child, lookup)),
454
+ mapDefinition(definition, (child) => resolveSubexpressions(child, lookup, goals)),
443
455
  ),
444
456
  assumptions: module.assumptions.map((assumption) => ({
445
457
  ...assumption,
446
- expression: resolveSubexpressions(assumption.expression, lookup),
458
+ expression: resolveSubexpressions(assumption.expression, lookup, goals),
447
459
  })),
448
460
  };
449
461
  };
@@ -1,6 +1,8 @@
1
- import type { Declaration, Definition, Expression, SourceLocation } from "./ast";
2
- import { TlaSyntaxError } from "./errors";
1
+ import type { Declaration, Definition, Expression, SourceLocation, Theorem } from "./ast";
2
+ import { createSanyError, formatRange } from "./errors";
3
3
  import {
4
+ ACTION_LEVEL,
5
+ analyzeAssumeProve,
4
6
  createLevelAnalyzer,
5
7
  getArgumentKey,
6
8
  MAX_LEVEL,
@@ -24,6 +26,7 @@ interface ModuleContext {
24
26
  variables: string[];
25
27
  definitions: Definition[];
26
28
  assumptions: Expression[];
29
+ theorems: Theorem[];
27
30
  getDefinition: (name: string) => Definition | undefined;
28
31
  }
29
32
 
@@ -46,10 +49,7 @@ interface Substituted {
46
49
  const getMaxLevel = (operator: OperatorLevels, index: number) =>
47
50
  operator.maxLevels[index] ?? MAX_LEVEL;
48
51
 
49
- export const checkInstances = (
50
- checks: InstanceCheck[],
51
- getModule: (name: string) => ModuleContext,
52
- ) => {
52
+ export const createInstanceChecker = (getModule: (name: string) => ModuleContext) => {
53
53
  const analyzers = new Map<string, ReturnType<typeof createLevelAnalyzer>>();
54
54
  const getAnalyzer = (name: string) => {
55
55
  const cached = analyzers.get(name);
@@ -101,17 +101,38 @@ export const checkInstances = (
101
101
  definition.formals.every((formal) => formal.name !== operator && formal.name !== param),
102
102
  ),
103
103
  );
104
+ const addAssumedLevels = (data: ReturnType<typeof analyzeAssumeProve>) => {
105
+ addLevels(data, () => true);
106
+ module.constants.forEach((constant) => {
107
+ if (data.params.has(constant.name)) {
108
+ putConstraint(levels.constraints, constant.name, ACTION_LEVEL);
109
+ }
110
+ });
111
+ };
104
112
  module.assumptions.forEach((assumption) =>
105
- addLevels(analyzer.analyze(assumption, new Map()), () => true),
113
+ addAssumedLevels(analyzer.analyze(assumption, new Map())),
114
+ );
115
+ module.theorems.forEach((theorem) =>
116
+ theorem.statement.kind === "AssumeProve"
117
+ ? addAssumedLevels(analyzeAssumeProve(theorem.statement, new Map(), analyzer))
118
+ : addLevels(analyzer.analyze(theorem.statement, new Map()), () => true),
106
119
  );
107
120
  moduleLevels.set(name, levels);
108
121
  return levels;
109
122
  };
110
123
 
111
- const messages = new Set<string>();
112
- checks.forEach((check) => {
113
- const location = `at line ${check.location.line}, column ${check.location.column}`;
114
- const addMessage = (message: string) => messages.add(`${message} ${location}`);
124
+ return (check: InstanceCheck) => {
125
+ const errors = new Map<string, { location: string; message: string }>();
126
+ // SANY reports each error at the whole instance.
127
+ const location = formatRange(
128
+ check.location.range ?? {
129
+ module: check.instancer,
130
+ start: check.location,
131
+ end: check.location,
132
+ },
133
+ );
134
+ const addMessage = (message: string) =>
135
+ errors.set(`${location}\n${message}`, { location, message });
115
136
  const instancee = getModule(check.module);
116
137
  const levels = getModuleLevels(check.module);
117
138
  const analyzer = getAnalyzer(check.instancer);
@@ -141,14 +162,14 @@ export const checkInstances = (
141
162
  ];
142
163
  });
143
164
  const getLevelMessage = (name: string, level: number) =>
144
- `Level error in instantiating module '${check.module}': the level of the expression or operator substituted for '${name}' must be at most ${level}`;
165
+ `Level error in instantiating module '${check.module}':\nThe level of the expression or operator substituted for '${name}' \nmust be at most ${level}.`;
145
166
  substituted.forEach((item) => {
146
167
  if (!levels.isConstant && item.level > item.maximumLevel) {
147
168
  addMessage(getLevelMessage(item.name, item.maximumLevel));
148
169
  }
149
170
  if (!item.isLeibniz) {
150
171
  addMessage(
151
- `Error in instantiating module '${check.module}': a non-Leibniz operator substituted for '${item.name}'`,
172
+ `Error in instantiating module '${check.module}':\n A non-Leibniz operator substituted for '${item.name}'.`,
152
173
  );
153
174
  }
154
175
  });
@@ -162,7 +183,7 @@ export const checkInstances = (
162
183
  const minimum = levels.argConstraints.get(getArgumentKey(item.name, index));
163
184
  if (minimum !== undefined && getMaxLevel(operator, index) < minimum) {
164
185
  addMessage(
165
- `Level error in instantiating module '${check.module}': the level of the argument ${index + 1} of the operator ${operator.name} must be at least ${minimum}`,
186
+ `Level error in instantiating module '${check.module}':\nThe level of the argument ${index + 1} of the operator ${operator.name} \nmust be at least ${minimum}.`,
166
187
  );
167
188
  }
168
189
  });
@@ -175,10 +196,10 @@ export const checkInstances = (
175
196
  const maximum = getMaxLevel(operator, parameter.index);
176
197
  if (argument.level > maximum) {
177
198
  addMessage(
178
- `Level error when instantiating module '${check.module}': the level of the argument ${parameter.index} of the operator ${parameter.operator}' must be at most ${maximum}`,
199
+ `Level error when instantiating module '${check.module}':\nThe level of the argument ${parameter.index} of the operator ${parameter.operator}' \nmust be at most ${maximum}.`,
179
200
  );
180
201
  }
181
202
  });
182
- });
183
- if (messages.size > 0) throw new TlaSyntaxError([...messages].join("\n"));
203
+ if (errors.size > 0) throw createSanyError([...errors.values()]);
204
+ };
184
205
  };
package/src/successors.ts CHANGED
@@ -7,7 +7,12 @@ import {
7
7
  type QuantifierExpression,
8
8
  } from "./ast";
9
9
  import { getReadVariables } from "./dependencies";
10
- import { TlaEvaluationError, TlaIncompleteStateError } from "./errors";
10
+ import {
11
+ TlaEvaluationError,
12
+ TlaIllegalStateError,
13
+ TlaIncompleteStateError,
14
+ TlaUnassignedError,
15
+ } from "./errors";
11
16
  import { EXIT_STATUS, setExitCode } from "./exit-codes";
12
17
  import {
13
18
  describeLocation,
@@ -53,6 +58,7 @@ export interface Successor {
53
58
  interface Run {
54
59
  environment: Environment;
55
60
  isInit: boolean;
61
+ isEnabled: boolean;
56
62
  current: Value[] | undefined;
57
63
  isStopped: boolean;
58
64
  }
@@ -113,11 +119,30 @@ const holds = (expression: Expression, context: Context, value = evaluate(expres
113
119
  const isAssignmentOperator = (operator: string) =>
114
120
  operator === "=" || operator === "\\in" || operator === "\\subseteq";
115
121
 
122
+ const tracedRunners = new WeakMap<Environment, WeakMap<Expression, Runner>[]>();
123
+
124
+ const getRunners = (environment: Environment, isInit: boolean) => {
125
+ if (!environment.trace) return isInit ? initRunners : nextRunners;
126
+ const runners = tracedRunners.get(environment) ?? [new WeakMap(), new WeakMap()];
127
+ tracedRunners.set(environment, runners);
128
+ return runners[isInit ? 0 : 1];
129
+ };
130
+
116
131
  const getRunner = (expression: Expression, environment: Environment, isInit: boolean): Runner => {
117
- const runners = isInit ? initRunners : nextRunners;
132
+ const runners = getRunners(environment, isInit);
118
133
  const cached = runners.get(expression);
119
134
  if (cached) return cached;
120
- const runner = compileAction(expression, environment, isInit);
135
+ const compiled = compileAction(expression, environment, isInit);
136
+ const trace = environment.trace;
137
+ // TLC's CallStackTool keeps an action's expression on the stack while the rest of the action runs.
138
+ const runner: Runner = trace
139
+ ? (run, scope, partial, action, isFixed, onComplete) => {
140
+ const depth = trace.length;
141
+ trace.push(expression);
142
+ compiled(run, scope, partial, action, isFixed, onComplete);
143
+ trace.length = depth;
144
+ }
145
+ : compiled;
121
146
  runners.set(expression, runner);
122
147
  return runner;
123
148
  };
@@ -201,6 +226,23 @@ const getUnchangedIndices = (
201
226
  return getUnchangedIndices(definition.body, environment, visited);
202
227
  };
203
228
 
229
+ // TLC's CallStackTool keeps each expression that UNCHANGED takes apart on the stack.
230
+ const getUnchangedFrames = (expression: Expression, environment: Environment): Expression[] => {
231
+ if (expression.kind === "Tuple") {
232
+ return [
233
+ expression,
234
+ ...expression.elements.flatMap((element) => getUnchangedFrames(element, environment)),
235
+ ];
236
+ }
237
+ const definition =
238
+ expression.kind === "Identifier" && !environment.variableIndex.has(expression.name)
239
+ ? getZeroArityBody(expression.name, environment)
240
+ : undefined;
241
+ return definition
242
+ ? [expression, ...getUnchangedFrames(definition.body, environment)]
243
+ : [expression];
244
+ };
245
+
204
246
  const ACTION_KINDS = new Set([
205
247
  "Label",
206
248
  "And",
@@ -333,6 +375,7 @@ const compileConjunction = (
333
375
  ): Runner => {
334
376
  const conjuncts = operands.map((operand) => toConjunct(operand, environment, isInit));
335
377
  const evaluators: (Evaluator | undefined)[] = conjuncts.map(() => undefined);
378
+ const trace = environment.trace;
336
379
  const runFrom = (
337
380
  start: number,
338
381
  run: Run,
@@ -353,6 +396,12 @@ const compileConjunction = (
353
396
  return;
354
397
  }
355
398
  const conjunct = conjuncts[index];
399
+ if (trace) {
400
+ trace.push(conjunct.expression);
401
+ if (conjunct.expression.kind === "Unchanged") {
402
+ trace.push(...getUnchangedFrames(conjunct.expression.expression, environment));
403
+ }
404
+ }
356
405
  if (conjunct.kind === "Guard") {
357
406
  context ??= getContext(run, scope, current);
358
407
  const evaluator = (evaluators[index] ??= getEntryEvaluator(
@@ -771,7 +820,8 @@ const compileAction = (
771
820
  }
772
821
  };
773
822
  }
774
- const hoisted = isInit ? undefined : getHoistedGuards(expression, environment);
823
+ const hoisted =
824
+ isInit || environment.trace ? undefined : getHoistedGuards(expression, environment);
775
825
  if (hoisted) {
776
826
  const rest = compileConjunction(hoisted.rest, environment, isInit);
777
827
  return (run, scope, partial, action, isFixed, onComplete) => {
@@ -906,8 +956,17 @@ const compileAction = (
906
956
  const unchanged = getUnchangedWrapper(expression.subscript);
907
957
  return (run, scope, partial, action, isFixed, onComplete) =>
908
958
  body(run, scope, partial, action, isFixed, (nextPartial, nextAction) => {
909
- if (!holds(unchanged, getContext(run, scope, nextPartial)))
910
- onComplete(nextPartial, nextAction);
959
+ // ENABLED evaluates the subscript on the successor that the action specifies. TLC names
960
+ // a variable that the action leaves without a value.
961
+ try {
962
+ if (!holds(unchanged, getContext(run, scope, nextPartial)))
963
+ onComplete(nextPartial, nextAction);
964
+ } catch (error) {
965
+ if (!run.isEnabled || !(error instanceof TlaUnassignedError)) throw error;
966
+ throw new TlaEvaluationError(
967
+ `The action formula A appearing in a WF_v(A) or SF_v(A) operator does not specify the primed value of the variable ${error.variable} occurring in the state formula v.\n`,
968
+ );
969
+ }
911
970
  });
912
971
  }
913
972
  case "BoxAction":
@@ -984,7 +1043,13 @@ export const isEnabled = (expression: Expression, context: Context): boolean =>
984
1043
  );
985
1044
  }
986
1045
  const environment = context.environment;
987
- const run: Run = { environment, isInit: false, current: state, isStopped: false };
1046
+ const run: Run = {
1047
+ environment,
1048
+ isInit: false,
1049
+ isEnabled: true,
1050
+ current: state,
1051
+ isStopped: false,
1052
+ };
988
1053
  // TLC stops computing ENABLED at the first successor, so it skips the rest of the action.
989
1054
  getRunner(expression, environment, false)(
990
1055
  run,
@@ -1005,7 +1070,13 @@ export const forEachInitialState = (
1005
1070
  onState: (state: Value[]) => boolean,
1006
1071
  scope?: Scope,
1007
1072
  ) => {
1008
- const run: Run = { environment, isInit: true, current: undefined, isStopped: false };
1073
+ const run: Run = {
1074
+ environment,
1075
+ isInit: true,
1076
+ isEnabled: false,
1077
+ current: undefined,
1078
+ isStopped: false,
1079
+ };
1009
1080
  getRunner(expression, environment, true)(
1010
1081
  run,
1011
1082
  scope,
@@ -1015,14 +1086,7 @@ export const forEachInitialState = (
1015
1086
  (partial) => {
1016
1087
  if (run.isStopped) return;
1017
1088
  if (!isComplete(partial)) {
1018
- // TLC reports an initial state that isn't completely specified as an illegal state, not as
1019
- // an evaluation failure.
1020
- throw setExitCode(
1021
- new TlaEvaluationError(
1022
- `The initial predicate does not assign ${getMissingVariables(partial, environment).join(", ")}`,
1023
- ),
1024
- EXIT_STATUS.error,
1025
- );
1089
+ throw setExitCode(new TlaIllegalStateError(partial), EXIT_STATUS.error);
1026
1090
  }
1027
1091
  run.isStopped = onState(partial);
1028
1092
  },
@@ -1054,7 +1118,13 @@ export const forEachSuccessor = (
1054
1118
  onSuccessor: (successor: Successor) => boolean,
1055
1119
  scope?: Scope,
1056
1120
  ) => {
1057
- const run: Run = { environment, isInit: false, current: state, isStopped: false };
1121
+ const run: Run = {
1122
+ environment,
1123
+ isInit: false,
1124
+ isEnabled: false,
1125
+ current: state,
1126
+ isStopped: false,
1127
+ };
1058
1128
  const counter = { successors: 0 };
1059
1129
  getRunner(expression, environment, false)(
1060
1130
  run,
@@ -0,0 +1,29 @@
1
+ import type { Expression } from "./ast";
2
+ import { TlaEvaluationError } from "./errors";
3
+ import type { Value } from "./values";
4
+
5
+ // While TLC replays a failure, it gives each set, tuple or record it builds the expression that
6
+ // built it. A method of such a value that fails prepends that expression to the error's trace, and
7
+ // TLC reports the error as one it was unable to fingerprint.
8
+ export const valueSources: { current: WeakMap<object, Expression> | undefined } = {
9
+ current: undefined,
10
+ };
11
+
12
+ const fingerprintTraces = new WeakMap<TlaEvaluationError, Expression[]>();
13
+
14
+ export const getFingerprintTrace = (error: unknown) =>
15
+ error instanceof TlaEvaluationError ? fingerprintTraces.get(error) : undefined;
16
+
17
+ export const withSource = <T>(value: Value, run: () => T): T => {
18
+ const sources = valueSources.current;
19
+ if (!sources || typeof value !== "object") return run();
20
+ try {
21
+ return run();
22
+ } catch (error) {
23
+ const source = sources.get(value);
24
+ if (source && error instanceof TlaEvaluationError) {
25
+ fingerprintTraces.set(error, [source, ...(fingerprintTraces.get(error) ?? [])]);
26
+ }
27
+ throw error;
28
+ }
29
+ };