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

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 (84) hide show
  1. package/README.md +16 -2
  2. package/dist/cli.cjs +1 -1
  3. package/dist/cli.js +1 -1
  4. package/dist/index.cjs +1 -1
  5. package/dist/index.d.cts +159 -8
  6. package/dist/index.d.ts +159 -8
  7. package/dist/index.js +1 -1
  8. package/dist/parallel-worker.cjs +1 -1
  9. package/dist/parallel-worker.js +2 -2
  10. package/dist/parallel.cjs +1 -1
  11. package/dist/parallel.js +2 -2
  12. package/dist/run-cli.cjs +1351 -19
  13. package/dist/run-cli.js +1351 -19
  14. package/dist/transfer.cjs +88 -18
  15. package/dist/transfer.js +88 -18
  16. package/package.json +5 -1
  17. package/src/ast.ts +147 -6
  18. package/src/bags.ts +4 -7
  19. package/src/builtins.ts +29 -11
  20. package/src/bundled-modules.ts +3 -3
  21. package/src/canonical.ts +4 -3
  22. package/src/check.ts +1539 -235
  23. package/src/cli-options.ts +11 -5
  24. package/src/cli.ts +8 -1
  25. package/src/codegen.ts +77 -37
  26. package/src/config.ts +254 -181
  27. package/src/dependencies.ts +2 -2
  28. package/src/environment.ts +524 -140
  29. package/src/errors.ts +224 -3
  30. package/src/evaluate.ts +796 -246
  31. package/src/exit-codes.ts +22 -43
  32. package/src/index.ts +1 -0
  33. package/src/instances.ts +19 -16
  34. package/src/java-overrides.ts +104 -25
  35. package/src/levels.ts +191 -45
  36. package/src/lexer.ts +127 -30
  37. package/src/live-check.ts +828 -0
  38. package/src/liveness.ts +218 -572
  39. package/src/obligation-expression.ts +2 -2
  40. package/src/obligation-source.ts +2 -0
  41. package/src/parallel-worker.ts +13 -4
  42. package/src/parallel.ts +73 -6
  43. package/src/parser.ts +456 -147
  44. package/src/pcal-ast.ts +770 -0
  45. package/src/pcal-parse.ts +1523 -0
  46. package/src/pcal-tokenize.ts +516 -0
  47. package/src/pcal-translate.ts +1230 -0
  48. package/src/pcal-validate.ts +454 -0
  49. package/src/randomization.ts +24 -7
  50. package/src/resolve.ts +1481 -426
  51. package/src/run-cli.ts +1200 -143
  52. package/src/runtime.ts +19 -1
  53. package/src/sany-builtins.ts +147 -0
  54. package/src/sany-generator.ts +3128 -0
  55. package/src/sany-levels.ts +1208 -0
  56. package/src/sany-lexer.ts +545 -0
  57. package/src/sany-linter.ts +122 -0
  58. package/src/sany-modules.ts +1398 -0
  59. package/src/sany-nodes.ts +463 -0
  60. package/src/sany-parse-error.ts +2161 -0
  61. package/src/sany-report.ts +356 -0
  62. package/src/sany-selectors.ts +738 -0
  63. package/src/sany-source.ts +248 -0
  64. package/src/sany-xml.ts +1017 -0
  65. package/src/spec-description.ts +42 -11
  66. package/src/standard-modules.ts +200 -148
  67. package/src/standard-ranges.ts +116 -0
  68. package/src/state-graph.ts +180 -0
  69. package/src/subexpressions.ts +231 -171
  70. package/src/substitution-levels.ts +38 -17
  71. package/src/successors.ts +219 -107
  72. package/src/symmetry.ts +180 -52
  73. package/src/tableau.ts +54 -25
  74. package/src/tlc-ext.ts +42 -29
  75. package/src/tlc-messages.ts +329 -0
  76. package/src/tlc-module.ts +52 -43
  77. package/src/tlc-order.ts +73 -9
  78. package/src/tlc-random.ts +37 -9
  79. package/src/tlc-replay.ts +655 -0
  80. package/src/tlc-summary.ts +20 -5
  81. package/src/tlc-version.ts +18 -0
  82. package/src/transfer.ts +15 -3
  83. package/src/value-sources.ts +29 -0
  84. package/src/values.ts +724 -180
package/src/liveness.ts CHANGED
@@ -1,14 +1,16 @@
1
- import type { Definition, Expression } from "./ast";
2
- import { TlaConfigError, TlaEvaluationError } from "./errors";
1
+ import { isLocallyResolved, type Bound, type Definition, type Expression } from "./ast";
2
+ import { getUnexpectedException, TlaEvaluationError, TlaStackOverflowError } from "./errors";
3
3
  import {
4
- describeLocation,
4
+ describeNode,
5
+ describeRange,
5
6
  bindDefinitions,
6
7
  bindOperatorArguments,
7
8
  evaluate,
8
9
  expectBoolean,
9
10
  forEachBinding,
11
+ forEachBoundElement,
12
+ getBoundElements,
10
13
  getDefinition,
11
- isLocallyResolved,
12
14
  lookupScope,
13
15
  resolveApplyOperator,
14
16
  resolveGlobalOperator,
@@ -21,75 +23,44 @@ import {
21
23
  import { mapChildren } from "./instances";
22
24
  import { ACTION_LEVEL, TEMPORAL_LEVEL } from "./levels";
23
25
  import { isEnabled } from "./successors";
26
+ import { EXIT_STATUS, setExitCode } from "./exit-codes";
27
+ import { isEvalException } from "./tlc-messages";
24
28
  import {
25
29
  createBoolean,
26
30
  createJunction,
27
31
  createPair,
28
32
  createUnary,
29
33
  getLiveLevel,
30
- getSolutions,
31
- isFulfilling,
32
34
  type LiveEnabled,
33
35
  type LiveExpression,
34
- type Solution,
35
- type Tableau,
36
36
  } from "./tableau";
37
- import { isSameValue, type Value } from "./values";
37
+ import type { Value } from "./values";
38
38
 
39
39
  export interface ScopedExpression {
40
40
  expression: Expression;
41
41
  scope: Scope | undefined;
42
42
  }
43
43
 
44
- export interface TemporalProperty extends ScopedExpression {
45
- name: string;
44
+ // A part of a temporal formula, with the name TLC gives the part when the formula is a property:
45
+ // a conjunct's location, or the name of the definition the part is the body of.
46
+ interface ExpandedExpression extends ScopedExpression {
47
+ name: string | undefined;
46
48
  }
47
49
 
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 {
50
+ export interface TemporalProperty extends ScopedExpression {
60
51
  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
52
  }
73
53
 
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
- }
54
+ const MAXIMUM_EXPANSION_DEPTH = 100;
83
55
 
84
- interface BehaviorGraph {
85
- states: number[];
86
- tableauNodes: number[];
87
- edges: number[][];
88
- initial: number[];
89
- parents: number[];
90
- }
56
+ export const createTautologyError = () =>
57
+ setExitCode(
58
+ new TlaEvaluationError("Temporal formula is a tautology (its negation is unsatisfiable)."),
59
+ EXIT_STATUS.livenessEvaluationFailure,
60
+ );
91
61
 
92
- const MAXIMUM_EXPANSION_DEPTH = 100;
62
+ // TLC expands a temporal formula that refers to itself until Java's stack overflows.
63
+ const createStackOverflowError = () => setExitCode(new TlaStackOverflowError(), EXIT_STATUS.error);
93
64
 
94
65
  const TEMPORAL_OPERATORS = new Set(["~>", "-+->"]);
95
66
 
@@ -104,9 +75,10 @@ const getConstantContext = (environment: Environment, scope: Scope | undefined):
104
75
  next: undefined,
105
76
  });
106
77
 
107
- const createCannotHandleError = (expression: Expression) =>
78
+ // TLC adds the message of the error that stopped it, when it has one.
79
+ const createCannotHandleError = (expression: Expression, inner?: string) =>
108
80
  new TlaEvaluationError(
109
- `TLC cannot handle the temporal formula at ${describeLocation(expression)}`,
81
+ `TLC cannot handle the temporal formula ${describeRange(expression)}${inner === undefined ? "" : `:\n${inner}`}`,
110
82
  );
111
83
 
112
84
  export const getLevel = (
@@ -129,7 +101,7 @@ export const getLevel = (
129
101
  const definition = getDefinition(name, environment);
130
102
  if (definition) return getDefinitionLevel(definition, environment);
131
103
  const builtin = environment.builtins.get(environment.substitutions.get(name) ?? name);
132
- return builtin ? (builtin.isStateLevel ? 1 : 0) : undefined;
104
+ return builtin ? (builtin.isStateLevel && !builtin.isLevelConstant ? 1 : 0) : undefined;
133
105
  };
134
106
  const getNameLevel = (name: string, node: Expression) => {
135
107
  if (shadowed.has(name)) return 0;
@@ -193,21 +165,53 @@ const getDefinitionLevel = (definition: Definition, environment: Environment) =>
193
165
  return level;
194
166
  };
195
167
 
168
+ // TLC leaves a formula whose sets it fails to enumerate, and doesn't expect an EvalException.
169
+ const getUnrolledElements = (bounds: Bound[], context: Context) => {
170
+ try {
171
+ return getBoundElements(bounds, context);
172
+ } catch (error) {
173
+ if (!(error instanceof TlaEvaluationError)) throw error;
174
+ if (!isEvalException(error)) return undefined;
175
+ throw setExitCode(
176
+ new TlaEvaluationError(
177
+ `${getUnexpectedException("tlc2.tool.EvalException")}${error.message}`,
178
+ ),
179
+ EXIT_STATUS.error,
180
+ );
181
+ }
182
+ };
183
+
196
184
  export const expandTemporal = (
197
185
  expression: Expression,
198
186
  scope: Scope | undefined,
199
187
  environment: Environment,
200
- isUnrollingForall: boolean,
188
+ // Whether TLC expands the formula as a property, which unrolls each \A over a constant set.
189
+ isProperty: boolean,
201
190
  expanding = new Set<Definition>(),
202
- ): ScopedExpression[] => {
191
+ // Whether the expansion entered the body of an instance's definition. Like TLC, it then no
192
+ // longer expands an operator applied to arguments.
193
+ isSubstituted = false,
194
+ name?: string,
195
+ ): ExpandedExpression[] => {
203
196
  const expand = (
204
197
  child: Expression,
205
198
  childScope: Scope | undefined,
199
+ childName = name,
206
200
  childExpanding = expanding,
207
- ): ScopedExpression[] =>
208
- expandTemporal(child, childScope, environment, isUnrollingForall, childExpanding);
201
+ definition?: Definition,
202
+ ): ExpandedExpression[] =>
203
+ expandTemporal(
204
+ child,
205
+ childScope,
206
+ environment,
207
+ isProperty,
208
+ childExpanding,
209
+ isSubstituted ||
210
+ (definition !== undefined && environment.substitutedDefinitions.has(definition)),
211
+ childName,
212
+ );
209
213
  if (expression.kind === "And") {
210
- return expression.operands.flatMap((operand) => expand(operand, scope));
214
+ return expression.operands.flatMap((operand) => expand(operand, scope, describeRange(operand)));
211
215
  }
212
216
  if (expression.kind === "Label") return expand(expression.body, scope);
213
217
  if (expression.kind === "Let") {
@@ -228,35 +232,59 @@ export const expandTemporal = (
228
232
  getDefinitionLevel(definition, environment) > 0
229
233
  ) {
230
234
  if (expanding.has(definition)) {
231
- throw new TlaConfigError(`The definition of ${expression.name} refers to itself`);
235
+ throw createStackOverflowError();
232
236
  }
233
- return expand(definition.body, undefined, new Set([...expanding, definition]));
237
+ return expand(
238
+ definition.body,
239
+ undefined,
240
+ definition.name,
241
+ new Set([...expanding, definition]),
242
+ definition,
243
+ );
234
244
  }
235
245
  }
236
246
  const context = getConstantContext(environment, scope);
237
- if (expression.kind === "Apply" && getLevel(expression, scope, environment) === TEMPORAL_LEVEL) {
247
+ // TLC 1.7.4 never expands an operator applied to arguments. A property expands every one it
248
+ // applies, but a specification only the temporal ones.
249
+ if (
250
+ expression.kind === "Apply" &&
251
+ environment.runtime.version !== "1.7.4" &&
252
+ (isProperty || getLevel(expression, scope, environment) === TEMPORAL_LEVEL)
253
+ ) {
238
254
  const operator = resolveApplyOperator(expression, context);
239
255
  const definition = isLocallyResolved(expression)
240
256
  ? undefined
241
257
  : getDefinition(expression.operator, environment);
242
- if (operator?.kind === "Closure" && !definition?.isRecursive) {
243
- return expand(operator.body, bindOperatorArguments(operator, expression.args, context));
258
+ const isExpandable =
259
+ operator?.kind === "Closure" &&
260
+ operator.params.length === expression.args.length &&
261
+ !definition?.isRecursive &&
262
+ !isSubstituted;
263
+ if (isExpandable) {
264
+ return expand(
265
+ operator.body,
266
+ bindOperatorArguments(operator, expression.args, context),
267
+ expression.operator,
268
+ expanding,
269
+ definition,
270
+ );
244
271
  }
245
272
  }
246
273
  const isUnrolled =
247
- isUnrollingForall &&
274
+ isProperty &&
248
275
  expression.kind === "Forall" &&
249
- getLevel(expression.body, scope, environment) === TEMPORAL_LEVEL &&
250
276
  expression.bounds.every((bound) => getLevel(bound.set, scope, environment) === 0);
251
- if (isUnrolled) {
252
- const expanded: ScopedExpression[] = [];
253
- forEachBinding(expression.bounds, context, (boundScope) => {
254
- expanded.push(...expand(expression.body, boundScope));
277
+ const sets = isUnrolled ? getUnrolledElements(expression.bounds, context) : undefined;
278
+ if (isUnrolled && sets) {
279
+ const expanded: ExpandedExpression[] = [];
280
+ forEachBoundElement(expression.bounds, sets, scope, (boundScope) => {
281
+ expanded.push(...expand(expression.body, boundScope, describeRange(expression.body)));
255
282
  return false;
256
283
  });
284
+ if (expanded.length === 0) throw createTautologyError();
257
285
  return expanded;
258
286
  }
259
- return [{ expression, scope }];
287
+ return [{ expression, scope, name }];
260
288
  };
261
289
 
262
290
  const bindLetDefinitions = (
@@ -278,22 +306,24 @@ const createAngleAction = (action: Expression, subscript: Expression): Expressio
278
306
  location: action.location,
279
307
  });
280
308
 
281
- const toLiveExpression = (
309
+ export const toLiveExpression = (
282
310
  root: Expression,
283
311
  rootScope: Scope | undefined,
284
312
  environment: Environment,
285
313
  ): LiveExpression => {
314
+ const is174 = environment.runtime.version === "1.7.4";
286
315
  const toAtom = (
287
316
  expression: Expression,
288
317
  scope: Scope | undefined,
289
318
  level: number,
290
319
  ): LiveExpression => {
291
- const atomLevel = level === 0 ? getLevel(expression, scope, environment) : level;
320
+ // TLC after 1.7.4 bounds the level of a formula whose parts are constant by the formula's own.
321
+ const atomLevel = level === 0 && !is174 ? getLevel(expression, scope, environment) : level;
292
322
  if (atomLevel === 0) {
293
323
  const value = evaluate(expression, getConstantContext(environment, scope));
294
324
  if (typeof value !== "boolean") {
295
325
  throw new TlaEvaluationError(
296
- `TLC expected a boolean in the temporal formula at ${describeLocation(expression)}`,
326
+ `TLC expected a boolean value, but did not find one. ${describeNode(expression)}`,
297
327
  );
298
328
  }
299
329
  return createBoolean(value);
@@ -311,9 +341,7 @@ const toLiveExpression = (
311
341
  scope: Scope | undefined,
312
342
  ) => {
313
343
  if (expansion.depth >= MAXIMUM_EXPANSION_DEPTH) {
314
- throw new TlaEvaluationError(
315
- `TLC overflowed the stack while expanding the temporal formula at ${describeLocation(expression)}`,
316
- );
344
+ throw createStackOverflowError();
317
345
  }
318
346
  expansion.depth++;
319
347
  const result = convert(body, bodyScope);
@@ -333,7 +361,9 @@ const toLiveExpression = (
333
361
  ? lookupScope(scope, name)
334
362
  : undefined;
335
363
  if (binding?.kind === "Thunk" && definitionThunks.has(binding)) {
336
- return expand(binding.expression, binding.scope, expression, scope);
364
+ return expandCall(expression, () =>
365
+ expand(binding.expression, binding.scope, expression, scope),
366
+ );
337
367
  }
338
368
  const operator =
339
369
  binding?.kind === "Operator"
@@ -345,32 +375,104 @@ const toLiveExpression = (
345
375
  : resolveGlobalOperator(name, environment);
346
376
  if (operator?.kind !== "Closure") throw createCannotHandleError(expression);
347
377
  const args = expression.kind === "Apply" ? expression.args : [];
348
- return expand(operator.body, bindOperatorArguments(operator, args, context), expression, scope);
378
+ const isRecursive =
379
+ !isLocallyResolved(expression) && getDefinition(name, environment)?.isRecursive === true;
380
+ return expandCall(
381
+ expression,
382
+ () => {
383
+ // TLC 1.7.4 evaluates the arguments of an operator it expands.
384
+ if (is174) {
385
+ args
386
+ .filter((arg) => arg.kind !== "Lambda" && arg.kind !== "OperatorReference")
387
+ .forEach((arg) => evaluate(arg, context));
388
+ }
389
+ return expand(
390
+ operator.body,
391
+ bindOperatorArguments(operator, args, context),
392
+ expression,
393
+ scope,
394
+ );
395
+ },
396
+ isRecursive,
397
+ );
398
+ };
399
+
400
+ // TLC takes an application of an operator whose expansion fails for a formula it can't handle,
401
+ // except that TLC after 1.7.4 fails as the expansion of a recursive operator does.
402
+ const expandCall = (
403
+ expression: Expression,
404
+ expandBody: () => LiveExpression,
405
+ isRecursive = false,
406
+ ) => {
407
+ try {
408
+ return expandBody();
409
+ } catch (error) {
410
+ const isRethrown = error instanceof TlaStackOverflowError || (isRecursive && !is174);
411
+ if (!(error instanceof TlaEvaluationError) || isRethrown) throw error;
412
+ throw createCannotHandleError(expression);
413
+ }
349
414
  };
350
415
 
351
416
  const convertQuantifier = (
352
417
  expression: Expression & { kind: "Forall" | "Exists" },
353
418
  scope: Scope | undefined,
354
419
  ) => {
420
+ const level = getLevel(expression, scope, environment);
355
421
  const isConstant = expression.bounds.every(
356
422
  (bound) => getLevel(bound.set, scope, environment) === 0,
357
423
  );
358
- if (!isConstant) throw createCannotHandleError(expression);
424
+ if (!isConstant) {
425
+ if (level <= ACTION_LEVEL) return toAtom(expression, scope, level);
426
+ throw createCannotHandleError(expression);
427
+ }
359
428
  const operands: LiveExpression[] = [];
360
- forEachBinding(expression.bounds, getConstantContext(environment, scope), (boundScope) => {
361
- operands.push(convert(expression.body, boundScope));
362
- return false;
363
- });
364
429
  const isForall = expression.kind === "Forall";
430
+ // TLC takes a quantified formula whose body fails for one it can't handle, and under \A it adds
431
+ // the message of a failure that isn't an EvalException.
432
+ try {
433
+ forEachBinding(expression.bounds, getConstantContext(environment, scope), (boundScope) => {
434
+ operands.push(convert(expression.body, boundScope));
435
+ return false;
436
+ });
437
+ } catch (error) {
438
+ if (!(error instanceof TlaEvaluationError) || error instanceof TlaStackOverflowError) {
439
+ throw error;
440
+ }
441
+ if (level <= ACTION_LEVEL) return toAtom(expression, scope, level);
442
+ throw createCannotHandleError(
443
+ expression,
444
+ isForall && !isEvalException(error) ? error.message : undefined,
445
+ );
446
+ }
365
447
  if (operands.length === 0) return createBoolean(isForall);
366
- const result = createJunction(isForall ? "And" : "Or", operands);
367
- const level = getLiveLevel(result);
368
- return level > ACTION_LEVEL ? result : toAtom(expression, scope, level);
448
+ return toWhole(expression, scope, createJunction(isForall ? "And" : "Or", operands));
449
+ };
450
+
451
+ // TLC takes a formula whose translated parts are below temporal level whole, at their level.
452
+ const toWhole = (expression: Expression, scope: Scope | undefined, parts: LiveExpression) => {
453
+ const level = getLiveLevel(parts);
454
+ return level > ACTION_LEVEL ? parts : toAtom(expression, scope, level);
369
455
  };
370
456
 
457
+ // The formulas below temporal level whose parts TLC's Liveness.astToLive translates, as one
458
+ // that is constant, such as a quantifier over the empty set, can make the formula constant.
459
+ const isTranslatedWhole = (expression: Expression) =>
460
+ expression.kind === "Label" ||
461
+ expression.kind === "Let" ||
462
+ expression.kind === "And" ||
463
+ expression.kind === "Or" ||
464
+ expression.kind === "Forall" ||
465
+ expression.kind === "Exists" ||
466
+ expression.kind === "If" ||
467
+ (expression.kind === "Apply" &&
468
+ ((expression.operator === "~" && !isLocallyResolved(expression)) ||
469
+ expression.operator === "=>"));
470
+
371
471
  const convert = (expression: Expression, scope: Scope | undefined): LiveExpression => {
372
472
  const level = getLevel(expression, scope, environment);
373
- if (level <= ACTION_LEVEL) return toAtom(expression, scope, level);
473
+ if (level <= ACTION_LEVEL && !isTranslatedWhole(expression)) {
474
+ return toAtom(expression, scope, level);
475
+ }
374
476
  switch (expression.kind) {
375
477
  case "Label":
376
478
  return convert(expression.body, scope);
@@ -391,38 +493,51 @@ const toLiveExpression = (
391
493
  );
392
494
  }
393
495
  if (expression.operator === "~" && !isLocallyResolved(expression)) {
394
- return createUnary("Not", convert(args[0], scope));
496
+ return toWhole(expression, scope, createUnary("Not", convert(args[0], scope)));
395
497
  }
396
498
  if (expression.operator === "=>") {
397
- return createPair(
398
- "Or",
399
- createUnary("Not", convert(args[0], scope)),
400
- convert(args[1], scope),
499
+ return toWhole(
500
+ expression,
501
+ scope,
502
+ createPair("Or", createUnary("Not", convert(args[0], scope)), convert(args[1], scope)),
401
503
  );
402
504
  }
403
505
  return convertCall(expression, scope);
404
506
  }
405
507
  case "And":
406
508
  case "Or":
407
- return createJunction(
408
- expression.kind,
409
- expression.operands.map((operand) => convert(operand, scope)),
509
+ return toWhole(
510
+ expression,
511
+ scope,
512
+ createJunction(
513
+ expression.kind,
514
+ expression.operands.map((operand) => convert(operand, scope)),
515
+ ),
410
516
  );
411
517
  case "Forall":
412
518
  case "Exists":
413
519
  return convertQuantifier(expression, scope);
414
520
  case "If": {
415
- if (getLevel(expression.condition, scope, environment) === 0) {
521
+ // TLC 1.7.4 translates both branches whatever the guard.
522
+ if (!is174 && getLevel(expression.condition, scope, environment) === 0) {
416
523
  const condition = evaluate(expression.condition, getConstantContext(environment, scope));
417
524
  if (typeof condition === "boolean") {
418
525
  return convert(condition ? expression.consequent : expression.alternative, scope);
419
526
  }
420
527
  }
421
528
  const condition = convert(expression.condition, scope);
422
- return createPair(
423
- "Or",
424
- createPair("And", condition, convert(expression.consequent, scope)),
425
- createPair("And", createUnary("Not", condition), convert(expression.alternative, scope)),
529
+ return toWhole(
530
+ expression,
531
+ scope,
532
+ createPair(
533
+ "Or",
534
+ createPair("And", condition, convert(expression.consequent, scope)),
535
+ createPair(
536
+ "And",
537
+ createUnary("Not", condition),
538
+ convert(expression.alternative, scope),
539
+ ),
540
+ ),
426
541
  );
427
542
  }
428
543
  case "Always":
@@ -464,7 +579,7 @@ const toLiveExpression = (
464
579
  return convert(root, rootScope);
465
580
  };
466
581
 
467
- const evaluateLive = (
582
+ export const evaluateLive = (
468
583
  expression: LiveExpression,
469
584
  state: Value[],
470
585
  next: Value[] | undefined,
@@ -512,7 +627,7 @@ const evaluateLive = (
512
627
  }
513
628
  };
514
629
 
515
- const evaluateOnLasso = (
630
+ export const evaluateOnLasso = (
516
631
  expression: LiveExpression,
517
632
  path: Value[][],
518
633
  cycleStart: number,
@@ -547,472 +662,3 @@ const evaluateOnLasso = (
547
662
  );
548
663
  }
549
664
  };
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
- };