tla-ts 0.0.3 → 0.0.4-dev.0be9567

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 (86) hide show
  1. package/README.md +32 -12
  2. package/dist/cli.cjs +1 -1
  3. package/dist/cli.js +1 -1
  4. package/dist/index.cjs +1 -1
  5. package/dist/index.d.cts +162 -8
  6. package/dist/index.d.ts +162 -8
  7. package/dist/index.js +1 -1
  8. package/dist/parallel-worker.cjs +2 -2
  9. package/dist/parallel-worker.js +2 -2
  10. package/dist/parallel.cjs +1 -1
  11. package/dist/parallel.js +2 -2
  12. package/dist/run-cli.cjs +45 -18
  13. package/dist/run-cli.js +45 -18
  14. package/dist/transfer.cjs +1393 -18
  15. package/dist/transfer.js +1393 -18
  16. package/package.json +5 -1
  17. package/src/ast.ts +147 -6
  18. package/src/bags.ts +4 -7
  19. package/src/builtins.ts +29 -11
  20. package/src/bundled-modules.ts +3 -3
  21. package/src/canonical.ts +4 -3
  22. package/src/check.ts +1539 -235
  23. package/src/cli-options.ts +11 -5
  24. package/src/cli.ts +8 -1
  25. package/src/codegen.ts +98 -39
  26. package/src/config.ts +254 -181
  27. package/src/dependencies.ts +2 -2
  28. package/src/environment.ts +540 -140
  29. package/src/errors.ts +224 -3
  30. package/src/evaluate.ts +994 -279
  31. package/src/exit-codes.ts +22 -43
  32. package/src/fingerprints.ts +46 -11
  33. package/src/index.ts +1 -0
  34. package/src/instances.ts +19 -16
  35. package/src/java-overrides.ts +104 -25
  36. package/src/levels.ts +191 -45
  37. package/src/lexer.ts +127 -30
  38. package/src/live-check.ts +867 -0
  39. package/src/liveness.ts +218 -572
  40. package/src/obligation-expression.ts +2 -2
  41. package/src/obligation-source.ts +2 -0
  42. package/src/parallel-worker.ts +174 -213
  43. package/src/parallel.ts +131 -39
  44. package/src/parser.ts +456 -147
  45. package/src/pcal-ast.ts +770 -0
  46. package/src/pcal-parse.ts +1523 -0
  47. package/src/pcal-tokenize.ts +516 -0
  48. package/src/pcal-translate.ts +1230 -0
  49. package/src/pcal-validate.ts +454 -0
  50. package/src/randomization.ts +24 -7
  51. package/src/resolve.ts +1481 -426
  52. package/src/run-cli.ts +1212 -143
  53. package/src/runtime.ts +19 -1
  54. package/src/sany-builtins.ts +147 -0
  55. package/src/sany-generator.ts +3128 -0
  56. package/src/sany-levels.ts +1208 -0
  57. package/src/sany-lexer.ts +545 -0
  58. package/src/sany-linter.ts +122 -0
  59. package/src/sany-modules.ts +1398 -0
  60. package/src/sany-nodes.ts +463 -0
  61. package/src/sany-parse-error.ts +2161 -0
  62. package/src/sany-report.ts +356 -0
  63. package/src/sany-selectors.ts +738 -0
  64. package/src/sany-source.ts +248 -0
  65. package/src/sany-xml.ts +1017 -0
  66. package/src/spec-description.ts +42 -11
  67. package/src/standard-modules.ts +203 -148
  68. package/src/standard-ranges.ts +116 -0
  69. package/src/state-graph.ts +180 -0
  70. package/src/subexpressions.ts +231 -171
  71. package/src/substitution-levels.ts +38 -17
  72. package/src/successors.ts +220 -108
  73. package/src/symmetry.ts +194 -54
  74. package/src/tableau.ts +54 -25
  75. package/src/tlc-ext.ts +42 -29
  76. package/src/tlc-messages.ts +329 -0
  77. package/src/tlc-module.ts +52 -43
  78. package/src/tlc-modules.ts +4 -0
  79. package/src/tlc-order.ts +78 -10
  80. package/src/tlc-random.ts +37 -9
  81. package/src/tlc-replay.ts +655 -0
  82. package/src/tlc-summary.ts +20 -5
  83. package/src/tlc-version.ts +18 -0
  84. package/src/transfer.ts +15 -3
  85. package/src/value-sources.ts +29 -0
  86. package/src/values.ts +743 -189
@@ -0,0 +1,867 @@
1
+ import { TlaEvaluationError } from "./errors";
2
+ import { hasRepeatedEffects, type Environment } from "./evaluate";
3
+ import {
4
+ createTautologyError,
5
+ evaluateLive,
6
+ evaluateOnLasso,
7
+ toLiveExpression,
8
+ type ScopedExpression,
9
+ type TemporalProperty,
10
+ } from "./liveness";
11
+ import {
12
+ createJunction,
13
+ createUnary,
14
+ getSolutions,
15
+ getTermKey,
16
+ isFulfilling,
17
+ type LiveExpression,
18
+ type Solution,
19
+ type Tableau,
20
+ } from "./tableau";
21
+ import { isSameValue, type Value } from "./values";
22
+
23
+ export interface LiveSuccessor {
24
+ index: number;
25
+ state: Value[];
26
+ }
27
+
28
+ export interface Lasso {
29
+ prefix: number[];
30
+ cycle: number[];
31
+ // Whether the solution that the lasso violates constrains the cycle, as a liveness property does.
32
+ // TLC warns that a stuttering counterexample to one may come from a missing fairness constraint.
33
+ isCycleConstrained: boolean;
34
+ }
35
+
36
+ export interface LivenessChecker {
37
+ // How many solutions of the negated properties TLC checks, which it calls branches.
38
+ branches: number;
39
+ // With a tracing environment, the checks record their call stack as TLC's replay of a failed
40
+ // check does.
41
+ addInitialState: (index: number, state: Value[], tracing?: Environment) => void;
42
+ addState: (
43
+ index: number,
44
+ state: Value[],
45
+ successors: LiveSuccessor[],
46
+ tracing?: Environment,
47
+ ) => number[] | undefined;
48
+ findViolation: () => Lasso | undefined;
49
+ getViolatedProperties: (path: Value[][], cycleStart: number) => string[];
50
+ }
51
+
52
+ export interface LiveGraph {
53
+ getFingerprint: (successor: LiveSuccessor) => number;
54
+ getSuccessors: (index: number, state: Value[]) => LiveSuccessor[];
55
+ }
56
+
57
+ // Numbers in a typed array that doubles as it fills, so a graph of millions of nodes takes a few
58
+ // bytes for each.
59
+ interface Pool<Data extends Int32Array | Uint8Array> {
60
+ data: Data;
61
+ length: number;
62
+ create: (length: number) => Data;
63
+ }
64
+
65
+ // TLC's behavior graph for one solution: a node per state, or per state and tableau node.
66
+ interface Check {
67
+ solution: Solution;
68
+ // One id per distinct action check across the solutions.
69
+ actionIds: Int32Array;
70
+ nodeStates: number[];
71
+ nodeTableaux: number[];
72
+ // Where a node's edges start in edgeTargets, or UNWRITTEN until TLC writes the node with its
73
+ // successors, and how many it has.
74
+ edgeStarts: number[];
75
+ edgeCounts: number[];
76
+ edgeTargets: Pool<Int32Array>;
77
+ // The results of the action checks on each edge, and of the state checks on each state, which
78
+ // are the same for every node of the state.
79
+ edgeActions: Pool<Uint8Array>;
80
+ stateResults: Pool<Uint8Array>;
81
+ initial: number[];
82
+ // The nodes of each state in the order the check records them, a list through nextSiblings.
83
+ firstNodes: Pool<Int32Array>;
84
+ lastNodes: Pool<Int32Array>;
85
+ nextSiblings: number[];
86
+ nodeIds: NodeTable;
87
+ isDone: boolean[];
88
+ errorNode: number | undefined;
89
+ }
90
+
91
+ const containsAlways = (expression: LiveExpression): boolean => {
92
+ switch (expression.kind) {
93
+ case "Always":
94
+ return true;
95
+ case "Eventually":
96
+ case "Not":
97
+ case "Next":
98
+ return containsAlways(expression.body);
99
+ case "And":
100
+ case "Or":
101
+ return expression.operands.some(containsAlways);
102
+ default:
103
+ return false;
104
+ }
105
+ };
106
+
107
+ // TLC's OrderOfSolution#hasEmptyPEMAndBoxFreePromises, negated.
108
+ const isCycleConstrained = (solution: Solution) =>
109
+ solution.promises.some((promise) => containsAlways(promise.body)) ||
110
+ solution.models.some(
111
+ (model) =>
112
+ model.eventuallyAlways.length > 0 ||
113
+ model.infinitelyOftenStates.length > 0 ||
114
+ model.infinitelyOftenActions.length > 0,
115
+ );
116
+
117
+ const isSameState = (left: Value[], right: Value[]) =>
118
+ left.every((value, position) => isSameValue(value, right[position]));
119
+
120
+ const removeRepeats = (path: number[]) =>
121
+ path.filter((node, position) => position === 0 || path[position - 1] !== node);
122
+
123
+ const createPool = <Data extends Int32Array | Uint8Array>(
124
+ create: (length: number) => Data,
125
+ ): Pool<Data> => ({ data: create(1024), length: 0, create });
126
+
127
+ const writeToPool = <Data extends Int32Array | Uint8Array>(
128
+ pool: Pool<Data>,
129
+ offset: number,
130
+ values: ArrayLike<number>,
131
+ ) => {
132
+ const end = offset + values.length;
133
+ if (end > pool.data.length) {
134
+ const data = pool.create(Math.max(2 * pool.data.length, end));
135
+ data.set(pool.data);
136
+ pool.data = data;
137
+ }
138
+ pool.data.set(values, offset);
139
+ pool.length = Math.max(pool.length, end);
140
+ };
141
+
142
+ const NO_NODE = -1;
143
+
144
+ // A Map holds at most 2^24 entries, so each tableau node of a state finds its node in an
145
+ // open-addressing table of (state plus one, tableau node, node) triples.
146
+ interface NodeTable {
147
+ slots: Int32Array;
148
+ size: number;
149
+ shift: number;
150
+ }
151
+
152
+ const getNodeSlot = (table: NodeTable, state: number, tableauNode: number) => {
153
+ const mask = table.slots.length / 3 - 1;
154
+ const hash = Math.imul(Math.imul(state, 0x9e3779b1) ^ tableauNode, 0x85ebca6b) >>> table.shift;
155
+ for (let index = hash; ; index = (index + 1) & mask) {
156
+ const slot = index * 3;
157
+ const stored = table.slots[slot];
158
+ if (stored === 0 || (stored === state + 1 && table.slots[slot + 1] === tableauNode)) {
159
+ return slot;
160
+ }
161
+ }
162
+ };
163
+
164
+ const createNodes = (length: number) => new Int32Array(length).fill(NO_NODE);
165
+
166
+ const UNWRITTEN = -1;
167
+
168
+ const isWritten = (check: Check, node: number) =>
169
+ (check.edgeStarts[node] ?? UNWRITTEN) !== UNWRITTEN;
170
+
171
+ const getSuccessors = (check: Check, node: number) => {
172
+ const start = check.edgeStarts[node];
173
+ return check.edgeTargets.data.subarray(start, start + check.edgeCounts[node]);
174
+ };
175
+
176
+ const getStateResult = (check: Check, node: number, position: number) =>
177
+ check.stateResults.data[check.nodeStates[node] * check.solution.stateChecks.length + position] ===
178
+ 1;
179
+
180
+ // A node owns one entry in each of its check's per-node arrays.
181
+ const pushNode = (check: Check, state: number, tableauNode: number) => {
182
+ check.nodeStates.push(state);
183
+ check.nodeTableaux.push(tableauNode);
184
+ check.edgeStarts.push(UNWRITTEN);
185
+ check.edgeCounts.push(0);
186
+ check.nextSiblings.push(NO_NODE);
187
+ return check.nodeStates.length - 1;
188
+ };
189
+
190
+ // The nodes of the state, in the order the check recorded them.
191
+ const getStateNodes = (check: Check, state: number) => {
192
+ const nodes: number[] = [];
193
+ for (
194
+ let node = check.firstNodes.data[state] ?? NO_NODE;
195
+ node !== NO_NODE;
196
+ node = check.nextSiblings[node]
197
+ ) {
198
+ nodes.push(node);
199
+ }
200
+ return nodes;
201
+ };
202
+
203
+ const SUCCESSOR_CAPACITY = 16;
204
+
205
+ const SCC_MARKER = -42;
206
+
207
+ const UNVISITED = -1;
208
+
209
+ const MAXIMUM_LINK = Number.MAX_SAFE_INTEGER;
210
+
211
+ export const createLivenessChecker = (
212
+ properties: TemporalProperty[],
213
+ temporals: ScopedExpression[],
214
+ environment: Environment,
215
+ graph: LiveGraph,
216
+ ): LivenessChecker | undefined => {
217
+ if (properties.length === 0) return undefined;
218
+ const fairness = temporals.map((item) =>
219
+ toLiveExpression(item.expression, item.scope, environment),
220
+ );
221
+ const negations = properties.map((property) =>
222
+ createUnary("Not", toLiveExpression(property.expression, property.scope, environment)),
223
+ );
224
+ const violation = negations.length === 1 ? negations[0] : createJunction("Or", negations);
225
+ const formula =
226
+ fairness.length === 0 ? violation : createJunction("And", [...fairness, violation]);
227
+ const solutions = getSolutions(formula);
228
+ if (solutions.length === 0) {
229
+ throw createTautologyError();
230
+ }
231
+ const actionIds = new Map<string, number>();
232
+ const checks = solutions.map((solution): Check => ({
233
+ solution,
234
+ actionIds: Int32Array.from(solution.actionChecks, (predicate) => {
235
+ const key = getTermKey(predicate);
236
+ const id = actionIds.get(key) ?? actionIds.size;
237
+ actionIds.set(key, id);
238
+ return id;
239
+ }),
240
+ nodeStates: [],
241
+ nodeTableaux: [],
242
+ edgeStarts: [],
243
+ edgeCounts: [],
244
+ edgeTargets: createPool((length) => new Int32Array(length)),
245
+ edgeActions: createPool((length) => new Uint8Array(length)),
246
+ stateResults: createPool((length) => new Uint8Array(length)),
247
+ initial: [],
248
+ firstNodes: createPool(createNodes),
249
+ lastNodes: createPool(createNodes),
250
+ nextSiblings: [],
251
+ nodeIds: { slots: new Int32Array(3 << 10), size: 0, shift: 22 },
252
+ isDone: [],
253
+ errorNode: undefined,
254
+ }));
255
+ const capacity = { multiplier: 1 };
256
+
257
+ // TLC evaluates every check on its own. Without side effects the order can't show, so the
258
+ // checks of one state share their results.
259
+ const isShared = !hasRepeatedEffects(environment);
260
+ const evaluation = { environment };
261
+ const shared = {
262
+ states: new Map<Value[], Map<LiveExpression, boolean>>(),
263
+ actions: new Map<Value[], Map<Value[], Int8Array>>(),
264
+ };
265
+ const getStateCache = (state: Value[]) => {
266
+ const cache = shared.states.get(state) ?? new Map<LiveExpression, boolean>();
267
+ shared.states.set(state, cache);
268
+ return cache;
269
+ };
270
+ // TLCGet("level") reads the level of the state whose successors the checks run on.
271
+ const evaluateFrom = <Result>(source: number | undefined, evaluate: () => Result) => {
272
+ environment.runtime.setLivenessSource(source);
273
+ const result = evaluate();
274
+ environment.runtime.setLivenessSource(undefined);
275
+ return result;
276
+ };
277
+ const evaluateState = (predicate: LiveExpression, state: Value[]) =>
278
+ evaluateLive(
279
+ predicate,
280
+ state,
281
+ undefined,
282
+ evaluation.environment,
283
+ isShared ? getStateCache(state) : new Map(),
284
+ );
285
+ const checkState = (check: Check, source: number, state: Value[]) =>
286
+ evaluateFrom(source, () =>
287
+ Uint8Array.from(check.solution.stateChecks, (predicate) =>
288
+ evaluateState(predicate, state) ? 1 : 0,
289
+ ),
290
+ );
291
+ const checkAction = (check: Check, source: number, state: Value[], successor: Value[]) =>
292
+ evaluateFrom(source, () => {
293
+ const predicates = check.solution.actionChecks;
294
+ if (!isShared) {
295
+ return Uint8Array.from(predicates, (predicate) =>
296
+ evaluateLive(predicate, state, successor, evaluation.environment, new Map()) ? 1 : 0,
297
+ );
298
+ }
299
+ const stateCache = getStateCache(state);
300
+ const results = shared.actions.get(state) ?? new Map<Value[], Int8Array>();
301
+ shared.actions.set(state, results);
302
+ const known = results.get(successor) ?? new Int8Array(actionIds.size).fill(-1);
303
+ results.set(successor, known);
304
+ return Uint8Array.from(check.actionIds, (id, position) => {
305
+ if (known[id] === -1) {
306
+ known[id] = evaluateLive(
307
+ predicates[position],
308
+ state,
309
+ successor,
310
+ evaluation.environment,
311
+ stateCache,
312
+ )
313
+ ? 1
314
+ : 0;
315
+ }
316
+ return known[id];
317
+ });
318
+ });
319
+ const isConsistent = (
320
+ tableau: Tableau,
321
+ node: number,
322
+ source: number | undefined,
323
+ state: Value[],
324
+ ) =>
325
+ evaluateFrom(source, () =>
326
+ tableau.nodes[node].statePredicates.every((predicate) => evaluateState(predicate, state)),
327
+ );
328
+ // TLC 1.7.4 doesn't stop at a tableau node that accepts every behavior, so it finds a violation
329
+ // of a property like a safety property only in its liveness checks.
330
+ const isAccepting = (tableau: Tableau, node: number) => {
331
+ if (environment.runtime.version === "1.7.4") return false;
332
+ const tableauNode = tableau.nodes[node];
333
+ return (
334
+ tableauNode.particle.length === 0 &&
335
+ tableauNode.successors.length === 1 &&
336
+ tableauNode.successors[0] === node
337
+ );
338
+ };
339
+ const hasEmptyModel = (check: Check) =>
340
+ check.solution.models.some(
341
+ (model) =>
342
+ model.eventuallyAlways.length === 0 &&
343
+ model.infinitelyOftenStates.length === 0 &&
344
+ model.infinitelyOftenActions.length === 0,
345
+ );
346
+
347
+ const getNodeId = (check: Check, state: number, tableauNode: number) => {
348
+ if (!check.solution.tableau) return state;
349
+ const slots = check.nodeIds.slots;
350
+ const slot = getNodeSlot(check.nodeIds, state, tableauNode);
351
+ return slots[slot] === 0 ? undefined : slots[slot + 2];
352
+ };
353
+ const recordNode = (check: Check, state: number, tableauNode: number) => {
354
+ const node = pushNode(check, state, tableauNode);
355
+ const table = check.nodeIds;
356
+ if (++table.size * 2 > table.slots.length / 3) {
357
+ const old = table.slots;
358
+ table.slots = new Int32Array(old.length * 2);
359
+ table.shift--;
360
+ for (let slot = 0; slot < old.length; slot += 3) {
361
+ if (old[slot] !== 0) {
362
+ table.slots.set(
363
+ old.subarray(slot, slot + 3),
364
+ getNodeSlot(table, old[slot] - 1, old[slot + 1]),
365
+ );
366
+ }
367
+ }
368
+ }
369
+ table.slots.set([state + 1, tableauNode, node], getNodeSlot(table, state, tableauNode));
370
+ const last = check.lastNodes.data[state] ?? NO_NODE;
371
+ if (last === NO_NODE) writeToPool(check.firstNodes, state, [node]);
372
+ else check.nextSiblings[last] = node;
373
+ writeToPool(check.lastNodes, state, [node]);
374
+ return node;
375
+ };
376
+ const writeNode = (
377
+ check: Check,
378
+ node: number,
379
+ targets: number[],
380
+ actions: Uint8Array[],
381
+ stateResults: Uint8Array,
382
+ ) => {
383
+ const start = check.edgeTargets.length;
384
+ const actionCount = check.solution.actionChecks.length;
385
+ writeToPool(check.edgeTargets, start, targets);
386
+ actions.forEach((results, position) =>
387
+ writeToPool(check.edgeActions, (start + position) * actionCount, results),
388
+ );
389
+ writeToPool(check.stateResults, check.nodeStates[node] * stateResults.length, stateResults);
390
+ check.edgeStarts[node] = start;
391
+ check.edgeCounts[node] = targets.length;
392
+ };
393
+
394
+ // TLC collects a state's successors and the state itself in a SetOfStates, a hash set it
395
+ // iterates in slot order. Its capacity starts at 16 times a factor that grows with every set
396
+ // that outgrows it.
397
+ const getSuccessorSet = (index: number, state: Value[], successors: LiveSuccessor[]) => {
398
+ const table = {
399
+ slots: Array.from<LiveSuccessor | undefined>({
400
+ length: SUCCESSOR_CAPACITY * capacity.multiplier,
401
+ }),
402
+ count: 0,
403
+ };
404
+ const insert = (slots: (LiveSuccessor | undefined)[], successor: LiveSuccessor) => {
405
+ for (
406
+ let slot = (graph.getFingerprint(successor) & 0x7fffffff) % slots.length;
407
+ ;
408
+ slot = (slot + 1) % slots.length
409
+ ) {
410
+ const entry = slots[slot];
411
+ if (entry === undefined) {
412
+ slots[slot] = successor;
413
+ return true;
414
+ }
415
+ if (entry.index === successor.index && isSameState(entry.state, successor.state))
416
+ return false;
417
+ }
418
+ };
419
+ const put = (successor: LiveSuccessor) => {
420
+ if (table.count >= table.slots.length >> 1) {
421
+ const old = table.slots;
422
+ table.slots = Array.from<LiveSuccessor | undefined>({ length: 2 * old.length + 1 });
423
+ for (const entry of old) if (entry) insert(table.slots, entry);
424
+ }
425
+ if (insert(table.slots, successor)) table.count++;
426
+ };
427
+ successors.forEach(put);
428
+ put({ index, state });
429
+ if (table.slots.length > SUCCESSOR_CAPACITY * capacity.multiplier) capacity.multiplier++;
430
+ return table.slots.filter((entry): entry is LiveSuccessor => entry !== undefined);
431
+ };
432
+
433
+ // TLC's TableauLiveChecker#addNextState for a node it finds after it expanded the node's state.
434
+ const expandLate = (
435
+ check: Check,
436
+ tableau: Tableau,
437
+ state: Value[],
438
+ index: number,
439
+ node: number,
440
+ ) => {
441
+ const stateResults = checkState(check, index, state);
442
+ const tableauNode = tableau.nodes[check.nodeTableaux[node]];
443
+ const actions: Uint8Array[] = [];
444
+ const successors: number[] = [];
445
+ const selfActions =
446
+ tableauNode.successors.length > 0
447
+ ? checkAction(check, index, state, state)
448
+ : new Uint8Array(0);
449
+ for (const next of tableauNode.successors) {
450
+ if (!isConsistent(tableau, next, index, state)) continue;
451
+ if (isAccepting(tableau, next) && check.errorNode === undefined && hasEmptyModel(check)) {
452
+ check.errorNode = node;
453
+ return;
454
+ }
455
+ const existing = getNodeId(check, index, next);
456
+ if (existing !== undefined && successors.includes(existing)) continue;
457
+ const target = existing ?? recordNode(check, index, next);
458
+ successors.push(target);
459
+ actions.push(selfActions);
460
+ if (existing === undefined) expandLate(check, tableau, state, index, target);
461
+ }
462
+ for (const successor of graph.getSuccessors(index, state)) {
463
+ const successorActions = checkAction(check, index, state, successor.state);
464
+ const isDone = check.isDone[successor.index] === true;
465
+ for (const next of tableauNode.successors) {
466
+ if (!isConsistent(tableau, next, index, successor.state)) continue;
467
+ // A successor the search never stored follows a violation or an error, after which nothing
468
+ // checks the graph. TLC records its node, which it never expands.
469
+ if (successor.index === -1) continue;
470
+ const existing = getNodeId(check, successor.index, next);
471
+ if (existing !== undefined && successors.includes(existing)) continue;
472
+ const target = existing ?? recordNode(check, successor.index, next);
473
+ successors.push(target);
474
+ actions.push(successorActions);
475
+ if (existing === undefined && isDone) {
476
+ expandLate(check, tableau, successor.state, successor.index, target);
477
+ }
478
+ }
479
+ }
480
+ if (successors.length > 0) writeNode(check, node, successors, actions, stateResults);
481
+ };
482
+
483
+ const addTableauState = (
484
+ check: Check,
485
+ tableau: Tableau,
486
+ set: LiveSuccessor[],
487
+ actionResults: Uint8Array[],
488
+ stateResults: Uint8Array,
489
+ index: number,
490
+ ) => {
491
+ const consistency = tableau.nodes.map((_, node) =>
492
+ set.map((successor) => isConsistent(tableau, node, index, successor.state)),
493
+ );
494
+ check.isDone[index] = true;
495
+ // TLC expands the nodes recorded before the loop, not the ones the loop records.
496
+ for (const node of getStateNodes(check, index)) {
497
+ const successors: number[] = [];
498
+ const actions: Uint8Array[] = [];
499
+ set.forEach((successor, position) => {
500
+ const isDone = check.isDone[successor.index] === true;
501
+ for (const next of tableau.nodes[check.nodeTableaux[node]].successors) {
502
+ if (!consistency[next][position]) continue;
503
+ const existing = getNodeId(check, successor.index, next);
504
+ if (existing !== undefined && successors.includes(existing)) continue;
505
+ const target = existing ?? recordNode(check, successor.index, next);
506
+ successors.push(target);
507
+ actions.push(actionResults[position]);
508
+ if (existing === undefined && isDone) {
509
+ expandLate(check, tableau, successor.state, successor.index, target);
510
+ }
511
+ }
512
+ });
513
+ writeNode(check, node, successors, actions, stateResults);
514
+ }
515
+ if (check.errorNode === undefined) return undefined;
516
+ return removeRepeats(
517
+ getPath(check, check.errorNode)
518
+ .reverse()
519
+ .map((node) => check.nodeStates[node]),
520
+ );
521
+ };
522
+
523
+ const addPlainState = (
524
+ check: Check,
525
+ set: LiveSuccessor[],
526
+ actionResults: Uint8Array[],
527
+ stateResults: Uint8Array,
528
+ index: number,
529
+ ) => {
530
+ while (check.nodeStates.length <= index) pushNode(check, check.nodeStates.length, -1);
531
+ const successors: number[] = [];
532
+ const actions: Uint8Array[] = [];
533
+ set.forEach((successor, position) => {
534
+ if (isWritten(check, successor.index) && successors.includes(successor.index)) return;
535
+ successors.push(successor.index);
536
+ actions.push(actionResults[position]);
537
+ });
538
+ writeNode(check, index, successors, actions, stateResults);
539
+ return undefined;
540
+ };
541
+
542
+ // The shortest path from an initial node to the node, last node first, as TLC's getPath finds it.
543
+ const getPath = (check: Check, target: number) => {
544
+ if (check.initial.includes(target)) return [target];
545
+ const parents = new Map<number, number>();
546
+ const queue: number[] = [];
547
+ for (const node of check.initial) {
548
+ if (!isWritten(check, node)) continue;
549
+ queue.push(node);
550
+ parents.set(node, -1);
551
+ }
552
+ for (let position = 0; position < queue.length; position++) {
553
+ const current = queue[position];
554
+ for (const next of getSuccessors(check, current)) {
555
+ if (next === current && check.solution.tableau) continue;
556
+ if (next === target) {
557
+ const path = [target];
558
+ for (let node = current; node !== -1; node = parents.get(node) ?? -1) path.push(node);
559
+ return path;
560
+ }
561
+ if (!isWritten(check, next) || parents.has(next)) continue;
562
+ parents.set(next, current);
563
+ queue.push(next);
564
+ }
565
+ }
566
+ throw new TlaEvaluationError(`Couldn't re-create liveness trace (path) starting at: ${target}`);
567
+ };
568
+
569
+ // TLC's LiveWorker#checkSccs, a Tarjan search that pushes every successor of a node at once.
570
+ const findInModel = (check: Check, model: Solution["models"][number]): Lasso | undefined => {
571
+ const solution = check.solution;
572
+ const actionCount = solution.actionChecks.length;
573
+ const getAction = (node: number, edge: number, position: number) =>
574
+ check.edgeActions.data[(check.edgeStarts[node] + edge) * actionCount + position] === 1;
575
+ const isAllowed = (node: number, edge: number) =>
576
+ model.eventuallyAlways.every((position) => getAction(node, edge, position));
577
+ const links = new Float64Array(check.nodeStates.length).fill(UNVISITED);
578
+ const queue = check.initial.filter((node) => isWritten(check, node));
579
+ const components: number[] = [];
580
+
581
+ const isStuttering = (node: number) => {
582
+ const edge = getSuccessors(check, node).indexOf(node);
583
+ return edge !== -1 && isAllowed(node, edge);
584
+ };
585
+ const isFulfilled = (node: number, promise: Solution["promises"][number]) =>
586
+ solution.tableau !== undefined &&
587
+ isFulfilling(solution.tableau.nodes[check.nodeTableaux[node]].particle, promise);
588
+
589
+ const checkComponent = (root: number) => {
590
+ const top = components.pop() ?? root;
591
+ if (top === root && !isStuttering(top)) {
592
+ links[top] = MAXIMUM_LINK;
593
+ return undefined;
594
+ }
595
+ const members = new Set<number>();
596
+ const membersByState = new Map<number, number[]>();
597
+ for (let member = top; ; member = components.pop() ?? root) {
598
+ members.add(member);
599
+ const siblings = membersByState.get(check.nodeStates[member]);
600
+ if (siblings) siblings.push(member);
601
+ else membersByState.set(check.nodeStates[member], [member]);
602
+ links[member] = MAXIMUM_LINK;
603
+ if (member === root) break;
604
+ }
605
+ const isStateSatisfied = model.infinitelyOftenStates.every((position) =>
606
+ [...members].some((node) => getStateResult(check, node, position)),
607
+ );
608
+ const isActionSatisfied = model.infinitelyOftenActions.every((position) =>
609
+ [...members].some((node) =>
610
+ getSuccessors(check, node).some(
611
+ (next, edge) =>
612
+ members.has(next) && isAllowed(node, edge) && getAction(node, edge, position),
613
+ ),
614
+ ),
615
+ );
616
+ const isPromiseSatisfied = solution.promises.every((promise) =>
617
+ [...members].some((node) => isFulfilled(node, promise)),
618
+ );
619
+ if (!isStateSatisfied || !isActionSatisfied || !isPromiseSatisfied) return undefined;
620
+ return getLasso(root, members, membersByState);
621
+ };
622
+
623
+ // TLC's LiveWorker#printTrace: a prefix to the root, a greedy walk through the component
624
+ // until it satisfies every check, and a breadth-first path back to the root.
625
+ const getLasso = (
626
+ root: number,
627
+ members: Set<number>,
628
+ membersByState: Map<number, number[]>,
629
+ ) => {
630
+ const prefix = removeRepeats(
631
+ getPath(check, root)
632
+ .reverse()
633
+ .map((node) => check.nodeStates[node]),
634
+ );
635
+ const cycleStack: number[] = [];
636
+ const seen = new Set<number>([root]);
637
+ const stateDone = model.infinitelyOftenStates.map(() => false);
638
+ const actionDone = model.infinitelyOftenActions.map(() => false);
639
+ const promiseDone = solution.promises.map(() => false);
640
+ const remaining = { count: stateDone.length + actionDone.length + promiseDone.length };
641
+ const current = { node: root };
642
+ const isMember = (node: number) => members.has(node);
643
+ const take = (next: number) => {
644
+ cycleStack.push(current.node);
645
+ current.node = next;
646
+ };
647
+ while (remaining.count > 0) {
648
+ const countAtStart = remaining.count;
649
+ while (true) {
650
+ model.infinitelyOftenStates.forEach((position, slot) => {
651
+ if (!stateDone[slot] && getStateResult(check, current.node, position)) {
652
+ stateDone[slot] = true;
653
+ remaining.count--;
654
+ }
655
+ });
656
+ solution.promises.forEach((promise, position) => {
657
+ if (!promiseDone[position] && isFulfilled(current.node, promise)) {
658
+ promiseDone[position] = true;
659
+ remaining.count--;
660
+ }
661
+ });
662
+ if (remaining.count <= 0) break;
663
+ const step = { last: -1, unvisited: -1 };
664
+ const countBeforeActions = remaining.count;
665
+ const taken = getSuccessors(check, current.node).some((next, edge) => {
666
+ if (membersByState.has(check.nodeStates[next])) {
667
+ if (!isMember(next) || !isAllowed(current.node, edge)) return false;
668
+ step.last = next;
669
+ model.infinitelyOftenActions.forEach((position, slot) => {
670
+ if (!actionDone[slot] && getAction(current.node, edge, position)) {
671
+ actionDone[slot] = true;
672
+ remaining.count--;
673
+ }
674
+ });
675
+ }
676
+ if (remaining.count < countBeforeActions) {
677
+ take(next);
678
+ seen.clear();
679
+ return true;
680
+ }
681
+ if (isMember(next) && !seen.has(next)) step.unvisited = next;
682
+ return false;
683
+ });
684
+ if (taken) break;
685
+ if (remaining.count < countAtStart) {
686
+ take(step.last);
687
+ seen.clear();
688
+ break;
689
+ }
690
+ while (step.unvisited === -1) {
691
+ const previous = cycleStack.pop();
692
+ if (previous === undefined) {
693
+ throw new TlaEvaluationError(
694
+ "TLC failed to build the counterexample of a liveness property",
695
+ );
696
+ }
697
+ current.node = previous;
698
+ step.unvisited =
699
+ getSuccessors(check, previous).find((next) => isMember(next) && !seen.has(next)) ??
700
+ -1;
701
+ }
702
+ take(step.unvisited);
703
+ seen.add(step.unvisited);
704
+ }
705
+ }
706
+ const postfix = getClosingPath(root, current.node, membersByState, isAllowed);
707
+ for (let position = cycleStack.length - 1; position >= 0; position--) {
708
+ const state = check.nodeStates[cycleStack[position]];
709
+ if (postfix[postfix.length - 1] !== state) postfix.push(state);
710
+ }
711
+ const cycleState = prefix[prefix.length - 1];
712
+ if (postfix[postfix.length - 1] === cycleState) postfix.pop();
713
+ return {
714
+ prefix: prefix.slice(0, -1),
715
+ cycle: [cycleState, ...postfix.reverse()],
716
+ isCycleConstrained: isCycleConstrained(solution),
717
+ };
718
+ };
719
+
720
+ // TLC's LiveWorker#bfsPostFix, the states from the walk's end back to the root, last first.
721
+ const getClosingPath = (
722
+ root: number,
723
+ end: number,
724
+ membersByState: Map<number, number[]>,
725
+ isAllowedEdge: (node: number, edge: number) => boolean,
726
+ ) => {
727
+ if (end === root) return [];
728
+ const start = check.nodeStates[end];
729
+ const parents = new Map<number, number>();
730
+ const seen = new Set<number>([start]);
731
+ const queue: [number, number][] = [];
732
+ for (let state = start, parent = -1, position = 0; ; position++) {
733
+ for (const node of membersByState.get(state) ?? []) {
734
+ for (const [edge, next] of getSuccessors(check, node).entries()) {
735
+ if (next === node || !isAllowedEdge(node, edge)) continue;
736
+ if (next === root) {
737
+ const path: number[] = [];
738
+ for (let item = state, itemParent = parent; item !== start;) {
739
+ path.push(item);
740
+ item = itemParent;
741
+ itemParent = parents.get(item) ?? -1;
742
+ }
743
+ path.push(start);
744
+ return path;
745
+ }
746
+ const nextState = check.nodeStates[next];
747
+ if (!membersByState.has(nextState) || seen.has(nextState)) continue;
748
+ seen.add(nextState);
749
+ queue.push([nextState, state]);
750
+ }
751
+ }
752
+ parents.set(state, parent);
753
+ const item = queue[position];
754
+ if (item === undefined) {
755
+ throw new TlaEvaluationError(
756
+ "TLC failed to build the counterexample of a liveness property",
757
+ );
758
+ }
759
+ state = item[0];
760
+ parent = item[1];
761
+ }
762
+ };
763
+
764
+ for (let position = 0; position < queue.length; position++) {
765
+ const stack = [queue[position], UNVISITED, 0];
766
+ const counter = { link: 0 };
767
+ while (stack.length >= 3) {
768
+ const lowLink = stack.pop() ?? 0;
769
+ const location = stack.pop();
770
+ const node = stack.pop() ?? 0;
771
+ if (location === SCC_MARKER) {
772
+ if (links[node] === lowLink) {
773
+ const lasso = checkComponent(node);
774
+ if (lasso) return lasso;
775
+ }
776
+ stack.push(Math.min(stack.pop() ?? lowLink, lowLink));
777
+ continue;
778
+ }
779
+ if (links[node] !== UNVISITED) {
780
+ stack.push(Math.min(lowLink, links[node]));
781
+ continue;
782
+ }
783
+ links[node] = counter.link;
784
+ stack.push(lowLink, node, SCC_MARKER);
785
+ components.push(node);
786
+ const nextLowLink = { value: counter.link++ };
787
+ getSuccessors(check, node).forEach((next, edge) => {
788
+ if (!isWritten(check, next)) return;
789
+ if (!isAllowed(node, edge)) {
790
+ if (links[next] === UNVISITED) queue.push(next);
791
+ return;
792
+ }
793
+ if (links[next] === UNVISITED) stack.push(next, UNVISITED);
794
+ else nextLowLink.value = Math.min(nextLowLink.value, links[next]);
795
+ });
796
+ stack.push(nextLowLink.value);
797
+ }
798
+ }
799
+ return undefined;
800
+ };
801
+
802
+ return {
803
+ branches: checks.length,
804
+ addInitialState: (index, state, tracing) => {
805
+ evaluation.environment = tracing ?? environment;
806
+ shared.states.clear();
807
+ shared.actions.clear();
808
+ try {
809
+ for (const check of checks) {
810
+ const tableau = check.solution.tableau;
811
+ if (!tableau) {
812
+ check.initial.push(index);
813
+ continue;
814
+ }
815
+ for (let node = 0; node < tableau.initialCount; node++) {
816
+ if (!isConsistent(tableau, node, undefined, state)) continue;
817
+ check.initial.push(getNodeId(check, index, node) ?? recordNode(check, index, node));
818
+ }
819
+ }
820
+ } finally {
821
+ evaluation.environment = environment;
822
+ }
823
+ },
824
+ addState: (index, state, successors, tracing) => {
825
+ evaluation.environment = tracing ?? environment;
826
+ shared.states.clear();
827
+ shared.actions.clear();
828
+ try {
829
+ const set = getSuccessorSet(index, state, successors);
830
+ for (const check of checks) {
831
+ const actionResults = set.map((successor) =>
832
+ checkAction(check, index, state, successor.state),
833
+ );
834
+ const stateResults = checkState(check, index, state);
835
+ const tableau = check.solution.tableau;
836
+ const accepted = tableau
837
+ ? addTableauState(check, tableau, set, actionResults, stateResults, index)
838
+ : addPlainState(check, set, actionResults, stateResults, index);
839
+ if (accepted) return accepted;
840
+ }
841
+ return undefined;
842
+ } finally {
843
+ evaluation.environment = environment;
844
+ }
845
+ },
846
+ findViolation: () => {
847
+ for (const check of checks) {
848
+ for (const model of check.solution.models) {
849
+ const lasso = findInModel(check, model);
850
+ if (lasso) return lasso;
851
+ }
852
+ }
853
+ return undefined;
854
+ },
855
+ // TLC names every property that the counterexample violates, once each.
856
+ getViolatedProperties: (path, cycleStart) => [
857
+ ...new Set(
858
+ properties
859
+ .filter(
860
+ (_, position) =>
861
+ !evaluateOnLasso(negations[position].body, path, cycleStart, 0, environment),
862
+ )
863
+ .map((property) => property.name),
864
+ ),
865
+ ],
866
+ };
867
+ };