tla-ts 0.0.3-dev.eba78ea → 0.0.3-dev.f6f300a

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,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,43 @@ 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
+ const isWritten = (check: Check, node: number) => check.offsets[node] !== -1;
104
+
105
+ const getPending = (check: Check, node: number) => (check.pending[node] ??= []);
106
+
107
+ const getSuccessors = (check: Check, node: number) => {
108
+ const offset = check.edgeOffsets[node];
109
+ return check.edges.ids.subarray(offset + 1, offset + 1 + check.edges.ids[offset]);
110
+ };
111
+
112
+ const getStateResult = (check: Check, node: number, position: number) =>
113
+ check.results.bytes[check.offsets[node] + position] === 1;
114
+
98
115
  const SUCCESSOR_CAPACITY = 16;
99
116
 
100
117
  const SCC_MARKER = -42;
@@ -121,26 +138,29 @@ export const createLivenessChecker = (
121
138
  fairness.length === 0 ? violation : createJunction("And", [...fairness, violation]);
122
139
  const solutions = getSolutions(formula);
123
140
  if (solutions.length === 0) {
124
- throw new TlaEvaluationError("Temporal formula is a tautology (its negation is unsatisfiable)");
141
+ throw setExitCode(
142
+ new TlaEvaluationError(TAUTOLOGY_MESSAGE),
143
+ EXIT_STATUS.livenessEvaluationFailure,
144
+ );
125
145
  }
126
146
  const actionIds = new Map<string, number>();
127
147
  const checks = solutions.map((solution): Check => ({
128
148
  solution,
129
149
  actionIds: Int32Array.from(solution.actionChecks, (predicate) => {
130
- const key = getLiveKey(predicate);
150
+ const key = getTermKey(predicate);
131
151
  const id = actionIds.get(key) ?? actionIds.size;
132
152
  actionIds.set(key, id);
133
153
  return id;
134
154
  }),
135
155
  nodeStates: [],
136
156
  nodeTableaux: [],
137
- successors: [],
138
- actions: [],
139
- stateResults: [],
140
- isWritten: [],
157
+ pending: [],
158
+ offsets: [],
159
+ results: { bytes: new Uint8Array(1024), length: 0 },
160
+ edgeOffsets: [],
161
+ edges: { ids: new Int32Array(1024), length: 0 },
141
162
  initial: [],
142
- nodeIds: new Map(),
143
- nodesByState: new Map(),
163
+ nodeIds: { slots: new Int32Array(3 << 10), size: 0, shift: 22 },
144
164
  isDone: [],
145
165
  errorNode: undefined,
146
166
  }));
@@ -226,18 +246,35 @@ export const createLivenessChecker = (
226
246
  model.infinitelyOftenActions.length === 0,
227
247
  );
228
248
 
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;
249
+ const getNodeId = (check: Check, state: number, tableauNode: number) => {
250
+ if (!check.solution.tableau) return state;
251
+ const slots = check.nodeIds.slots;
252
+ const slot = getNodeSlot(check.nodeIds, state, tableauNode);
253
+ return slots[slot] === 0 ? undefined : slots[slot + 2];
254
+ };
233
255
  const recordNode = (check: Check, state: number, tableauNode: number) => {
234
256
  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]);
257
+ const table = check.nodeIds;
258
+ if (++table.size * 2 > table.slots.length / 3) {
259
+ const old = table.slots;
260
+ table.slots = new Int32Array(old.length * 2);
261
+ table.shift--;
262
+ for (let slot = 0; slot < old.length; slot += 3) {
263
+ if (old[slot] !== 0)
264
+ table.slots.set(
265
+ old.subarray(slot, slot + 3),
266
+ getNodeSlot(table, old[slot] - 1, old[slot + 1]),
267
+ );
268
+ }
269
+ }
270
+ table.slots.set([state + 1, tableauNode, node], getNodeSlot(table, state, tableauNode));
239
271
  return node;
240
272
  };
273
+ // A state's nodes in the order they were recorded, which is the order of their ids.
274
+ const getStateNodes = (check: Check, tableau: Tableau, state: number) =>
275
+ tableau.nodes
276
+ .flatMap((_, tableauNode) => getNodeId(check, state, tableauNode) ?? [])
277
+ .sort((left, right) => left - right);
241
278
  const writeNode = (
242
279
  check: Check,
243
280
  node: number,
@@ -245,11 +282,32 @@ export const createLivenessChecker = (
245
282
  stateResults: Uint8Array,
246
283
  ) => {
247
284
  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;
285
+ const results = check.results;
286
+ const offset = results.length;
287
+ results.length += stateResults.length + actions.length * actionCount;
288
+ if (results.length > results.bytes.length) {
289
+ const grown = new Uint8Array(Math.max(2 * results.bytes.length, results.length));
290
+ grown.set(results.bytes);
291
+ results.bytes = grown;
292
+ }
293
+ results.bytes.set(stateResults, offset);
294
+ actions.forEach((edge, position) =>
295
+ results.bytes.set(edge, offset + stateResults.length + position * actionCount),
296
+ );
297
+ check.offsets[node] = offset;
298
+ const successors = check.pending[node] ?? [];
299
+ const edges = check.edges;
300
+ const edgeOffset = edges.length;
301
+ edges.length += successors.length + 1;
302
+ if (edges.length > edges.ids.length) {
303
+ const grown = new Int32Array(Math.max(2 * edges.ids.length, edges.length));
304
+ grown.set(edges.ids);
305
+ edges.ids = grown;
306
+ }
307
+ edges.ids[edgeOffset] = successors.length;
308
+ edges.ids.set(successors, edgeOffset + 1);
309
+ check.edgeOffsets[node] = edgeOffset;
310
+ check.pending[node] = undefined;
253
311
  };
254
312
 
255
313
  // TLC collects a state's successors and the state itself in a SetOfStates, a hash set it
@@ -302,7 +360,7 @@ export const createLivenessChecker = (
302
360
  const stateResults = checkState(check, index, state);
303
361
  const tableauNode = tableau.nodes[check.nodeTableaux[node]];
304
362
  const actions: Uint8Array[] = [];
305
- const successors = check.successors[node];
363
+ const successors = getPending(check, node);
306
364
  const selfActions =
307
365
  tableauNode.successors.length > 0
308
366
  ? checkAction(check, index, state, state)
@@ -351,8 +409,8 @@ export const createLivenessChecker = (
351
409
  );
352
410
  check.isDone[index] = true;
353
411
  // 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];
412
+ for (const node of getStateNodes(check, tableau, index)) {
413
+ const successors = getPending(check, node);
356
414
  const actions: Uint8Array[] = [];
357
415
  set.forEach((successor, position) => {
358
416
  const isDone = check.isDone[successor.index] === true;
@@ -386,10 +444,10 @@ export const createLivenessChecker = (
386
444
  index: number,
387
445
  ) => {
388
446
  while (check.nodeStates.length <= index) pushNode(check, check.nodeStates.length, -1);
389
- const successors = check.successors[index];
447
+ const successors = getPending(check, index);
390
448
  const actions: Uint8Array[] = [];
391
449
  set.forEach((successor, position) => {
392
- if (check.isWritten[successor.index] && successors.includes(successor.index)) return;
450
+ if (isWritten(check, successor.index) && successors.includes(successor.index)) return;
393
451
  successors.push(successor.index);
394
452
  actions.push(actionResults[position]);
395
453
  });
@@ -403,20 +461,20 @@ export const createLivenessChecker = (
403
461
  const parents = new Map<number, number>();
404
462
  const queue: number[] = [];
405
463
  for (const node of check.initial) {
406
- if (!check.isWritten[node]) continue;
464
+ if (!isWritten(check, node)) continue;
407
465
  queue.push(node);
408
466
  parents.set(node, -1);
409
467
  }
410
468
  for (let position = 0; position < queue.length; position++) {
411
469
  const current = queue[position];
412
- for (const next of check.successors[current]) {
470
+ for (const next of getSuccessors(check, current)) {
413
471
  if (next === current && check.solution.tableau) continue;
414
472
  if (next === target) {
415
473
  const path = [target];
416
474
  for (let node = current; node !== -1; node = parents.get(node) ?? -1) path.push(node);
417
475
  return path;
418
476
  }
419
- if (!check.isWritten[next] || parents.has(next)) continue;
477
+ if (!isWritten(check, next) || parents.has(next)) continue;
420
478
  parents.set(next, current);
421
479
  queue.push(next);
422
480
  }
@@ -428,16 +486,17 @@ export const createLivenessChecker = (
428
486
  const findInModel = (check: Check, model: Solution["models"][number]): Lasso | undefined => {
429
487
  const solution = check.solution;
430
488
  const actionCount = solution.actionChecks.length;
489
+ const stateCount = solution.stateChecks.length;
431
490
  const getAction = (node: number, edge: number, position: number) =>
432
- check.actions[node][edge * actionCount + position] === 1;
491
+ check.results.bytes[check.offsets[node] + stateCount + edge * actionCount + position] === 1;
433
492
  const isAllowed = (node: number, edge: number) =>
434
493
  model.eventuallyAlways.every((position) => getAction(node, edge, position));
435
494
  const links = new Float64Array(check.nodeStates.length).fill(UNVISITED);
436
- const queue = check.initial.filter((node) => check.isWritten[node]);
495
+ const queue = check.initial.filter((node) => isWritten(check, node));
437
496
  const components: number[] = [];
438
497
 
439
498
  const isStuttering = (node: number) => {
440
- const edge = check.successors[node].indexOf(node);
499
+ const edge = getSuccessors(check, node).indexOf(node);
441
500
  return edge !== -1 && isAllowed(node, edge);
442
501
  };
443
502
  const isFulfilled = (node: number, promise: Solution["promises"][number]) =>
@@ -461,11 +520,11 @@ export const createLivenessChecker = (
461
520
  if (member === root) break;
462
521
  }
463
522
  const isStateSatisfied = model.infinitelyOftenStates.every((position) =>
464
- [...members].some((node) => check.stateResults[node][position] === 1),
523
+ [...members].some((node) => getStateResult(check, node, position)),
465
524
  );
466
525
  const isActionSatisfied = model.infinitelyOftenActions.every((position) =>
467
526
  [...members].some((node) =>
468
- check.successors[node].some(
527
+ getSuccessors(check, node).some(
469
528
  (next, edge) =>
470
529
  members.has(next) && isAllowed(node, edge) && getAction(node, edge, position),
471
530
  ),
@@ -506,7 +565,7 @@ export const createLivenessChecker = (
506
565
  const countAtStart = remaining.count;
507
566
  while (true) {
508
567
  model.infinitelyOftenStates.forEach((position, slot) => {
509
- if (!stateDone[slot] && check.stateResults[current.node][position] === 1) {
568
+ if (!stateDone[slot] && getStateResult(check, current.node, position)) {
510
569
  stateDone[slot] = true;
511
570
  remaining.count--;
512
571
  }
@@ -520,7 +579,7 @@ export const createLivenessChecker = (
520
579
  if (remaining.count <= 0) break;
521
580
  const step = { last: -1, unvisited: -1 };
522
581
  const countBeforeActions = remaining.count;
523
- const successors = check.successors[current.node];
582
+ const successors = getSuccessors(check, current.node);
524
583
  const taken = successors.some((next, edge) => {
525
584
  if (membersByState.has(check.nodeStates[next])) {
526
585
  if (!isMember(next) || !isAllowed(current.node, edge)) return false;
@@ -555,7 +614,8 @@ export const createLivenessChecker = (
555
614
  }
556
615
  current.node = previous;
557
616
  step.unvisited =
558
- check.successors[previous].find((next) => isMember(next) && !seen.has(next)) ?? -1;
617
+ getSuccessors(check, previous).find((next) => isMember(next) && !seen.has(next)) ??
618
+ -1;
559
619
  }
560
620
  take(step.unvisited);
561
621
  seen.add(step.unvisited);
@@ -585,7 +645,7 @@ export const createLivenessChecker = (
585
645
  const queue: [number, number][] = [];
586
646
  for (let state = start, parent = -1, position = 0; ; position++) {
587
647
  for (const node of membersByState.get(state) ?? []) {
588
- for (const [edge, next] of check.successors[node].entries()) {
648
+ for (const [edge, next] of getSuccessors(check, node).entries()) {
589
649
  if (next === node || !isAllowedEdge(node, edge)) continue;
590
650
  if (next === root) {
591
651
  const path: number[] = [];
@@ -638,8 +698,8 @@ export const createLivenessChecker = (
638
698
  stack.push(lowLink, node, SCC_MARKER);
639
699
  components.push(node);
640
700
  const nextLowLink = { value: counter.link++ };
641
- check.successors[node].forEach((next, edge) => {
642
- if (!check.isWritten[next]) return;
701
+ getSuccessors(check, node).forEach((next, edge) => {
702
+ if (!isWritten(check, next)) return;
643
703
  if (!isAllowed(node, edge)) {
644
704
  if (links[next] === UNVISITED) queue.push(next);
645
705
  return;
package/src/liveness.ts CHANGED
@@ -1,7 +1,9 @@
1
1
  import { isLocallyResolved, type Definition, type Expression } from "./ast";
2
- import { TlaConfigError, TlaEvaluationError } from "./errors";
2
+ import { STACK_OVERFLOW, TlaEvaluationError } from "./errors";
3
+ import { EXIT_STATUS, setExitCode } from "./exit-codes";
3
4
  import {
4
5
  describeLocation,
6
+ describeRange,
5
7
  bindDefinitions,
6
8
  bindOperatorArguments,
7
9
  evaluate,
@@ -36,6 +38,10 @@ export interface ScopedExpression {
36
38
  scope: Scope | undefined;
37
39
  }
38
40
 
41
+ export interface NamedExpression extends ScopedExpression {
42
+ name: string;
43
+ }
44
+
39
45
  export interface TemporalProperty extends ScopedExpression {
40
46
  name: string;
41
47
  }
@@ -144,21 +150,27 @@ const getDefinitionLevel = (definition: Definition, environment: Environment) =>
144
150
  return level;
145
151
  };
146
152
 
153
+ export const TAUTOLOGY_MESSAGE = "Temporal formula is a tautology (its negation is unsatisfiable).";
154
+
155
+ // TLC names each part of a property after the operator it expands, or after the location of the
156
+ // conjunct or quantifier body it splits off.
147
157
  export const expandTemporal = (
148
158
  expression: Expression,
149
159
  scope: Scope | undefined,
150
160
  environment: Environment,
151
- isUnrollingForall: boolean,
161
+ isProperty: boolean,
162
+ name = "",
152
163
  expanding = new Set<Definition>(),
153
- ): ScopedExpression[] => {
164
+ ): NamedExpression[] => {
154
165
  const expand = (
155
166
  child: Expression,
156
167
  childScope: Scope | undefined,
168
+ childName = name,
157
169
  childExpanding = expanding,
158
- ): ScopedExpression[] =>
159
- expandTemporal(child, childScope, environment, isUnrollingForall, childExpanding);
170
+ ): NamedExpression[] =>
171
+ expandTemporal(child, childScope, environment, isProperty, childName, childExpanding);
160
172
  if (expression.kind === "And") {
161
- return expression.operands.flatMap((operand) => expand(operand, scope));
173
+ return expression.operands.flatMap((operand) => expand(operand, scope, describeRange(operand)));
162
174
  }
163
175
  if (expression.kind === "Label") return expand(expression.body, scope);
164
176
  if (expression.kind === "Let") {
@@ -179,35 +191,60 @@ export const expandTemporal = (
179
191
  getDefinitionLevel(definition, environment) > 0
180
192
  ) {
181
193
  if (expanding.has(definition)) {
182
- throw new TlaConfigError(`The definition of ${expression.name} refers to itself`);
194
+ throw setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error);
183
195
  }
184
- return expand(definition.body, undefined, new Set([...expanding, definition]));
196
+ return expand(
197
+ definition.body,
198
+ undefined,
199
+ expression.name,
200
+ new Set([...expanding, definition]),
201
+ );
185
202
  }
186
203
  }
187
204
  const context = getConstantContext(environment, scope);
188
- if (expression.kind === "Apply" && getLevel(expression, scope, environment) === TEMPORAL_LEVEL) {
205
+ // A property expands every operator it applies and unrolls every \A over constant sets, but a
206
+ // specification only expands the temporal ones.
207
+ const isExpanded = (child: Expression) =>
208
+ isProperty || getLevel(child, scope, environment) === TEMPORAL_LEVEL;
209
+ if (expression.kind === "Apply" && isExpanded(expression)) {
189
210
  const operator = resolveApplyOperator(expression, context);
190
211
  const definition = isLocallyResolved(expression)
191
212
  ? undefined
192
213
  : getDefinition(expression.operator, environment);
193
- if (operator?.kind === "Closure" && !definition?.isRecursive) {
194
- return expand(operator.body, bindOperatorArguments(operator, expression.args, context));
214
+ const isExpandable =
215
+ operator?.kind === "Closure" &&
216
+ operator.params.length === expression.args.length &&
217
+ !definition?.isRecursive;
218
+ if (isExpandable) {
219
+ return expand(
220
+ operator.body,
221
+ bindOperatorArguments(operator, expression.args, context),
222
+ expression.operator,
223
+ );
195
224
  }
196
225
  }
197
226
  const isUnrolled =
198
- isUnrollingForall &&
227
+ isProperty &&
199
228
  expression.kind === "Forall" &&
200
- getLevel(expression.body, scope, environment) === TEMPORAL_LEVEL &&
201
229
  expression.bounds.every((bound) => getLevel(bound.set, scope, environment) === 0);
202
230
  if (isUnrolled) {
203
- const expanded: ScopedExpression[] = [];
231
+ const expanded: NamedExpression[] = [];
232
+ const bindings = { count: 0 };
204
233
  forEachBinding(expression.bounds, context, (boundScope) => {
205
- expanded.push(...expand(expression.body, boundScope));
234
+ bindings.count++;
235
+ expanded.push(...expand(expression.body, boundScope, describeRange(expression.body)));
206
236
  return false;
207
237
  });
238
+ // TLC rejects a property that quantifies over no elements before it checks anything.
239
+ if (bindings.count === 0) {
240
+ throw setExitCode(
241
+ new TlaEvaluationError(TAUTOLOGY_MESSAGE),
242
+ EXIT_STATUS.livenessEvaluationFailure,
243
+ );
244
+ }
208
245
  return expanded;
209
246
  }
210
- return [{ expression, scope }];
247
+ return [{ expression, scope, name }];
211
248
  };
212
249
 
213
250
  const bindLetDefinitions = (
@@ -262,9 +299,7 @@ export const toLiveExpression = (
262
299
  scope: Scope | undefined,
263
300
  ) => {
264
301
  if (expansion.depth >= MAXIMUM_EXPANSION_DEPTH) {
265
- throw new TlaEvaluationError(
266
- `TLC overflowed the stack while expanding the temporal formula at ${describeLocation(expression)}`,
267
- );
302
+ throw setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error);
268
303
  }
269
304
  expansion.depth++;
270
305
  const result = convert(body, bodyScope);
@@ -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,8 +89,7 @@ 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
+ const holds = (expression: Expression, context: Context, value = evaluate(expression, context)) => {
92
93
  if (typeof value === "boolean") return value;
93
94
  try {
94
95
  return expectBoolean(value, `the action at ${describeLocation(expression)}`);
@@ -320,6 +321,7 @@ const compileConjunction = (
320
321
  isInit: boolean,
321
322
  ): Runner => {
322
323
  const conjuncts = operands.map((operand) => toConjunct(operand, environment, isInit));
324
+ const evaluators: (Evaluator | undefined)[] = conjuncts.map(() => undefined);
323
325
  const runFrom = (
324
326
  start: number,
325
327
  run: Run,
@@ -342,12 +344,17 @@ const compileConjunction = (
342
344
  const conjunct = conjuncts[index];
343
345
  if (conjunct.kind === "Guard") {
344
346
  context ??= getContext(run, scope, current);
345
- if (!holds(conjunct.expression, context)) return;
347
+ const evaluator = (evaluators[index] ??= getEntryEvaluator(
348
+ conjunct.expression,
349
+ environment,
350
+ ));
351
+ if (!holds(conjunct.expression, context, evaluator(context))) return;
346
352
  continue;
347
353
  }
348
354
  if (conjunct.kind === "Assign") {
349
355
  context ??= getContext(run, scope, current);
350
- const value = evaluate(conjunct.value, context);
356
+ const evaluator = (evaluators[index] ??= getEntryEvaluator(conjunct.value, environment));
357
+ const value = evaluator(context);
351
358
  const assigned = current[conjunct.index];
352
359
  if (assigned === undefined) {
353
360
  current = assign(current, conjunct.index, value);
@@ -412,7 +419,7 @@ const compileMembership = (
412
419
  expression.operator === "\\subseteq" ? { kind: "Subset", base: evaluated } : evaluated;
413
420
  if (!isEnumerable(value)) {
414
421
  throw new TlaEvaluationError(
415
- `In computing next states, the right side of \\in is not enumerable: ${formatValue(value)} at ${describeLocation(expression)}`,
422
+ `In computing ${run.isInit ? "initial" : "next"} states, the right side of \\IN is not enumerable.\n${describeRange(expression)}`,
416
423
  );
417
424
  }
418
425
  const elements = getStreamedElements(value);
@@ -859,7 +866,7 @@ const compileAction = (
859
866
  const body = arm?.body ?? other;
860
867
  if (!body)
861
868
  throw new TlaEvaluationError(
862
- `${UNEXPECTED_EXCEPTION}In computing next states, TLC encountered a CASE with no conditions true.\n${describeRange(expression)}`,
869
+ `In computing ${run.isInit ? "initial" : "next"} states, TLC encountered a CASE with no conditions true.\n${describeRange(expression)}`,
863
870
  );
864
871
  body(run, scope, partial, action, isFixed, onComplete);
865
872
  };
@@ -1050,7 +1057,7 @@ export const forEachSuccessor = (
1050
1057
  (partial, action) => {
1051
1058
  if (run.isStopped) return;
1052
1059
  if (!isComplete(partial)) {
1053
- throw new TlaEvaluationError(
1060
+ throw new TlaIncompleteStateError(
1054
1061
  `Successor state is not completely specified by action ${action ?? "Next"}. The following variables are not assigned: ${getMissingVariables(partial, environment).join(", ")}`,
1055
1062
  );
1056
1063
  }