tla-ts 0.0.3-dev.79f7ed7 → 0.0.3-dev.852fbc8

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 (50) hide show
  1. package/README.md +16 -2
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +55 -22
  4. package/dist/index.d.ts +55 -22
  5. package/dist/index.js +1 -1
  6. package/dist/parallel-worker.cjs +1 -1
  7. package/dist/parallel-worker.js +2 -2
  8. package/dist/parallel.cjs +1 -1
  9. package/dist/parallel.js +2 -2
  10. package/dist/run-cli.cjs +19 -16
  11. package/dist/run-cli.js +20 -17
  12. package/dist/transfer.cjs +37 -16
  13. package/dist/transfer.js +37 -16
  14. package/package.json +1 -1
  15. package/src/ast.ts +93 -0
  16. package/src/check.ts +511 -99
  17. package/src/cli-options.ts +11 -5
  18. package/src/codegen.ts +15 -22
  19. package/src/config.ts +224 -170
  20. package/src/dependencies.ts +2 -2
  21. package/src/environment.ts +116 -28
  22. package/src/errors.ts +87 -3
  23. package/src/evaluate.ts +252 -156
  24. package/src/exit-codes.ts +39 -42
  25. package/src/instances.ts +16 -15
  26. package/src/levels.ts +62 -34
  27. package/src/lexer.ts +5 -1
  28. package/src/live-check.ts +772 -0
  29. package/src/liveness.ts +120 -543
  30. package/src/parallel-worker.ts +7 -3
  31. package/src/parallel.ts +20 -4
  32. package/src/parser.ts +33 -11
  33. package/src/resolve.ts +122 -44
  34. package/src/run-cli.ts +112 -20
  35. package/src/runtime.ts +3 -1
  36. package/src/spec-description.ts +19 -8
  37. package/src/standard-modules.ts +10 -9
  38. package/src/state-graph.ts +157 -0
  39. package/src/subexpressions.ts +10 -10
  40. package/src/successors.ts +183 -39
  41. package/src/symmetry.ts +30 -8
  42. package/src/tableau.ts +51 -24
  43. package/src/tlc-ext.ts +29 -12
  44. package/src/tlc-module.ts +14 -33
  45. package/src/tlc-modules.ts +4 -0
  46. package/src/tlc-order.ts +25 -7
  47. package/src/tlc-random.ts +9 -6
  48. package/src/tlc-summary.ts +20 -5
  49. package/src/value-sources.ts +29 -0
  50. package/src/values.ts +179 -57
package/src/runtime.ts CHANGED
@@ -6,7 +6,7 @@ export interface CheckerRuntime {
6
6
  getBehavior: (state: Value[]) => Value[][];
7
7
  getSpecification: () => Value;
8
8
  counterExample: Value | undefined;
9
- setLivenessSource: (index: number) => void;
9
+ setLivenessSource: (index: number | undefined) => void;
10
10
  getCurrentState: () => Value[] | undefined;
11
11
  getFingerprint: (state: Value[]) => bigint;
12
12
  getRandom: () => JavaRandom;
@@ -24,6 +24,7 @@ export interface CheckerRuntime {
24
24
  properties: Map<string, string>;
25
25
  possibleCounts: Map<string, number>;
26
26
  isStopped: boolean;
27
+ isStarted: boolean;
27
28
  checkDeadlock: boolean;
28
29
  startedAt: number;
29
30
  }
@@ -75,6 +76,7 @@ export const createRuntime = (checkDeadlock: boolean, seed = 0n): CheckerRuntime
75
76
  properties: new Map(),
76
77
  possibleCounts: new Map(),
77
78
  isStopped: false,
79
+ isStarted: false,
78
80
  checkDeadlock,
79
81
  startedAt: Date.now(),
80
82
  };
@@ -1,16 +1,20 @@
1
- import type { Definition, Expression, SourceLocation, SourceRange } from "./ast";
1
+ import {
2
+ isLocallyResolved,
3
+ type Definition,
4
+ type Expression,
5
+ type SourceLocation,
6
+ type SourceRange,
7
+ } from "./ast";
2
8
  import type { ModelConfig } from "./config";
3
9
  import type { InstanceAction } from "./environment";
4
- import { TlaError } from "./errors";
10
+ import { formatRange, TlaError } from "./errors";
5
11
  import {
6
12
  bindDefinitions,
7
13
  bindOperatorArguments,
8
14
  evaluate,
9
15
  forEachBinding,
10
- formatRange,
11
16
  getDefinition,
12
17
  isConstantLevel,
13
- isLocallyResolved,
14
18
  lookupScope,
15
19
  resolveGlobalOperator,
16
20
  type Closure,
@@ -464,10 +468,17 @@ export const getNextActions = (
464
468
  instanceActions: Map<string, InstanceAction>,
465
469
  ) => describe(config, environment, instanceActions).actions;
466
470
 
467
- export const getActionLabel = (action: SpecAction) => {
468
- const parameters = action.parameters.map((parameter) => formatValue(parameter[1]));
469
- return `${action.name === UNNAMED_ACTION ? "Action" : action.name}${parameters.length === 0 ? "" : `(${parameters.join(",")})`} ${formatRange(action.location.range ?? BUILTIN_RANGE)}`;
470
- };
471
+ const formatParameters = (action: SpecAction) =>
472
+ action.parameters.length === 0
473
+ ? ""
474
+ : `(${action.parameters.map((parameter) => formatValue(parameter[1])).join(",")})`;
475
+
476
+ export const getActionLabel = (action: SpecAction) =>
477
+ `${action.name === UNNAMED_ACTION ? "Action" : action.name}${formatParameters(action)} ${formatRange(action.location.range ?? BUILTIN_RANGE)}`;
478
+
479
+ // TLC's Action.getInvocationSignature, which names the action and the values of its parameters.
480
+ export const getActionSignature = (action: SpecAction) =>
481
+ `${action.name}${formatParameters(action)}`;
471
482
 
472
483
  export const getSpecificationValue = (
473
484
  config: ModelConfig,
@@ -40,6 +40,7 @@ import {
40
40
  isEnumerable,
41
41
  isFiniteSet,
42
42
  isFunctionValue,
43
+ isReducible,
43
44
  isSetValue,
44
45
  toFiniteSet,
45
46
  unionSorted,
@@ -47,7 +48,7 @@ import {
47
48
  createEnumeratedSet,
48
49
  EMPTY_SET,
49
50
  isEnumeratedSet,
50
- type IntervalValue,
51
+ type ReducibleSet,
51
52
  type MixedSetValue,
52
53
  type SetOperationValue,
53
54
  type SetValue,
@@ -75,12 +76,6 @@ const unionInTree = (sets: SetValue[], start: number, end: number): SetValue =>
75
76
 
76
77
  const SET_OPERATORS: SetOperationValue["operator"][] = ["\\cup", "\\cap", "\\"];
77
78
 
78
- type ReducibleSet = SetValue | MixedSetValue | IntervalValue;
79
-
80
- const isReducible = (value: Value): value is ReducibleSet =>
81
- typeof value === "object" &&
82
- (value.kind === "Set" || value.kind === "MixedSet" || value.kind === "Interval");
83
-
84
79
  const isMixedSet = (value: Value) => typeof value === "object" && value.kind === "MixedSet";
85
80
 
86
81
  const getReducibleElements = (set: ReducibleSet) =>
@@ -128,7 +123,7 @@ export const CORE_OPERATORS: Builtin[] = [
128
123
  ),
129
124
  defineOperator("\\subseteq", 2, (args) => {
130
125
  const left = getSet(args, 0, "\\subseteq");
131
- const right = getSet(args, 1, "\\subseteq");
126
+ const right = getValue(args, 1, "\\subseteq");
132
127
  const isPowerSets =
133
128
  typeof left === "object" &&
134
129
  left.kind === "Subset" &&
@@ -150,7 +145,13 @@ export const CORE_OPERATORS: Builtin[] = [
150
145
  : operator === "\\cap"
151
146
  ? intersectSorted
152
147
  : differenceSorted;
153
- 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
+ }
154
155
  }
155
156
  if (isReducible(left)) return combineReducible(operator, left, right);
156
157
  if (operator !== "\\" && isReducible(right)) return combineReducible(operator, right, left);
@@ -0,0 +1,157 @@
1
+ // A port of TLC's -dump writers, tlc2.util.StateWriter and tlc2.util.DotStateWriter.
2
+
3
+ export interface StateDump {
4
+ path: string;
5
+ dot?: boolean;
6
+ colorize?: boolean;
7
+ actionLabels?: boolean;
8
+ snapshot?: boolean;
9
+ }
10
+
11
+ export interface GraphState {
12
+ fingerprint: bigint;
13
+ level: number;
14
+ // The state as TLC prints it after evaluating the alias, and as it prints it without the alias.
15
+ getLabel: () => string;
16
+ getText: () => string;
17
+ }
18
+
19
+ export interface GraphAction {
20
+ name: string;
21
+ signature: string;
22
+ }
23
+
24
+ export interface StateWriter {
25
+ writeInitialState: (state: GraphState) => void;
26
+ writeSuccessor: (
27
+ state: GraphState,
28
+ successor: GraphState,
29
+ isSeen: boolean,
30
+ action: GraphAction | undefined,
31
+ ) => void;
32
+ close: () => void;
33
+ }
34
+
35
+ type WriteFile = ((path: string, content: string) => void) | undefined;
36
+
37
+ const COLOR_SCHEME = "paired12";
38
+ const LOAD_FACTOR = 0.75;
39
+ const INITIAL_CAPACITY = 16;
40
+
41
+ const getCapacity = (size: number, capacity = INITIAL_CAPACITY): number =>
42
+ size <= capacity * LOAD_FACTOR ? capacity : getCapacity(size, capacity * 2);
43
+
44
+ // The order in which a java.util.HashMap iterates over keys put in this order: by bucket, and in
45
+ // insertion order within a bucket. A bucket only becomes a tree once 8 keys collide in it.
46
+ const getJavaHashOrder = <Key>(keys: Key[], getHash: (key: Key) => number) => {
47
+ const mask = getCapacity(keys.length) - 1;
48
+ const getBucket = (key: Key) => {
49
+ const hash = getHash(key);
50
+ return (hash ^ (hash >>> 16)) & mask;
51
+ };
52
+ return keys
53
+ .map((key, position) => ({ key, position, bucket: getBucket(key) }))
54
+ .sort((left, right) => left.bucket - right.bucket || left.position - right.position)
55
+ .map((entry) => entry.key);
56
+ };
57
+
58
+ const getLongHash = (value: bigint) =>
59
+ Number(BigInt.asIntN(32, value ^ (BigInt.asUintN(64, value) >> 32n)));
60
+
61
+ const getStringHash = (text: string) =>
62
+ [...Array(text.length).keys()].reduce(
63
+ (hash, index) => (Math.imul(31, hash) + text.charCodeAt(index)) | 0,
64
+ 0,
65
+ );
66
+
67
+ const escape = (text: string) => text.replaceAll("\\", "\\\\").replaceAll('"', '\\"').trim();
68
+
69
+ const toDot = (text: string) => escape(text).replaceAll("\n", "\\n");
70
+
71
+ const createPlainWriter = (dump: StateDump, writeFile: WriteFile): StateWriter => {
72
+ const states: string[] = [];
73
+ const writeState = (state: GraphState) =>
74
+ states.push(`State ${states.length + 1}:\n${state.getText()}\n`);
75
+ return {
76
+ writeInitialState: writeState,
77
+ writeSuccessor: (_state, successor, isSeen) => {
78
+ if (!isSeen) writeState(successor);
79
+ },
80
+ close: () => writeFile?.(dump.path, states.join("")),
81
+ };
82
+ };
83
+
84
+ const createDotWriter = (dump: StateDump, writeFile: WriteFile): StateWriter => {
85
+ const lines = [
86
+ "strict digraph DiskGraph {\n",
87
+ "node [shape=box,style=rounded]\n",
88
+ dump.colorize ? `edge [colorscheme="${COLOR_SCHEME}"]\n` : "",
89
+ "nodesep=0.35;\n",
90
+ "subgraph cluster_graph {\n",
91
+ 'color="white";\n',
92
+ ];
93
+ const ranks = new Map<number, Set<bigint>>();
94
+ const colors = new Map<string, number>();
95
+ const addRank = (state: GraphState) => {
96
+ const rank = ranks.get(state.level) ?? new Set();
97
+ ranks.set(state.level, rank.add(state.fingerprint));
98
+ };
99
+ // TLC colors an edge by the name of its action, numbering the names from 2 as it finds them.
100
+ const getColor = (action: GraphAction | undefined) => {
101
+ if (!action) return 1;
102
+ const color = colors.get(action.name) ?? colors.size + 2;
103
+ colors.set(action.name, color);
104
+ return color;
105
+ };
106
+ const getLegend = () =>
107
+ [
108
+ `subgraph cluster_legend {graph[style=bold];label = "Next State Actions" style="solid"\n`,
109
+ `node [ labeljust="l",colorscheme="${COLOR_SCHEME}",style=filled,shape=record ]\n`,
110
+ ...getJavaHashOrder([...colors.keys()], getStringHash).map(
111
+ (name) => `${name.replaceAll("!", ":")} [label="${name}",fillcolor=${colors.get(name)}]\n`,
112
+ ),
113
+ "}",
114
+ ].join("");
115
+ const getEnding = () =>
116
+ [
117
+ ...getJavaHashOrder([...ranks], (rank) => rank[0]).map(
118
+ (rank) =>
119
+ `{rank = same; ${getJavaHashOrder([...rank[1]], getLongHash)
120
+ .map((fingerprint) => `${fingerprint};`)
121
+ .join("")}}\n`,
122
+ ),
123
+ "}\n",
124
+ dump.colorize && colors.size > 1 ? getLegend() : "",
125
+ "}",
126
+ ].join("");
127
+ const writeSnapshot = () => {
128
+ if (dump.snapshot) {
129
+ writeFile?.(dump.path.replaceAll(".dot", "_snapshot.dot"), lines.join("") + getEnding());
130
+ }
131
+ };
132
+ return {
133
+ writeInitialState: (state) => {
134
+ lines.push(`${state.fingerprint} [label="${toDot(state.getLabel())}",style = filled]\n`);
135
+ addRank(state);
136
+ writeSnapshot();
137
+ },
138
+ writeSuccessor: (state, successor, isSeen, action) => {
139
+ const color = dump.colorize ? String(getColor(action)) : "black";
140
+ const label = dump.actionLabels && action ? escape(action.signature) : "";
141
+ lines.push(
142
+ `${state.fingerprint} -> ${successor.fingerprint} [label="${label}",color="${color}",fontcolor="${color}"];\n`,
143
+ );
144
+ if (!isSeen) {
145
+ lines.push(
146
+ `${successor.fingerprint} [label="${toDot(successor.getLabel())}",tooltip="${toDot(successor.getText())}"];\n`,
147
+ );
148
+ }
149
+ addRank(state);
150
+ writeSnapshot();
151
+ },
152
+ close: () => writeFile?.(dump.path, lines.join("") + getEnding()),
153
+ };
154
+ };
155
+
156
+ export const createStateWriter = (dump: StateDump, writeFile: WriteFile) =>
157
+ dump.dot ? createDotWriter(dump, writeFile) : createPlainWriter(dump, writeFile);
@@ -1,15 +1,15 @@
1
- import type {
2
- Bound,
3
- Definition,
4
- Expression,
5
- Instance,
6
- Module,
7
- OperatorParam,
8
- Selector,
9
- SourceLocation,
1
+ import {
2
+ getChildren,
3
+ type Bound,
4
+ type Definition,
5
+ type Expression,
6
+ type Instance,
7
+ type Module,
8
+ type OperatorParam,
9
+ type Selector,
10
+ type SourceLocation,
10
11
  } from "./ast";
11
12
  import { TlaSyntaxError } from "./errors";
12
- import { getChildren } from "./evaluate";
13
13
  import { getSourceName, mapChildren, mapDefinition } from "./instances";
14
14
  import { getArity, getBoundNames, getPatternNames, LOCAL_RESOLUTION } from "./resolve";
15
15
 
package/src/successors.ts CHANGED
@@ -1,28 +1,41 @@
1
- import type { Bound, Definition, Expression } from "./ast";
1
+ import {
2
+ getChildren,
3
+ isLocallyResolved,
4
+ type Bound,
5
+ type Definition,
6
+ type Expression,
7
+ type QuantifierExpression,
8
+ } from "./ast";
2
9
  import { getReadVariables } from "./dependencies";
3
- import { TlaEvaluationError } from "./errors";
10
+ import {
11
+ TlaEvaluationError,
12
+ TlaIllegalStateError,
13
+ TlaIncompleteStateError,
14
+ TlaUnassignedError,
15
+ } from "./errors";
4
16
  import { EXIT_STATUS, setExitCode } from "./exit-codes";
5
17
  import {
6
18
  describeLocation,
19
+ describeRange,
7
20
  bindArgument,
8
21
  bindDefinitions,
9
22
  bindOperatorArguments,
10
23
  bindValue,
11
24
  compileArgumentScope,
12
25
  evaluate,
26
+ getEntryEvaluator,
13
27
  expectBoolean,
14
28
  forEachBinding,
15
29
  getBoundsDomain,
16
- getChildren,
17
30
  getDefinition,
18
31
  getEnumeratedElements,
19
32
  getReevaluatedDefinitions,
20
33
  lookupScope,
21
34
  resolveApplyOperator,
22
35
  resolveGlobalOperator,
23
- isLocallyResolved,
24
36
  type Context,
25
37
  type Environment,
38
+ type Evaluator,
26
39
  type Scope,
27
40
  type State,
28
41
  } from "./evaluate";
@@ -45,6 +58,7 @@ export interface Successor {
45
58
  interface Run {
46
59
  environment: Environment;
47
60
  isInit: boolean;
61
+ isEnabled: boolean;
48
62
  current: Value[] | undefined;
49
63
  isStopped: boolean;
50
64
  }
@@ -81,25 +95,54 @@ const assign = (partial: State, index: number, value: Value) => {
81
95
  return copy;
82
96
  };
83
97
 
84
- const holds = (expression: Expression, context: Context) => {
85
- const 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) => {
86
100
  if (typeof value === "boolean") return value;
87
- try {
88
- return expectBoolean(value, `the action at ${describeLocation(expression)}`);
89
- } catch (error) {
90
- // TLC fails with an unexpected exception when the next-state relation isn't a boolean.
91
- 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
+ );
92
115
  }
116
+ return expectFormula(expression, value, context.next === undefined);
93
117
  };
94
118
 
95
119
  const isAssignmentOperator = (operator: string) =>
96
120
  operator === "=" || operator === "\\in" || operator === "\\subseteq";
97
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
+
98
131
  const getRunner = (expression: Expression, environment: Environment, isInit: boolean): Runner => {
99
- const runners = isInit ? initRunners : nextRunners;
132
+ const runners = getRunners(environment, isInit);
100
133
  const cached = runners.get(expression);
101
134
  if (cached) return cached;
102
- 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;
103
146
  runners.set(expression, runner);
104
147
  return runner;
105
148
  };
@@ -183,6 +226,23 @@ const getUnchangedIndices = (
183
226
  return getUnchangedIndices(definition.body, environment, visited);
184
227
  };
185
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
+
186
246
  const ACTION_KINDS = new Set([
187
247
  "Label",
188
248
  "And",
@@ -287,12 +347,35 @@ const toConjunct = (
287
347
  return { kind: "Branch", expression, runner: getRunner(expression, environment, isInit) };
288
348
  };
289
349
 
350
+ // The leading guards of `\E x \in S, y \in T : P /\ Q` that read no inner bound hold for every inner
351
+ // binding alike, so they can run once for each element of the outermost bound.
352
+ const getHoistedGuards = (expression: QuantifierExpression, environment: Environment) => {
353
+ if (expression.bounds.length < 2 || expression.body.kind !== "And") return undefined;
354
+ const names = expression.bounds.flatMap((bound) =>
355
+ bound.pattern.kind === "Name" ? [bound.pattern.name] : [],
356
+ );
357
+ if (names.length !== expression.bounds.length) return undefined;
358
+ const innerNames = new Set(names.slice(0, -1));
359
+ const operands = expression.body.operands;
360
+ const index = operands.findIndex((operand) => {
361
+ if (getReadVariables(operand, environment) === undefined) return true;
362
+ if (hasBranches(operand, environment, new Set())) return true;
363
+ const readLocals = getReadLocals(operand, NO_NAMES);
364
+ return !readLocals || readLocals.some((name) => innerNames.has(name));
365
+ });
366
+ const count = index === -1 ? operands.length : index;
367
+ if (count === 0) return undefined;
368
+ return { names, guards: operands.slice(0, count), rest: operands.slice(count) };
369
+ };
370
+
290
371
  const compileConjunction = (
291
372
  operands: Expression[],
292
373
  environment: Environment,
293
374
  isInit: boolean,
294
375
  ): Runner => {
295
376
  const conjuncts = operands.map((operand) => toConjunct(operand, environment, isInit));
377
+ const evaluators: (Evaluator | undefined)[] = conjuncts.map(() => undefined);
378
+ const trace = environment.trace;
296
379
  const runFrom = (
297
380
  start: number,
298
381
  run: Run,
@@ -313,14 +396,25 @@ const compileConjunction = (
313
396
  return;
314
397
  }
315
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
+ }
316
405
  if (conjunct.kind === "Guard") {
317
406
  context ??= getContext(run, scope, current);
318
- if (!holds(conjunct.expression, context)) return;
407
+ const evaluator = (evaluators[index] ??= getEntryEvaluator(
408
+ conjunct.expression,
409
+ environment,
410
+ ));
411
+ if (!holds(conjunct.expression, context, evaluator(context))) return;
319
412
  continue;
320
413
  }
321
414
  if (conjunct.kind === "Assign") {
322
415
  context ??= getContext(run, scope, current);
323
- const value = evaluate(conjunct.value, context);
416
+ const evaluator = (evaluators[index] ??= getEntryEvaluator(conjunct.value, environment));
417
+ const value = evaluator(context);
324
418
  const assigned = current[conjunct.index];
325
419
  if (assigned === undefined) {
326
420
  current = assign(current, conjunct.index, value);
@@ -357,10 +451,7 @@ const compileConjunction = (
357
451
  };
358
452
 
359
453
  const holdsInInit = (expression: Expression, context: Context) =>
360
- expectBoolean(
361
- evaluate(expression, context),
362
- `the initial predicate at ${describeLocation(expression)}`,
363
- );
454
+ expectFormula(expression, evaluate(expression, context), true);
364
455
 
365
456
  const compileGuard =
366
457
  (expression: Expression): Runner =>
@@ -385,7 +476,7 @@ const compileMembership = (
385
476
  expression.operator === "\\subseteq" ? { kind: "Subset", base: evaluated } : evaluated;
386
477
  if (!isEnumerable(value)) {
387
478
  throw new TlaEvaluationError(
388
- `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)}`,
389
480
  );
390
481
  }
391
482
  const elements = getStreamedElements(value);
@@ -729,6 +820,34 @@ const compileAction = (
729
820
  }
730
821
  };
731
822
  }
823
+ const hoisted =
824
+ isInit || environment.trace ? undefined : getHoistedGuards(expression, environment);
825
+ if (hoisted) {
826
+ const rest = compileConjunction(hoisted.rest, environment, isInit);
827
+ return (run, scope, partial, action, isFixed, onComplete) => {
828
+ const context = getContext(run, scope, partial);
829
+ const sets = expression.bounds.map((innerBound) =>
830
+ getEnumeratedElements(evaluate(innerBound.set, context), innerBound.set),
831
+ );
832
+ if (sets.some((elements) => elements.length === 0)) return;
833
+ const visit = (index: number, boundScope: Scope | undefined): void => {
834
+ if (index < 0) {
835
+ rest(run, boundScope, partial, action, isFixed, onComplete);
836
+ return;
837
+ }
838
+ for (const element of sets[index]) {
839
+ if (run.isStopped) return;
840
+ const elementScope = bindValue(boundScope, hoisted.names[index], element);
841
+ if (index === sets.length - 1) {
842
+ const guardContext = getContext(run, elementScope, partial);
843
+ if (!hoisted.guards.every((guard) => holds(guard, guardContext))) continue;
844
+ }
845
+ visit(index - 1, elementScope);
846
+ }
847
+ };
848
+ visit(sets.length - 1, scope);
849
+ };
850
+ }
732
851
  return (run, scope, partial, action, isFixed, onComplete) => {
733
852
  forEachBinding(expression.bounds, getContext(run, scope, partial), (boundScope) => {
734
853
  body(run, boundScope, partial, action, isFixed, onComplete);
@@ -804,7 +923,9 @@ const compileAction = (
804
923
  );
805
924
  const body = arm?.body ?? other;
806
925
  if (!body)
807
- throw new TlaEvaluationError(`No CASE guard is true at ${describeLocation(expression)}`);
926
+ throw new TlaEvaluationError(
927
+ `In computing ${run.isInit ? "initial" : "next"} states, TLC encountered a CASE with no conditions true.\n${describeRange(expression)}`,
928
+ );
808
929
  body(run, scope, partial, action, isFixed, onComplete);
809
930
  };
810
931
  }
@@ -835,8 +956,17 @@ const compileAction = (
835
956
  const unchanged = getUnchangedWrapper(expression.subscript);
836
957
  return (run, scope, partial, action, isFixed, onComplete) =>
837
958
  body(run, scope, partial, action, isFixed, (nextPartial, nextAction) => {
838
- if (!holds(unchanged, getContext(run, scope, nextPartial)))
839
- 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
+ }
840
970
  });
841
971
  }
842
972
  case "BoxAction":
@@ -913,18 +1043,25 @@ export const isEnabled = (expression: Expression, context: Context): boolean =>
913
1043
  );
914
1044
  }
915
1045
  const environment = context.environment;
916
- const found = { value: false };
1046
+ const run: Run = {
1047
+ environment,
1048
+ isInit: false,
1049
+ isEnabled: true,
1050
+ current: state,
1051
+ isStopped: false,
1052
+ };
1053
+ // TLC stops computing ENABLED at the first successor, so it skips the rest of the action.
917
1054
  getRunner(expression, environment, false)(
918
- { environment, isInit: false, current: state, isStopped: false },
1055
+ run,
919
1056
  context.scope,
920
1057
  getEmptyState(environment),
921
1058
  undefined,
922
1059
  false,
923
1060
  () => {
924
- found.value = true;
1061
+ run.isStopped = true;
925
1062
  },
926
1063
  );
927
- return found.value;
1064
+ return run.isStopped;
928
1065
  };
929
1066
 
930
1067
  export const forEachInitialState = (
@@ -933,7 +1070,13 @@ export const forEachInitialState = (
933
1070
  onState: (state: Value[]) => boolean,
934
1071
  scope?: Scope,
935
1072
  ) => {
936
- 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
+ };
937
1080
  getRunner(expression, environment, true)(
938
1081
  run,
939
1082
  scope,
@@ -943,14 +1086,7 @@ export const forEachInitialState = (
943
1086
  (partial) => {
944
1087
  if (run.isStopped) return;
945
1088
  if (!isComplete(partial)) {
946
- // TLC reports an initial state that isn't completely specified as an illegal state, not as
947
- // an evaluation failure.
948
- throw setExitCode(
949
- new TlaEvaluationError(
950
- `The initial predicate does not assign ${getMissingVariables(partial, environment).join(", ")}`,
951
- ),
952
- EXIT_STATUS.error,
953
- );
1089
+ throw setExitCode(new TlaIllegalStateError(partial), EXIT_STATUS.error);
954
1090
  }
955
1091
  run.isStopped = onState(partial);
956
1092
  },
@@ -982,7 +1118,13 @@ export const forEachSuccessor = (
982
1118
  onSuccessor: (successor: Successor) => boolean,
983
1119
  scope?: Scope,
984
1120
  ) => {
985
- 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
+ };
986
1128
  const counter = { successors: 0 };
987
1129
  getRunner(expression, environment, false)(
988
1130
  run,
@@ -993,8 +1135,10 @@ export const forEachSuccessor = (
993
1135
  (partial, action) => {
994
1136
  if (run.isStopped) return;
995
1137
  if (!isComplete(partial)) {
996
- throw new TlaEvaluationError(
997
- `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(),
998
1142
  );
999
1143
  }
1000
1144
  counter.successors++;