tla-ts 0.0.2 → 0.0.3-dev.14337b3

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 (65) hide show
  1. package/README.md +78 -12
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +85 -15
  4. package/dist/index.d.ts +85 -15
  5. package/dist/index.js +1 -1
  6. package/dist/parallel-worker.cjs +2 -2
  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 +22 -2
  11. package/dist/run-cli.js +22 -2
  12. package/dist/transfer.cjs +37 -16
  13. package/dist/transfer.js +37 -16
  14. package/package.json +3 -1
  15. package/src/ast.ts +137 -4
  16. package/src/check.ts +378 -100
  17. package/src/cli-options.ts +64 -0
  18. package/src/codegen.ts +15 -22
  19. package/src/config.ts +224 -170
  20. package/src/dependencies.ts +2 -2
  21. package/src/environment.ts +116 -28
  22. package/src/errors.ts +101 -3
  23. package/src/evaluate.ts +129 -153
  24. package/src/exit-codes.ts +39 -42
  25. package/src/fingerprints.ts +46 -11
  26. package/src/instances.ts +16 -15
  27. package/src/levels.ts +62 -34
  28. package/src/lexer.ts +11 -2
  29. package/src/live-check.ts +772 -0
  30. package/src/liveness.ts +116 -543
  31. package/src/obligation-action.ts +384 -0
  32. package/src/obligation-anon.ts +575 -0
  33. package/src/obligation-deref.ts +637 -0
  34. package/src/obligation-expression.ts +1060 -0
  35. package/src/obligation-format.ts +406 -0
  36. package/src/obligation-generate.ts +1074 -0
  37. package/src/obligation-levels.ts +329 -0
  38. package/src/obligation-module.ts +1042 -0
  39. package/src/obligation-printer.ts +889 -0
  40. package/src/obligation-proof.ts +76 -0
  41. package/src/obligation-source.ts +1084 -0
  42. package/src/obligation-tuples.ts +184 -0
  43. package/src/obligations.ts +316 -0
  44. package/src/parallel-worker.ts +168 -212
  45. package/src/parallel.ts +78 -37
  46. package/src/parser.ts +315 -60
  47. package/src/resolve.ts +122 -44
  48. package/src/run-cli.ts +376 -44
  49. package/src/runtime.ts +3 -1
  50. package/src/spec-description.ts +19 -8
  51. package/src/standard-levels.ts +3 -3
  52. package/src/standard-modules.ts +2 -7
  53. package/src/state-graph.ts +157 -0
  54. package/src/subexpressions.ts +10 -10
  55. package/src/successors.ts +99 -25
  56. package/src/symmetry.ts +30 -8
  57. package/src/tableau.ts +51 -24
  58. package/src/tlc-ext.ts +29 -12
  59. package/src/tlc-module.ts +14 -33
  60. package/src/tlc-modules.ts +4 -0
  61. package/src/tlc-order.ts +25 -7
  62. package/src/tlc-random.ts +9 -6
  63. package/src/tlc-summary.ts +20 -5
  64. package/src/transfer.ts +22 -1
  65. package/src/values.ts +179 -42
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,
@@ -27,66 +28,22 @@ import {
27
28
  createPair,
28
29
  createUnary,
29
30
  getLiveLevel,
30
- getSolutions,
31
- isFulfilling,
32
31
  type LiveEnabled,
33
32
  type LiveExpression,
34
- type Solution,
35
- type Tableau,
36
33
  } from "./tableau";
37
- import { isSameValue, type Value } from "./values";
34
+ import type { Value } from "./values";
38
35
 
39
36
  export interface ScopedExpression {
40
37
  expression: Expression;
41
38
  scope: Scope | undefined;
42
39
  }
43
40
 
44
- export interface TemporalProperty extends ScopedExpression {
45
- name: string;
46
- }
47
-
48
- export interface LiveSuccessor {
49
- index: number;
50
- state: Value[];
51
- }
52
-
53
- export interface Lasso {
41
+ export interface NamedExpression extends ScopedExpression {
54
42
  name: string;
55
- prefix: number[];
56
- cycle: number[];
57
43
  }
58
44
 
59
- interface SafetyViolation {
45
+ export interface TemporalProperty extends ScopedExpression {
60
46
  name: string;
61
- path: number[];
62
- }
63
-
64
- export interface LivenessChecker {
65
- addInitialState: (index: number, state: Value[]) => void;
66
- addState: (
67
- index: number,
68
- state: Value[],
69
- successors: LiveSuccessor[],
70
- ) => SafetyViolation | undefined;
71
- findViolation: () => Lasso | undefined;
72
- }
73
-
74
- interface Check {
75
- solution: Solution;
76
- stateResults: Uint8Array[];
77
- actionResults: Uint8Array[];
78
- consistency: Uint8Array[];
79
- product: BehaviorGraph | undefined;
80
- productNodes: Map<number, number>;
81
- nodesByState: Map<number, number[]>;
82
- }
83
-
84
- interface BehaviorGraph {
85
- states: number[];
86
- tableauNodes: number[];
87
- edges: number[][];
88
- initial: number[];
89
- parents: number[];
90
47
  }
91
48
 
92
49
  const MAXIMUM_EXPANSION_DEPTH = 100;
@@ -104,6 +61,23 @@ const getConstantContext = (environment: Environment, scope: Scope | undefined):
104
61
  next: undefined,
105
62
  });
106
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
+
107
81
  const createCannotHandleError = (expression: Expression) =>
108
82
  new TlaEvaluationError(
109
83
  `TLC cannot handle the temporal formula at ${describeLocation(expression)}`,
@@ -193,21 +167,27 @@ const getDefinitionLevel = (definition: Definition, environment: Environment) =>
193
167
  return level;
194
168
  };
195
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.
196
174
  export const expandTemporal = (
197
175
  expression: Expression,
198
176
  scope: Scope | undefined,
199
177
  environment: Environment,
200
- isUnrollingForall: boolean,
178
+ isProperty: boolean,
179
+ name = "",
201
180
  expanding = new Set<Definition>(),
202
- ): ScopedExpression[] => {
181
+ ): NamedExpression[] => {
203
182
  const expand = (
204
183
  child: Expression,
205
184
  childScope: Scope | undefined,
185
+ childName = name,
206
186
  childExpanding = expanding,
207
- ): ScopedExpression[] =>
208
- expandTemporal(child, childScope, environment, isUnrollingForall, childExpanding);
187
+ ): NamedExpression[] =>
188
+ expandTemporal(child, childScope, environment, isProperty, childName, childExpanding);
209
189
  if (expression.kind === "And") {
210
- return expression.operands.flatMap((operand) => expand(operand, scope));
190
+ return expression.operands.flatMap((operand) => expand(operand, scope, describeRange(operand)));
211
191
  }
212
192
  if (expression.kind === "Label") return expand(expression.body, scope);
213
193
  if (expression.kind === "Let") {
@@ -228,35 +208,60 @@ export const expandTemporal = (
228
208
  getDefinitionLevel(definition, environment) > 0
229
209
  ) {
230
210
  if (expanding.has(definition)) {
231
- throw new TlaConfigError(`The definition of ${expression.name} refers to itself`);
211
+ throw setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error);
232
212
  }
233
- return expand(definition.body, undefined, new Set([...expanding, definition]));
213
+ return expand(
214
+ definition.body,
215
+ undefined,
216
+ expression.name,
217
+ new Set([...expanding, definition]),
218
+ );
234
219
  }
235
220
  }
236
221
  const context = getConstantContext(environment, scope);
237
- if (expression.kind === "Apply" && getLevel(expression, scope, environment) === TEMPORAL_LEVEL) {
222
+ // A property expands every operator it applies and unrolls every \A over constant sets, but a
223
+ // specification only expands the temporal ones.
224
+ const isExpanded = (child: Expression) =>
225
+ isProperty || getLevel(child, scope, environment) === TEMPORAL_LEVEL;
226
+ if (expression.kind === "Apply" && isExpanded(expression)) {
238
227
  const operator = resolveApplyOperator(expression, context);
239
228
  const definition = isLocallyResolved(expression)
240
229
  ? undefined
241
230
  : getDefinition(expression.operator, environment);
242
- if (operator?.kind === "Closure" && !definition?.isRecursive) {
243
- return expand(operator.body, bindOperatorArguments(operator, expression.args, context));
231
+ const isExpandable =
232
+ operator?.kind === "Closure" &&
233
+ operator.params.length === expression.args.length &&
234
+ !definition?.isRecursive;
235
+ if (isExpandable) {
236
+ return expand(
237
+ operator.body,
238
+ bindOperatorArguments(operator, expression.args, context),
239
+ expression.operator,
240
+ );
244
241
  }
245
242
  }
246
243
  const isUnrolled =
247
- isUnrollingForall &&
244
+ isProperty &&
248
245
  expression.kind === "Forall" &&
249
- getLevel(expression.body, scope, environment) === TEMPORAL_LEVEL &&
250
246
  expression.bounds.every((bound) => getLevel(bound.set, scope, environment) === 0);
251
247
  if (isUnrolled) {
252
- const expanded: ScopedExpression[] = [];
248
+ const expanded: NamedExpression[] = [];
249
+ const bindings = { count: 0 };
253
250
  forEachBinding(expression.bounds, context, (boundScope) => {
254
- expanded.push(...expand(expression.body, boundScope));
251
+ bindings.count++;
252
+ expanded.push(...expand(expression.body, boundScope, describeRange(expression.body)));
255
253
  return false;
256
254
  });
255
+ // TLC rejects a property that quantifies over no elements before it checks anything.
256
+ if (bindings.count === 0) {
257
+ throw setExitCode(
258
+ new TlaEvaluationError(TAUTOLOGY_MESSAGE),
259
+ EXIT_STATUS.livenessEvaluationFailure,
260
+ );
261
+ }
257
262
  return expanded;
258
263
  }
259
- return [{ expression, scope }];
264
+ return [{ expression, scope, name }];
260
265
  };
261
266
 
262
267
  const bindLetDefinitions = (
@@ -278,7 +283,7 @@ const createAngleAction = (action: Expression, subscript: Expression): Expressio
278
283
  location: action.location,
279
284
  });
280
285
 
281
- const toLiveExpression = (
286
+ export const toLiveExpression = (
282
287
  root: Expression,
283
288
  rootScope: Scope | undefined,
284
289
  environment: Environment,
@@ -290,7 +295,7 @@ const toLiveExpression = (
290
295
  ): LiveExpression => {
291
296
  const atomLevel = level === 0 ? getLevel(expression, scope, environment) : level;
292
297
  if (atomLevel === 0) {
293
- const value = evaluate(expression, getConstantContext(environment, scope));
298
+ const value = evaluateConstant(expression, getConstantContext(environment, scope));
294
299
  if (typeof value !== "boolean") {
295
300
  throw new TlaEvaluationError(
296
301
  `TLC expected a boolean in the temporal formula at ${describeLocation(expression)}`,
@@ -311,9 +316,7 @@ const toLiveExpression = (
311
316
  scope: Scope | undefined,
312
317
  ) => {
313
318
  if (expansion.depth >= MAXIMUM_EXPANSION_DEPTH) {
314
- throw new TlaEvaluationError(
315
- `TLC overflowed the stack while expanding the temporal formula at ${describeLocation(expression)}`,
316
- );
319
+ throw setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error);
317
320
  }
318
321
  expansion.depth++;
319
322
  const result = convert(body, bodyScope);
@@ -368,9 +371,45 @@ const toLiveExpression = (
368
371
  return level > ACTION_LEVEL ? result : toAtom(expression, scope, level);
369
372
  };
370
373
 
374
+ // TLC translates the operands of a connective even when the whole formula is a state or action
375
+ // predicate, so it fails on a constant operand before it checks any state.
376
+ const convertOperands = (expression: Expression, scope: Scope | undefined) => {
377
+ switch (expression.kind) {
378
+ case "Label":
379
+ convert(expression.body, scope);
380
+ return;
381
+ case "Let":
382
+ convert(expression.body, bindLetDefinitions(expression, scope, environment));
383
+ return;
384
+ case "And":
385
+ case "Or":
386
+ for (const operand of expression.operands) convert(operand, scope);
387
+ return;
388
+ case "Apply":
389
+ if (
390
+ expression.operator === "=>" ||
391
+ (expression.operator === "~" && !isLocallyResolved(expression))
392
+ ) {
393
+ for (const operand of expression.args) convert(operand, scope);
394
+ }
395
+ return;
396
+ case "If": {
397
+ const condition = convert(expression.condition, scope);
398
+ const branches =
399
+ condition.kind === "Boolean"
400
+ ? [condition.value ? expression.consequent : expression.alternative]
401
+ : [expression.consequent, expression.alternative];
402
+ for (const branch of branches) convert(branch, scope);
403
+ }
404
+ }
405
+ };
406
+
371
407
  const convert = (expression: Expression, scope: Scope | undefined): LiveExpression => {
372
408
  const level = getLevel(expression, scope, environment);
373
- if (level <= ACTION_LEVEL) return toAtom(expression, scope, level);
409
+ if (level <= ACTION_LEVEL) {
410
+ convertOperands(expression, scope);
411
+ return toAtom(expression, scope, level);
412
+ }
374
413
  switch (expression.kind) {
375
414
  case "Label":
376
415
  return convert(expression.body, scope);
@@ -413,7 +452,10 @@ const toLiveExpression = (
413
452
  return convertQuantifier(expression, scope);
414
453
  case "If": {
415
454
  if (getLevel(expression.condition, scope, environment) === 0) {
416
- const condition = evaluate(expression.condition, getConstantContext(environment, scope));
455
+ const condition = evaluateConstant(
456
+ expression.condition,
457
+ getConstantContext(environment, scope),
458
+ );
417
459
  if (typeof condition === "boolean") {
418
460
  return convert(condition ? expression.consequent : expression.alternative, scope);
419
461
  }
@@ -464,7 +506,7 @@ const toLiveExpression = (
464
506
  return convert(root, rootScope);
465
507
  };
466
508
 
467
- const evaluateLive = (
509
+ export const evaluateLive = (
468
510
  expression: LiveExpression,
469
511
  state: Value[],
470
512
  next: Value[] | undefined,
@@ -512,7 +554,7 @@ const evaluateLive = (
512
554
  }
513
555
  };
514
556
 
515
- const evaluateOnLasso = (
557
+ export const evaluateOnLasso = (
516
558
  expression: LiveExpression,
517
559
  path: Value[][],
518
560
  cycleStart: number,
@@ -547,472 +589,3 @@ const evaluateOnLasso = (
547
589
  );
548
590
  }
549
591
  };
550
-
551
- const liveKeys = new WeakMap<LiveExpression, string>();
552
-
553
- const atomCount = { value: 0 };
554
-
555
- const getLiveKey = (expression: LiveExpression): string => {
556
- const cached = liveKeys.get(expression);
557
- if (cached !== undefined) return cached;
558
- const key =
559
- expression.kind === "Boolean"
560
- ? String(expression.value)
561
- : "body" in expression
562
- ? `${expression.kind}(${getLiveKey(expression.body)})`
563
- : "operands" in expression
564
- ? `${expression.kind}(${expression.operands.map(getLiveKey).join(",")})`
565
- : `${expression.kind}#${atomCount.value++}`;
566
- liveKeys.set(expression, key);
567
- return key;
568
- };
569
-
570
- const isSameState = (left: Value[], right: Value[]) =>
571
- left.every((value, position) => isSameValue(value, right[position]));
572
-
573
- const getStronglyConnectedComponents = (
574
- nodeCount: number,
575
- getSuccessors: (node: number) => number[],
576
- visit: (component: number[], successors: (node: number) => number[]) => boolean,
577
- ) => {
578
- const order = new Int32Array(nodeCount).fill(-1);
579
- const lowLink = new Int32Array(nodeCount);
580
- const onStack = new Uint8Array(nodeCount);
581
- const stack: number[] = [];
582
- const counter = { value: 0 };
583
- const successorCache = new Map<number, number[]>();
584
- const getCachedSuccessors = (node: number) => {
585
- const cached = successorCache.get(node);
586
- if (cached) return cached;
587
- const successors = getSuccessors(node);
588
- successorCache.set(node, successors);
589
- return successors;
590
- };
591
- for (let root = 0; root < nodeCount; root++) {
592
- if (order[root] !== -1) continue;
593
- const frames: { node: number; position: number }[] = [];
594
- const open = (node: number) => {
595
- order[node] = counter.value;
596
- lowLink[node] = counter.value++;
597
- stack.push(node);
598
- onStack[node] = 1;
599
- frames.push({ node, position: 0 });
600
- };
601
- open(root);
602
- while (frames.length > 0) {
603
- const frame = frames[frames.length - 1];
604
- const successors = getCachedSuccessors(frame.node);
605
- if (frame.position < successors.length) {
606
- const target = successors[frame.position++];
607
- if (order[target] === -1) open(target);
608
- else if (onStack[target])
609
- lowLink[frame.node] = Math.min(lowLink[frame.node], order[target]);
610
- continue;
611
- }
612
- frames.pop();
613
- const parent = frames[frames.length - 1];
614
- if (parent) lowLink[parent.node] = Math.min(lowLink[parent.node], lowLink[frame.node]);
615
- if (lowLink[frame.node] !== order[frame.node]) continue;
616
- const component: number[] = [];
617
- while (true) {
618
- const member = stack.pop();
619
- if (member === undefined) break;
620
- onStack[member] = 0;
621
- component.push(member);
622
- if (member === frame.node) break;
623
- }
624
- const isFound = visit(component, getCachedSuccessors);
625
- component.forEach((member) => successorCache.delete(member));
626
- if (isFound) return;
627
- }
628
- }
629
- };
630
-
631
- const getShortestPath = (
632
- from: number,
633
- to: number,
634
- members: Set<number>,
635
- getSuccessors: (node: number) => number[],
636
- ) => {
637
- if (from === to) return [from];
638
- const parents = new Map<number, number>([[from, -1]]);
639
- const queue = [from];
640
- for (let position = 0; position < queue.length; position++) {
641
- for (const target of getSuccessors(queue[position])) {
642
- if (parents.has(target) || !members.has(target)) continue;
643
- parents.set(target, queue[position]);
644
- if (target === to) {
645
- const path: number[] = [];
646
- for (let node = to; node !== -1; node = parents.get(node) ?? -1) path.push(node);
647
- return path.reverse();
648
- }
649
- queue.push(target);
650
- }
651
- }
652
- return [from];
653
- };
654
-
655
- const removeRepeats = (path: number[]) =>
656
- path.filter((node, position) => position === 0 || path[position - 1] !== node);
657
-
658
- export const createLivenessChecker = (
659
- properties: TemporalProperty[],
660
- temporals: ScopedExpression[],
661
- environment: Environment,
662
- ): LivenessChecker | undefined => {
663
- if (properties.length === 0) return undefined;
664
- const fairness = temporals.map((item) =>
665
- toLiveExpression(item.expression, item.scope, environment),
666
- );
667
- const negations = properties.map((property) =>
668
- createUnary("Not", toLiveExpression(property.expression, property.scope, environment)),
669
- );
670
- const violation = negations.length === 1 ? negations[0] : createJunction("Or", negations);
671
- const formula =
672
- fairness.length === 0 ? violation : createJunction("And", [...fairness, violation]);
673
- const solutions = getSolutions(formula);
674
- if (solutions.length === 0) {
675
- throw new TlaEvaluationError("Temporal formula is a tautology (its negation is unsatisfiable)");
676
- }
677
- const checks = solutions.map((solution): Check => ({
678
- solution,
679
- stateResults: [],
680
- actionResults: [],
681
- consistency: [],
682
- product: solution.tableau && {
683
- states: [],
684
- tableauNodes: [],
685
- edges: [],
686
- initial: [],
687
- parents: [],
688
- },
689
- productNodes: new Map(),
690
- nodesByState: new Map(),
691
- }));
692
- const actionKeys = new Map<string, number>();
693
- const actionIds = checks.map((check) =>
694
- check.solution.actionChecks.map((predicate) => {
695
- const key = getLiveKey(predicate);
696
- const known = actionKeys.get(key);
697
- if (known !== undefined) return known;
698
- actionKeys.set(key, actionKeys.size);
699
- return actionKeys.size - 1;
700
- }),
701
- );
702
- const states: Value[][] = [];
703
- const targets: number[][] = [];
704
- const edgeStates: Value[][][] = [];
705
- const initial: number[] = [];
706
-
707
- const isConsistent = (
708
- predicates: LiveExpression[],
709
- state: Value[],
710
- cache: Map<LiveExpression, boolean>,
711
- ) =>
712
- predicates.every((predicate) => evaluateLive(predicate, state, undefined, environment, cache));
713
-
714
- const getProductNode = (
715
- check: Check,
716
- product: BehaviorGraph,
717
- state: number,
718
- tableauNode: number,
719
- parent: number,
720
- ) => {
721
- const key = state * (check.solution.tableau?.nodes.length ?? 1) + tableauNode;
722
- const existing = check.productNodes.get(key);
723
- if (existing !== undefined) return { node: existing, isNew: false };
724
- const node = product.states.length;
725
- check.productNodes.set(key, node);
726
- product.states.push(state);
727
- product.tableauNodes.push(tableauNode);
728
- product.edges.push([]);
729
- product.parents.push(parent);
730
- const siblings = check.nodesByState.get(state);
731
- if (siblings) siblings.push(node);
732
- else check.nodesByState.set(state, [node]);
733
- return { node, isNew: true };
734
- };
735
-
736
- const getAttribution = (path: number[], cycleStart: number) => {
737
- const lasso = path.map((state) => states[state]);
738
- return (
739
- properties.find(
740
- (_, position) =>
741
- !evaluateOnLasso(negations[position].body, lasso, cycleStart, 0, environment),
742
- ) ?? properties[0]
743
- ).name;
744
- };
745
-
746
- const expandProduct = (check: Check, product: BehaviorGraph, tableau: Tableau, state: number) => {
747
- const hasEmptyModel = check.solution.models.some(
748
- (model) =>
749
- model.eventuallyAlways.length === 0 &&
750
- model.infinitelyOftenStates.length === 0 &&
751
- model.infinitelyOftenActions.length === 0,
752
- );
753
- const nodeCount = tableau.nodes.length;
754
- const pending = (check.nodesByState.get(state) ?? []).map((node) => ({ node, isDone: false }));
755
- while (pending.length > 0) {
756
- const item = pending.pop();
757
- if (!item) break;
758
- const source = product.states[item.node];
759
- const successors = tableau.nodes[product.tableauNodes[item.node]].successors;
760
- const isAccepted =
761
- item.isDone &&
762
- hasEmptyModel &&
763
- successors.some((successor) => {
764
- const node = tableau.nodes[successor];
765
- return node.particle.length === 0 && node.successors.every((next) => next === successor);
766
- });
767
- if (isAccepted) {
768
- const path = removeRepeats(
769
- getPrefix(product, item.node).map((node) => product.states[node]),
770
- );
771
- return { name: getAttribution(path, path.length - 1), path };
772
- }
773
- const consistency = check.consistency[source];
774
- targets[source].forEach((target, edgeIndex) => {
775
- for (const successor of successors) {
776
- if (!consistency[edgeIndex * nodeCount + successor]) continue;
777
- const created = getProductNode(check, product, target, successor, item.node);
778
- product.edges[item.node].push(created.node, edgeIndex);
779
- if (created.isNew && targets[target] !== undefined) {
780
- pending.push({ node: created.node, isDone: true });
781
- }
782
- }
783
- });
784
- }
785
- return undefined;
786
- };
787
-
788
- const addInitialState = (index: number, state: Value[]) => {
789
- initial.push(index);
790
- states[index] = state;
791
- for (const check of checks) {
792
- const tableau = check.solution.tableau;
793
- const product = check.product;
794
- if (!tableau || !product) continue;
795
- const cache = new Map<LiveExpression, boolean>();
796
- for (let node = 0; node < tableau.initialCount; node++) {
797
- if (!isConsistent(tableau.nodes[node].statePredicates, state, cache)) continue;
798
- product.initial.push(getProductNode(check, product, index, node, -1).node);
799
- }
800
- }
801
- };
802
-
803
- const addState = (index: number, state: Value[], successors: LiveSuccessor[]) => {
804
- environment.runtime.setLivenessSource(index);
805
- states[index] = state;
806
- const edges: LiveSuccessor[] = [];
807
- const edgesByTarget = new Map<number, LiveSuccessor[]>();
808
- for (const successor of [...successors, { index, state }]) {
809
- const sameTarget = edgesByTarget.get(successor.index);
810
- const isDuplicate =
811
- sameTarget !== undefined &&
812
- (successor.index < index ||
813
- sameTarget.some((edge) => isSameState(edge.state, successor.state)));
814
- if (isDuplicate) continue;
815
- edges.push(successor);
816
- if (sameTarget) sameTarget.push(successor);
817
- else edgesByTarget.set(successor.index, [successor]);
818
- }
819
- targets[index] = edges.map((edge) => edge.index);
820
- edgeStates[index] = edges.map((edge) => edge.state);
821
- const stateCache = new Map<LiveExpression, boolean>();
822
- const successorCaches = edges.map(() => new Map<LiveExpression, boolean>());
823
- for (const check of checks) {
824
- const solution = check.solution;
825
- check.stateResults[index] = Uint8Array.from(solution.stateChecks, (predicate) =>
826
- evaluateLive(predicate, state, undefined, environment, stateCache) ? 1 : 0,
827
- );
828
- const tableau = solution.tableau;
829
- const product = check.product;
830
- if (!tableau || !product) continue;
831
- const nodeCount = tableau.nodes.length;
832
- const consistency = new Uint8Array(edges.length * nodeCount);
833
- edges.forEach((edge, edgeIndex) => {
834
- tableau.nodes.forEach((node, nodeIndex) => {
835
- const isTrue = isConsistent(node.statePredicates, edge.state, successorCaches[edgeIndex]);
836
- consistency[edgeIndex * nodeCount + nodeIndex] = isTrue ? 1 : 0;
837
- });
838
- });
839
- check.consistency[index] = consistency;
840
- const accepted = expandProduct(check, product, tableau, index);
841
- if (accepted) return accepted;
842
- }
843
- return undefined;
844
- };
845
-
846
- const computeActionResults = (source: number) => {
847
- environment.runtime.setLivenessSource(source);
848
- const state = states[source];
849
- const successors = edgeStates[source];
850
- const values = successors.map(() => new Int8Array(actionKeys.size).fill(-1));
851
- checks.forEach((check, checkIndex) => {
852
- const solution = check.solution;
853
- const ids = actionIds[checkIndex];
854
- const stateResults = check.stateResults[source];
855
- const stateCache = new Map(
856
- solution.stateChecks.map((predicate, position) => [
857
- predicate,
858
- stateResults[position] === 1,
859
- ]),
860
- );
861
- const actionCount = solution.actionChecks.length;
862
- const actions = new Uint8Array(successors.length * actionCount);
863
- successors.forEach((successor, edgeIndex) => {
864
- const known = values[edgeIndex];
865
- for (let position = 0; position < actionCount; position++) {
866
- const actionId = ids[position];
867
- if (known[actionId] === -1) {
868
- const predicate = solution.actionChecks[position];
869
- known[actionId] = evaluateLive(predicate, state, successor, environment, stateCache)
870
- ? 1
871
- : 0;
872
- }
873
- actions[edgeIndex * actionCount + position] = known[actionId];
874
- }
875
- });
876
- check.actionResults[source] = actions;
877
- });
878
- };
879
-
880
- const getActionResults = (check: Check, source: number) => {
881
- if (check.actionResults[source] === undefined) computeActionResults(source);
882
- return check.actionResults[source];
883
- };
884
-
885
- const getGraph = (check: Check): BehaviorGraph =>
886
- check.product ?? {
887
- states: states.map((_, index) => index),
888
- tableauNodes: states.map(() => -1),
889
- edges: Array.from({ length: states.length }, (_, index) =>
890
- (targets[index] ?? []).flatMap((target, edgeIndex) => [target, edgeIndex]),
891
- ),
892
- initial,
893
- parents: [],
894
- };
895
-
896
- const getPrefix = (graph: BehaviorGraph, entry: number) => {
897
- if (graph.parents.length > 0) {
898
- const path: number[] = [];
899
- for (let node = entry; node !== -1; node = graph.parents[node]) path.push(node);
900
- return path.reverse();
901
- }
902
- const parents = new Map<number, number>(graph.initial.map((node) => [node, -1]));
903
- const queue = [...graph.initial];
904
- for (let position = 0; position < queue.length && !parents.has(entry); position++) {
905
- const edges = graph.edges[queue[position]];
906
- for (let offset = 0; offset < edges.length; offset += 2) {
907
- if (parents.has(edges[offset])) continue;
908
- parents.set(edges[offset], queue[position]);
909
- queue.push(edges[offset]);
910
- }
911
- }
912
- const path: number[] = [];
913
- for (let node = entry; node !== -1; node = parents.get(node) ?? -1) path.push(node);
914
- return path.reverse();
915
- };
916
-
917
- const findInCheck = (check: Check): Lasso | undefined => {
918
- const solution = check.solution;
919
- const tableau = solution.tableau;
920
- const graph = getGraph(check);
921
- const actionCount = solution.actionChecks.length;
922
- const getAction = (node: number, edgeIndex: number, position: number) =>
923
- getActionResults(check, graph.states[node])[edgeIndex * actionCount + position] === 1;
924
- for (const model of solution.models) {
925
- const isAllowed = (node: number, edgeIndex: number) =>
926
- model.eventuallyAlways.every((position) => getAction(node, edgeIndex, position));
927
- const getSuccessors = (node: number) => {
928
- const edges = graph.edges[node];
929
- const successors: number[] = [];
930
- for (let offset = 0; offset < edges.length; offset += 2) {
931
- if (isAllowed(node, edges[offset + 1])) successors.push(edges[offset]);
932
- }
933
- return successors;
934
- };
935
- const lasso = { value: undefined as Lasso | undefined };
936
- getStronglyConnectedComponents(
937
- graph.states.length,
938
- getSuccessors,
939
- (component, successors) => {
940
- const members = new Set(component);
941
- if (component.length === 1 && !successors(component[0]).includes(component[0]))
942
- return false;
943
- const stateWitnesses = model.infinitelyOftenStates.map((position) =>
944
- component.find((node) => check.stateResults[graph.states[node]][position] === 1),
945
- );
946
- const actionWitnesses = model.infinitelyOftenActions.map((position) => {
947
- for (const node of component) {
948
- const edges = graph.edges[node];
949
- for (let offset = 0; offset < edges.length; offset += 2) {
950
- const isWitness =
951
- members.has(edges[offset]) &&
952
- isAllowed(node, edges[offset + 1]) &&
953
- getAction(node, edges[offset + 1], position);
954
- if (isWitness) return [node, edges[offset]];
955
- }
956
- }
957
- return undefined;
958
- });
959
- const promiseWitnesses = solution.promises.map((promise) =>
960
- component.find(
961
- (node) =>
962
- tableau !== undefined &&
963
- isFulfilling(tableau.nodes[graph.tableauNodes[node]].particle, promise),
964
- ),
965
- );
966
- const isViolation =
967
- stateWitnesses.every((witness) => witness !== undefined) &&
968
- actionWitnesses.every((witness) => witness !== undefined) &&
969
- promiseWitnesses.every((witness) => witness !== undefined);
970
- if (!isViolation) return false;
971
- const entry = component[component.length - 1];
972
- const waypoints = [
973
- ...stateWitnesses.flatMap((witness) => witness ?? []),
974
- ...actionWitnesses.flatMap((witness) => witness ?? []),
975
- ...promiseWitnesses.flatMap((witness) => witness ?? []),
976
- ];
977
- const cycle = [entry];
978
- for (const waypoint of waypoints) {
979
- cycle.push(
980
- ...getShortestPath(cycle[cycle.length - 1], waypoint, members, successors).slice(1),
981
- );
982
- }
983
- if (cycle.length === 1 && !successors(entry).includes(entry)) {
984
- cycle.push(successors(entry).find((node) => members.has(node)) ?? entry);
985
- }
986
- const closing = getShortestPath(cycle[cycle.length - 1], entry, members, successors);
987
- cycle.push(...closing.slice(1, -1));
988
- const prefix = removeRepeats(getPrefix(graph, entry).map((node) => graph.states[node]));
989
- const cycleStates = removeRepeats(cycle.map((node) => graph.states[node]));
990
- if (cycleStates.length > 1 && cycleStates[cycleStates.length - 1] === cycleStates[0]) {
991
- cycleStates.pop();
992
- }
993
- prefix.pop();
994
- lasso.value = {
995
- name: getAttribution([...prefix, ...cycleStates], prefix.length),
996
- prefix,
997
- cycle: cycleStates,
998
- };
999
- return true;
1000
- },
1001
- );
1002
- if (lasso.value) return lasso.value;
1003
- }
1004
- return undefined;
1005
- };
1006
-
1007
- return {
1008
- addInitialState,
1009
- addState,
1010
- findViolation: () => {
1011
- for (const check of checks) {
1012
- const lasso = findInCheck(check);
1013
- if (lasso) return lasso;
1014
- }
1015
- return undefined;
1016
- },
1017
- };
1018
- };