tla-ts 0.0.3-dev.bffbba3 → 0.0.3-dev.c8c988d

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.
@@ -7,13 +7,12 @@ import {
7
7
  } from "./ast";
8
8
  import type { ModelConfig } from "./config";
9
9
  import type { InstanceAction } from "./environment";
10
- import { TlaError } from "./errors";
10
+ import { formatRange, TlaError } from "./errors";
11
11
  import {
12
12
  bindDefinitions,
13
13
  bindOperatorArguments,
14
14
  evaluate,
15
15
  forEachBinding,
16
- formatRange,
17
16
  getDefinition,
18
17
  isConstantLevel,
19
18
  lookupScope,
@@ -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}`);
@@ -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
 
@@ -101,17 +104,38 @@ export const checkInstances = (
101
104
  definition.formals.every((formal) => formal.name !== operator && formal.name !== param),
102
105
  ),
103
106
  );
107
+ const addAssumedLevels = (data: ReturnType<typeof analyzeAssumeProve>) => {
108
+ addLevels(data, () => true);
109
+ module.constants.forEach((constant) => {
110
+ if (data.params.has(constant.name)) {
111
+ putConstraint(levels.constraints, constant.name, ACTION_LEVEL);
112
+ }
113
+ });
114
+ };
104
115
  module.assumptions.forEach((assumption) =>
105
- addLevels(analyzer.analyze(assumption, new Map()), () => true),
116
+ addAssumedLevels(analyzer.analyze(assumption, new Map())),
117
+ );
118
+ module.theorems.forEach((theorem) =>
119
+ theorem.statement.kind === "AssumeProve"
120
+ ? addAssumedLevels(analyzeAssumeProve(theorem.statement, new Map(), analyzer))
121
+ : addLevels(analyzer.analyze(theorem.statement, new Map()), () => true),
106
122
  );
107
123
  moduleLevels.set(name, levels);
108
124
  return levels;
109
125
  };
110
126
 
111
- const messages = new Set<string>();
127
+ const errors = new Map<string, { location: string; message: string }>();
112
128
  checks.forEach((check) => {
113
- const location = `at line ${check.location.line}, column ${check.location.column}`;
114
- const addMessage = (message: string) => messages.add(`${message} ${location}`);
129
+ // SANY reports each error at the whole instance.
130
+ const location = formatRange(
131
+ check.location.range ?? {
132
+ module: check.instancer,
133
+ start: check.location,
134
+ end: check.location,
135
+ },
136
+ );
137
+ const addMessage = (message: string) =>
138
+ errors.set(`${location}\n${message}`, { location, message });
115
139
  const instancee = getModule(check.module);
116
140
  const levels = getModuleLevels(check.module);
117
141
  const analyzer = getAnalyzer(check.instancer);
@@ -141,14 +165,14 @@ export const checkInstances = (
141
165
  ];
142
166
  });
143
167
  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}`;
168
+ `Level error in instantiating module '${check.module}':\nThe level of the expression or operator substituted for '${name}' \nmust be at most ${level}.`;
145
169
  substituted.forEach((item) => {
146
170
  if (!levels.isConstant && item.level > item.maximumLevel) {
147
171
  addMessage(getLevelMessage(item.name, item.maximumLevel));
148
172
  }
149
173
  if (!item.isLeibniz) {
150
174
  addMessage(
151
- `Error in instantiating module '${check.module}': a non-Leibniz operator substituted for '${item.name}'`,
175
+ `Error in instantiating module '${check.module}':\n A non-Leibniz operator substituted for '${item.name}'.`,
152
176
  );
153
177
  }
154
178
  });
@@ -162,7 +186,7 @@ export const checkInstances = (
162
186
  const minimum = levels.argConstraints.get(getArgumentKey(item.name, index));
163
187
  if (minimum !== undefined && getMaxLevel(operator, index) < minimum) {
164
188
  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}`,
189
+ `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
190
  );
167
191
  }
168
192
  });
@@ -175,10 +199,10 @@ export const checkInstances = (
175
199
  const maximum = getMaxLevel(operator, parameter.index);
176
200
  if (argument.level > maximum) {
177
201
  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}`,
202
+ `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
203
  );
180
204
  }
181
205
  });
182
206
  });
183
- if (messages.size > 0) throw new TlaSyntaxError([...messages].join("\n"));
207
+ if (errors.size > 0) throw createSanyError([...errors.values()]);
184
208
  };
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, UNEXPECTED_EXCEPTION } 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
  }
@@ -89,24 +95,54 @@ const assign = (partial: State, index: number, value: Value) => {
89
95
  return copy;
90
96
  };
91
97
 
92
- const holds = (expression: Expression, context: Context, value = evaluate(expression, context)) => {
98
+ // TLC's Tool.getInitStates and Tool.getNextStates report a value where they expect a formula.
99
+ const expectFormula = (expression: Expression, value: Value, isInit: boolean) => {
93
100
  if (typeof value === "boolean") return value;
94
- try {
95
- return expectBoolean(value, `the action at ${describeLocation(expression)}`);
96
- } catch (error) {
97
- // TLC fails with an unexpected exception when the next-state relation isn't a boolean.
98
- throw context.next === undefined ? error : setExitCode(error, EXIT_STATUS.error);
101
+ throw new TlaEvaluationError(
102
+ `In computing ${isInit ? "initial" : "next"} states, TLC expected a boolean expression,\nbut instead found ${formatValue(value)}.\n${describeRange(expression)}`,
103
+ );
104
+ };
105
+
106
+ const holds = (expression: Expression, context: Context, value = evaluate(expression, context)) => {
107
+ // TLC rejects a number in the next-state relation when it splits the relation into actions.
108
+ if (context.next !== undefined && expression.kind === "Number") {
109
+ throw setExitCode(
110
+ new TlaEvaluationError(
111
+ `The next state relation is not a boolean expression.\n${expression.text ?? expression.value}`,
112
+ ),
113
+ EXIT_STATUS.error,
114
+ );
99
115
  }
116
+ return expectFormula(expression, value, context.next === undefined);
100
117
  };
101
118
 
102
119
  const isAssignmentOperator = (operator: string) =>
103
120
  operator === "=" || operator === "\\in" || operator === "\\subseteq";
104
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
+
105
131
  const getRunner = (expression: Expression, environment: Environment, isInit: boolean): Runner => {
106
- const runners = isInit ? initRunners : nextRunners;
132
+ const runners = getRunners(environment, isInit);
107
133
  const cached = runners.get(expression);
108
134
  if (cached) return cached;
109
- 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;
110
146
  runners.set(expression, runner);
111
147
  return runner;
112
148
  };
@@ -190,6 +226,23 @@ const getUnchangedIndices = (
190
226
  return getUnchangedIndices(definition.body, environment, visited);
191
227
  };
192
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
+
193
246
  const ACTION_KINDS = new Set([
194
247
  "Label",
195
248
  "And",
@@ -322,6 +375,7 @@ const compileConjunction = (
322
375
  ): Runner => {
323
376
  const conjuncts = operands.map((operand) => toConjunct(operand, environment, isInit));
324
377
  const evaluators: (Evaluator | undefined)[] = conjuncts.map(() => undefined);
378
+ const trace = environment.trace;
325
379
  const runFrom = (
326
380
  start: number,
327
381
  run: Run,
@@ -342,6 +396,12 @@ const compileConjunction = (
342
396
  return;
343
397
  }
344
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
+ }
345
405
  if (conjunct.kind === "Guard") {
346
406
  context ??= getContext(run, scope, current);
347
407
  const evaluator = (evaluators[index] ??= getEntryEvaluator(
@@ -391,10 +451,7 @@ const compileConjunction = (
391
451
  };
392
452
 
393
453
  const holdsInInit = (expression: Expression, context: Context) =>
394
- expectBoolean(
395
- evaluate(expression, context),
396
- `the initial predicate at ${describeLocation(expression)}`,
397
- );
454
+ expectFormula(expression, evaluate(expression, context), true);
398
455
 
399
456
  const compileGuard =
400
457
  (expression: Expression): Runner =>
@@ -419,7 +476,7 @@ const compileMembership = (
419
476
  expression.operator === "\\subseteq" ? { kind: "Subset", base: evaluated } : evaluated;
420
477
  if (!isEnumerable(value)) {
421
478
  throw new TlaEvaluationError(
422
- `In computing next states, the right side of \\in is not enumerable: ${formatValue(value)} at ${describeLocation(expression)}`,
479
+ `In computing ${run.isInit ? "initial" : "next"} states, the right side of \\IN is not enumerable.\n${describeRange(expression)}`,
423
480
  );
424
481
  }
425
482
  const elements = getStreamedElements(value);
@@ -763,7 +820,8 @@ const compileAction = (
763
820
  }
764
821
  };
765
822
  }
766
- const hoisted = isInit ? undefined : getHoistedGuards(expression, environment);
823
+ const hoisted =
824
+ isInit || environment.trace ? undefined : getHoistedGuards(expression, environment);
767
825
  if (hoisted) {
768
826
  const rest = compileConjunction(hoisted.rest, environment, isInit);
769
827
  return (run, scope, partial, action, isFixed, onComplete) => {
@@ -866,7 +924,7 @@ const compileAction = (
866
924
  const body = arm?.body ?? other;
867
925
  if (!body)
868
926
  throw new TlaEvaluationError(
869
- `${UNEXPECTED_EXCEPTION}In computing next states, TLC encountered a CASE with no conditions true.\n${describeRange(expression)}`,
927
+ `In computing ${run.isInit ? "initial" : "next"} states, TLC encountered a CASE with no conditions true.\n${describeRange(expression)}`,
870
928
  );
871
929
  body(run, scope, partial, action, isFixed, onComplete);
872
930
  };
@@ -898,8 +956,17 @@ const compileAction = (
898
956
  const unchanged = getUnchangedWrapper(expression.subscript);
899
957
  return (run, scope, partial, action, isFixed, onComplete) =>
900
958
  body(run, scope, partial, action, isFixed, (nextPartial, nextAction) => {
901
- if (!holds(unchanged, getContext(run, scope, nextPartial)))
902
- 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
+ }
903
970
  });
904
971
  }
905
972
  case "BoxAction":
@@ -976,7 +1043,13 @@ export const isEnabled = (expression: Expression, context: Context): boolean =>
976
1043
  );
977
1044
  }
978
1045
  const environment = context.environment;
979
- 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
+ };
980
1053
  // TLC stops computing ENABLED at the first successor, so it skips the rest of the action.
981
1054
  getRunner(expression, environment, false)(
982
1055
  run,
@@ -997,7 +1070,13 @@ export const forEachInitialState = (
997
1070
  onState: (state: Value[]) => boolean,
998
1071
  scope?: Scope,
999
1072
  ) => {
1000
- 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
+ };
1001
1080
  getRunner(expression, environment, true)(
1002
1081
  run,
1003
1082
  scope,
@@ -1007,14 +1086,7 @@ export const forEachInitialState = (
1007
1086
  (partial) => {
1008
1087
  if (run.isStopped) return;
1009
1088
  if (!isComplete(partial)) {
1010
- // TLC reports an initial state that isn't completely specified as an illegal state, not as
1011
- // an evaluation failure.
1012
- throw setExitCode(
1013
- new TlaEvaluationError(
1014
- `The initial predicate does not assign ${getMissingVariables(partial, environment).join(", ")}`,
1015
- ),
1016
- EXIT_STATUS.error,
1017
- );
1089
+ throw setExitCode(new TlaIllegalStateError(partial), EXIT_STATUS.error);
1018
1090
  }
1019
1091
  run.isStopped = onState(partial);
1020
1092
  },
@@ -1046,7 +1118,13 @@ export const forEachSuccessor = (
1046
1118
  onSuccessor: (successor: Successor) => boolean,
1047
1119
  scope?: Scope,
1048
1120
  ) => {
1049
- 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
+ };
1050
1128
  const counter = { successors: 0 };
1051
1129
  getRunner(expression, environment, false)(
1052
1130
  run,
@@ -1057,8 +1135,10 @@ export const forEachSuccessor = (
1057
1135
  (partial, action) => {
1058
1136
  if (run.isStopped) return;
1059
1137
  if (!isComplete(partial)) {
1060
- throw new TlaEvaluationError(
1061
- `Successor state is not completely specified by action ${action ?? "Next"}. The following variables are not assigned: ${getMissingVariables(partial, environment).join(", ")}`,
1138
+ throw new TlaIncompleteStateError(
1139
+ partial,
1140
+ action,
1141
+ getMissingVariables(partial, environment).sort(),
1062
1142
  );
1063
1143
  }
1064
1144
  counter.successors++;
package/src/symmetry.ts CHANGED
@@ -1,5 +1,6 @@
1
- import { TlaConfigError } from "./errors";
1
+ import { TlaConfigError, TlaEvaluationError, UNEXPECTED_EXCEPTION } from "./errors";
2
2
  import { evaluate, type Environment } from "./evaluate";
3
+ import { EXIT_STATUS, setExitCode } from "./exit-codes";
3
4
  import {
4
5
  compareValues,
5
6
  createFunction,
@@ -47,9 +48,13 @@ const composePermutations = (first: Images, second: Images) => {
47
48
  return composed;
48
49
  };
49
50
 
50
- const toImages = (value: Value, name: string) => {
51
+ // TLC checks the symmetry set outside any phase that reports an error itself.
52
+ const createSymmetryError = (message: string) =>
53
+ setExitCode(new TlaEvaluationError(`${UNEXPECTED_EXCEPTION}${message}`), EXIT_STATUS.error);
54
+
55
+ const toImages = (value: Value) => {
51
56
  if (!isFunctionValue(value)) {
52
- throw new TlaConfigError(`The symmetry values of ${name} must be functions`);
57
+ throw createSymmetryError("The symmetry values must be function records.");
53
58
  }
54
59
  const functionValue = toFiniteFunction(value);
55
60
  const permutation: Images = new Map();
@@ -65,8 +70,13 @@ const toImages = (value: Value, name: string) => {
65
70
 
66
71
  export const getSymmetryGroup = (name: string, environment: Environment): Permutation[] => {
67
72
  const definition = environment.definitions.get(name);
73
+ if (definition === undefined && !environment.constants.has(name)) {
74
+ throw new TlaConfigError(
75
+ `The symmetry function ${name} specified in the configuration file\nis not defined in the specification.`,
76
+ );
77
+ }
68
78
  if (definition?.kind !== "Operator" || definition.params.length > 0) {
69
- throw new TlaConfigError(`The symmetry function ${name} must specify a set of permutations`);
79
+ throw createSymmetryError(`The symmetry function ${name} must specify a set of permutations.`);
70
80
  }
71
81
  const value = evaluate(definition.body, {
72
82
  environment,
@@ -75,9 +85,9 @@ export const getSymmetryGroup = (name: string, environment: Environment): Permut
75
85
  next: undefined,
76
86
  });
77
87
  if (!isSetValue(value) || !isEnumerable(value)) {
78
- throw new TlaConfigError("The symmetry operator must specify a set of functions");
88
+ throw createSymmetryError("The symmetry operator must specify a set of functions.");
79
89
  }
80
- const permutations = toFiniteSet(value).elements.map((element) => toImages(element, name));
90
+ const permutations = toFiniteSet(value).elements.map(toImages);
81
91
  const isDisabled =
82
92
  definition.body.kind === "Apply" && definition.body.args.length >= permutations.length;
83
93
  if (isDisabled) return [];
package/src/tableau.ts CHANGED
@@ -289,7 +289,7 @@ const toDisjunctiveNormalForm = (expression: LiveExpression): LiveExpression =>
289
289
  total.value *= normal.operands.length;
290
290
  if (total.value > MAXIMUM_DISJUNCTS) {
291
291
  throw new TlaEvaluationError(
292
- "TLC cannot handle the temporal formula because it exceeds the maximum supported size in disjunctive normal form",
292
+ "TLC cannot handle the temporal formula because it exceeds the maximum supported size in disjunctive normal form.",
293
293
  );
294
294
  }
295
295
  }
package/src/tlc-module.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { TlaModuleError } from "./errors";
1
+ import { TlaEvaluationError, TlaModuleError } from "./errors";
2
2
  import { EXIT_STATUS } from "./exit-codes";
3
3
  import type { Builtin } from "./evaluate";
4
4
  import { prettyPrint } from "./pretty-print";
@@ -48,7 +48,7 @@ const getRuntimeValue = (
48
48
  state: (Value | undefined)[] | undefined,
49
49
  ) => {
50
50
  if (!runtime.isStarted && CHECKER_KEYS.has(key)) {
51
- throw new TlaModuleError(`TLCGet(${key}) was undefined.`);
51
+ throw new TlaEvaluationError(`TLCGet(${key}) was undefined.`);
52
52
  }
53
53
  const duration = Math.floor((Date.now() - runtime.startedAt) / 1000);
54
54
  switch (key) {
@@ -104,11 +104,11 @@ const getRuntimeValue = (
104
104
  }
105
105
  if (key.startsWith(NAMED_REGISTER_PREFIX)) {
106
106
  const value = getNamedRegisters(runtime).get(key);
107
- if (value === undefined) throw new TlaModuleError(`TLCGet(${key}) was undefined.`);
107
+ if (value === undefined) throw new TlaEvaluationError(`TLCGet(${key}) was undefined.`);
108
108
  return value;
109
109
  }
110
110
  if (key.startsWith("-D")) return rankString(runtime.properties.get(key.slice(2)) ?? key);
111
- throw new TlaModuleError(`TLCGet(${key}) was undefined.`);
111
+ throw new TlaEvaluationError(`TLCGet(${key}) was undefined.`);
112
112
  };
113
113
 
114
114
  const getPermutations = (elements: Value[]): Value[][] =>
@@ -197,11 +197,11 @@ export const createTlcOperators = (
197
197
  const key = getValue(args, 0, "TLCGet");
198
198
  if (typeof key === "number" && key >= 0) {
199
199
  const value = runtime.registers.get(key);
200
- if (value === undefined) throw new TlaModuleError(`TLCGet(${key}) was undefined.`);
200
+ if (value === undefined) throw new TlaEvaluationError(`TLCGet(${key}) was undefined.`);
201
201
  return value;
202
202
  }
203
203
  if (typeof key !== "string") {
204
- throw new TlaModuleError(
204
+ throw new TlaEvaluationError(
205
205
  `The argument of TLCGet should be a nonnegative integer, but instead it is:\n${formatValue(key)}`,
206
206
  );
207
207
  }
@@ -1013,6 +1013,10 @@ export const TLC_JAVA_METHODS = new Map([
1013
1013
  "RandomElement",
1014
1014
  "public static tlc2.value.impl.Value tlc2.module.TLC.RandomElement(tlc2.value.impl.Value)",
1015
1015
  ],
1016
+ [
1017
+ "TLCGet",
1018
+ "public static tlc2.value.impl.Value tlc2.module.TLCGetSet.TLCGetEval(tlc2.tool.impl.Tool,tla2sany.semantic.ExprOrOpArgNode[],tlc2.util.Context,tlc2.tool.TLCState,tlc2.tool.TLCState,int,tlc2.tool.coverage.CostModel)",
1019
+ ],
1016
1020
  [
1017
1021
  "TLCEval",
1018
1022
  "public static tlc2.value.impl.Value tlc2.module.TLCEval.tlcEval(tlc2.tool.impl.Tool,tla2sany.semantic.ExprOrOpArgNode[],tlc2.util.Context,tlc2.tool.TLCState,tlc2.tool.TLCState,int,tlc2.tool.coverage.CostModel)",
package/src/tlc-order.ts CHANGED
@@ -278,9 +278,13 @@ const createModuleSet = (source: string, loadModule: ModuleLoader) => {
278
278
  (name === undefined ? undefined : nestedModules.get(name)) ?? getFile(name);
279
279
  };
280
280
 
281
- // The variables in the order TLC compares them: the reverse of the root module's context
282
- // enumeration, as ModuleNode.getVariableDecls returns them.
283
- export const getTlcVariableOrder = (source: string, loadModule: ModuleLoader): string[] => {
281
+ // The constants or variables in the order of ModuleNode.getConstantDecls or getVariableDecls: the
282
+ // reverse of the root module's context enumeration. TLC compares a state's variables in this order.
283
+ export const getTlcDeclarationOrder = (
284
+ source: string,
285
+ loadModule: ModuleLoader,
286
+ kind: "constant" | "variable",
287
+ ): string[] => {
284
288
  const getParsed = createModuleSet(source, loadModule);
285
289
  const getUnits = (unit: ParsedModule) => {
286
290
  const tokens = unit.tokens;
@@ -400,7 +404,7 @@ export const getTlcVariableOrder = (source: string, loadModule: ModuleLoader): s
400
404
  };
401
405
  return getContext(undefined)
402
406
  .enumerate()
403
- .filter((entry) => entry.kind === "variable")
407
+ .filter((entry) => entry.kind === kind)
404
408
  .map((entry) => entry.name)
405
409
  .reverse();
406
410
  };