tla-ts 0.0.3-dev.a57ca4f → 0.0.3-dev.a85c0bd

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/live-check.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { TlaEvaluationError } from "./errors";
2
+ import { EXIT_STATUS, setExitCode } from "./exit-codes";
2
3
  import { hasRepeatedEffects, type Environment } from "./evaluate";
3
4
  import {
4
5
  evaluateLive,
@@ -12,6 +13,7 @@ import {
12
13
  createJunction,
13
14
  createUnary,
14
15
  getSolutions,
16
+ getTermKey,
15
17
  isFulfilling,
16
18
  type LiveExpression,
17
19
  type Solution,
@@ -48,37 +50,21 @@ interface Check {
48
50
  actionIds: Int32Array;
49
51
  nodeStates: number[];
50
52
  nodeTableaux: number[];
51
- successors: number[][];
52
- actions: Uint8Array[];
53
- stateResults: Uint8Array[];
54
- isWritten: boolean[];
53
+ // The successors a node gathers until it is written.
54
+ pending: (number[] | undefined)[];
55
+ // Each written node's state results, then its action results edge by edge, from the node's
56
+ // offset in one buffer, so a node costs no objects of its own. An unwritten node has offset -1.
57
+ offsets: number[];
58
+ results: { bytes: Uint8Array; length: number };
59
+ // Each written node's successor count, then its successors, from the node's edge offset.
60
+ edgeOffsets: number[];
61
+ edges: { ids: Int32Array; length: number };
55
62
  initial: number[];
56
- nodeIds: Map<number, number>;
57
- nodesByState: Map<number, number[]>;
63
+ nodeIds: NodeTable;
58
64
  isDone: boolean[];
59
65
  errorNode: number | undefined;
60
66
  }
61
67
 
62
- const liveKeys = new WeakMap<LiveExpression, string>();
63
-
64
- const atomCount = { value: 0 };
65
-
66
- // Each solution builds its own junctions over shared atoms, so equal checks get equal keys.
67
- const getLiveKey = (expression: LiveExpression): string => {
68
- const cached = liveKeys.get(expression);
69
- if (cached !== undefined) return cached;
70
- const key =
71
- expression.kind === "Boolean"
72
- ? String(expression.value)
73
- : "body" in expression
74
- ? `${expression.kind}(${getLiveKey(expression.body)})`
75
- : "operands" in expression
76
- ? `${expression.kind}(${expression.operands.map(getLiveKey).join(",")})`
77
- : `${expression.kind}#${atomCount.value++}`;
78
- liveKeys.set(expression, key);
79
- return key;
80
- };
81
-
82
68
  const isSameState = (left: Value[], right: Value[]) =>
83
69
  left.every((value, position) => isSameValue(value, right[position]));
84
70
 
@@ -89,13 +75,45 @@ const removeRepeats = (path: number[]) =>
89
75
  const pushNode = (check: Check, state: number, tableauNode: number) => {
90
76
  check.nodeStates.push(state);
91
77
  check.nodeTableaux.push(tableauNode);
92
- check.successors.push([]);
93
- check.actions.push(new Uint8Array(0));
94
- check.stateResults.push(new Uint8Array(0));
95
- check.isWritten.push(false);
78
+ check.pending.push(undefined);
79
+ check.offsets.push(-1);
80
+ check.edgeOffsets.push(-1);
96
81
  return check.nodeStates.length - 1;
97
82
  };
98
83
 
84
+ // A Map holds at most 2^24 entries, so each tableau node of a state finds its node in an
85
+ // open-addressing table of (state plus one, tableau node, node) triples.
86
+ interface NodeTable {
87
+ slots: Int32Array;
88
+ size: number;
89
+ shift: number;
90
+ }
91
+
92
+ const getNodeSlot = (table: NodeTable, state: number, tableauNode: number) => {
93
+ const mask = table.slots.length / 3 - 1;
94
+ const hash = Math.imul(Math.imul(state, 0x9e3779b1) ^ tableauNode, 0x85ebca6b) >>> table.shift;
95
+ for (let index = hash; ; index = (index + 1) & mask) {
96
+ const slot = index * 3;
97
+ const stored = table.slots[slot];
98
+ if (stored === 0 || (stored === state + 1 && table.slots[slot + 1] === tableauNode))
99
+ return slot;
100
+ }
101
+ };
102
+
103
+ // Without a tableau a node is a state, so a successor the search hasn't expanded yet may lie past
104
+ // the per-node arrays.
105
+ const isWritten = (check: Check, node: number) => (check.offsets[node] ?? -1) !== -1;
106
+
107
+ const getPending = (check: Check, node: number) => (check.pending[node] ??= []);
108
+
109
+ const getSuccessors = (check: Check, node: number) => {
110
+ const offset = check.edgeOffsets[node];
111
+ return check.edges.ids.subarray(offset + 1, offset + 1 + check.edges.ids[offset]);
112
+ };
113
+
114
+ const getStateResult = (check: Check, node: number, position: number) =>
115
+ check.results.bytes[check.offsets[node] + position] === 1;
116
+
99
117
  const SUCCESSOR_CAPACITY = 16;
100
118
 
101
119
  const SCC_MARKER = -42;
@@ -122,26 +140,29 @@ export const createLivenessChecker = (
122
140
  fairness.length === 0 ? violation : createJunction("And", [...fairness, violation]);
123
141
  const solutions = getSolutions(formula);
124
142
  if (solutions.length === 0) {
125
- throw new TlaEvaluationError(TAUTOLOGY_MESSAGE);
143
+ throw setExitCode(
144
+ new TlaEvaluationError(TAUTOLOGY_MESSAGE),
145
+ EXIT_STATUS.livenessEvaluationFailure,
146
+ );
126
147
  }
127
148
  const actionIds = new Map<string, number>();
128
149
  const checks = solutions.map((solution): Check => ({
129
150
  solution,
130
151
  actionIds: Int32Array.from(solution.actionChecks, (predicate) => {
131
- const key = getLiveKey(predicate);
152
+ const key = getTermKey(predicate);
132
153
  const id = actionIds.get(key) ?? actionIds.size;
133
154
  actionIds.set(key, id);
134
155
  return id;
135
156
  }),
136
157
  nodeStates: [],
137
158
  nodeTableaux: [],
138
- successors: [],
139
- actions: [],
140
- stateResults: [],
141
- isWritten: [],
159
+ pending: [],
160
+ offsets: [],
161
+ results: { bytes: new Uint8Array(1024), length: 0 },
162
+ edgeOffsets: [],
163
+ edges: { ids: new Int32Array(1024), length: 0 },
142
164
  initial: [],
143
- nodeIds: new Map(),
144
- nodesByState: new Map(),
165
+ nodeIds: { slots: new Int32Array(3 << 10), size: 0, shift: 22 },
145
166
  isDone: [],
146
167
  errorNode: undefined,
147
168
  }));
@@ -227,18 +248,35 @@ export const createLivenessChecker = (
227
248
  model.infinitelyOftenActions.length === 0,
228
249
  );
229
250
 
230
- const getNodeId = (check: Check, state: number, tableauNode: number) =>
231
- check.solution.tableau
232
- ? check.nodeIds.get(state * check.solution.tableau.nodes.length + tableauNode)
233
- : state;
251
+ const getNodeId = (check: Check, state: number, tableauNode: number) => {
252
+ if (!check.solution.tableau) return state;
253
+ const slots = check.nodeIds.slots;
254
+ const slot = getNodeSlot(check.nodeIds, state, tableauNode);
255
+ return slots[slot] === 0 ? undefined : slots[slot + 2];
256
+ };
234
257
  const recordNode = (check: Check, state: number, tableauNode: number) => {
235
258
  const node = pushNode(check, state, tableauNode);
236
- check.nodeIds.set(state * (check.solution.tableau?.nodes.length ?? 1) + tableauNode, node);
237
- const siblings = check.nodesByState.get(state);
238
- if (siblings) siblings.push(node);
239
- else check.nodesByState.set(state, [node]);
259
+ const table = check.nodeIds;
260
+ if (++table.size * 2 > table.slots.length / 3) {
261
+ const old = table.slots;
262
+ table.slots = new Int32Array(old.length * 2);
263
+ table.shift--;
264
+ for (let slot = 0; slot < old.length; slot += 3) {
265
+ if (old[slot] !== 0)
266
+ table.slots.set(
267
+ old.subarray(slot, slot + 3),
268
+ getNodeSlot(table, old[slot] - 1, old[slot + 1]),
269
+ );
270
+ }
271
+ }
272
+ table.slots.set([state + 1, tableauNode, node], getNodeSlot(table, state, tableauNode));
240
273
  return node;
241
274
  };
275
+ // A state's nodes in the order they were recorded, which is the order of their ids.
276
+ const getStateNodes = (check: Check, tableau: Tableau, state: number) =>
277
+ tableau.nodes
278
+ .flatMap((_, tableauNode) => getNodeId(check, state, tableauNode) ?? [])
279
+ .sort((left, right) => left - right);
242
280
  const writeNode = (
243
281
  check: Check,
244
282
  node: number,
@@ -246,11 +284,32 @@ export const createLivenessChecker = (
246
284
  stateResults: Uint8Array,
247
285
  ) => {
248
286
  const actionCount = check.solution.actionChecks.length;
249
- const packed = new Uint8Array(actions.length * actionCount);
250
- actions.forEach((results, position) => packed.set(results, position * actionCount));
251
- check.actions[node] = packed;
252
- check.stateResults[node] = stateResults;
253
- check.isWritten[node] = true;
287
+ const results = check.results;
288
+ const offset = results.length;
289
+ results.length += stateResults.length + actions.length * actionCount;
290
+ if (results.length > results.bytes.length) {
291
+ const grown = new Uint8Array(Math.max(2 * results.bytes.length, results.length));
292
+ grown.set(results.bytes);
293
+ results.bytes = grown;
294
+ }
295
+ results.bytes.set(stateResults, offset);
296
+ actions.forEach((edge, position) =>
297
+ results.bytes.set(edge, offset + stateResults.length + position * actionCount),
298
+ );
299
+ check.offsets[node] = offset;
300
+ const successors = check.pending[node] ?? [];
301
+ const edges = check.edges;
302
+ const edgeOffset = edges.length;
303
+ edges.length += successors.length + 1;
304
+ if (edges.length > edges.ids.length) {
305
+ const grown = new Int32Array(Math.max(2 * edges.ids.length, edges.length));
306
+ grown.set(edges.ids);
307
+ edges.ids = grown;
308
+ }
309
+ edges.ids[edgeOffset] = successors.length;
310
+ edges.ids.set(successors, edgeOffset + 1);
311
+ check.edgeOffsets[node] = edgeOffset;
312
+ check.pending[node] = undefined;
254
313
  };
255
314
 
256
315
  // TLC collects a state's successors and the state itself in a SetOfStates, a hash set it
@@ -303,7 +362,7 @@ export const createLivenessChecker = (
303
362
  const stateResults = checkState(check, index, state);
304
363
  const tableauNode = tableau.nodes[check.nodeTableaux[node]];
305
364
  const actions: Uint8Array[] = [];
306
- const successors = check.successors[node];
365
+ const successors = getPending(check, node);
307
366
  const selfActions =
308
367
  tableauNode.successors.length > 0
309
368
  ? checkAction(check, index, state, state)
@@ -352,8 +411,8 @@ export const createLivenessChecker = (
352
411
  );
353
412
  check.isDone[index] = true;
354
413
  // TLC expands the nodes recorded before the loop, not the ones the loop records.
355
- for (const node of (check.nodesByState.get(index) ?? []).slice()) {
356
- const successors = check.successors[node];
414
+ for (const node of getStateNodes(check, tableau, index)) {
415
+ const successors = getPending(check, node);
357
416
  const actions: Uint8Array[] = [];
358
417
  set.forEach((successor, position) => {
359
418
  const isDone = check.isDone[successor.index] === true;
@@ -387,10 +446,10 @@ export const createLivenessChecker = (
387
446
  index: number,
388
447
  ) => {
389
448
  while (check.nodeStates.length <= index) pushNode(check, check.nodeStates.length, -1);
390
- const successors = check.successors[index];
449
+ const successors = getPending(check, index);
391
450
  const actions: Uint8Array[] = [];
392
451
  set.forEach((successor, position) => {
393
- if (check.isWritten[successor.index] && successors.includes(successor.index)) return;
452
+ if (isWritten(check, successor.index) && successors.includes(successor.index)) return;
394
453
  successors.push(successor.index);
395
454
  actions.push(actionResults[position]);
396
455
  });
@@ -404,20 +463,20 @@ export const createLivenessChecker = (
404
463
  const parents = new Map<number, number>();
405
464
  const queue: number[] = [];
406
465
  for (const node of check.initial) {
407
- if (!check.isWritten[node]) continue;
466
+ if (!isWritten(check, node)) continue;
408
467
  queue.push(node);
409
468
  parents.set(node, -1);
410
469
  }
411
470
  for (let position = 0; position < queue.length; position++) {
412
471
  const current = queue[position];
413
- for (const next of check.successors[current]) {
472
+ for (const next of getSuccessors(check, current)) {
414
473
  if (next === current && check.solution.tableau) continue;
415
474
  if (next === target) {
416
475
  const path = [target];
417
476
  for (let node = current; node !== -1; node = parents.get(node) ?? -1) path.push(node);
418
477
  return path;
419
478
  }
420
- if (!check.isWritten[next] || parents.has(next)) continue;
479
+ if (!isWritten(check, next) || parents.has(next)) continue;
421
480
  parents.set(next, current);
422
481
  queue.push(next);
423
482
  }
@@ -429,16 +488,17 @@ export const createLivenessChecker = (
429
488
  const findInModel = (check: Check, model: Solution["models"][number]): Lasso | undefined => {
430
489
  const solution = check.solution;
431
490
  const actionCount = solution.actionChecks.length;
491
+ const stateCount = solution.stateChecks.length;
432
492
  const getAction = (node: number, edge: number, position: number) =>
433
- check.actions[node][edge * actionCount + position] === 1;
493
+ check.results.bytes[check.offsets[node] + stateCount + edge * actionCount + position] === 1;
434
494
  const isAllowed = (node: number, edge: number) =>
435
495
  model.eventuallyAlways.every((position) => getAction(node, edge, position));
436
496
  const links = new Float64Array(check.nodeStates.length).fill(UNVISITED);
437
- const queue = check.initial.filter((node) => check.isWritten[node]);
497
+ const queue = check.initial.filter((node) => isWritten(check, node));
438
498
  const components: number[] = [];
439
499
 
440
500
  const isStuttering = (node: number) => {
441
- const edge = check.successors[node].indexOf(node);
501
+ const edge = getSuccessors(check, node).indexOf(node);
442
502
  return edge !== -1 && isAllowed(node, edge);
443
503
  };
444
504
  const isFulfilled = (node: number, promise: Solution["promises"][number]) =>
@@ -462,11 +522,11 @@ export const createLivenessChecker = (
462
522
  if (member === root) break;
463
523
  }
464
524
  const isStateSatisfied = model.infinitelyOftenStates.every((position) =>
465
- [...members].some((node) => check.stateResults[node][position] === 1),
525
+ [...members].some((node) => getStateResult(check, node, position)),
466
526
  );
467
527
  const isActionSatisfied = model.infinitelyOftenActions.every((position) =>
468
528
  [...members].some((node) =>
469
- check.successors[node].some(
529
+ getSuccessors(check, node).some(
470
530
  (next, edge) =>
471
531
  members.has(next) && isAllowed(node, edge) && getAction(node, edge, position),
472
532
  ),
@@ -507,7 +567,7 @@ export const createLivenessChecker = (
507
567
  const countAtStart = remaining.count;
508
568
  while (true) {
509
569
  model.infinitelyOftenStates.forEach((position, slot) => {
510
- if (!stateDone[slot] && check.stateResults[current.node][position] === 1) {
570
+ if (!stateDone[slot] && getStateResult(check, current.node, position)) {
511
571
  stateDone[slot] = true;
512
572
  remaining.count--;
513
573
  }
@@ -521,7 +581,7 @@ export const createLivenessChecker = (
521
581
  if (remaining.count <= 0) break;
522
582
  const step = { last: -1, unvisited: -1 };
523
583
  const countBeforeActions = remaining.count;
524
- const successors = check.successors[current.node];
584
+ const successors = getSuccessors(check, current.node);
525
585
  const taken = successors.some((next, edge) => {
526
586
  if (membersByState.has(check.nodeStates[next])) {
527
587
  if (!isMember(next) || !isAllowed(current.node, edge)) return false;
@@ -556,7 +616,8 @@ export const createLivenessChecker = (
556
616
  }
557
617
  current.node = previous;
558
618
  step.unvisited =
559
- check.successors[previous].find((next) => isMember(next) && !seen.has(next)) ?? -1;
619
+ getSuccessors(check, previous).find((next) => isMember(next) && !seen.has(next)) ??
620
+ -1;
560
621
  }
561
622
  take(step.unvisited);
562
623
  seen.add(step.unvisited);
@@ -586,7 +647,7 @@ export const createLivenessChecker = (
586
647
  const queue: [number, number][] = [];
587
648
  for (let state = start, parent = -1, position = 0; ; position++) {
588
649
  for (const node of membersByState.get(state) ?? []) {
589
- for (const [edge, next] of check.successors[node].entries()) {
650
+ for (const [edge, next] of getSuccessors(check, node).entries()) {
590
651
  if (next === node || !isAllowedEdge(node, edge)) continue;
591
652
  if (next === root) {
592
653
  const path: number[] = [];
@@ -639,8 +700,8 @@ export const createLivenessChecker = (
639
700
  stack.push(lowLink, node, SCC_MARKER);
640
701
  components.push(node);
641
702
  const nextLowLink = { value: counter.link++ };
642
- check.successors[node].forEach((next, edge) => {
643
- if (!check.isWritten[next]) return;
703
+ getSuccessors(check, node).forEach((next, edge) => {
704
+ if (!isWritten(check, next)) return;
644
705
  if (!isAllowed(node, edge)) {
645
706
  if (links[next] === UNVISITED) queue.push(next);
646
707
  return;
package/src/liveness.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { isLocallyResolved, type Definition, type Expression } from "./ast";
2
- import { TlaConfigError, TlaEvaluationError } from "./errors";
3
- import { EXIT_STATUS, setExitCode } from "./exit-codes";
2
+ import { STACK_OVERFLOW, TlaEvaluationError, TlaModuleError, UNEXPECTED_EXCEPTION } from "./errors";
3
+ import { EXIT_STATUS, getOwnExitCode, setExitCode } from "./exit-codes";
4
4
  import {
5
5
  describeLocation,
6
6
  describeRange,
@@ -61,6 +61,23 @@ const getConstantContext = (environment: Environment, scope: Scope | undefined):
61
61
  next: undefined,
62
62
  });
63
63
 
64
+ // TLC evaluates the constant parts of a property while it processes the spec. Its top-level handler
65
+ // prints a failure without a TLC error code of its own as an unexpected exception.
66
+ const evaluateConstant = (expression: Expression, context: Context) => {
67
+ try {
68
+ return evaluate(expression, context);
69
+ } catch (error) {
70
+ if (!(error instanceof TlaEvaluationError) || error instanceof TlaModuleError) throw error;
71
+ const code = getOwnExitCode(error);
72
+ throw code === undefined
73
+ ? setExitCode(
74
+ new TlaEvaluationError(`${UNEXPECTED_EXCEPTION}${error.message}`, error),
75
+ EXIT_STATUS.error,
76
+ )
77
+ : setExitCode(error, code);
78
+ }
79
+ };
80
+
64
81
  const createCannotHandleError = (expression: Expression) =>
65
82
  new TlaEvaluationError(
66
83
  `TLC cannot handle the temporal formula at ${describeLocation(expression)}`,
@@ -191,7 +208,7 @@ export const expandTemporal = (
191
208
  getDefinitionLevel(definition, environment) > 0
192
209
  ) {
193
210
  if (expanding.has(definition)) {
194
- throw new TlaConfigError(`The definition of ${expression.name} refers to itself`);
211
+ throw setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error);
195
212
  }
196
213
  return expand(
197
214
  definition.body,
@@ -278,7 +295,7 @@ export const toLiveExpression = (
278
295
  ): LiveExpression => {
279
296
  const atomLevel = level === 0 ? getLevel(expression, scope, environment) : level;
280
297
  if (atomLevel === 0) {
281
- const value = evaluate(expression, getConstantContext(environment, scope));
298
+ const value = evaluateConstant(expression, getConstantContext(environment, scope));
282
299
  if (typeof value !== "boolean") {
283
300
  throw new TlaEvaluationError(
284
301
  `TLC expected a boolean in the temporal formula at ${describeLocation(expression)}`,
@@ -299,9 +316,7 @@ export const toLiveExpression = (
299
316
  scope: Scope | undefined,
300
317
  ) => {
301
318
  if (expansion.depth >= MAXIMUM_EXPANSION_DEPTH) {
302
- throw new TlaEvaluationError(
303
- `TLC overflowed the stack while expanding the temporal formula at ${describeLocation(expression)}`,
304
- );
319
+ throw setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error);
305
320
  }
306
321
  expansion.depth++;
307
322
  const result = convert(body, bodyScope);
@@ -356,9 +371,45 @@ export const toLiveExpression = (
356
371
  return level > ACTION_LEVEL ? result : toAtom(expression, scope, level);
357
372
  };
358
373
 
374
+ // TLC translates the operands of a connective even when the whole formula is a state or action
375
+ // predicate, so it fails on a constant operand before it checks any state.
376
+ const convertOperands = (expression: Expression, scope: Scope | undefined) => {
377
+ switch (expression.kind) {
378
+ case "Label":
379
+ convert(expression.body, scope);
380
+ return;
381
+ case "Let":
382
+ convert(expression.body, bindLetDefinitions(expression, scope, environment));
383
+ return;
384
+ case "And":
385
+ case "Or":
386
+ for (const operand of expression.operands) convert(operand, scope);
387
+ return;
388
+ case "Apply":
389
+ if (
390
+ expression.operator === "=>" ||
391
+ (expression.operator === "~" && !isLocallyResolved(expression))
392
+ ) {
393
+ for (const operand of expression.args) convert(operand, scope);
394
+ }
395
+ return;
396
+ case "If": {
397
+ const condition = convert(expression.condition, scope);
398
+ const branches =
399
+ condition.kind === "Boolean"
400
+ ? [condition.value ? expression.consequent : expression.alternative]
401
+ : [expression.consequent, expression.alternative];
402
+ for (const branch of branches) convert(branch, scope);
403
+ }
404
+ }
405
+ };
406
+
359
407
  const convert = (expression: Expression, scope: Scope | undefined): LiveExpression => {
360
408
  const level = getLevel(expression, scope, environment);
361
- if (level <= ACTION_LEVEL) return toAtom(expression, scope, level);
409
+ if (level <= ACTION_LEVEL) {
410
+ convertOperands(expression, scope);
411
+ return toAtom(expression, scope, level);
412
+ }
362
413
  switch (expression.kind) {
363
414
  case "Label":
364
415
  return convert(expression.body, scope);
@@ -401,7 +452,10 @@ export const toLiveExpression = (
401
452
  return convertQuantifier(expression, scope);
402
453
  case "If": {
403
454
  if (getLevel(expression.condition, scope, environment) === 0) {
404
- const condition = evaluate(expression.condition, getConstantContext(environment, scope));
455
+ const condition = evaluateConstant(
456
+ expression.condition,
457
+ getConstantContext(environment, scope),
458
+ );
405
459
  if (typeof condition === "boolean") {
406
460
  return convert(condition ? expression.consequent : expression.alternative, scope);
407
461
  }
@@ -15,7 +15,7 @@ import type {
15
15
  WorkerMessage,
16
16
  } from "./parallel";
17
17
  import { getSuccessors, type Successor } from "./successors";
18
- import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
18
+ import { getTlcStringOrder, getTlcDeclarationOrder } from "./tlc-order";
19
19
  import { OUT_DEGREE_BUCKETS } from "./tlc-summary";
20
20
  import { createStateDecoder, createStateEncoder, type EncodedStates } from "./transfer";
21
21
  import { getRankedStringCount, setStringOrder, type Value } from "./values";
@@ -61,7 +61,7 @@ const run = (start: StartMessage, parent: Port) => {
61
61
  });
62
62
  const environment = specification.environment;
63
63
  const search = createSearch(start.config, environment, () =>
64
- getTlcVariableOrder(start.source, loadModule),
64
+ getTlcDeclarationOrder(start.source, loadModule, "variable"),
65
65
  );
66
66
  const nextAction = search?.spec.next;
67
67
  if (!search || nextAction === undefined)
package/src/parallel.ts CHANGED
@@ -20,7 +20,7 @@ import {
20
20
  type SharedFingerprints,
21
21
  } from "./fingerprints";
22
22
  import { getInitialStates } from "./successors";
23
- import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
23
+ import { getTlcStringOrder, getTlcDeclarationOrder } from "./tlc-order";
24
24
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc-summary";
25
25
  import { createStateEncoder, type EncodedStates } from "./transfer";
26
26
  import { getRankedStringCount, setStringOrder, type Value } from "./values";
@@ -150,7 +150,7 @@ export const check = async (options: CheckOptions): Promise<CheckResult> => {
150
150
  });
151
151
  const environment = specification.environment;
152
152
  const search = createSearch(config, environment, () =>
153
- getTlcVariableOrder(options.source, loadModule),
153
+ getTlcDeclarationOrder(options.source, loadModule, "variable"),
154
154
  );
155
155
  if (findAssumptionViolation(specification.assumptions, environment)) return fallBack();
156
156
  if (
package/src/successors.ts CHANGED
@@ -7,7 +7,7 @@ import {
7
7
  type QuantifierExpression,
8
8
  } from "./ast";
9
9
  import { getReadVariables } from "./dependencies";
10
- import { TlaEvaluationError, UNEXPECTED_EXCEPTION } from "./errors";
10
+ import { TlaEvaluationError, TlaIncompleteStateError } from "./errors";
11
11
  import { EXIT_STATUS, setExitCode } from "./exit-codes";
12
12
  import {
13
13
  describeLocation,
@@ -18,6 +18,7 @@ import {
18
18
  bindValue,
19
19
  compileArgumentScope,
20
20
  evaluate,
21
+ getEntryEvaluator,
21
22
  expectBoolean,
22
23
  forEachBinding,
23
24
  getBoundsDomain,
@@ -29,6 +30,7 @@ import {
29
30
  resolveGlobalOperator,
30
31
  type Context,
31
32
  type Environment,
33
+ type Evaluator,
32
34
  type Scope,
33
35
  type State,
34
36
  } from "./evaluate";
@@ -87,15 +89,25 @@ const assign = (partial: State, index: number, value: Value) => {
87
89
  return copy;
88
90
  };
89
91
 
90
- const holds = (expression: Expression, context: Context) => {
91
- const value = evaluate(expression, context);
92
+ // TLC's Tool.getInitStates and Tool.getNextStates report a value where they expect a formula.
93
+ const expectFormula = (expression: Expression, value: Value, isInit: boolean) => {
92
94
  if (typeof value === "boolean") return value;
93
- try {
94
- return expectBoolean(value, `the action at ${describeLocation(expression)}`);
95
- } catch (error) {
96
- // TLC fails with an unexpected exception when the next-state relation isn't a boolean.
97
- throw context.next === undefined ? error : setExitCode(error, EXIT_STATUS.error);
95
+ throw new TlaEvaluationError(
96
+ `In computing ${isInit ? "initial" : "next"} states, TLC expected a boolean expression,\nbut instead found ${formatValue(value)}.\n${describeRange(expression)}`,
97
+ );
98
+ };
99
+
100
+ const holds = (expression: Expression, context: Context, value = evaluate(expression, context)) => {
101
+ // TLC rejects a number in the next-state relation when it splits the relation into actions.
102
+ if (context.next !== undefined && expression.kind === "Number") {
103
+ throw setExitCode(
104
+ new TlaEvaluationError(
105
+ `The next state relation is not a boolean expression.\n${expression.text ?? expression.value}`,
106
+ ),
107
+ EXIT_STATUS.error,
108
+ );
98
109
  }
110
+ return expectFormula(expression, value, context.next === undefined);
99
111
  };
100
112
 
101
113
  const isAssignmentOperator = (operator: string) =>
@@ -320,6 +332,7 @@ const compileConjunction = (
320
332
  isInit: boolean,
321
333
  ): Runner => {
322
334
  const conjuncts = operands.map((operand) => toConjunct(operand, environment, isInit));
335
+ const evaluators: (Evaluator | undefined)[] = conjuncts.map(() => undefined);
323
336
  const runFrom = (
324
337
  start: number,
325
338
  run: Run,
@@ -342,12 +355,17 @@ const compileConjunction = (
342
355
  const conjunct = conjuncts[index];
343
356
  if (conjunct.kind === "Guard") {
344
357
  context ??= getContext(run, scope, current);
345
- if (!holds(conjunct.expression, context)) return;
358
+ const evaluator = (evaluators[index] ??= getEntryEvaluator(
359
+ conjunct.expression,
360
+ environment,
361
+ ));
362
+ if (!holds(conjunct.expression, context, evaluator(context))) return;
346
363
  continue;
347
364
  }
348
365
  if (conjunct.kind === "Assign") {
349
366
  context ??= getContext(run, scope, current);
350
- const value = evaluate(conjunct.value, context);
367
+ const evaluator = (evaluators[index] ??= getEntryEvaluator(conjunct.value, environment));
368
+ const value = evaluator(context);
351
369
  const assigned = current[conjunct.index];
352
370
  if (assigned === undefined) {
353
371
  current = assign(current, conjunct.index, value);
@@ -384,10 +402,7 @@ const compileConjunction = (
384
402
  };
385
403
 
386
404
  const holdsInInit = (expression: Expression, context: Context) =>
387
- expectBoolean(
388
- evaluate(expression, context),
389
- `the initial predicate at ${describeLocation(expression)}`,
390
- );
405
+ expectFormula(expression, evaluate(expression, context), true);
391
406
 
392
407
  const compileGuard =
393
408
  (expression: Expression): Runner =>
@@ -412,7 +427,7 @@ const compileMembership = (
412
427
  expression.operator === "\\subseteq" ? { kind: "Subset", base: evaluated } : evaluated;
413
428
  if (!isEnumerable(value)) {
414
429
  throw new TlaEvaluationError(
415
- `In computing next states, the right side of \\in is not enumerable: ${formatValue(value)} at ${describeLocation(expression)}`,
430
+ `In computing ${run.isInit ? "initial" : "next"} states, the right side of \\IN is not enumerable.\n${describeRange(expression)}`,
416
431
  );
417
432
  }
418
433
  const elements = getStreamedElements(value);
@@ -859,7 +874,7 @@ const compileAction = (
859
874
  const body = arm?.body ?? other;
860
875
  if (!body)
861
876
  throw new TlaEvaluationError(
862
- `${UNEXPECTED_EXCEPTION}In computing next states, TLC encountered a CASE with no conditions true.\n${describeRange(expression)}`,
877
+ `In computing ${run.isInit ? "initial" : "next"} states, TLC encountered a CASE with no conditions true.\n${describeRange(expression)}`,
863
878
  );
864
879
  body(run, scope, partial, action, isFixed, onComplete);
865
880
  };
@@ -1050,8 +1065,10 @@ export const forEachSuccessor = (
1050
1065
  (partial, action) => {
1051
1066
  if (run.isStopped) return;
1052
1067
  if (!isComplete(partial)) {
1053
- throw new TlaEvaluationError(
1054
- `Successor state is not completely specified by action ${action ?? "Next"}. The following variables are not assigned: ${getMissingVariables(partial, environment).join(", ")}`,
1068
+ throw new TlaIncompleteStateError(
1069
+ partial,
1070
+ action,
1071
+ getMissingVariables(partial, environment).sort(),
1055
1072
  );
1056
1073
  }
1057
1074
  counter.successors++;