tla-ts 0.0.3-dev.3cf2ad0 → 0.0.3-dev.3ff2308

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 (51) hide show
  1. package/README.md +16 -2
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +54 -22
  4. package/dist/index.d.ts +54 -22
  5. package/dist/index.js +1 -1
  6. package/dist/parallel-worker.cjs +1 -1
  7. package/dist/parallel-worker.js +2 -2
  8. package/dist/parallel.cjs +1 -1
  9. package/dist/parallel.js +2 -2
  10. package/dist/run-cli.cjs +19 -16
  11. package/dist/run-cli.js +20 -17
  12. package/dist/transfer.cjs +37 -16
  13. package/dist/transfer.js +37 -16
  14. package/package.json +1 -1
  15. package/src/ast.ts +93 -0
  16. package/src/builtins.ts +9 -3
  17. package/src/check.ts +511 -99
  18. package/src/cli-options.ts +11 -5
  19. package/src/codegen.ts +15 -22
  20. package/src/config.ts +224 -170
  21. package/src/dependencies.ts +2 -2
  22. package/src/environment.ts +121 -29
  23. package/src/errors.ts +87 -3
  24. package/src/evaluate.ts +255 -159
  25. package/src/exit-codes.ts +39 -42
  26. package/src/instances.ts +16 -15
  27. package/src/levels.ts +62 -34
  28. package/src/lexer.ts +5 -1
  29. package/src/live-check.ts +772 -0
  30. package/src/liveness.ts +120 -543
  31. package/src/parallel-worker.ts +7 -3
  32. package/src/parallel.ts +20 -4
  33. package/src/parser.ts +33 -11
  34. package/src/resolve.ts +122 -44
  35. package/src/run-cli.ts +112 -20
  36. package/src/runtime.ts +3 -1
  37. package/src/spec-description.ts +19 -8
  38. package/src/standard-modules.ts +52 -43
  39. package/src/state-graph.ts +157 -0
  40. package/src/subexpressions.ts +10 -10
  41. package/src/successors.ts +183 -39
  42. package/src/symmetry.ts +25 -7
  43. package/src/tableau.ts +51 -24
  44. package/src/tlc-ext.ts +29 -12
  45. package/src/tlc-module.ts +14 -33
  46. package/src/tlc-modules.ts +4 -0
  47. package/src/tlc-order.ts +25 -7
  48. package/src/tlc-random.ts +9 -6
  49. package/src/tlc-summary.ts +20 -5
  50. package/src/value-sources.ts +29 -0
  51. package/src/values.ts +207 -53
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,64 @@ 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
+ const expanded = expand(
214
+ definition.body,
215
+ undefined,
216
+ expression.name,
217
+ new Set([...expanding, definition]),
218
+ );
219
+ // TLC takes the body of a state-level definition in a specification as one initial predicate.
220
+ return !isProperty && getDefinitionLevel(definition, environment) < ACTION_LEVEL
221
+ ? [{ expression: definition.body, scope: undefined, name: expression.name }]
222
+ : expanded;
234
223
  }
235
224
  }
236
225
  const context = getConstantContext(environment, scope);
237
- if (expression.kind === "Apply" && getLevel(expression, scope, environment) === TEMPORAL_LEVEL) {
226
+ // A property expands every operator it applies and unrolls every \A over constant sets, but a
227
+ // specification only expands the temporal ones.
228
+ const isExpanded = (child: Expression) =>
229
+ isProperty || getLevel(child, scope, environment) === TEMPORAL_LEVEL;
230
+ if (expression.kind === "Apply" && isExpanded(expression)) {
238
231
  const operator = resolveApplyOperator(expression, context);
239
232
  const definition = isLocallyResolved(expression)
240
233
  ? undefined
241
234
  : getDefinition(expression.operator, environment);
242
- if (operator?.kind === "Closure" && !definition?.isRecursive) {
243
- return expand(operator.body, bindOperatorArguments(operator, expression.args, context));
235
+ const isExpandable =
236
+ operator?.kind === "Closure" &&
237
+ operator.params.length === expression.args.length &&
238
+ !definition?.isRecursive;
239
+ if (isExpandable) {
240
+ return expand(
241
+ operator.body,
242
+ bindOperatorArguments(operator, expression.args, context),
243
+ expression.operator,
244
+ );
244
245
  }
245
246
  }
246
247
  const isUnrolled =
247
- isUnrollingForall &&
248
+ isProperty &&
248
249
  expression.kind === "Forall" &&
249
- getLevel(expression.body, scope, environment) === TEMPORAL_LEVEL &&
250
250
  expression.bounds.every((bound) => getLevel(bound.set, scope, environment) === 0);
251
251
  if (isUnrolled) {
252
- const expanded: ScopedExpression[] = [];
252
+ const expanded: NamedExpression[] = [];
253
+ const bindings = { count: 0 };
253
254
  forEachBinding(expression.bounds, context, (boundScope) => {
254
- expanded.push(...expand(expression.body, boundScope));
255
+ bindings.count++;
256
+ expanded.push(...expand(expression.body, boundScope, describeRange(expression.body)));
255
257
  return false;
256
258
  });
259
+ // TLC rejects a property that quantifies over no elements before it checks anything.
260
+ if (bindings.count === 0) {
261
+ throw setExitCode(
262
+ new TlaEvaluationError(TAUTOLOGY_MESSAGE),
263
+ EXIT_STATUS.livenessEvaluationFailure,
264
+ );
265
+ }
257
266
  return expanded;
258
267
  }
259
- return [{ expression, scope }];
268
+ return [{ expression, scope, name }];
260
269
  };
261
270
 
262
271
  const bindLetDefinitions = (
@@ -278,7 +287,7 @@ const createAngleAction = (action: Expression, subscript: Expression): Expressio
278
287
  location: action.location,
279
288
  });
280
289
 
281
- const toLiveExpression = (
290
+ export const toLiveExpression = (
282
291
  root: Expression,
283
292
  rootScope: Scope | undefined,
284
293
  environment: Environment,
@@ -290,7 +299,7 @@ const toLiveExpression = (
290
299
  ): LiveExpression => {
291
300
  const atomLevel = level === 0 ? getLevel(expression, scope, environment) : level;
292
301
  if (atomLevel === 0) {
293
- const value = evaluate(expression, getConstantContext(environment, scope));
302
+ const value = evaluateConstant(expression, getConstantContext(environment, scope));
294
303
  if (typeof value !== "boolean") {
295
304
  throw new TlaEvaluationError(
296
305
  `TLC expected a boolean in the temporal formula at ${describeLocation(expression)}`,
@@ -311,9 +320,7 @@ const toLiveExpression = (
311
320
  scope: Scope | undefined,
312
321
  ) => {
313
322
  if (expansion.depth >= MAXIMUM_EXPANSION_DEPTH) {
314
- throw new TlaEvaluationError(
315
- `TLC overflowed the stack while expanding the temporal formula at ${describeLocation(expression)}`,
316
- );
323
+ throw setExitCode(new TlaEvaluationError(STACK_OVERFLOW), EXIT_STATUS.error);
317
324
  }
318
325
  expansion.depth++;
319
326
  const result = convert(body, bodyScope);
@@ -368,9 +375,45 @@ const toLiveExpression = (
368
375
  return level > ACTION_LEVEL ? result : toAtom(expression, scope, level);
369
376
  };
370
377
 
378
+ // TLC translates the operands of a connective even when the whole formula is a state or action
379
+ // predicate, so it fails on a constant operand before it checks any state.
380
+ const convertOperands = (expression: Expression, scope: Scope | undefined) => {
381
+ switch (expression.kind) {
382
+ case "Label":
383
+ convert(expression.body, scope);
384
+ return;
385
+ case "Let":
386
+ convert(expression.body, bindLetDefinitions(expression, scope, environment));
387
+ return;
388
+ case "And":
389
+ case "Or":
390
+ for (const operand of expression.operands) convert(operand, scope);
391
+ return;
392
+ case "Apply":
393
+ if (
394
+ expression.operator === "=>" ||
395
+ (expression.operator === "~" && !isLocallyResolved(expression))
396
+ ) {
397
+ for (const operand of expression.args) convert(operand, scope);
398
+ }
399
+ return;
400
+ case "If": {
401
+ const condition = convert(expression.condition, scope);
402
+ const branches =
403
+ condition.kind === "Boolean"
404
+ ? [condition.value ? expression.consequent : expression.alternative]
405
+ : [expression.consequent, expression.alternative];
406
+ for (const branch of branches) convert(branch, scope);
407
+ }
408
+ }
409
+ };
410
+
371
411
  const convert = (expression: Expression, scope: Scope | undefined): LiveExpression => {
372
412
  const level = getLevel(expression, scope, environment);
373
- if (level <= ACTION_LEVEL) return toAtom(expression, scope, level);
413
+ if (level <= ACTION_LEVEL) {
414
+ convertOperands(expression, scope);
415
+ return toAtom(expression, scope, level);
416
+ }
374
417
  switch (expression.kind) {
375
418
  case "Label":
376
419
  return convert(expression.body, scope);
@@ -413,7 +456,10 @@ const toLiveExpression = (
413
456
  return convertQuantifier(expression, scope);
414
457
  case "If": {
415
458
  if (getLevel(expression.condition, scope, environment) === 0) {
416
- const condition = evaluate(expression.condition, getConstantContext(environment, scope));
459
+ const condition = evaluateConstant(
460
+ expression.condition,
461
+ getConstantContext(environment, scope),
462
+ );
417
463
  if (typeof condition === "boolean") {
418
464
  return convert(condition ? expression.consequent : expression.alternative, scope);
419
465
  }
@@ -464,7 +510,7 @@ const toLiveExpression = (
464
510
  return convert(root, rootScope);
465
511
  };
466
512
 
467
- const evaluateLive = (
513
+ export const evaluateLive = (
468
514
  expression: LiveExpression,
469
515
  state: Value[],
470
516
  next: Value[] | undefined,
@@ -512,7 +558,7 @@ const evaluateLive = (
512
558
  }
513
559
  };
514
560
 
515
- const evaluateOnLasso = (
561
+ export const evaluateOnLasso = (
516
562
  expression: LiveExpression,
517
563
  path: Value[][],
518
564
  cycleStart: number,
@@ -547,472 +593,3 @@ const evaluateOnLasso = (
547
593
  );
548
594
  }
549
595
  };
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
- };