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

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/evaluate.ts CHANGED
@@ -10,11 +10,10 @@ import {
10
10
  type NumberExpression,
11
11
  type OperatorParam,
12
12
  type RecordField,
13
- type SourceRange,
14
13
  } from "./ast";
15
14
  import { getKindString } from "./builtins";
16
- import { TlaEvaluationError } from "./errors";
17
- import { EXIT_STATUS, setExitCode } from "./exit-codes";
15
+ import { formatRange, TlaEvaluationError } from "./errors";
16
+ import { EXIT_STATUS, setExitCode, setOwnExitCode } from "./exit-codes";
18
17
  import { generateEvaluator } from "./codegen";
19
18
  import type { CheckerRuntime } from "./runtime";
20
19
  import { getReadVariables } from "./dependencies";
@@ -30,6 +29,7 @@ import {
30
29
  createSortedSet,
31
30
  createWrittenRecord,
32
31
  createTuple,
32
+ describeMissingField,
33
33
  formatValue,
34
34
  getDomain,
35
35
  getFunctionDomain,
@@ -38,6 +38,7 @@ import {
38
38
  getValueHash,
39
39
  isFunctionValue,
40
40
  isOverriddenSet,
41
+ isRecordValue,
41
42
  isSameValue,
42
43
  markLambdaFunction,
43
44
  isReducible,
@@ -47,6 +48,7 @@ import {
47
48
  toFiniteSet,
48
49
  updateFunction,
49
50
  valuesEqual,
51
+ type FunctionValue,
50
52
  type LazyFunctionSource,
51
53
  type LazyFunctionValue,
52
54
  type Value,
@@ -143,9 +145,6 @@ const EXCEPT_AT = "@";
143
145
  export const describeLocation = (expression: Expression) =>
144
146
  `line ${expression.location.line}, column ${expression.location.column}`;
145
147
 
146
- export const formatRange = (range: SourceRange) =>
147
- `line ${range.start.line}, col ${range.start.column} to line ${range.end.line}, col ${range.end.column} of module ${range.module}`;
148
-
149
148
  export const describeRange = (expression: Expression) => {
150
149
  const range = expression.location.range;
151
150
  return range ? formatRange(range) : describeLocation(expression);
@@ -182,8 +181,17 @@ export const getConjunctError = (
182
181
  };
183
182
 
184
183
  export const getFieldError =
185
- (expression: Expression & { kind: "FieldAccess" }) => (record: Value) =>
186
- `Attempted to select nonexistent field "${expression.field}" from the record\n${formatValue(record)}\n${describeRange(expression)}`;
184
+ (expression: Expression & { kind: "FieldAccess" }) => (record: FunctionValue) =>
185
+ isRecordValue(record)
186
+ ? `Attempted to select nonexistent field "${expression.field}" from the record\n${formatValue(record)}\n${describeRange(expression)}`
187
+ : describeMissingField(record, expression.field);
188
+
189
+ export const getNonFunctionError = (expression: Expression) => (value: Value) =>
190
+ `A non-function (${getKindString(value)}) was applied as a function.\n${describeRange(expression)}`;
191
+
192
+ export const getNonRecordError =
193
+ (expression: Expression & { kind: "FieldAccess" }) => (value: Value) =>
194
+ `Attempted to select field "${expression.field}" from a non-record value ${formatValue(value)}\n${describeRange(expression)}`;
187
195
 
188
196
  export const getDomainOperator = (expression: Expression) => (value: Value) => {
189
197
  if (!isFunctionValue(value)) {
@@ -1325,6 +1333,11 @@ const compileApply = (
1325
1333
  if (definition?.kind === "Function") {
1326
1334
  throw new TlaEvaluationError(`${expression.operator} is a function; apply it with brackets`);
1327
1335
  }
1336
+ if (expression.operator === "\\cdot") {
1337
+ throw new TlaEvaluationError(
1338
+ "The current version of TLC does not support action composition. An incomplete implementation can be enabled via the tlc2.tool.impl.Tool.cdot=true java property.",
1339
+ );
1340
+ }
1328
1341
  throw new TlaEvaluationError(
1329
1342
  `Unknown operator ${expression.operator} at ${describeLocation(expression)}`,
1330
1343
  );
@@ -1574,7 +1587,12 @@ export const hasDuplicateFields = (sortedFields: RecordField[]) =>
1574
1587
  sortedFields.some((field, index) => index > 0 && sortedFields[index - 1].name === field.name);
1575
1588
 
1576
1589
  export const createUnassignedError = (name: string, expression: Expression) =>
1577
- new TlaEvaluationError(`The variable ${name} is not assigned at ${describeLocation(expression)}`);
1590
+ setOwnExitCode(
1591
+ new TlaEvaluationError(
1592
+ `In evaluation, the identifier ${name} is either undefined or not an operator.\n${describeRange(expression)}`,
1593
+ ),
1594
+ EXIT_STATUS.configParseError,
1595
+ );
1578
1596
 
1579
1597
  export const createPrimeOutsideActionError = (expression: Expression) =>
1580
1598
  new TlaEvaluationError(
@@ -1762,18 +1780,31 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1762
1780
  keepLazy(expression.function);
1763
1781
  const evaluateFunction = child(expression.function);
1764
1782
  const args = expression.args.map(child);
1783
+ const describeNonFunction = getNonFunctionError(expression);
1765
1784
  if (args.length === 1) {
1766
1785
  const argument = args[0];
1767
- return (context) => applyFunction(evaluateFunction(context), argument(context));
1786
+ return (context) =>
1787
+ applyFunction(
1788
+ evaluateFunction(context),
1789
+ argument(context),
1790
+ undefined,
1791
+ describeNonFunction,
1792
+ );
1768
1793
  }
1769
1794
  return (context) =>
1770
- applyFunction(evaluateFunction(context), createTuple(args.map((arg) => arg(context))));
1795
+ applyFunction(
1796
+ evaluateFunction(context),
1797
+ createTuple(args.map((arg) => arg(context))),
1798
+ undefined,
1799
+ describeNonFunction,
1800
+ );
1771
1801
  }
1772
1802
  case "FieldAccess": {
1773
1803
  const record = child(expression.record);
1774
1804
  const field = expression.field;
1775
1805
  const describeMissing = getFieldError(expression);
1776
- return (context) => applyFunction(record(context), field, describeMissing);
1806
+ const describeNonRecord = getNonRecordError(expression);
1807
+ return (context) => applyFunction(record(context), field, describeMissing, describeNonRecord);
1777
1808
  }
1778
1809
  case "Product": {
1779
1810
  const factors = expression.factors.map(child);
package/src/exit-codes.ts CHANGED
@@ -26,7 +26,19 @@ export const setExitCode = <Thrown>(error: Thrown, code: number) => {
26
26
 
27
27
  export const getExitCode = (error: Error) => exitCodes.get(error);
28
28
 
29
- // TLC exits with 255 when it fails to process or evaluate a liveness property, in any phase.
29
+ const ownExitCodes = new WeakMap<Error, number>();
30
+
31
+ // The exit status of the error code TLC gives an EvalException, which TLC uses only where it
32
+ // doesn't report the error again as a nested expression.
33
+ export const setOwnExitCode = <Thrown extends Error>(error: Thrown, code: number) => {
34
+ ownExitCodes.set(error, code);
35
+ return error;
36
+ };
37
+
38
+ export const getOwnExitCode = (error: unknown) =>
39
+ error instanceof Error ? ownExitCodes.get(error) : undefined;
40
+
41
+ // TLC exits with 255 when it fails to process or evaluate a liveness property.
30
42
  const withErrorExitCode = <Result>(run: () => Result) => {
31
43
  try {
32
44
  return run();
@@ -41,8 +53,15 @@ export const withLivenessExitCode = (
41
53
  const checker = withErrorExitCode(create);
42
54
  return (
43
55
  checker && {
44
- addInitialState: (index, state) =>
45
- withErrorExitCode(() => checker.addInitialState(index, state)),
56
+ // TLC replays the initial states to report an error, but skips the liveness check of a
57
+ // state it has already seen, so it exits with the status of the error's own code.
58
+ addInitialState: (index, state) => {
59
+ try {
60
+ checker.addInitialState(index, state);
61
+ } catch (error) {
62
+ throw setExitCode(error, getOwnExitCode(error) ?? EXIT_STATUS.error);
63
+ }
64
+ },
46
65
  addState: (index, state, successors) =>
47
66
  withErrorExitCode(() => checker.addState(index, state, successors)),
48
67
  findViolation: () => withErrorExitCode(() => checker.findViolation()),
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,
@@ -49,13 +50,17 @@ interface Check {
49
50
  actionIds: Int32Array;
50
51
  nodeStates: number[];
51
52
  nodeTableaux: number[];
52
- successors: number[][];
53
- actions: Uint8Array[];
54
- stateResults: Uint8Array[];
55
- 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 };
56
62
  initial: number[];
57
- nodeIds: Map<number, number>;
58
- nodesByState: Map<number, number[]>;
63
+ nodeIds: NodeTable;
59
64
  isDone: boolean[];
60
65
  errorNode: number | undefined;
61
66
  }
@@ -70,13 +75,45 @@ const removeRepeats = (path: number[]) =>
70
75
  const pushNode = (check: Check, state: number, tableauNode: number) => {
71
76
  check.nodeStates.push(state);
72
77
  check.nodeTableaux.push(tableauNode);
73
- check.successors.push([]);
74
- check.actions.push(new Uint8Array(0));
75
- check.stateResults.push(new Uint8Array(0));
76
- check.isWritten.push(false);
78
+ check.pending.push(undefined);
79
+ check.offsets.push(-1);
80
+ check.edgeOffsets.push(-1);
77
81
  return check.nodeStates.length - 1;
78
82
  };
79
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
+
80
117
  const SUCCESSOR_CAPACITY = 16;
81
118
 
82
119
  const SCC_MARKER = -42;
@@ -103,7 +140,10 @@ export const createLivenessChecker = (
103
140
  fairness.length === 0 ? violation : createJunction("And", [...fairness, violation]);
104
141
  const solutions = getSolutions(formula);
105
142
  if (solutions.length === 0) {
106
- throw new TlaEvaluationError(TAUTOLOGY_MESSAGE);
143
+ throw setExitCode(
144
+ new TlaEvaluationError(TAUTOLOGY_MESSAGE),
145
+ EXIT_STATUS.livenessEvaluationFailure,
146
+ );
107
147
  }
108
148
  const actionIds = new Map<string, number>();
109
149
  const checks = solutions.map((solution): Check => ({
@@ -116,13 +156,13 @@ export const createLivenessChecker = (
116
156
  }),
117
157
  nodeStates: [],
118
158
  nodeTableaux: [],
119
- successors: [],
120
- actions: [],
121
- stateResults: [],
122
- isWritten: [],
159
+ pending: [],
160
+ offsets: [],
161
+ results: { bytes: new Uint8Array(1024), length: 0 },
162
+ edgeOffsets: [],
163
+ edges: { ids: new Int32Array(1024), length: 0 },
123
164
  initial: [],
124
- nodeIds: new Map(),
125
- nodesByState: new Map(),
165
+ nodeIds: { slots: new Int32Array(3 << 10), size: 0, shift: 22 },
126
166
  isDone: [],
127
167
  errorNode: undefined,
128
168
  }));
@@ -208,18 +248,35 @@ export const createLivenessChecker = (
208
248
  model.infinitelyOftenActions.length === 0,
209
249
  );
210
250
 
211
- const getNodeId = (check: Check, state: number, tableauNode: number) =>
212
- check.solution.tableau
213
- ? check.nodeIds.get(state * check.solution.tableau.nodes.length + tableauNode)
214
- : 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
+ };
215
257
  const recordNode = (check: Check, state: number, tableauNode: number) => {
216
258
  const node = pushNode(check, state, tableauNode);
217
- check.nodeIds.set(state * (check.solution.tableau?.nodes.length ?? 1) + tableauNode, node);
218
- const siblings = check.nodesByState.get(state);
219
- if (siblings) siblings.push(node);
220
- 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));
221
273
  return node;
222
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);
223
280
  const writeNode = (
224
281
  check: Check,
225
282
  node: number,
@@ -227,11 +284,32 @@ export const createLivenessChecker = (
227
284
  stateResults: Uint8Array,
228
285
  ) => {
229
286
  const actionCount = check.solution.actionChecks.length;
230
- const packed = new Uint8Array(actions.length * actionCount);
231
- actions.forEach((results, position) => packed.set(results, position * actionCount));
232
- check.actions[node] = packed;
233
- check.stateResults[node] = stateResults;
234
- 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;
235
313
  };
236
314
 
237
315
  // TLC collects a state's successors and the state itself in a SetOfStates, a hash set it
@@ -284,7 +362,7 @@ export const createLivenessChecker = (
284
362
  const stateResults = checkState(check, index, state);
285
363
  const tableauNode = tableau.nodes[check.nodeTableaux[node]];
286
364
  const actions: Uint8Array[] = [];
287
- const successors = check.successors[node];
365
+ const successors = getPending(check, node);
288
366
  const selfActions =
289
367
  tableauNode.successors.length > 0
290
368
  ? checkAction(check, index, state, state)
@@ -333,8 +411,8 @@ export const createLivenessChecker = (
333
411
  );
334
412
  check.isDone[index] = true;
335
413
  // TLC expands the nodes recorded before the loop, not the ones the loop records.
336
- for (const node of (check.nodesByState.get(index) ?? []).slice()) {
337
- const successors = check.successors[node];
414
+ for (const node of getStateNodes(check, tableau, index)) {
415
+ const successors = getPending(check, node);
338
416
  const actions: Uint8Array[] = [];
339
417
  set.forEach((successor, position) => {
340
418
  const isDone = check.isDone[successor.index] === true;
@@ -368,10 +446,10 @@ export const createLivenessChecker = (
368
446
  index: number,
369
447
  ) => {
370
448
  while (check.nodeStates.length <= index) pushNode(check, check.nodeStates.length, -1);
371
- const successors = check.successors[index];
449
+ const successors = getPending(check, index);
372
450
  const actions: Uint8Array[] = [];
373
451
  set.forEach((successor, position) => {
374
- if (check.isWritten[successor.index] && successors.includes(successor.index)) return;
452
+ if (isWritten(check, successor.index) && successors.includes(successor.index)) return;
375
453
  successors.push(successor.index);
376
454
  actions.push(actionResults[position]);
377
455
  });
@@ -385,20 +463,20 @@ export const createLivenessChecker = (
385
463
  const parents = new Map<number, number>();
386
464
  const queue: number[] = [];
387
465
  for (const node of check.initial) {
388
- if (!check.isWritten[node]) continue;
466
+ if (!isWritten(check, node)) continue;
389
467
  queue.push(node);
390
468
  parents.set(node, -1);
391
469
  }
392
470
  for (let position = 0; position < queue.length; position++) {
393
471
  const current = queue[position];
394
- for (const next of check.successors[current]) {
472
+ for (const next of getSuccessors(check, current)) {
395
473
  if (next === current && check.solution.tableau) continue;
396
474
  if (next === target) {
397
475
  const path = [target];
398
476
  for (let node = current; node !== -1; node = parents.get(node) ?? -1) path.push(node);
399
477
  return path;
400
478
  }
401
- if (!check.isWritten[next] || parents.has(next)) continue;
479
+ if (!isWritten(check, next) || parents.has(next)) continue;
402
480
  parents.set(next, current);
403
481
  queue.push(next);
404
482
  }
@@ -410,16 +488,17 @@ export const createLivenessChecker = (
410
488
  const findInModel = (check: Check, model: Solution["models"][number]): Lasso | undefined => {
411
489
  const solution = check.solution;
412
490
  const actionCount = solution.actionChecks.length;
491
+ const stateCount = solution.stateChecks.length;
413
492
  const getAction = (node: number, edge: number, position: number) =>
414
- check.actions[node][edge * actionCount + position] === 1;
493
+ check.results.bytes[check.offsets[node] + stateCount + edge * actionCount + position] === 1;
415
494
  const isAllowed = (node: number, edge: number) =>
416
495
  model.eventuallyAlways.every((position) => getAction(node, edge, position));
417
496
  const links = new Float64Array(check.nodeStates.length).fill(UNVISITED);
418
- const queue = check.initial.filter((node) => check.isWritten[node]);
497
+ const queue = check.initial.filter((node) => isWritten(check, node));
419
498
  const components: number[] = [];
420
499
 
421
500
  const isStuttering = (node: number) => {
422
- const edge = check.successors[node].indexOf(node);
501
+ const edge = getSuccessors(check, node).indexOf(node);
423
502
  return edge !== -1 && isAllowed(node, edge);
424
503
  };
425
504
  const isFulfilled = (node: number, promise: Solution["promises"][number]) =>
@@ -443,11 +522,11 @@ export const createLivenessChecker = (
443
522
  if (member === root) break;
444
523
  }
445
524
  const isStateSatisfied = model.infinitelyOftenStates.every((position) =>
446
- [...members].some((node) => check.stateResults[node][position] === 1),
525
+ [...members].some((node) => getStateResult(check, node, position)),
447
526
  );
448
527
  const isActionSatisfied = model.infinitelyOftenActions.every((position) =>
449
528
  [...members].some((node) =>
450
- check.successors[node].some(
529
+ getSuccessors(check, node).some(
451
530
  (next, edge) =>
452
531
  members.has(next) && isAllowed(node, edge) && getAction(node, edge, position),
453
532
  ),
@@ -488,7 +567,7 @@ export const createLivenessChecker = (
488
567
  const countAtStart = remaining.count;
489
568
  while (true) {
490
569
  model.infinitelyOftenStates.forEach((position, slot) => {
491
- if (!stateDone[slot] && check.stateResults[current.node][position] === 1) {
570
+ if (!stateDone[slot] && getStateResult(check, current.node, position)) {
492
571
  stateDone[slot] = true;
493
572
  remaining.count--;
494
573
  }
@@ -502,7 +581,7 @@ export const createLivenessChecker = (
502
581
  if (remaining.count <= 0) break;
503
582
  const step = { last: -1, unvisited: -1 };
504
583
  const countBeforeActions = remaining.count;
505
- const successors = check.successors[current.node];
584
+ const successors = getSuccessors(check, current.node);
506
585
  const taken = successors.some((next, edge) => {
507
586
  if (membersByState.has(check.nodeStates[next])) {
508
587
  if (!isMember(next) || !isAllowed(current.node, edge)) return false;
@@ -537,7 +616,8 @@ export const createLivenessChecker = (
537
616
  }
538
617
  current.node = previous;
539
618
  step.unvisited =
540
- check.successors[previous].find((next) => isMember(next) && !seen.has(next)) ?? -1;
619
+ getSuccessors(check, previous).find((next) => isMember(next) && !seen.has(next)) ??
620
+ -1;
541
621
  }
542
622
  take(step.unvisited);
543
623
  seen.add(step.unvisited);
@@ -567,7 +647,7 @@ export const createLivenessChecker = (
567
647
  const queue: [number, number][] = [];
568
648
  for (let state = start, parent = -1, position = 0; ; position++) {
569
649
  for (const node of membersByState.get(state) ?? []) {
570
- for (const [edge, next] of check.successors[node].entries()) {
650
+ for (const [edge, next] of getSuccessors(check, node).entries()) {
571
651
  if (next === node || !isAllowedEdge(node, edge)) continue;
572
652
  if (next === root) {
573
653
  const path: number[] = [];
@@ -620,8 +700,8 @@ export const createLivenessChecker = (
620
700
  stack.push(lowLink, node, SCC_MARKER);
621
701
  components.push(node);
622
702
  const nextLowLink = { value: counter.link++ };
623
- check.successors[node].forEach((next, edge) => {
624
- if (!check.isWritten[next]) return;
703
+ getSuccessors(check, node).forEach((next, edge) => {
704
+ if (!isWritten(check, next)) return;
625
705
  if (!isAllowed(node, edge)) {
626
706
  if (links[next] === UNVISITED) queue.push(next);
627
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 (