tla-ts 0.0.1 → 0.0.3-dev.19c763f

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 (74) hide show
  1. package/README.md +98 -39
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.d.cts +225 -30
  4. package/dist/index.d.ts +225 -30
  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 +21 -1
  11. package/dist/run-cli.js +21 -1
  12. package/dist/transfer.cjs +400 -39
  13. package/dist/transfer.js +400 -39
  14. package/package.json +6 -2
  15. package/src/ast.ts +213 -6
  16. package/src/bags.ts +161 -71
  17. package/src/builtins.ts +203 -23
  18. package/src/bundled-modules.ts +63 -32
  19. package/src/check.ts +1086 -244
  20. package/src/cli-options.ts +64 -0
  21. package/src/codegen.ts +58 -34
  22. package/src/config.ts +39 -11
  23. package/src/dependencies.ts +2 -2
  24. package/src/environment.ts +557 -153
  25. package/src/errors.ts +66 -1
  26. package/src/evaluate.ts +547 -255
  27. package/src/exit-codes.ts +53 -0
  28. package/src/fingerprints.ts +48 -13
  29. package/src/index.ts +9 -4
  30. package/src/instances.ts +235 -79
  31. package/src/java-overrides.ts +241 -0
  32. package/src/json.ts +153 -72
  33. package/src/levels.ts +850 -0
  34. package/src/lexer.ts +108 -29
  35. package/src/live-check.ts +710 -0
  36. package/src/liveness.ts +37 -599
  37. package/src/obligation-action.ts +384 -0
  38. package/src/obligation-anon.ts +575 -0
  39. package/src/obligation-deref.ts +637 -0
  40. package/src/obligation-expression.ts +1060 -0
  41. package/src/obligation-format.ts +406 -0
  42. package/src/obligation-generate.ts +1074 -0
  43. package/src/obligation-levels.ts +329 -0
  44. package/src/obligation-module.ts +1042 -0
  45. package/src/obligation-printer.ts +889 -0
  46. package/src/obligation-proof.ts +76 -0
  47. package/src/obligation-source.ts +1084 -0
  48. package/src/obligation-tuples.ts +184 -0
  49. package/src/obligations.ts +316 -0
  50. package/src/parallel-worker.ts +186 -201
  51. package/src/parallel.ts +179 -84
  52. package/src/parser.ts +970 -206
  53. package/src/pretty-print.ts +259 -0
  54. package/src/randomization.ts +24 -113
  55. package/src/resolve.ts +483 -51
  56. package/src/run-cli.ts +473 -62
  57. package/src/runtime.ts +65 -28
  58. package/src/spec-description.ts +521 -0
  59. package/src/standard-levels.ts +105 -0
  60. package/src/standard-modules.ts +223 -92
  61. package/src/state-graph.ts +157 -0
  62. package/src/subexpressions.ts +31 -45
  63. package/src/substitution-levels.ts +184 -0
  64. package/src/successors.ts +276 -53
  65. package/src/symmetry.ts +79 -23
  66. package/src/tableau.ts +43 -37
  67. package/src/tlc-ext.ts +148 -44
  68. package/src/tlc-module.ts +71 -66
  69. package/src/tlc-modules.ts +1022 -0
  70. package/src/tlc-order.ts +511 -0
  71. package/src/tlc-random.ts +411 -0
  72. package/src/tlc-summary.ts +109 -0
  73. package/src/transfer.ts +26 -5
  74. package/src/values.ts +1245 -176
package/src/liveness.ts CHANGED
@@ -1,13 +1,13 @@
1
- import type { Definition, Expression, SourceLocation } from "./ast";
1
+ import { isLocallyResolved, type Definition, type Expression } from "./ast";
2
2
  import { TlaConfigError, TlaEvaluationError } from "./errors";
3
3
  import {
4
+ describeLocation,
4
5
  bindDefinitions,
5
6
  bindOperatorArguments,
6
7
  evaluate,
7
8
  expectBoolean,
8
9
  forEachBinding,
9
10
  getDefinition,
10
- isLocallyResolved,
11
11
  lookupScope,
12
12
  resolveApplyOperator,
13
13
  resolveGlobalOperator,
@@ -18,22 +18,18 @@ import {
18
18
  type Thunk,
19
19
  } from "./evaluate";
20
20
  import { mapChildren } from "./instances";
21
+ import { ACTION_LEVEL, TEMPORAL_LEVEL } from "./levels";
21
22
  import { isEnabled } from "./successors";
22
23
  import {
24
+ createBoolean,
23
25
  createJunction,
24
26
  createPair,
25
27
  createUnary,
26
- FALSE,
27
28
  getLiveLevel,
28
- getSolutions,
29
- isFulfilling,
30
- TRUE,
31
29
  type LiveEnabled,
32
30
  type LiveExpression,
33
- type Solution,
34
- type Tableau,
35
31
  } from "./tableau";
36
- import { isSameValue, type Value } from "./values";
32
+ import type { Value } from "./values";
37
33
 
38
34
  export interface ScopedExpression {
39
35
  expression: Expression;
@@ -44,54 +40,6 @@ export interface TemporalProperty extends ScopedExpression {
44
40
  name: string;
45
41
  }
46
42
 
47
- export interface LiveSuccessor {
48
- index: number;
49
- state: Value[];
50
- }
51
-
52
- export interface Lasso {
53
- name: string;
54
- prefix: number[];
55
- cycle: number[];
56
- }
57
-
58
- export interface SafetyViolation {
59
- name: string;
60
- path: number[];
61
- }
62
-
63
- export interface LivenessChecker {
64
- addInitialState: (index: number, state: Value[]) => void;
65
- addState: (
66
- index: number,
67
- state: Value[],
68
- successors: LiveSuccessor[],
69
- ) => SafetyViolation | undefined;
70
- findViolation: () => Lasso | undefined;
71
- }
72
-
73
- interface Check {
74
- solution: Solution;
75
- stateResults: Uint8Array[];
76
- actionResults: Uint8Array[];
77
- consistency: Uint8Array[];
78
- product: BehaviorGraph | undefined;
79
- productNodes: Map<number, number>;
80
- nodesByState: Map<number, number[]>;
81
- }
82
-
83
- interface BehaviorGraph {
84
- states: number[];
85
- tableauNodes: number[];
86
- edges: number[][];
87
- initial: number[];
88
- parents: number[];
89
- }
90
-
91
- export const ACTION_LEVEL = 2;
92
-
93
- export const TEMPORAL_LEVEL = 3;
94
-
95
43
  const MAXIMUM_EXPANSION_DEPTH = 100;
96
44
 
97
45
  const TEMPORAL_OPERATORS = new Set(["~>", "-+->"]);
@@ -107,9 +55,6 @@ const getConstantContext = (environment: Environment, scope: Scope | undefined):
107
55
  next: undefined,
108
56
  });
109
57
 
110
- const describeLocation = (expression: Expression) =>
111
- `line ${expression.location.line}, column ${expression.location.column}`;
112
-
113
58
  const createCannotHandleError = (expression: Expression) =>
114
59
  new TlaEvaluationError(
115
60
  `TLC cannot handle the temporal formula at ${describeLocation(expression)}`,
@@ -121,7 +66,7 @@ export const getLevel = (
121
66
  environment: Environment,
122
67
  shadowed = new Set<string>(),
123
68
  ): number => {
124
- const getBindingLevel = (name: string): number | undefined => {
69
+ const getBindingLevel = (name: string) => {
125
70
  const binding = lookupScope(scope, name);
126
71
  if (!binding) return undefined;
127
72
  if (binding.kind === "Value") return 0;
@@ -129,7 +74,7 @@ export const getLevel = (
129
74
  const operator = binding.operator;
130
75
  return operator.kind === "Closure" ? getLevel(operator.body, operator.scope, environment) : 0;
131
76
  };
132
- const getGlobalLevel = (name: string): number | undefined => {
77
+ const getGlobalLevel = (name: string) => {
133
78
  if (environment.variableIndex.has(name)) return 1;
134
79
  if (environment.constants.has(name)) return 0;
135
80
  const definition = getDefinition(name, environment);
@@ -186,7 +131,7 @@ export const getLevel = (
186
131
  }
187
132
  };
188
133
 
189
- const getDefinitionLevel = (definition: Definition, environment: Environment): number => {
134
+ const getDefinitionLevel = (definition: Definition, environment: Environment) => {
190
135
  const cached = definitionLevels.get(definition);
191
136
  if (cached !== undefined) return cached;
192
137
  definitionLevels.set(definition, 0);
@@ -203,34 +148,40 @@ export const expandTemporal = (
203
148
  expression: Expression,
204
149
  scope: Scope | undefined,
205
150
  environment: Environment,
151
+ isUnrollingForall: boolean,
206
152
  expanding = new Set<Definition>(),
207
153
  ): ScopedExpression[] => {
154
+ const expand = (
155
+ child: Expression,
156
+ childScope: Scope | undefined,
157
+ childExpanding = expanding,
158
+ ): ScopedExpression[] =>
159
+ expandTemporal(child, childScope, environment, isUnrollingForall, childExpanding);
208
160
  if (expression.kind === "And") {
209
- return expression.operands.flatMap((operand) =>
210
- expandTemporal(operand, scope, environment, expanding),
211
- );
161
+ return expression.operands.flatMap((operand) => expand(operand, scope));
212
162
  }
213
- if (expression.kind === "Label") {
214
- return expandTemporal(expression.body, scope, environment, expanding);
163
+ if (expression.kind === "Label") return expand(expression.body, scope);
164
+ if (expression.kind === "Let") {
165
+ return expand(expression.body, bindLetDefinitions(expression, scope, environment));
215
166
  }
216
167
  if (expression.kind === "Identifier") {
217
168
  const binding = isLocallyResolved(expression) ? lookupScope(scope, expression.name) : undefined;
218
169
  if (binding?.kind === "Thunk") {
219
- return expandTemporal(binding.expression, binding.scope, environment, expanding);
170
+ return expand(binding.expression, binding.scope);
220
171
  }
221
172
  const definition = environment.constants.has(expression.name)
222
173
  ? undefined
223
174
  : getDefinition(expression.name, environment);
224
- if (!binding && definition?.kind === "Operator" && definition.params.length === 0) {
175
+ if (
176
+ !binding &&
177
+ definition?.kind === "Operator" &&
178
+ definition.params.length === 0 &&
179
+ getDefinitionLevel(definition, environment) > 0
180
+ ) {
225
181
  if (expanding.has(definition)) {
226
182
  throw new TlaConfigError(`The definition of ${expression.name} refers to itself`);
227
183
  }
228
- return expandTemporal(
229
- definition.body,
230
- undefined,
231
- environment,
232
- new Set([...expanding, definition]),
233
- );
184
+ return expand(definition.body, undefined, new Set([...expanding, definition]));
234
185
  }
235
186
  }
236
187
  const context = getConstantContext(environment, scope);
@@ -240,22 +191,18 @@ export const expandTemporal = (
240
191
  ? undefined
241
192
  : getDefinition(expression.operator, environment);
242
193
  if (operator?.kind === "Closure" && !definition?.isRecursive) {
243
- return expandTemporal(
244
- operator.body,
245
- bindOperatorArguments(operator, expression.args, context),
246
- environment,
247
- expanding,
248
- );
194
+ return expand(operator.body, bindOperatorArguments(operator, expression.args, context));
249
195
  }
250
196
  }
251
197
  const isUnrolled =
198
+ isUnrollingForall &&
252
199
  expression.kind === "Forall" &&
253
200
  getLevel(expression.body, scope, environment) === TEMPORAL_LEVEL &&
254
201
  expression.bounds.every((bound) => getLevel(bound.set, scope, environment) === 0);
255
- if (expression.kind === "Forall" && isUnrolled) {
202
+ if (isUnrolled) {
256
203
  const expanded: ScopedExpression[] = [];
257
204
  forEachBinding(expression.bounds, context, (boundScope) => {
258
- expanded.push(...expandTemporal(expression.body, boundScope, environment, expanding));
205
+ expanded.push(...expand(expression.body, boundScope));
259
206
  return false;
260
207
  });
261
208
  return expanded;
@@ -263,52 +210,6 @@ export const expandTemporal = (
263
210
  return [{ expression, scope }];
264
211
  };
265
212
 
266
- const toLiteral = (value: Value, location: SourceLocation): Expression | undefined => {
267
- if (typeof value === "number") return { kind: "Number", value, location };
268
- if (typeof value === "string") return { kind: "String", value, location };
269
- if (typeof value === "boolean") {
270
- return { kind: "Identifier", name: value ? "TRUE" : "FALSE", location };
271
- }
272
- return undefined;
273
- };
274
-
275
- export const toUnscopedExpression = (
276
- expression: Expression,
277
- scope: Scope | undefined,
278
- ): Expression | undefined => {
279
- const definitions: Definition[] = [];
280
- for (let current = scope; current; current = current.parent) {
281
- const binding = current.binding;
282
- const closure =
283
- binding.kind === "Operator" && binding.operator.kind === "Closure"
284
- ? binding.operator
285
- : undefined;
286
- const body =
287
- binding.kind === "Thunk"
288
- ? binding.expression
289
- : binding.kind === "Value"
290
- ? toLiteral(binding.value, expression.location)
291
- : closure?.body;
292
- const isUnscoped =
293
- binding.kind === "Thunk"
294
- ? binding.scope === undefined
295
- : binding.kind === "Value" || closure?.scope === undefined;
296
- if (!body || !isUnscoped) return undefined;
297
- definitions.unshift({
298
- kind: "Operator",
299
- name: current.name,
300
- params: closure?.params ?? [],
301
- body,
302
- isLocal: true,
303
- isRecursive: false,
304
- location: body.location,
305
- });
306
- }
307
- return definitions.length === 0
308
- ? expression
309
- : { kind: "Let", definitions, body: expression, location: expression.location };
310
- };
311
-
312
213
  const bindLetDefinitions = (
313
214
  expression: Expression & { kind: "Let" },
314
215
  scope: Scope | undefined,
@@ -328,7 +229,7 @@ const createAngleAction = (action: Expression, subscript: Expression): Expressio
328
229
  location: action.location,
329
230
  });
330
231
 
331
- const toLiveExpression = (
232
+ export const toLiveExpression = (
332
233
  root: Expression,
333
234
  rootScope: Scope | undefined,
334
235
  environment: Environment,
@@ -346,7 +247,7 @@ const toLiveExpression = (
346
247
  `TLC expected a boolean in the temporal formula at ${describeLocation(expression)}`,
347
248
  );
348
249
  }
349
- return value ? TRUE : FALSE;
250
+ return createBoolean(value);
350
251
  }
351
252
  if (atomLevel === 1) return { kind: "State", expression, scope };
352
253
  return { kind: "Action", expression, unchanged: undefined, scope };
@@ -375,7 +276,7 @@ const toLiveExpression = (
375
276
  const convertCall = (
376
277
  expression: Expression & { kind: "Identifier" | "Apply" },
377
278
  scope: Scope | undefined,
378
- ): LiveExpression => {
279
+ ) => {
379
280
  const name = expression.kind === "Identifier" ? expression.name : expression.operator;
380
281
  const context = getConstantContext(environment, scope);
381
282
  const binding =
@@ -412,7 +313,7 @@ const toLiveExpression = (
412
313
  return false;
413
314
  });
414
315
  const isForall = expression.kind === "Forall";
415
- if (operands.length === 0) return isForall ? TRUE : FALSE;
316
+ if (operands.length === 0) return createBoolean(isForall);
416
317
  const result = createJunction(isForall ? "And" : "Or", operands);
417
318
  const level = getLiveLevel(result);
418
319
  return level > ACTION_LEVEL ? result : toAtom(expression, scope, level);
@@ -514,7 +415,7 @@ const toLiveExpression = (
514
415
  return convert(root, rootScope);
515
416
  };
516
417
 
517
- const evaluateLive = (
418
+ export const evaluateLive = (
518
419
  expression: LiveExpression,
519
420
  state: Value[],
520
421
  next: Value[] | undefined,
@@ -562,7 +463,7 @@ const evaluateLive = (
562
463
  }
563
464
  };
564
465
 
565
- const evaluateOnLasso = (
466
+ export const evaluateOnLasso = (
566
467
  expression: LiveExpression,
567
468
  path: Value[][],
568
469
  cycleStart: number,
@@ -597,466 +498,3 @@ const evaluateOnLasso = (
597
498
  );
598
499
  }
599
500
  };
600
-
601
- const liveKeys = new WeakMap<LiveExpression, string>();
602
-
603
- const atomCount = { value: 0 };
604
-
605
- const getLiveKey = (expression: LiveExpression): string => {
606
- const cached = liveKeys.get(expression);
607
- if (cached !== undefined) return cached;
608
- const key =
609
- expression.kind === "Boolean"
610
- ? String(expression.value)
611
- : "body" in expression
612
- ? `${expression.kind}(${getLiveKey(expression.body)})`
613
- : "operands" in expression
614
- ? `${expression.kind}(${expression.operands.map(getLiveKey).join(",")})`
615
- : `${expression.kind}#${atomCount.value++}`;
616
- liveKeys.set(expression, key);
617
- return key;
618
- };
619
-
620
- const isSameState = (left: Value[], right: Value[]) =>
621
- left.every((value, position) => isSameValue(value, right[position]));
622
-
623
- const getStronglyConnectedComponents = (
624
- nodeCount: number,
625
- getSuccessors: (node: number) => number[],
626
- visit: (component: number[], successors: (node: number) => number[]) => boolean,
627
- ) => {
628
- const order = new Int32Array(nodeCount).fill(-1);
629
- const lowLink = new Int32Array(nodeCount);
630
- const onStack = new Uint8Array(nodeCount);
631
- const stack: number[] = [];
632
- const counter = { value: 0 };
633
- const successorCache = new Map<number, number[]>();
634
- const getCachedSuccessors = (node: number) => {
635
- const cached = successorCache.get(node);
636
- if (cached) return cached;
637
- const successors = getSuccessors(node);
638
- successorCache.set(node, successors);
639
- return successors;
640
- };
641
- for (let root = 0; root < nodeCount; root++) {
642
- if (order[root] !== -1) continue;
643
- const frames: { node: number; position: number }[] = [];
644
- const open = (node: number) => {
645
- order[node] = counter.value;
646
- lowLink[node] = counter.value++;
647
- stack.push(node);
648
- onStack[node] = 1;
649
- frames.push({ node, position: 0 });
650
- };
651
- open(root);
652
- while (frames.length > 0) {
653
- const frame = frames[frames.length - 1];
654
- const successors = getCachedSuccessors(frame.node);
655
- if (frame.position < successors.length) {
656
- const target = successors[frame.position++];
657
- if (order[target] === -1) open(target);
658
- else if (onStack[target])
659
- lowLink[frame.node] = Math.min(lowLink[frame.node], order[target]);
660
- continue;
661
- }
662
- frames.pop();
663
- const parent = frames[frames.length - 1];
664
- if (parent) lowLink[parent.node] = Math.min(lowLink[parent.node], lowLink[frame.node]);
665
- if (lowLink[frame.node] !== order[frame.node]) continue;
666
- const component: number[] = [];
667
- while (true) {
668
- const member = stack.pop();
669
- if (member === undefined) break;
670
- onStack[member] = 0;
671
- component.push(member);
672
- if (member === frame.node) break;
673
- }
674
- const isFound = visit(component, getCachedSuccessors);
675
- component.forEach((member) => successorCache.delete(member));
676
- if (isFound) return;
677
- }
678
- }
679
- };
680
-
681
- const getShortestPath = (
682
- from: number,
683
- to: number,
684
- members: Set<number>,
685
- getSuccessors: (node: number) => number[],
686
- ) => {
687
- if (from === to) return [from];
688
- const parents = new Map<number, number>([[from, -1]]);
689
- const queue = [from];
690
- for (let position = 0; position < queue.length; position++) {
691
- for (const target of getSuccessors(queue[position])) {
692
- if (parents.has(target) || !members.has(target)) continue;
693
- parents.set(target, queue[position]);
694
- if (target === to) {
695
- const path: number[] = [];
696
- for (let node = to; node !== -1; node = parents.get(node) ?? -1) path.push(node);
697
- return path.reverse();
698
- }
699
- queue.push(target);
700
- }
701
- }
702
- return [from];
703
- };
704
-
705
- const removeRepeats = (path: number[]) =>
706
- path.filter((node, position) => position === 0 || path[position - 1] !== node);
707
-
708
- export const createLivenessChecker = (
709
- properties: TemporalProperty[],
710
- temporals: ScopedExpression[],
711
- environment: Environment,
712
- ): LivenessChecker | undefined => {
713
- if (properties.length === 0) return undefined;
714
- const fairness = temporals.map((item) =>
715
- toLiveExpression(item.expression, item.scope, environment),
716
- );
717
- const negations = properties.map((property) =>
718
- createUnary("Not", toLiveExpression(property.expression, property.scope, environment)),
719
- );
720
- const violation = negations.length === 1 ? negations[0] : createJunction("Or", negations);
721
- const formula =
722
- fairness.length === 0 ? violation : createJunction("And", [...fairness, violation]);
723
- const solutions = getSolutions(formula);
724
- if (solutions.length === 0) {
725
- throw new TlaEvaluationError("Temporal formula is a tautology (its negation is unsatisfiable)");
726
- }
727
- const checks = solutions.map((solution): Check => ({
728
- solution,
729
- stateResults: [],
730
- actionResults: [],
731
- consistency: [],
732
- product: solution.tableau && {
733
- states: [],
734
- tableauNodes: [],
735
- edges: [],
736
- initial: [],
737
- parents: [],
738
- },
739
- productNodes: new Map(),
740
- nodesByState: new Map(),
741
- }));
742
- const actionKeys = new Map<string, number>();
743
- const actionIds = checks.map((check) =>
744
- check.solution.actionChecks.map((predicate) => {
745
- const key = getLiveKey(predicate);
746
- const known = actionKeys.get(key);
747
- if (known !== undefined) return known;
748
- actionKeys.set(key, actionKeys.size);
749
- return actionKeys.size - 1;
750
- }),
751
- );
752
- const states: Value[][] = [];
753
- const targets: number[][] = [];
754
- const edgeStates: Value[][][] = [];
755
- const initial: number[] = [];
756
-
757
- const isConsistent = (
758
- predicates: LiveExpression[],
759
- state: Value[],
760
- cache: Map<LiveExpression, boolean>,
761
- ) =>
762
- predicates.every((predicate) => evaluateLive(predicate, state, undefined, environment, cache));
763
-
764
- const getProductNode = (
765
- check: Check,
766
- product: BehaviorGraph,
767
- state: number,
768
- tableauNode: number,
769
- parent: number,
770
- ) => {
771
- const key = state * (check.solution.tableau?.nodes.length ?? 1) + tableauNode;
772
- const existing = check.productNodes.get(key);
773
- if (existing !== undefined) return { node: existing, isNew: false };
774
- const node = product.states.length;
775
- check.productNodes.set(key, node);
776
- product.states.push(state);
777
- product.tableauNodes.push(tableauNode);
778
- product.edges.push([]);
779
- product.parents.push(parent);
780
- const siblings = check.nodesByState.get(state);
781
- if (siblings) siblings.push(node);
782
- else check.nodesByState.set(state, [node]);
783
- return { node, isNew: true };
784
- };
785
-
786
- const getAttribution = (path: number[], cycleStart: number) => {
787
- const lasso = path.map((state) => states[state]);
788
- return (
789
- properties.find(
790
- (_, position) =>
791
- !evaluateOnLasso(negations[position].body, lasso, cycleStart, 0, environment),
792
- ) ?? properties[0]
793
- ).name;
794
- };
795
-
796
- const expandProduct = (check: Check, product: BehaviorGraph, tableau: Tableau, state: number) => {
797
- const hasEmptyModel = check.solution.models.some(
798
- (model) =>
799
- model.eventuallyAlways.length === 0 &&
800
- model.infinitelyOftenStates.length === 0 &&
801
- model.infinitelyOftenActions.length === 0,
802
- );
803
- const nodeCount = tableau.nodes.length;
804
- const pending = (check.nodesByState.get(state) ?? []).map((node) => ({ node, isDone: false }));
805
- while (pending.length > 0) {
806
- const item = pending.pop();
807
- if (!item) break;
808
- const source = product.states[item.node];
809
- const successors = tableau.nodes[product.tableauNodes[item.node]].successors;
810
- const isAccepted =
811
- item.isDone &&
812
- hasEmptyModel &&
813
- successors.some((successor) => {
814
- const node = tableau.nodes[successor];
815
- return node.particle.length === 0 && node.successors.every((next) => next === successor);
816
- });
817
- if (isAccepted) {
818
- const path = removeRepeats(
819
- getPrefix(product, item.node).map((node) => product.states[node]),
820
- );
821
- return { name: getAttribution(path, path.length - 1), path };
822
- }
823
- const consistency = check.consistency[source];
824
- targets[source].forEach((target, edgeIndex) => {
825
- for (const successor of successors) {
826
- if (!consistency[edgeIndex * nodeCount + successor]) continue;
827
- const created = getProductNode(check, product, target, successor, item.node);
828
- product.edges[item.node].push(created.node, edgeIndex);
829
- if (created.isNew && targets[target] !== undefined) {
830
- pending.push({ node: created.node, isDone: true });
831
- }
832
- }
833
- });
834
- }
835
- return undefined;
836
- };
837
-
838
- const addInitialState = (index: number, state: Value[]) => {
839
- initial.push(index);
840
- states[index] = state;
841
- for (const check of checks) {
842
- const tableau = check.solution.tableau;
843
- const product = check.product;
844
- if (!tableau || !product) continue;
845
- const cache = new Map<LiveExpression, boolean>();
846
- for (let node = 0; node < tableau.initialCount; node++) {
847
- if (!isConsistent(tableau.nodes[node].statePredicates, state, cache)) continue;
848
- product.initial.push(getProductNode(check, product, index, node, -1).node);
849
- }
850
- }
851
- };
852
-
853
- const addState = (index: number, state: Value[], successors: LiveSuccessor[]) => {
854
- states[index] = state;
855
- const edges: LiveSuccessor[] = [];
856
- const edgesByTarget = new Map<number, LiveSuccessor[]>();
857
- for (const successor of [...successors, { index, state }]) {
858
- const sameTarget = edgesByTarget.get(successor.index);
859
- const isDuplicate =
860
- sameTarget !== undefined &&
861
- (successor.index < index ||
862
- sameTarget.some((edge) => isSameState(edge.state, successor.state)));
863
- if (isDuplicate) continue;
864
- edges.push(successor);
865
- if (sameTarget) sameTarget.push(successor);
866
- else edgesByTarget.set(successor.index, [successor]);
867
- }
868
- targets[index] = edges.map((edge) => edge.index);
869
- edgeStates[index] = edges.map((edge) => edge.state);
870
- const stateCache = new Map<LiveExpression, boolean>();
871
- const successorCaches = edges.map(() => new Map<LiveExpression, boolean>());
872
- for (const check of checks) {
873
- const solution = check.solution;
874
- check.stateResults[index] = Uint8Array.from(solution.stateChecks, (predicate) =>
875
- evaluateLive(predicate, state, undefined, environment, stateCache) ? 1 : 0,
876
- );
877
- const tableau = solution.tableau;
878
- const product = check.product;
879
- if (!tableau || !product) continue;
880
- const nodeCount = tableau.nodes.length;
881
- const consistency = new Uint8Array(edges.length * nodeCount);
882
- edges.forEach((edge, edgeIndex) => {
883
- tableau.nodes.forEach((node, nodeIndex) => {
884
- const isTrue = isConsistent(node.statePredicates, edge.state, successorCaches[edgeIndex]);
885
- consistency[edgeIndex * nodeCount + nodeIndex] = isTrue ? 1 : 0;
886
- });
887
- });
888
- check.consistency[index] = consistency;
889
- const accepted = expandProduct(check, product, tableau, index);
890
- if (accepted) return accepted;
891
- }
892
- return undefined;
893
- };
894
-
895
- const computeActionResults = (source: number) => {
896
- const state = states[source];
897
- const successors = edgeStates[source];
898
- const values = successors.map(() => new Int8Array(actionKeys.size).fill(-1));
899
- checks.forEach((check, checkIndex) => {
900
- const solution = check.solution;
901
- const ids = actionIds[checkIndex];
902
- const stateResults = check.stateResults[source];
903
- const stateCache = new Map(
904
- solution.stateChecks.map((predicate, position) => [
905
- predicate,
906
- stateResults[position] === 1,
907
- ]),
908
- );
909
- const actionCount = solution.actionChecks.length;
910
- const actions = new Uint8Array(successors.length * actionCount);
911
- successors.forEach((successor, edgeIndex) => {
912
- const known = values[edgeIndex];
913
- for (let position = 0; position < actionCount; position++) {
914
- const id = ids[position];
915
- if (known[id] === -1) {
916
- const predicate = solution.actionChecks[position];
917
- known[id] = evaluateLive(predicate, state, successor, environment, stateCache) ? 1 : 0;
918
- }
919
- actions[edgeIndex * actionCount + position] = known[id];
920
- }
921
- });
922
- check.actionResults[source] = actions;
923
- });
924
- };
925
-
926
- const getActionResults = (check: Check, source: number) => {
927
- if (check.actionResults[source] === undefined) computeActionResults(source);
928
- return check.actionResults[source];
929
- };
930
-
931
- const getGraph = (check: Check): BehaviorGraph =>
932
- check.product ?? {
933
- states: states.map((_, index) => index),
934
- tableauNodes: states.map(() => -1),
935
- edges: targets.map((list) => list.flatMap((target, edgeIndex) => [target, edgeIndex])),
936
- initial,
937
- parents: [],
938
- };
939
-
940
- const getPrefix = (graph: BehaviorGraph, entry: number) => {
941
- if (graph.parents.length > 0) {
942
- const path: number[] = [];
943
- for (let node = entry; node !== -1; node = graph.parents[node]) path.push(node);
944
- return path.reverse();
945
- }
946
- const parents = new Map<number, number>(graph.initial.map((node) => [node, -1]));
947
- const queue = [...graph.initial];
948
- for (let position = 0; position < queue.length && !parents.has(entry); position++) {
949
- const edges = graph.edges[queue[position]];
950
- for (let offset = 0; offset < edges.length; offset += 2) {
951
- if (parents.has(edges[offset])) continue;
952
- parents.set(edges[offset], queue[position]);
953
- queue.push(edges[offset]);
954
- }
955
- }
956
- const path: number[] = [];
957
- for (let node = entry; node !== -1; node = parents.get(node) ?? -1) path.push(node);
958
- return path.reverse();
959
- };
960
-
961
- const findInCheck = (check: Check): Lasso | undefined => {
962
- const solution = check.solution;
963
- const tableau = solution.tableau;
964
- const graph = getGraph(check);
965
- const actionCount = solution.actionChecks.length;
966
- const getAction = (node: number, edgeIndex: number, position: number) =>
967
- getActionResults(check, graph.states[node])[edgeIndex * actionCount + position] === 1;
968
- for (const model of solution.models) {
969
- const isAllowed = (node: number, edgeIndex: number) =>
970
- model.eventuallyAlways.every((position) => getAction(node, edgeIndex, position));
971
- const getSuccessors = (node: number) => {
972
- const edges = graph.edges[node];
973
- const successors: number[] = [];
974
- for (let offset = 0; offset < edges.length; offset += 2) {
975
- if (isAllowed(node, edges[offset + 1])) successors.push(edges[offset]);
976
- }
977
- return successors;
978
- };
979
- const lasso = { value: undefined as Lasso | undefined };
980
- getStronglyConnectedComponents(
981
- graph.states.length,
982
- getSuccessors,
983
- (component, successors) => {
984
- const members = new Set(component);
985
- if (component.length === 1 && !successors(component[0]).includes(component[0]))
986
- return false;
987
- const stateWitnesses = model.infinitelyOftenStates.map((position) =>
988
- component.find((node) => check.stateResults[graph.states[node]][position] === 1),
989
- );
990
- const actionWitnesses = model.infinitelyOftenActions.map((position) => {
991
- for (const node of component) {
992
- const edges = graph.edges[node];
993
- for (let offset = 0; offset < edges.length; offset += 2) {
994
- const isWitness =
995
- members.has(edges[offset]) &&
996
- isAllowed(node, edges[offset + 1]) &&
997
- getAction(node, edges[offset + 1], position);
998
- if (isWitness) return [node, edges[offset]];
999
- }
1000
- }
1001
- return undefined;
1002
- });
1003
- const promiseWitnesses = solution.promises.map((promise) =>
1004
- component.find(
1005
- (node) =>
1006
- tableau !== undefined &&
1007
- isFulfilling(tableau.nodes[graph.tableauNodes[node]].particle, promise),
1008
- ),
1009
- );
1010
- const isViolation =
1011
- stateWitnesses.every((witness) => witness !== undefined) &&
1012
- actionWitnesses.every((witness) => witness !== undefined) &&
1013
- promiseWitnesses.every((witness) => witness !== undefined);
1014
- if (!isViolation) return false;
1015
- const entry = component[component.length - 1];
1016
- const waypoints = [
1017
- ...stateWitnesses.flatMap((witness) => (witness === undefined ? [] : [witness])),
1018
- ...actionWitnesses.flatMap((witness) => witness ?? []),
1019
- ...promiseWitnesses.flatMap((witness) => (witness === undefined ? [] : [witness])),
1020
- ];
1021
- const cycle = [entry];
1022
- for (const waypoint of waypoints) {
1023
- cycle.push(
1024
- ...getShortestPath(cycle[cycle.length - 1], waypoint, members, successors).slice(1),
1025
- );
1026
- }
1027
- if (cycle.length === 1 && !successors(entry).includes(entry)) {
1028
- cycle.push(successors(entry).find((node) => members.has(node)) ?? entry);
1029
- }
1030
- const closing = getShortestPath(cycle[cycle.length - 1], entry, members, successors);
1031
- cycle.push(...closing.slice(1, -1));
1032
- const prefix = removeRepeats(getPrefix(graph, entry).map((node) => graph.states[node]));
1033
- const cycleStates = removeRepeats(cycle.map((node) => graph.states[node]));
1034
- if (cycleStates.length > 1 && cycleStates[cycleStates.length - 1] === cycleStates[0]) {
1035
- cycleStates.pop();
1036
- }
1037
- prefix.pop();
1038
- lasso.value = {
1039
- name: getAttribution([...prefix, ...cycleStates], prefix.length),
1040
- prefix,
1041
- cycle: cycleStates,
1042
- };
1043
- return true;
1044
- },
1045
- );
1046
- if (lasso.value) return lasso.value;
1047
- }
1048
- return undefined;
1049
- };
1050
-
1051
- return {
1052
- addInitialState,
1053
- addState,
1054
- findViolation: () => {
1055
- for (const check of checks) {
1056
- const lasso = findInCheck(check);
1057
- if (lasso) return lasso;
1058
- }
1059
- return undefined;
1060
- },
1061
- };
1062
- };