tla-ts 0.0.3-dev.b0f84e8 → 0.0.3-dev.b4e335d

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/dist/cli.cjs +1 -1
  2. package/dist/cli.js +1 -1
  3. package/dist/index.cjs +1 -1
  4. package/dist/index.d.cts +150 -8
  5. package/dist/index.d.ts +150 -8
  6. package/dist/index.js +1 -1
  7. package/dist/parallel-worker.cjs +1 -1
  8. package/dist/parallel-worker.js +2 -2
  9. package/dist/parallel.cjs +1 -1
  10. package/dist/parallel.js +2 -2
  11. package/dist/run-cli.cjs +1351 -20
  12. package/dist/run-cli.js +1351 -20
  13. package/dist/transfer.cjs +86 -28
  14. package/dist/transfer.js +86 -28
  15. package/package.json +5 -1
  16. package/src/ast.ts +57 -6
  17. package/src/bags.ts +4 -7
  18. package/src/builtins.ts +29 -11
  19. package/src/bundled-modules.ts +3 -3
  20. package/src/canonical.ts +4 -3
  21. package/src/check.ts +1393 -226
  22. package/src/cli.ts +8 -1
  23. package/src/codegen.ts +68 -18
  24. package/src/config.ts +252 -179
  25. package/src/environment.ts +457 -132
  26. package/src/errors.ts +217 -3
  27. package/src/evaluate.ts +722 -112
  28. package/src/exit-codes.ts +5 -4
  29. package/src/index.ts +1 -0
  30. package/src/instances.ts +4 -2
  31. package/src/java-overrides.ts +104 -25
  32. package/src/levels.ts +183 -37
  33. package/src/lexer.ts +112 -29
  34. package/src/live-check.ts +220 -102
  35. package/src/liveness.ts +216 -52
  36. package/src/obligation-expression.ts +2 -2
  37. package/src/obligation-source.ts +2 -0
  38. package/src/parallel-worker.ts +8 -3
  39. package/src/parallel.ts +56 -5
  40. package/src/parser.ts +445 -147
  41. package/src/pcal-ast.ts +770 -0
  42. package/src/pcal-parse.ts +1523 -0
  43. package/src/pcal-tokenize.ts +516 -0
  44. package/src/pcal-translate.ts +1230 -0
  45. package/src/pcal-validate.ts +454 -0
  46. package/src/randomization.ts +24 -7
  47. package/src/resolve.ts +1465 -411
  48. package/src/run-cli.ts +1167 -155
  49. package/src/runtime.ts +16 -0
  50. package/src/sany-builtins.ts +147 -0
  51. package/src/sany-generator.ts +3128 -0
  52. package/src/sany-levels.ts +1208 -0
  53. package/src/sany-lexer.ts +545 -0
  54. package/src/sany-linter.ts +122 -0
  55. package/src/sany-modules.ts +1398 -0
  56. package/src/sany-nodes.ts +463 -0
  57. package/src/sany-parse-error.ts +2161 -0
  58. package/src/sany-report.ts +354 -0
  59. package/src/sany-selectors.ts +738 -0
  60. package/src/sany-source.ts +248 -0
  61. package/src/sany-xml.ts +1017 -0
  62. package/src/spec-description.ts +26 -7
  63. package/src/standard-modules.ts +200 -148
  64. package/src/standard-ranges.ts +116 -0
  65. package/src/state-graph.ts +29 -6
  66. package/src/subexpressions.ts +221 -161
  67. package/src/substitution-levels.ts +38 -17
  68. package/src/successors.ts +207 -103
  69. package/src/symmetry.ts +180 -52
  70. package/src/tableau.ts +54 -25
  71. package/src/tlc-ext.ts +13 -17
  72. package/src/tlc-messages.ts +329 -0
  73. package/src/tlc-module.ts +46 -18
  74. package/src/tlc-order.ts +56 -6
  75. package/src/tlc-random.ts +37 -9
  76. package/src/tlc-replay.ts +655 -0
  77. package/src/tlc-summary.ts +20 -5
  78. package/src/tlc-version.ts +18 -0
  79. package/src/transfer.ts +15 -3
  80. package/src/value-sources.ts +29 -0
  81. package/src/values.ts +697 -180
@@ -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
@@ -1,17 +1,19 @@
1
1
  import {
2
2
  getChildren,
3
3
  isLocallyResolved,
4
- type Bound,
5
4
  type Definition,
6
5
  type Expression,
6
+ type QuantifierExpression,
7
7
  } from "./ast";
8
+ import { getKindString } from "./builtins";
8
9
  import { getReadVariables } from "./dependencies";
9
- import { TlaEvaluationError, UNEXPECTED_EXCEPTION } from "./errors";
10
+ import { TlaEvaluationError, TlaIllegalStateError, TlaIncompleteSuccessorError } from "./errors";
10
11
  import { EXIT_STATUS, setExitCode } from "./exit-codes";
11
12
  import {
12
13
  describeLocation,
14
+ describeNode,
13
15
  describeRange,
14
- bindArgument,
16
+ bindLazyArguments,
15
17
  bindDefinitions,
16
18
  bindOperatorArguments,
17
19
  bindValue,
@@ -19,25 +21,27 @@ import {
19
21
  evaluate,
20
22
  expectBoolean,
21
23
  forEachBinding,
22
- getBoundsDomain,
24
+ getLazyFunction,
25
+ toKeepLazyContext,
23
26
  getDefinition,
24
- getEnumeratedElements,
27
+ getContextElements,
25
28
  getReevaluatedDefinitions,
26
29
  lookupScope,
27
30
  resolveApplyOperator,
28
31
  resolveGlobalOperator,
32
+ toUnspecifiedSubscriptError,
29
33
  type Context,
30
34
  type Environment,
31
35
  type Scope,
32
36
  type State,
33
37
  } from "./evaluate";
34
38
  import { mapChildren } from "./instances";
39
+ import { isAssignedShortcut, LITERAL_KINDS, replayEnabled } from "./tlc-replay";
35
40
  import {
36
- createTuple,
37
41
  formatValue,
38
42
  getStreamedElements,
39
- isElementOf,
40
- isEnumerable,
43
+ isFunctionValue,
44
+ isTlcEnumerable,
41
45
  valuesEqual,
42
46
  type Value,
43
47
  } from "./values";
@@ -50,6 +54,8 @@ export interface Successor {
50
54
  interface Run {
51
55
  environment: Environment;
52
56
  isInit: boolean;
57
+ // Whether the run computes ENABLED rather than the successors of the state.
58
+ isEnabled: boolean;
53
59
  current: Value[] | undefined;
54
60
  isStopped: boolean;
55
61
  }
@@ -86,15 +92,47 @@ const assign = (partial: State, index: number, value: Value) => {
86
92
  return copy;
87
93
  };
88
94
 
89
- const holds = (expression: Expression, context: Context) => {
95
+ // What TLC says it was computing when it fails.
96
+ const getComputation = (run: Run) =>
97
+ run.isInit ? "initial states" : run.isEnabled ? "ENABLED" : "next states";
98
+
99
+ // TLC fails with an unexpected exception when it fails to compute the next states or ENABLED.
100
+ const createRunError = (run: Run, message: string) => {
101
+ const error = new TlaEvaluationError(message);
102
+ return run.isInit ? error : setExitCode(error, EXIT_STATUS.error);
103
+ };
104
+
105
+ // TLC's message for a conjunct that isn't a boolean, which differs for a literal it walks to rather
106
+ // than evaluates.
107
+ const getNonBooleanMessage = (
108
+ run: Run,
109
+ value: Value,
110
+ expression: Expression,
111
+ isWalked: boolean,
112
+ ) => {
113
+ const node = describeNode(expression);
114
+ if (isWalked && LITERAL_KINDS.has(expression.kind)) {
115
+ return run.isEnabled
116
+ ? `Attempted to compute ENABLED on a non-boolean expression.\n${node}`
117
+ : `The ${run.isInit ? "init" : "next"} state relation is not a boolean expression.\n${node}`;
118
+ }
119
+ return `In computing ${getComputation(run)}, TLC expected a boolean expression,\nbut instead found ${formatValue(value)}.\n${node}`;
120
+ };
121
+
122
+ // TLC words an IF whose condition isn't a boolean differently for each computation.
123
+ const getIfConditionMessage = (run: Run, value: Value, expression: Expression) => {
124
+ const kind = getKindString(value);
125
+ const range = describeRange(expression);
126
+ if (run.isEnabled) {
127
+ return `In computing ENABLED, a non-boolean expression(${kind}) was used as the guard condition of an IF.\n${range}`;
128
+ }
129
+ return `In computing ${getComputation(run)}, a non-boolean expression (${kind}) was used as the condition of an IF.${run.isInit ? "\n" : ""}${range}`;
130
+ };
131
+
132
+ const holds = (run: Run, expression: Expression, context: Context, isWalked = true) => {
90
133
  const value = evaluate(expression, context);
91
134
  if (typeof value === "boolean") return value;
92
- try {
93
- return expectBoolean(value, `the action at ${describeLocation(expression)}`);
94
- } catch (error) {
95
- // TLC fails with an unexpected exception when the next-state relation isn't a boolean.
96
- throw context.next === undefined ? error : setExitCode(error, EXIT_STATUS.error);
97
- }
135
+ throw createRunError(run, getNonBooleanMessage(run, value, expression, isWalked));
98
136
  };
99
137
 
100
138
  const isAssignmentOperator = (operator: string) =>
@@ -292,6 +330,27 @@ const toConjunct = (
292
330
  return { kind: "Branch", expression, runner: getRunner(expression, environment, isInit) };
293
331
  };
294
332
 
333
+ // The leading guards of `\E x \in S, y \in T : P /\ Q` that read no inner bound hold for every inner
334
+ // binding alike, so they can run once for each element of the outermost bound.
335
+ const getHoistedGuards = (expression: QuantifierExpression, environment: Environment) => {
336
+ if (expression.bounds.length < 2 || expression.body.kind !== "And") return undefined;
337
+ const names = expression.bounds.flatMap((bound) =>
338
+ bound.pattern.kind === "Name" ? [bound.pattern.name] : [],
339
+ );
340
+ if (names.length !== expression.bounds.length) return undefined;
341
+ const innerNames = new Set(names.slice(0, -1));
342
+ const operands = expression.body.operands;
343
+ const index = operands.findIndex((operand) => {
344
+ if (getReadVariables(operand, environment) === undefined) return true;
345
+ if (hasBranches(operand, environment, new Set())) return true;
346
+ const readLocals = getReadLocals(operand, NO_NAMES);
347
+ return !readLocals || readLocals.some((name) => innerNames.has(name));
348
+ });
349
+ const count = index === -1 ? operands.length : index;
350
+ if (count === 0) return undefined;
351
+ return { names, guards: operands.slice(0, count), rest: operands.slice(count) };
352
+ };
353
+
295
354
  const compileConjunction = (
296
355
  operands: Expression[],
297
356
  environment: Environment,
@@ -308,11 +367,12 @@ const compileConjunction = (
308
367
  ): void => {
309
368
  let current = partial;
310
369
  let context: Context | undefined;
370
+ const isShortcut = isAssignedShortcut(run);
311
371
  for (let index = start; index < conjuncts.length; index++) {
312
- if (index > 0 && run.isInit && isComplete(current)) {
372
+ if (index > 0 && isShortcut && isComplete(current)) {
313
373
  context ??= getContext(run, scope, current);
314
374
  for (let rest = index; rest < conjuncts.length; rest++) {
315
- if (!holdsInInit(conjuncts[rest].expression, context)) return;
375
+ if (!holds(run, conjuncts[rest].expression, context, false)) return;
316
376
  }
317
377
  onComplete(current, action);
318
378
  return;
@@ -320,7 +380,7 @@ const compileConjunction = (
320
380
  const conjunct = conjuncts[index];
321
381
  if (conjunct.kind === "Guard") {
322
382
  context ??= getContext(run, scope, current);
323
- if (!holds(conjunct.expression, context)) return;
383
+ if (!holds(run, conjunct.expression, context)) return;
324
384
  continue;
325
385
  }
326
386
  if (conjunct.kind === "Assign") {
@@ -361,16 +421,10 @@ const compileConjunction = (
361
421
  runFrom(0, run, scope, partial, action, onComplete);
362
422
  };
363
423
 
364
- const holdsInInit = (expression: Expression, context: Context) =>
365
- expectBoolean(
366
- evaluate(expression, context),
367
- `the initial predicate at ${describeLocation(expression)}`,
368
- );
369
-
370
424
  const compileGuard =
371
425
  (expression: Expression): Runner =>
372
426
  (run, scope, partial, action, _isFixed, onComplete) => {
373
- if (holds(expression, getContext(run, scope, partial))) onComplete(partial, action);
427
+ if (holds(run, expression, getContext(run, scope, partial))) onComplete(partial, action);
374
428
  };
375
429
 
376
430
  const compileMembership = (
@@ -382,16 +436,17 @@ const compileMembership = (
382
436
  const index = getIndex(run, scope, partial);
383
437
  const context = getContext(run, scope, partial);
384
438
  if (partial[index] !== undefined) {
385
- if (holds(expression, context)) onComplete(partial, action);
439
+ if (holds(run, expression, context)) onComplete(partial, action);
386
440
  return;
387
441
  }
388
442
  const evaluated = evaluate(set, context);
389
443
  const value: Value =
390
444
  expression.operator === "\\subseteq" ? { kind: "Subset", base: evaluated } : evaluated;
391
- if (!isEnumerable(value)) {
392
- throw new TlaEvaluationError(
393
- `In computing next states, the right side of \\in is not enumerable: ${formatValue(value)} at ${describeLocation(expression)}`,
394
- );
445
+ if (!isTlcEnumerable(value)) {
446
+ const message = run.isEnabled
447
+ ? "The right side of \\IN is not enumerable."
448
+ : `In computing ${getComputation(run)}, the right side of \\IN is not enumerable.`;
449
+ throw createRunError(run, `${message}\n${describeRange(expression)}`);
395
450
  }
396
451
  const elements = getStreamedElements(value);
397
452
  for (let position = 0; position < elements.length && !run.isStopped; position++) {
@@ -441,65 +496,43 @@ const compileDynamicAssignment = (
441
496
  };
442
497
  };
443
498
 
444
- interface FunctionAction {
445
- bounds: Bound[];
446
- body: Expression;
447
- scope: Scope | undefined;
448
- }
449
-
450
- const getFunctionAction = (
451
- expression: Expression,
452
- scope: Scope | undefined,
453
- partial: State,
454
- run: Run,
455
- ): FunctionAction | undefined => {
456
- if (expression.kind === "FunctionConstruction") {
457
- return { bounds: expression.bounds, body: expression.body, scope };
458
- }
459
- if (expression.kind !== "Identifier") return undefined;
460
- const binding = lookupScope(scope, expression.name);
461
- if (binding?.kind === "Thunk") {
462
- return getFunctionAction(binding.expression, binding.scope, partial, run);
463
- }
464
- const definition = binding ? undefined : getDefinition(expression.name, run.environment);
465
- if (definition?.kind !== "Function") return undefined;
466
- const self = evaluate(expression, getContext(run, undefined, partial));
467
- return {
468
- bounds: definition.bounds,
469
- body: definition.body,
470
- scope: bindValue(undefined, definition.name, self),
471
- };
472
- };
473
-
499
+ // Tool.getInitStates and Tool.getNextStates walk the body of a function they apply that is still
500
+ // lazy, which they evaluate as TLC computes the initial states eagerly, and otherwise apply it.
474
501
  const compileFunctionAction = (
475
502
  expression: Expression & { kind: "FunctionApplication" },
476
503
  environment: Environment,
477
504
  isInit: boolean,
478
505
  ): Runner => {
479
- const guard = compileGuard(expression);
506
+ const node = describeRange(expression);
480
507
  return (run, scope, partial, action, isFixed, onComplete) => {
481
- const lambda = getFunctionAction(expression.function, scope, partial, run);
482
- if (!lambda) {
483
- guard(run, scope, partial, action, isFixed, onComplete);
508
+ const context = getContext(run, scope, partial);
509
+ const value = evaluate(expression.function, isInit ? context : toKeepLazyContext(context));
510
+ const lambda = getLazyFunction(value);
511
+ if (lambda !== undefined) {
512
+ getRunner(lambda.body, environment, isInit)(
513
+ run,
514
+ bindLazyArguments(lambda, expression, context),
515
+ partial,
516
+ action,
517
+ isFixed,
518
+ onComplete,
519
+ );
484
520
  return;
485
521
  }
486
- const context = getContext(run, scope, partial);
487
- const args = expression.args.map((arg) => evaluate(arg, context));
488
- const argument = args.length === 1 ? args[0] : createTuple(args);
489
- const domain = getBoundsDomain(lambda.bounds, getContext(run, lambda.scope, partial));
490
- if (!isElementOf(argument, domain)) {
491
- throw new TlaEvaluationError(
492
- `Attempted to apply a function to ${formatValue(argument)}, which is not in its domain at ${describeLocation(expression)}`,
522
+ if (!isFunctionValue(value)) {
523
+ throw createRunError(
524
+ run,
525
+ `In computing ${getComputation(run)}, a non-function (${getKindString(value)}) was applied as a function.\n${node}`,
493
526
  );
494
527
  }
495
- getRunner(lambda.body, environment, isInit)(
496
- run,
497
- bindArgument(lambda.bounds, lambda.scope, argument),
498
- partial,
499
- action,
500
- isFixed,
501
- onComplete,
502
- );
528
+ const result = evaluate(expression, context);
529
+ if (typeof result !== "boolean") {
530
+ throw createRunError(
531
+ run,
532
+ `In computing ${getComputation(run)}, TLC expected a boolean expression,\nbut didn't find one.\n${node}`,
533
+ );
534
+ }
535
+ if (result) onComplete(partial, action);
503
536
  };
504
537
  };
505
538
 
@@ -523,7 +556,7 @@ const compileUnchanged = (expression: Expression, environment: Environment): Run
523
556
  );
524
557
  return;
525
558
  }
526
- if (holds(unchanged, getContext(run, scope, partial))) onComplete(partial, action);
559
+ if (holds(run, unchanged, getContext(run, scope, partial))) onComplete(partial, action);
527
560
  };
528
561
  };
529
562
 
@@ -718,9 +751,10 @@ const compileAction = (
718
751
  if (expression.bounds.length === 1 && bound.pattern.kind === "Name") {
719
752
  const name = bound.pattern.name;
720
753
  return (run, scope, partial, action, isFixed, onComplete) => {
721
- const elements = getEnumeratedElements(
754
+ const elements = getContextElements(
722
755
  evaluate(bound.set, getContext(run, scope, partial)),
723
756
  bound.set,
757
+ environment.runtime.version,
724
758
  );
725
759
  for (let index = 0; index < elements.length && !run.isStopped; index++) {
726
760
  body(
@@ -734,6 +768,37 @@ const compileAction = (
734
768
  }
735
769
  };
736
770
  }
771
+ const hoisted = isInit ? undefined : getHoistedGuards(expression, environment);
772
+ if (hoisted) {
773
+ const rest = compileConjunction(hoisted.rest, environment, isInit);
774
+ return (run, scope, partial, action, isFixed, onComplete) => {
775
+ const context = getContext(run, scope, partial);
776
+ const sets = expression.bounds.map((innerBound) =>
777
+ getContextElements(
778
+ evaluate(innerBound.set, context),
779
+ innerBound.set,
780
+ environment.runtime.version,
781
+ ),
782
+ );
783
+ if (sets.some((elements) => elements.length === 0)) return;
784
+ const visit = (index: number, boundScope: Scope | undefined): void => {
785
+ if (index < 0) {
786
+ rest(run, boundScope, partial, action, isFixed, onComplete);
787
+ return;
788
+ }
789
+ for (const element of sets[index]) {
790
+ if (run.isStopped) return;
791
+ const elementScope = bindValue(boundScope, hoisted.names[index], element);
792
+ if (index === sets.length - 1) {
793
+ const guardContext = getContext(run, elementScope, partial);
794
+ if (!hoisted.guards.every((guard) => holds(run, guard, guardContext))) continue;
795
+ }
796
+ visit(index - 1, elementScope);
797
+ }
798
+ };
799
+ visit(sets.length - 1, scope);
800
+ };
801
+ }
737
802
  return (run, scope, partial, action, isFixed, onComplete) => {
738
803
  forEachBinding(expression.bounds, getContext(run, scope, partial), (boundScope) => {
739
804
  body(run, boundScope, partial, action, isFixed, onComplete);
@@ -761,7 +826,7 @@ const compileAction = (
761
826
  );
762
827
  if (isBoundToValues) {
763
828
  const isSatisfied = scopes.every((boundScope) =>
764
- holds(expression.body, getContext(run, boundScope, partial)),
829
+ holds(run, expression.body, getContext(run, boundScope, partial)),
765
830
  );
766
831
  if (isSatisfied) onComplete(partial, action);
767
832
  return;
@@ -775,7 +840,7 @@ const compileAction = (
775
840
  const isSatisfied = scopes
776
841
  .slice(index)
777
842
  .every((boundScope) =>
778
- holdsInInit(expression.body, getContext(run, boundScope, nextPartial)),
843
+ holds(run, expression.body, getContext(run, boundScope, nextPartial)),
779
844
  );
780
845
  if (isSatisfied) onComplete(nextPartial, nextAction);
781
846
  return;
@@ -792,26 +857,38 @@ const compileAction = (
792
857
  const alternative = child(expression.alternative);
793
858
  return (run, scope, partial, action, isFixed, onComplete) => {
794
859
  const condition = evaluate(expression.condition, getContext(run, scope, partial));
795
- const branch = expectBoolean(condition, "an IF condition") ? consequent : alternative;
860
+ if (typeof condition !== "boolean") {
861
+ throw createRunError(run, getIfConditionMessage(run, condition, expression));
862
+ }
863
+ const branch = condition ? consequent : alternative;
796
864
  branch(run, scope, partial, action, isFixed, onComplete);
797
865
  };
798
866
  }
799
867
  case "Case": {
800
868
  const arms = expression.arms.map((arm) => ({
801
869
  condition: arm.condition,
870
+ source: arm.body,
802
871
  body: child(arm.body),
803
872
  }));
804
873
  const other = expression.other ? child(expression.other) : undefined;
805
874
  return (run, scope, partial, action, isFixed, onComplete) => {
806
875
  const context = getContext(run, scope, partial);
807
- const arm = arms.find((candidate) =>
808
- expectBoolean(evaluate(candidate.condition, context), "a CASE guard"),
809
- );
876
+ const arm = arms.find((candidate) => {
877
+ const value = evaluate(candidate.condition, context);
878
+ if (typeof value === "boolean") return value;
879
+ // TLC leaves out the space before the kind under ENABLED.
880
+ throw createRunError(
881
+ run,
882
+ `In computing ${getComputation(run)}, a non-boolean expression${run.isEnabled ? "" : " "}(${getKindString(value)}) was used as a guard condition of a CASE.\n${describeNode(candidate.source)}`,
883
+ );
884
+ });
810
885
  const body = arm?.body ?? other;
811
- if (!body)
812
- throw new TlaEvaluationError(
813
- `${UNEXPECTED_EXCEPTION}In computing next states, TLC encountered a CASE with no conditions true.\n${describeRange(expression)}`,
886
+ if (!body) {
887
+ throw createRunError(
888
+ run,
889
+ `In computing ${getComputation(run)}, TLC encountered a CASE with no conditions true.\n${describeRange(expression)}`,
814
890
  );
891
+ }
815
892
  body(run, scope, partial, action, isFixed, onComplete);
816
893
  };
817
894
  }
@@ -840,10 +917,18 @@ const compileAction = (
840
917
  case "AngleAction": {
841
918
  const body = child(expression.action);
842
919
  const unchanged = getUnchangedWrapper(expression.subscript);
920
+ const isUnchanged = (run: Run, scope: Scope | undefined, nextPartial: State) => {
921
+ try {
922
+ return holds(run, unchanged, getContext(run, scope, nextPartial));
923
+ } catch (error) {
924
+ throw run.isEnabled
925
+ ? toUnspecifiedSubscriptError(error, environment.runtime.version)
926
+ : error;
927
+ }
928
+ };
843
929
  return (run, scope, partial, action, isFixed, onComplete) =>
844
930
  body(run, scope, partial, action, isFixed, (nextPartial, nextAction) => {
845
- if (!holds(unchanged, getContext(run, scope, nextPartial)))
846
- onComplete(nextPartial, nextAction);
931
+ if (!isUnchanged(run, scope, nextPartial)) onComplete(nextPartial, nextAction);
847
932
  });
848
933
  }
849
934
  case "BoxAction":
@@ -920,7 +1005,15 @@ export const isEnabled = (expression: Expression, context: Context): boolean =>
920
1005
  );
921
1006
  }
922
1007
  const environment = context.environment;
923
- const run: Run = { environment, isInit: false, current: state, isStopped: false };
1008
+ // TLC computes ENABLED again with its call stack recorded as it computes successors.
1009
+ if (environment.callStack) return replayEnabled(expression, context.scope, state, environment);
1010
+ const run: Run = {
1011
+ environment,
1012
+ isInit: false,
1013
+ isEnabled: true,
1014
+ current: state,
1015
+ isStopped: false,
1016
+ };
924
1017
  // TLC stops computing ENABLED at the first successor, so it skips the rest of the action.
925
1018
  getRunner(expression, environment, false)(
926
1019
  run,
@@ -941,7 +1034,13 @@ export const forEachInitialState = (
941
1034
  onState: (state: Value[]) => boolean,
942
1035
  scope?: Scope,
943
1036
  ) => {
944
- const run: Run = { environment, isInit: true, current: undefined, isStopped: false };
1037
+ const run: Run = {
1038
+ environment,
1039
+ isInit: true,
1040
+ isEnabled: false,
1041
+ current: undefined,
1042
+ isStopped: false,
1043
+ };
945
1044
  getRunner(expression, environment, true)(
946
1045
  run,
947
1046
  scope,
@@ -953,12 +1052,7 @@ export const forEachInitialState = (
953
1052
  if (!isComplete(partial)) {
954
1053
  // TLC reports an initial state that isn't completely specified as an illegal state, not as
955
1054
  // an evaluation failure.
956
- throw setExitCode(
957
- new TlaEvaluationError(
958
- `The initial predicate does not assign ${getMissingVariables(partial, environment).join(", ")}`,
959
- ),
960
- EXIT_STATUS.error,
961
- );
1055
+ throw setExitCode(new TlaIllegalStateError([...partial]), EXIT_STATUS.error);
962
1056
  }
963
1057
  run.isStopped = onState(partial);
964
1058
  },
@@ -990,7 +1084,13 @@ export const forEachSuccessor = (
990
1084
  onSuccessor: (successor: Successor) => boolean,
991
1085
  scope?: Scope,
992
1086
  ) => {
993
- const run: Run = { environment, isInit: false, current: state, isStopped: false };
1087
+ const run: Run = {
1088
+ environment,
1089
+ isInit: false,
1090
+ isEnabled: false,
1091
+ current: state,
1092
+ isStopped: false,
1093
+ };
994
1094
  const counter = { successors: 0 };
995
1095
  getRunner(expression, environment, false)(
996
1096
  run,
@@ -1001,8 +1101,12 @@ export const forEachSuccessor = (
1001
1101
  (partial, action) => {
1002
1102
  if (run.isStopped) return;
1003
1103
  if (!isComplete(partial)) {
1004
- throw new TlaEvaluationError(
1005
- `Successor state is not completely specified by action ${action ?? "Next"}. The following variables are not assigned: ${getMissingVariables(partial, environment).join(", ")}`,
1104
+ const missing = getMissingVariables(partial, environment);
1105
+ throw new TlaIncompleteSuccessorError(
1106
+ `Successor state is not completely specified by action ${action ?? "Next"}. The following variables are not assigned: ${missing.join(", ")}`,
1107
+ partial,
1108
+ action,
1109
+ missing,
1006
1110
  );
1007
1111
  }
1008
1112
  counter.successors++;