tla-ts 0.0.3-dev.b74f28c → 0.0.3-dev.bcfa494

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 (46) hide show
  1. package/README.md +16 -2
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +9 -0
  4. package/dist/index.d.ts +9 -0
  5. package/dist/index.js +1 -1
  6. package/dist/parallel-worker.cjs +1 -1
  7. package/dist/parallel-worker.js +2 -2
  8. package/dist/parallel.cjs +1 -1
  9. package/dist/parallel.js +2 -2
  10. package/dist/run-cli.cjs +17 -16
  11. package/dist/run-cli.js +6 -5
  12. package/dist/transfer.cjs +27 -15
  13. package/dist/transfer.js +27 -15
  14. package/package.json +1 -1
  15. package/src/ast.ts +90 -0
  16. package/src/check.ts +254 -74
  17. package/src/cli-options.ts +11 -5
  18. package/src/codegen.ts +9 -19
  19. package/src/dependencies.ts +2 -2
  20. package/src/environment.ts +88 -20
  21. package/src/errors.ts +18 -2
  22. package/src/evaluate.ts +85 -142
  23. package/src/exit-codes.ts +21 -43
  24. package/src/instances.ts +15 -14
  25. package/src/levels.ts +8 -8
  26. package/src/lexer.ts +5 -1
  27. package/src/live-check.ts +766 -0
  28. package/src/liveness.ts +54 -535
  29. package/src/parallel-worker.ts +7 -3
  30. package/src/parallel.ts +20 -4
  31. package/src/parser.ts +12 -1
  32. package/src/resolve.ts +16 -15
  33. package/src/run-cli.ts +58 -13
  34. package/src/runtime.ts +3 -1
  35. package/src/spec-description.ts +18 -6
  36. package/src/standard-modules.ts +2 -7
  37. package/src/state-graph.ts +157 -0
  38. package/src/subexpressions.ts +10 -10
  39. package/src/successors.ts +78 -14
  40. package/src/tableau.ts +50 -23
  41. package/src/tlc-ext.ts +29 -12
  42. package/src/tlc-module.ts +9 -28
  43. package/src/tlc-order.ts +25 -7
  44. package/src/tlc-random.ts +9 -6
  45. package/src/tlc-summary.ts +20 -5
  46. package/src/values.ts +59 -11
package/src/liveness.ts CHANGED
@@ -1,14 +1,15 @@
1
- import type { Definition, Expression } from "./ast";
1
+ import { isLocallyResolved, type Definition, type Expression } from "./ast";
2
2
  import { TlaConfigError, 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,
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 {
41
+ export interface NamedExpression extends ScopedExpression {
45
42
  name: string;
46
43
  }
47
44
 
48
- export interface LiveSuccessor {
49
- index: number;
50
- state: Value[];
51
- }
52
-
53
- export interface Lasso {
54
- name: string;
55
- prefix: number[];
56
- cycle: number[];
57
- }
58
-
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;
@@ -193,21 +150,27 @@ const getDefinitionLevel = (definition: Definition, environment: Environment) =>
193
150
  return level;
194
151
  };
195
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.
196
157
  export const expandTemporal = (
197
158
  expression: Expression,
198
159
  scope: Scope | undefined,
199
160
  environment: Environment,
200
- isUnrollingForall: boolean,
161
+ isProperty: boolean,
162
+ name = "",
201
163
  expanding = new Set<Definition>(),
202
- ): ScopedExpression[] => {
164
+ ): NamedExpression[] => {
203
165
  const expand = (
204
166
  child: Expression,
205
167
  childScope: Scope | undefined,
168
+ childName = name,
206
169
  childExpanding = expanding,
207
- ): ScopedExpression[] =>
208
- expandTemporal(child, childScope, environment, isUnrollingForall, childExpanding);
170
+ ): NamedExpression[] =>
171
+ expandTemporal(child, childScope, environment, isProperty, childName, childExpanding);
209
172
  if (expression.kind === "And") {
210
- return expression.operands.flatMap((operand) => expand(operand, scope));
173
+ return expression.operands.flatMap((operand) => expand(operand, scope, describeRange(operand)));
211
174
  }
212
175
  if (expression.kind === "Label") return expand(expression.body, scope);
213
176
  if (expression.kind === "Let") {
@@ -230,33 +193,58 @@ export const expandTemporal = (
230
193
  if (expanding.has(definition)) {
231
194
  throw new TlaConfigError(`The definition of ${expression.name} refers to itself`);
232
195
  }
233
- 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
+ );
234
202
  }
235
203
  }
236
204
  const context = getConstantContext(environment, scope);
237
- 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)) {
238
210
  const operator = resolveApplyOperator(expression, context);
239
211
  const definition = isLocallyResolved(expression)
240
212
  ? undefined
241
213
  : getDefinition(expression.operator, environment);
242
- if (operator?.kind === "Closure" && !definition?.isRecursive) {
243
- 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
+ );
244
224
  }
245
225
  }
246
226
  const isUnrolled =
247
- isUnrollingForall &&
227
+ isProperty &&
248
228
  expression.kind === "Forall" &&
249
- getLevel(expression.body, scope, environment) === TEMPORAL_LEVEL &&
250
229
  expression.bounds.every((bound) => getLevel(bound.set, scope, environment) === 0);
251
230
  if (isUnrolled) {
252
- const expanded: ScopedExpression[] = [];
231
+ const expanded: NamedExpression[] = [];
232
+ const bindings = { count: 0 };
253
233
  forEachBinding(expression.bounds, context, (boundScope) => {
254
- expanded.push(...expand(expression.body, boundScope));
234
+ bindings.count++;
235
+ expanded.push(...expand(expression.body, boundScope, describeRange(expression.body)));
255
236
  return false;
256
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
+ }
257
245
  return expanded;
258
246
  }
259
- return [{ expression, scope }];
247
+ return [{ expression, scope, name }];
260
248
  };
261
249
 
262
250
  const bindLetDefinitions = (
@@ -278,7 +266,7 @@ const createAngleAction = (action: Expression, subscript: Expression): Expressio
278
266
  location: action.location,
279
267
  });
280
268
 
281
- const toLiveExpression = (
269
+ export const toLiveExpression = (
282
270
  root: Expression,
283
271
  rootScope: Scope | undefined,
284
272
  environment: Environment,
@@ -464,7 +452,7 @@ const toLiveExpression = (
464
452
  return convert(root, rootScope);
465
453
  };
466
454
 
467
- const evaluateLive = (
455
+ export const evaluateLive = (
468
456
  expression: LiveExpression,
469
457
  state: Value[],
470
458
  next: Value[] | undefined,
@@ -512,7 +500,7 @@ const evaluateLive = (
512
500
  }
513
501
  };
514
502
 
515
- const evaluateOnLasso = (
503
+ export const evaluateOnLasso = (
516
504
  expression: LiveExpression,
517
505
  path: Value[][],
518
506
  cycleStart: number,
@@ -547,472 +535,3 @@ const evaluateOnLasso = (
547
535
  );
548
536
  }
549
537
  };
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
- };