tla-ts 0.0.3-dev.6a30eee → 0.0.3-dev.6d0aeb6

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 (54) hide show
  1. package/README.md +5 -1
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +58 -22
  4. package/dist/index.d.ts +58 -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 +20 -18
  11. package/dist/run-cli.js +22 -20
  12. package/dist/transfer.cjs +40 -15
  13. package/dist/transfer.js +40 -15
  14. package/package.json +1 -1
  15. package/src/ast.ts +101 -1
  16. package/src/builtins.ts +9 -3
  17. package/src/check.ts +473 -100
  18. package/src/cli-options.ts +11 -5
  19. package/src/codegen.ts +15 -22
  20. package/src/config.ts +224 -170
  21. package/src/dependencies.ts +2 -2
  22. package/src/environment.ts +158 -49
  23. package/src/errors.ts +93 -3
  24. package/src/evaluate.ts +214 -147
  25. package/src/exit-codes.ts +21 -14
  26. package/src/fingerprints.ts +2 -1
  27. package/src/instances.ts +16 -15
  28. package/src/levels.ts +181 -45
  29. package/src/live-check.ts +132 -70
  30. package/src/liveness.ts +118 -24
  31. package/src/parallel-worker.ts +2 -2
  32. package/src/parallel.ts +5 -2
  33. package/src/parser.ts +71 -19
  34. package/src/resolve.ts +490 -95
  35. package/src/run-cli.ts +104 -18
  36. package/src/runtime.ts +2 -0
  37. package/src/sany-lexer.ts +615 -0
  38. package/src/sany-parse-error.ts +3143 -0
  39. package/src/spec-description.ts +19 -8
  40. package/src/standard-modules.ts +54 -45
  41. package/src/state-graph.ts +157 -0
  42. package/src/subexpressions.ts +35 -23
  43. package/src/substitution-levels.ts +38 -17
  44. package/src/successors.ts +176 -36
  45. package/src/symmetry.ts +16 -6
  46. package/src/tableau.ts +51 -24
  47. package/src/tlc-ext.ts +29 -12
  48. package/src/tlc-module.ts +14 -33
  49. package/src/tlc-modules.ts +4 -0
  50. package/src/tlc-order.ts +8 -4
  51. package/src/tlc-random.ts +9 -6
  52. package/src/tlc-summary.ts +20 -5
  53. package/src/value-sources.ts +29 -0
  54. package/src/values.ts +242 -61
package/src/live-check.ts CHANGED
@@ -1,7 +1,9 @@
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,
6
+ TAUTOLOGY_MESSAGE,
5
7
  evaluateOnLasso,
6
8
  toLiveExpression,
7
9
  type ScopedExpression,
@@ -11,6 +13,7 @@ import {
11
13
  createJunction,
12
14
  createUnary,
13
15
  getSolutions,
16
+ getTermKey,
14
17
  isFulfilling,
15
18
  type LiveExpression,
16
19
  type Solution,
@@ -47,37 +50,21 @@ interface Check {
47
50
  actionIds: Int32Array;
48
51
  nodeStates: number[];
49
52
  nodeTableaux: number[];
50
- successors: number[][];
51
- actions: Uint8Array[];
52
- stateResults: Uint8Array[];
53
- 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 };
54
62
  initial: number[];
55
- nodeIds: Map<number, number>;
56
- nodesByState: Map<number, number[]>;
63
+ nodeIds: NodeTable;
57
64
  isDone: boolean[];
58
65
  errorNode: number | undefined;
59
66
  }
60
67
 
61
- const liveKeys = new WeakMap<LiveExpression, string>();
62
-
63
- const atomCount = { value: 0 };
64
-
65
- // Each solution builds its own junctions over shared atoms, so equal checks get equal keys.
66
- const getLiveKey = (expression: LiveExpression): string => {
67
- const cached = liveKeys.get(expression);
68
- if (cached !== undefined) return cached;
69
- const key =
70
- expression.kind === "Boolean"
71
- ? String(expression.value)
72
- : "body" in expression
73
- ? `${expression.kind}(${getLiveKey(expression.body)})`
74
- : "operands" in expression
75
- ? `${expression.kind}(${expression.operands.map(getLiveKey).join(",")})`
76
- : `${expression.kind}#${atomCount.value++}`;
77
- liveKeys.set(expression, key);
78
- return key;
79
- };
80
-
81
68
  const isSameState = (left: Value[], right: Value[]) =>
82
69
  left.every((value, position) => isSameValue(value, right[position]));
83
70
 
@@ -88,13 +75,45 @@ const removeRepeats = (path: number[]) =>
88
75
  const pushNode = (check: Check, state: number, tableauNode: number) => {
89
76
  check.nodeStates.push(state);
90
77
  check.nodeTableaux.push(tableauNode);
91
- check.successors.push([]);
92
- check.actions.push(new Uint8Array(0));
93
- check.stateResults.push(new Uint8Array(0));
94
- check.isWritten.push(false);
78
+ check.pending.push(undefined);
79
+ check.offsets.push(-1);
80
+ check.edgeOffsets.push(-1);
95
81
  return check.nodeStates.length - 1;
96
82
  };
97
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
+
98
117
  const SUCCESSOR_CAPACITY = 16;
99
118
 
100
119
  const SCC_MARKER = -42;
@@ -121,26 +140,29 @@ export const createLivenessChecker = (
121
140
  fairness.length === 0 ? violation : createJunction("And", [...fairness, violation]);
122
141
  const solutions = getSolutions(formula);
123
142
  if (solutions.length === 0) {
124
- throw new TlaEvaluationError("Temporal formula is a tautology (its negation is unsatisfiable)");
143
+ throw setExitCode(
144
+ new TlaEvaluationError(TAUTOLOGY_MESSAGE),
145
+ EXIT_STATUS.livenessEvaluationFailure,
146
+ );
125
147
  }
126
148
  const actionIds = new Map<string, number>();
127
149
  const checks = solutions.map((solution): Check => ({
128
150
  solution,
129
151
  actionIds: Int32Array.from(solution.actionChecks, (predicate) => {
130
- const key = getLiveKey(predicate);
152
+ const key = getTermKey(predicate);
131
153
  const id = actionIds.get(key) ?? actionIds.size;
132
154
  actionIds.set(key, id);
133
155
  return id;
134
156
  }),
135
157
  nodeStates: [],
136
158
  nodeTableaux: [],
137
- successors: [],
138
- actions: [],
139
- stateResults: [],
140
- isWritten: [],
159
+ pending: [],
160
+ offsets: [],
161
+ results: { bytes: new Uint8Array(1024), length: 0 },
162
+ edgeOffsets: [],
163
+ edges: { ids: new Int32Array(1024), length: 0 },
141
164
  initial: [],
142
- nodeIds: new Map(),
143
- nodesByState: new Map(),
165
+ nodeIds: { slots: new Int32Array(3 << 10), size: 0, shift: 22 },
144
166
  isDone: [],
145
167
  errorNode: undefined,
146
168
  }));
@@ -226,18 +248,35 @@ export const createLivenessChecker = (
226
248
  model.infinitelyOftenActions.length === 0,
227
249
  );
228
250
 
229
- const getNodeId = (check: Check, state: number, tableauNode: number) =>
230
- check.solution.tableau
231
- ? check.nodeIds.get(state * check.solution.tableau.nodes.length + tableauNode)
232
- : 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
+ };
233
257
  const recordNode = (check: Check, state: number, tableauNode: number) => {
234
258
  const node = pushNode(check, state, tableauNode);
235
- check.nodeIds.set(state * (check.solution.tableau?.nodes.length ?? 1) + tableauNode, node);
236
- const siblings = check.nodesByState.get(state);
237
- if (siblings) siblings.push(node);
238
- 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));
239
273
  return node;
240
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);
241
280
  const writeNode = (
242
281
  check: Check,
243
282
  node: number,
@@ -245,11 +284,32 @@ export const createLivenessChecker = (
245
284
  stateResults: Uint8Array,
246
285
  ) => {
247
286
  const actionCount = check.solution.actionChecks.length;
248
- const packed = new Uint8Array(actions.length * actionCount);
249
- actions.forEach((results, position) => packed.set(results, position * actionCount));
250
- check.actions[node] = packed;
251
- check.stateResults[node] = stateResults;
252
- 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;
253
313
  };
254
314
 
255
315
  // TLC collects a state's successors and the state itself in a SetOfStates, a hash set it
@@ -302,7 +362,7 @@ export const createLivenessChecker = (
302
362
  const stateResults = checkState(check, index, state);
303
363
  const tableauNode = tableau.nodes[check.nodeTableaux[node]];
304
364
  const actions: Uint8Array[] = [];
305
- const successors = check.successors[node];
365
+ const successors = getPending(check, node);
306
366
  const selfActions =
307
367
  tableauNode.successors.length > 0
308
368
  ? checkAction(check, index, state, state)
@@ -351,8 +411,8 @@ export const createLivenessChecker = (
351
411
  );
352
412
  check.isDone[index] = true;
353
413
  // TLC expands the nodes recorded before the loop, not the ones the loop records.
354
- for (const node of (check.nodesByState.get(index) ?? []).slice()) {
355
- const successors = check.successors[node];
414
+ for (const node of getStateNodes(check, tableau, index)) {
415
+ const successors = getPending(check, node);
356
416
  const actions: Uint8Array[] = [];
357
417
  set.forEach((successor, position) => {
358
418
  const isDone = check.isDone[successor.index] === true;
@@ -386,10 +446,10 @@ export const createLivenessChecker = (
386
446
  index: number,
387
447
  ) => {
388
448
  while (check.nodeStates.length <= index) pushNode(check, check.nodeStates.length, -1);
389
- const successors = check.successors[index];
449
+ const successors = getPending(check, index);
390
450
  const actions: Uint8Array[] = [];
391
451
  set.forEach((successor, position) => {
392
- if (check.isWritten[successor.index] && successors.includes(successor.index)) return;
452
+ if (isWritten(check, successor.index) && successors.includes(successor.index)) return;
393
453
  successors.push(successor.index);
394
454
  actions.push(actionResults[position]);
395
455
  });
@@ -403,20 +463,20 @@ export const createLivenessChecker = (
403
463
  const parents = new Map<number, number>();
404
464
  const queue: number[] = [];
405
465
  for (const node of check.initial) {
406
- if (!check.isWritten[node]) continue;
466
+ if (!isWritten(check, node)) continue;
407
467
  queue.push(node);
408
468
  parents.set(node, -1);
409
469
  }
410
470
  for (let position = 0; position < queue.length; position++) {
411
471
  const current = queue[position];
412
- for (const next of check.successors[current]) {
472
+ for (const next of getSuccessors(check, current)) {
413
473
  if (next === current && check.solution.tableau) continue;
414
474
  if (next === target) {
415
475
  const path = [target];
416
476
  for (let node = current; node !== -1; node = parents.get(node) ?? -1) path.push(node);
417
477
  return path;
418
478
  }
419
- if (!check.isWritten[next] || parents.has(next)) continue;
479
+ if (!isWritten(check, next) || parents.has(next)) continue;
420
480
  parents.set(next, current);
421
481
  queue.push(next);
422
482
  }
@@ -428,16 +488,17 @@ export const createLivenessChecker = (
428
488
  const findInModel = (check: Check, model: Solution["models"][number]): Lasso | undefined => {
429
489
  const solution = check.solution;
430
490
  const actionCount = solution.actionChecks.length;
491
+ const stateCount = solution.stateChecks.length;
431
492
  const getAction = (node: number, edge: number, position: number) =>
432
- check.actions[node][edge * actionCount + position] === 1;
493
+ check.results.bytes[check.offsets[node] + stateCount + edge * actionCount + position] === 1;
433
494
  const isAllowed = (node: number, edge: number) =>
434
495
  model.eventuallyAlways.every((position) => getAction(node, edge, position));
435
496
  const links = new Float64Array(check.nodeStates.length).fill(UNVISITED);
436
- const queue = check.initial.filter((node) => check.isWritten[node]);
497
+ const queue = check.initial.filter((node) => isWritten(check, node));
437
498
  const components: number[] = [];
438
499
 
439
500
  const isStuttering = (node: number) => {
440
- const edge = check.successors[node].indexOf(node);
501
+ const edge = getSuccessors(check, node).indexOf(node);
441
502
  return edge !== -1 && isAllowed(node, edge);
442
503
  };
443
504
  const isFulfilled = (node: number, promise: Solution["promises"][number]) =>
@@ -461,11 +522,11 @@ export const createLivenessChecker = (
461
522
  if (member === root) break;
462
523
  }
463
524
  const isStateSatisfied = model.infinitelyOftenStates.every((position) =>
464
- [...members].some((node) => check.stateResults[node][position] === 1),
525
+ [...members].some((node) => getStateResult(check, node, position)),
465
526
  );
466
527
  const isActionSatisfied = model.infinitelyOftenActions.every((position) =>
467
528
  [...members].some((node) =>
468
- check.successors[node].some(
529
+ getSuccessors(check, node).some(
469
530
  (next, edge) =>
470
531
  members.has(next) && isAllowed(node, edge) && getAction(node, edge, position),
471
532
  ),
@@ -506,7 +567,7 @@ export const createLivenessChecker = (
506
567
  const countAtStart = remaining.count;
507
568
  while (true) {
508
569
  model.infinitelyOftenStates.forEach((position, slot) => {
509
- if (!stateDone[slot] && check.stateResults[current.node][position] === 1) {
570
+ if (!stateDone[slot] && getStateResult(check, current.node, position)) {
510
571
  stateDone[slot] = true;
511
572
  remaining.count--;
512
573
  }
@@ -520,7 +581,7 @@ export const createLivenessChecker = (
520
581
  if (remaining.count <= 0) break;
521
582
  const step = { last: -1, unvisited: -1 };
522
583
  const countBeforeActions = remaining.count;
523
- const successors = check.successors[current.node];
584
+ const successors = getSuccessors(check, current.node);
524
585
  const taken = successors.some((next, edge) => {
525
586
  if (membersByState.has(check.nodeStates[next])) {
526
587
  if (!isMember(next) || !isAllowed(current.node, edge)) return false;
@@ -555,7 +616,8 @@ export const createLivenessChecker = (
555
616
  }
556
617
  current.node = previous;
557
618
  step.unvisited =
558
- check.successors[previous].find((next) => isMember(next) && !seen.has(next)) ?? -1;
619
+ getSuccessors(check, previous).find((next) => isMember(next) && !seen.has(next)) ??
620
+ -1;
559
621
  }
560
622
  take(step.unvisited);
561
623
  seen.add(step.unvisited);
@@ -585,7 +647,7 @@ export const createLivenessChecker = (
585
647
  const queue: [number, number][] = [];
586
648
  for (let state = start, parent = -1, position = 0; ; position++) {
587
649
  for (const node of membersByState.get(state) ?? []) {
588
- for (const [edge, next] of check.successors[node].entries()) {
650
+ for (const [edge, next] of getSuccessors(check, node).entries()) {
589
651
  if (next === node || !isAllowedEdge(node, edge)) continue;
590
652
  if (next === root) {
591
653
  const path: number[] = [];
@@ -638,8 +700,8 @@ export const createLivenessChecker = (
638
700
  stack.push(lowLink, node, SCC_MARKER);
639
701
  components.push(node);
640
702
  const nextLowLink = { value: counter.link++ };
641
- check.successors[node].forEach((next, edge) => {
642
- if (!check.isWritten[next]) return;
703
+ getSuccessors(check, node).forEach((next, edge) => {
704
+ if (!isWritten(check, next)) return;
643
705
  if (!isAllowed(node, edge)) {
644
706
  if (links[next] === UNVISITED) queue.push(next);
645
707
  return;
package/src/liveness.ts CHANGED
@@ -1,14 +1,15 @@
1
- import type { Definition, Expression } from "./ast";
2
- import { TlaConfigError, TlaEvaluationError } from "./errors";
1
+ import { isLocallyResolved, type Definition, type Expression } from "./ast";
2
+ import { STACK_OVERFLOW, TlaEvaluationError, TlaModuleError, UNEXPECTED_EXCEPTION } from "./errors";
3
+ import { EXIT_STATUS, getOwnExitCode, setExitCode } from "./exit-codes";
3
4
  import {
4
5
  describeLocation,
6
+ describeRange,
5
7
  bindDefinitions,
6
8
  bindOperatorArguments,
7
9
  evaluate,
8
10
  expectBoolean,
9
11
  forEachBinding,
10
12
  getDefinition,
11
- isLocallyResolved,
12
13
  lookupScope,
13
14
  resolveApplyOperator,
14
15
  resolveGlobalOperator,
@@ -37,6 +38,10 @@ export interface ScopedExpression {
37
38
  scope: Scope | undefined;
38
39
  }
39
40
 
41
+ export interface NamedExpression extends ScopedExpression {
42
+ name: string;
43
+ }
44
+
40
45
  export interface TemporalProperty extends ScopedExpression {
41
46
  name: string;
42
47
  }
@@ -56,6 +61,23 @@ const getConstantContext = (environment: Environment, scope: Scope | undefined):
56
61
  next: undefined,
57
62
  });
58
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
+
59
81
  const createCannotHandleError = (expression: Expression) =>
60
82
  new TlaEvaluationError(
61
83
  `TLC cannot handle the temporal formula at ${describeLocation(expression)}`,
@@ -145,21 +167,27 @@ const getDefinitionLevel = (definition: Definition, environment: Environment) =>
145
167
  return level;
146
168
  };
147
169
 
170
+ export const TAUTOLOGY_MESSAGE = "Temporal formula is a tautology (its negation is unsatisfiable).";
171
+
172
+ // TLC names each part of a property after the operator it expands, or after the location of the
173
+ // conjunct or quantifier body it splits off.
148
174
  export const expandTemporal = (
149
175
  expression: Expression,
150
176
  scope: Scope | undefined,
151
177
  environment: Environment,
152
- isUnrollingForall: boolean,
178
+ isProperty: boolean,
179
+ name = "",
153
180
  expanding = new Set<Definition>(),
154
- ): ScopedExpression[] => {
181
+ ): NamedExpression[] => {
155
182
  const expand = (
156
183
  child: Expression,
157
184
  childScope: Scope | undefined,
185
+ childName = name,
158
186
  childExpanding = expanding,
159
- ): ScopedExpression[] =>
160
- expandTemporal(child, childScope, environment, isUnrollingForall, childExpanding);
187
+ ): NamedExpression[] =>
188
+ expandTemporal(child, childScope, environment, isProperty, childName, childExpanding);
161
189
  if (expression.kind === "And") {
162
- return expression.operands.flatMap((operand) => expand(operand, scope));
190
+ return expression.operands.flatMap((operand) => expand(operand, scope, describeRange(operand)));
163
191
  }
164
192
  if (expression.kind === "Label") return expand(expression.body, scope);
165
193
  if (expression.kind === "Let") {
@@ -180,35 +208,64 @@ export const expandTemporal = (
180
208
  getDefinitionLevel(definition, environment) > 0
181
209
  ) {
182
210
  if (expanding.has(definition)) {
183
- throw new TlaConfigError(`The definition of ${expression.name} refers to itself`);
211
+ throw setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error);
184
212
  }
185
- return expand(definition.body, undefined, new Set([...expanding, definition]));
213
+ const expanded = expand(
214
+ definition.body,
215
+ undefined,
216
+ expression.name,
217
+ new Set([...expanding, definition]),
218
+ );
219
+ // TLC takes the body of a state-level definition in a specification as one initial predicate.
220
+ return !isProperty && getDefinitionLevel(definition, environment) < ACTION_LEVEL
221
+ ? [{ expression: definition.body, scope: undefined, name: expression.name }]
222
+ : expanded;
186
223
  }
187
224
  }
188
225
  const context = getConstantContext(environment, scope);
189
- if (expression.kind === "Apply" && getLevel(expression, scope, environment) === TEMPORAL_LEVEL) {
226
+ // A property expands every operator it applies and unrolls every \A over constant sets, but a
227
+ // specification only expands the temporal ones.
228
+ const isExpanded = (child: Expression) =>
229
+ isProperty || getLevel(child, scope, environment) === TEMPORAL_LEVEL;
230
+ if (expression.kind === "Apply" && isExpanded(expression)) {
190
231
  const operator = resolveApplyOperator(expression, context);
191
232
  const definition = isLocallyResolved(expression)
192
233
  ? undefined
193
234
  : getDefinition(expression.operator, environment);
194
- if (operator?.kind === "Closure" && !definition?.isRecursive) {
195
- return expand(operator.body, bindOperatorArguments(operator, expression.args, context));
235
+ const isExpandable =
236
+ operator?.kind === "Closure" &&
237
+ operator.params.length === expression.args.length &&
238
+ !definition?.isRecursive;
239
+ if (isExpandable) {
240
+ return expand(
241
+ operator.body,
242
+ bindOperatorArguments(operator, expression.args, context),
243
+ expression.operator,
244
+ );
196
245
  }
197
246
  }
198
247
  const isUnrolled =
199
- isUnrollingForall &&
248
+ isProperty &&
200
249
  expression.kind === "Forall" &&
201
- getLevel(expression.body, scope, environment) === TEMPORAL_LEVEL &&
202
250
  expression.bounds.every((bound) => getLevel(bound.set, scope, environment) === 0);
203
251
  if (isUnrolled) {
204
- const expanded: ScopedExpression[] = [];
252
+ const expanded: NamedExpression[] = [];
253
+ const bindings = { count: 0 };
205
254
  forEachBinding(expression.bounds, context, (boundScope) => {
206
- expanded.push(...expand(expression.body, boundScope));
255
+ bindings.count++;
256
+ expanded.push(...expand(expression.body, boundScope, describeRange(expression.body)));
207
257
  return false;
208
258
  });
259
+ // TLC rejects a property that quantifies over no elements before it checks anything.
260
+ if (bindings.count === 0) {
261
+ throw setExitCode(
262
+ new TlaEvaluationError(TAUTOLOGY_MESSAGE),
263
+ EXIT_STATUS.livenessEvaluationFailure,
264
+ );
265
+ }
209
266
  return expanded;
210
267
  }
211
- return [{ expression, scope }];
268
+ return [{ expression, scope, name }];
212
269
  };
213
270
 
214
271
  const bindLetDefinitions = (
@@ -242,7 +299,7 @@ export const toLiveExpression = (
242
299
  ): LiveExpression => {
243
300
  const atomLevel = level === 0 ? getLevel(expression, scope, environment) : level;
244
301
  if (atomLevel === 0) {
245
- const value = evaluate(expression, getConstantContext(environment, scope));
302
+ const value = evaluateConstant(expression, getConstantContext(environment, scope));
246
303
  if (typeof value !== "boolean") {
247
304
  throw new TlaEvaluationError(
248
305
  `TLC expected a boolean in the temporal formula at ${describeLocation(expression)}`,
@@ -263,9 +320,7 @@ export const toLiveExpression = (
263
320
  scope: Scope | undefined,
264
321
  ) => {
265
322
  if (expansion.depth >= MAXIMUM_EXPANSION_DEPTH) {
266
- throw new TlaEvaluationError(
267
- `TLC overflowed the stack while expanding the temporal formula at ${describeLocation(expression)}`,
268
- );
323
+ throw setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error);
269
324
  }
270
325
  expansion.depth++;
271
326
  const result = convert(body, bodyScope);
@@ -320,9 +375,45 @@ export const toLiveExpression = (
320
375
  return level > ACTION_LEVEL ? result : toAtom(expression, scope, level);
321
376
  };
322
377
 
378
+ // TLC translates the operands of a connective even when the whole formula is a state or action
379
+ // predicate, so it fails on a constant operand before it checks any state.
380
+ const convertOperands = (expression: Expression, scope: Scope | undefined) => {
381
+ switch (expression.kind) {
382
+ case "Label":
383
+ convert(expression.body, scope);
384
+ return;
385
+ case "Let":
386
+ convert(expression.body, bindLetDefinitions(expression, scope, environment));
387
+ return;
388
+ case "And":
389
+ case "Or":
390
+ for (const operand of expression.operands) convert(operand, scope);
391
+ return;
392
+ case "Apply":
393
+ if (
394
+ expression.operator === "=>" ||
395
+ (expression.operator === "~" && !isLocallyResolved(expression))
396
+ ) {
397
+ for (const operand of expression.args) convert(operand, scope);
398
+ }
399
+ return;
400
+ case "If": {
401
+ const condition = convert(expression.condition, scope);
402
+ const branches =
403
+ condition.kind === "Boolean"
404
+ ? [condition.value ? expression.consequent : expression.alternative]
405
+ : [expression.consequent, expression.alternative];
406
+ for (const branch of branches) convert(branch, scope);
407
+ }
408
+ }
409
+ };
410
+
323
411
  const convert = (expression: Expression, scope: Scope | undefined): LiveExpression => {
324
412
  const level = getLevel(expression, scope, environment);
325
- if (level <= ACTION_LEVEL) return toAtom(expression, scope, level);
413
+ if (level <= ACTION_LEVEL) {
414
+ convertOperands(expression, scope);
415
+ return toAtom(expression, scope, level);
416
+ }
326
417
  switch (expression.kind) {
327
418
  case "Label":
328
419
  return convert(expression.body, scope);
@@ -365,7 +456,10 @@ export const toLiveExpression = (
365
456
  return convertQuantifier(expression, scope);
366
457
  case "If": {
367
458
  if (getLevel(expression.condition, scope, environment) === 0) {
368
- const condition = evaluate(expression.condition, getConstantContext(environment, scope));
459
+ const condition = evaluateConstant(
460
+ expression.condition,
461
+ getConstantContext(environment, scope),
462
+ );
369
463
  if (typeof condition === "boolean") {
370
464
  return convert(condition ? expression.consequent : expression.alternative, scope);
371
465
  }
@@ -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";
@@ -114,9 +114,12 @@ export const check = async (options: CheckOptions): Promise<CheckResult> => {
114
114
  });
115
115
  };
116
116
  const count = options.workers ?? 1;
117
+ // TLC's workers write the -dump state graph in whichever order they find it, so one worker
118
+ // writes the graph a single TLC worker does.
117
119
  const isSequential =
118
120
  count < 2 ||
119
121
  typeof SharedArrayBuffer !== "function" ||
122
+ options.dump !== undefined ||
120
123
  config.view !== undefined ||
121
124
  config.postconditions.length > 0 ||
122
125
  config.possible.length > 0;
@@ -147,7 +150,7 @@ export const check = async (options: CheckOptions): Promise<CheckResult> => {
147
150
  });
148
151
  const environment = specification.environment;
149
152
  const search = createSearch(config, environment, () =>
150
- getTlcVariableOrder(options.source, loadModule),
153
+ getTlcDeclarationOrder(options.source, loadModule, "variable"),
151
154
  );
152
155
  if (findAssumptionViolation(specification.assumptions, environment)) return fallBack();
153
156
  if (