tla-ts 0.0.1 → 0.0.3-dev.037ac3b

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 +1132 -258
  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 +553 -258
  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 +692 -0
  36. package/src/liveness.ts +71 -596
  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 +218 -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 +336 -57
  65. package/src/symmetry.ts +79 -23
  66. package/src/tableau.ts +93 -60
  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 +414 -0
  72. package/src/tlc-summary.ts +124 -0
  73. package/src/transfer.ts +26 -5
  74. package/src/values.ts +1285 -179
package/src/check.ts CHANGED
@@ -1,41 +1,98 @@
1
- import type { Assumption, Expression, SourceLocation } from "./ast";
2
- import { parseConfig, type ModelConfig } from "./config";
1
+ import {
2
+ getChildren,
3
+ isLocallyResolved,
4
+ type Assumption,
5
+ type Definition,
6
+ type Expression,
7
+ type SourceLocation,
8
+ } from "./ast";
9
+ import { parseConfig, type ConfigValue, type ModelConfig } from "./config";
3
10
  import { getReadVariables } from "./dependencies";
4
11
  import { createEnvironment } from "./environment";
5
- import { TlaConfigError, TlaEvaluationError, TlaUnsupportedError } from "./errors";
6
12
  import {
13
+ getErrorExitCode,
14
+ TlaConfigError,
15
+ TlaEvaluationError,
16
+ TlaModuleError,
17
+ UNEXPECTED_EXCEPTION,
18
+ } from "./errors";
19
+ import { EXIT_STATUS, setExitCode, withLivenessExitCode } from "./exit-codes";
20
+ import {
21
+ describeRange,
7
22
  evaluate,
8
23
  expectBoolean,
24
+ formatRange,
9
25
  getDefinition,
26
+ isConstantLevel,
27
+ isImpure,
10
28
  type Context,
11
29
  type Environment,
12
30
  type Scope,
13
31
  } from "./evaluate";
14
32
  import {
15
- ACTION_LEVEL,
16
33
  createLivenessChecker,
17
- expandTemporal,
18
- getLevel,
19
- TEMPORAL_LEVEL,
20
- toUnscopedExpression,
34
+ type Lasso,
35
+ type LivenessChecker,
21
36
  type LiveSuccessor,
22
- type ScopedExpression,
23
- type TemporalProperty,
24
- } from "./liveness";
25
- import { parseModule } from "./parser";
26
- import { getInitialStates, getSuccessors } from "./successors";
37
+ } from "./live-check";
38
+ import { expandTemporal, getLevel, type ScopedExpression, type TemporalProperty } from "./liveness";
39
+ import { ACTION_LEVEL, createLevelAnalyzer, TEMPORAL_LEVEL } from "./levels";
40
+ import { prettyPrint } from "./pretty-print";
41
+ import {
42
+ forEachInitialState,
43
+ forEachSuccessor,
44
+ getInitialStates,
45
+ getSuccessors,
46
+ type Successor,
47
+ } from "./successors";
48
+ import {
49
+ getActionLabel,
50
+ getActionSignature,
51
+ getNextActions,
52
+ getSpecificationValue,
53
+ type SpecAction,
54
+ } from "./spec-description";
55
+ import {
56
+ createStateWriter,
57
+ type GraphState,
58
+ type StateDump,
59
+ type StateWriter,
60
+ } from "./state-graph";
27
61
  import { getRepresentative, getSymmetryGroup } from "./symmetry";
62
+ import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
63
+ import { createTlcFingerprinter, getTlcFingerprint } from "./tlc-random";
28
64
  import { createCanonicalizer } from "./canonical";
29
65
  import { getPossibleCounts, type CheckerRuntime } from "./runtime";
30
- import { combineHash, formatValue, getValueHash, isSameValue, type Value } from "./values";
66
+ import { createCounterExample } from "./tlc-ext";
67
+ import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc-summary";
68
+ import {
69
+ combineHash,
70
+ formatState,
71
+ formatValue,
72
+ getValueHash,
73
+ isFunctionValue,
74
+ isSameValue,
75
+ isUpdatedElementOf,
76
+ setStringOrder,
77
+ toFiniteFunction,
78
+ type Value,
79
+ } from "./values";
31
80
 
32
81
  export interface CheckOptions {
33
82
  source: string;
34
83
  config: string | ModelConfig;
35
84
  loadModule?: (name: string) => string | undefined;
85
+ loadClass?: (name: string) => Uint8Array | undefined;
36
86
  onPrint?: (text: string) => void;
87
+ onPause?: () => void;
37
88
  readFile?: (path: string) => string | undefined;
38
89
  writeFile?: (path: string, content: string) => void;
90
+ seed?: bigint;
91
+ workers?: number;
92
+ // TLC's -lncheck: "final" checks liveness only on the complete state graph.
93
+ livenessCheck?: "default" | "final";
94
+ // TLC's -dump: writes the reachable states, or with `dot` the state graph, through writeFile.
95
+ dump?: StateDump;
39
96
  }
40
97
 
41
98
  export type CheckStatus =
@@ -45,52 +102,91 @@ export type CheckStatus =
45
102
  | "property-violation"
46
103
  | "liveness-violation"
47
104
  | "postcondition-violation"
48
- | "deadlock";
105
+ | "deadlock"
106
+ | "error";
49
107
 
50
108
  export interface TraceStep {
51
109
  action: string | undefined;
110
+ // TLC's name, parameters and location for the action that took this step.
111
+ label: string | undefined;
52
112
  state: Record<string, Value>;
53
113
  }
54
114
 
55
115
  export interface Violation {
56
116
  name: string;
117
+ // Every temporal property that a liveness counterexample violates, in the configuration's order.
118
+ properties?: string[];
57
119
  trace: TraceStep[];
58
120
  loopStart: number | undefined;
121
+ loopLabel?: string;
59
122
  message?: string;
123
+ counts?: string;
124
+ unwitnessed?: Postcondition;
125
+ }
126
+
127
+ interface Postcondition {
128
+ name: string;
129
+ message: string;
130
+ counts?: string;
131
+ }
132
+
133
+ // An evaluation that failed during the search, with the behavior up to the state TLC was working on.
134
+ export interface EvaluationFailure {
135
+ message: string;
136
+ trace: TraceStep[];
137
+ initialState: Record<string, Value> | undefined;
138
+ exitCode: number;
60
139
  }
61
140
 
62
141
  export interface CheckResult {
63
142
  status: CheckStatus;
64
143
  violation: Violation | undefined;
144
+ failure: EvaluationFailure | undefined;
65
145
  generatedStates: number;
66
146
  distinctStates: number;
147
+ queuedStates: number;
67
148
  depth: number;
149
+ // How many states that TLC counts as expanded found each number of new states, when TLC prints
150
+ // the outdegree of the state graph.
151
+ outDegrees: number[] | undefined;
152
+ // The smallest distance between the fingerprints of two distinct states, when TLC estimates a
153
+ // collision from the actual fingerprints.
154
+ fingerprintDistance: bigint | undefined;
68
155
  }
69
156
 
70
- export interface NamedExpression {
157
+ interface NamedExpression {
71
158
  name: string;
72
159
  expression: Expression;
73
160
  scope: Scope | undefined;
74
161
  }
75
162
 
76
- export interface StateCheck extends NamedExpression {
163
+ interface StateCheck extends NamedExpression {
77
164
  variables: number[] | undefined;
165
+ membership: Membership | undefined;
78
166
  }
79
167
 
80
- export interface ActionProperty {
168
+ // A conjunct `x \in S` whose S reads no variables.
169
+ interface Membership {
170
+ variable: number;
171
+ set: Expression;
172
+ }
173
+
174
+ interface ActionProperty {
81
175
  name: string;
176
+ box: Expression;
82
177
  action: Expression;
83
178
  subscript: Expression;
84
179
  scope: Scope | undefined;
85
180
  }
86
181
 
87
- export interface Specification {
88
- init: Expression;
89
- next: Expression;
182
+ interface Specification {
183
+ init: Expression | undefined;
184
+ next: Expression | undefined;
185
+ scope: Scope | undefined;
90
186
  temporals: ScopedExpression[];
91
187
  }
92
188
 
93
- export interface Properties {
189
+ interface Properties {
94
190
  initialPredicates: NamedExpression[];
95
191
  invariants: NamedExpression[];
96
192
  actionProperties: ActionProperty[];
@@ -99,18 +195,106 @@ export interface Properties {
99
195
 
100
196
  const START: SourceLocation = { line: 0, column: 0 };
101
197
 
198
+ const INITIAL_RECOVERY_FAILURE = "Failed to recover the initial state from its fingerprint.";
199
+ const NEXT_RECOVERY_FAILURE = "Failed to recover the next state from its fingerprint.";
200
+
102
201
  const createIdentifier = (name: string): Expression => ({
103
202
  kind: "Identifier",
104
203
  name,
105
204
  location: START,
106
205
  });
107
206
 
108
- const getDefinitionBody = (name: string, environment: Environment) => {
207
+ // TLC leaves the kind out when it rejects arguments to the specification or a property.
208
+ const UNNAMED_ARGUMENT_KINDS = new Set(["name", "property"]);
209
+
210
+ // TLC checks liveness on the graph so far 3 seconds into the search and then every minute, once
211
+ // the graph has grown by a tenth and liveness checking has taken at most a fifth of the time.
212
+ const PERIODIC_START = 3000;
213
+ const PROGRESS_INTERVAL = 60_000;
214
+ const LIVENESS_GROWTH = 0.1;
215
+ const LIVENESS_RATIO = 0.2;
216
+
217
+ const getConfigOperator = (kind: string, name: string, environment: Environment) => {
109
218
  const definition = getDefinition(name, environment);
110
- if (definition?.kind !== "Operator" || definition.params.length > 0) {
111
- throw new TlaConfigError(`${name} is not defined as an operator without arguments`);
219
+ if (!definition) {
220
+ throw new TlaConfigError(
221
+ `The ${kind} ${name} specified in the configuration file\nis not defined in the specification.`,
222
+ );
223
+ }
224
+ if (definition.kind === "Operator" && definition.params.length > 0) {
225
+ throw new TlaConfigError(
226
+ UNNAMED_ARGUMENT_KINDS.has(kind)
227
+ ? `TLC requires ${name} not to take any argument.`
228
+ : `TLC requires ${kind} not to take any argument, but one was given: ${name}`,
229
+ );
112
230
  }
113
- return definition.body;
231
+ return definition;
232
+ };
233
+
234
+ const getConfigDefinition = (kind: string, name: string, environment: Environment) => {
235
+ const definition = getConfigOperator(kind, name, environment);
236
+ if (isConstantLevel(definition, environment)) {
237
+ throw new TlaConfigError(`The ${kind} ${name} cannot be a constant.`);
238
+ }
239
+ return definition;
240
+ };
241
+
242
+ // TLC evaluates every constant definition before it reads the configuration. It keeps a literal
243
+ // number or string, and a definition that fails to evaluate, as an operator.
244
+ const getConstantValue = (name: string, definition: Definition, environment: Environment) => {
245
+ if (!isConstantLevel(definition, environment)) return undefined;
246
+ if (definition.body.kind === "Number" || definition.body.kind === "String") return undefined;
247
+ try {
248
+ return evaluate(createIdentifier(name), getContext(environment, undefined, undefined));
249
+ } catch (error) {
250
+ if (error instanceof TlaEvaluationError) return undefined;
251
+ throw error;
252
+ }
253
+ };
254
+
255
+ const getConfigPredicate = (kind: string, name: string, environment: Environment) => {
256
+ const definition = getConfigOperator(kind, name, environment);
257
+ const value = getConstantValue(name, definition, environment);
258
+ if (value !== undefined && value !== true) {
259
+ throw new TlaConfigError(`The ${kind} of ${name} is equal to ${formatValue(value)}`);
260
+ }
261
+ return value === undefined ? definition : undefined;
262
+ };
263
+
264
+ const getInvariants = (names: string[], environment: Environment) => {
265
+ const analyzer = createLevelAnalyzer({
266
+ constants: new Set(environment.constants.keys()),
267
+ variables: new Set(environment.variables),
268
+ getDefinition: (name) => getDefinition(name, environment),
269
+ });
270
+ return names.flatMap((name) => {
271
+ const definition = getConfigPredicate("invariant", name, environment);
272
+ if (!definition) return [];
273
+ const levels = analyzer.analyzeDefinition(definition, new Map());
274
+ if (levels.level >= ACTION_LEVEL) {
275
+ const note =
276
+ levels.params.size === 0
277
+ ? ""
278
+ : "\nNote that a bug can cause TLC to incorrectly report this error.\nIf you believe your TLA+ or PlusCal specification to be correct,\nplease check if this bug described in LevelNode.java starting at line 590ff affects you.";
279
+ throw new TlaConfigError(
280
+ `The invariant ${name} is not a state predicate (one with no primes or temporal operators).${note}`,
281
+ );
282
+ }
283
+ return [{ name, expression: createIdentifier(name), scope: undefined }];
284
+ });
285
+ };
286
+
287
+ const toAliasRecord = (value: Value, fieldOrder: string[]) => {
288
+ if (!isFunctionValue(value)) return undefined;
289
+ const record = toFiniteFunction(value);
290
+ if (!record.domain.every((key) => typeof key === "string")) return undefined;
291
+ const entries = record.domain.map((key, index): [string, Value] => [
292
+ String(key),
293
+ record.range[index],
294
+ ]);
295
+ return Object.fromEntries(
296
+ entries.sort((left, right) => fieldOrder.indexOf(left[0]) - fieldOrder.indexOf(right[0])),
297
+ );
114
298
  };
115
299
 
116
300
  const getConjuncts = (expression: Expression, environment: Environment): Expression[] => {
@@ -125,39 +309,66 @@ const getConjuncts = (expression: Expression, environment: Environment): Express
125
309
  return [expression];
126
310
  };
127
311
 
128
- export const getSpecification = (config: ModelConfig, environment: Environment): Specification => {
312
+ const isConstantTrue = (item: ScopedExpression, environment: Environment, usage: string) => {
313
+ const conjunct = item.expression;
314
+ if (conjunct.kind !== "Identifier" || getLevel(conjunct, item.scope, environment) > 0) {
315
+ return false;
316
+ }
317
+ const value = evaluate(conjunct, getContext(environment, undefined, undefined, item.scope));
318
+ if (value === false) {
319
+ throw new TlaConfigError(`The spec is trivially false because ${conjunct.name} is false.`);
320
+ }
321
+ if (value !== true) {
322
+ throw new TlaConfigError(
323
+ `The operator ${conjunct.name}, which equals ${formatValue(value)},\ncannot be used as a ${usage}`,
324
+ );
325
+ }
326
+ return true;
327
+ };
328
+
329
+ const getSpecification = (config: ModelConfig, environment: Environment): Specification => {
129
330
  if (config.specification === undefined) {
130
- if (config.init === undefined)
131
- throw new TlaConfigError(
132
- "The configuration file did not specify the initial state predicate",
133
- );
134
- if (config.next === undefined)
135
- throw new TlaConfigError("The configuration does not specify NEXT");
136
- getDefinitionBody(config.init, environment);
137
- getDefinitionBody(config.next, environment);
331
+ const getOperator = (name: string | undefined, description: string) => {
332
+ if (name === undefined) return undefined;
333
+ const body = getConfigOperator(description, name, environment).body;
334
+ const identifier = createIdentifier(name);
335
+ // TLC evaluates a literal body later and reports that it is not a boolean.
336
+ const isLiteral = body.kind === "Number" || body.kind === "String";
337
+ if (!isLiteral && getLevel(identifier, undefined, environment) === 0) {
338
+ throw new TlaConfigError(`The ${description} ${name} cannot be a constant.`);
339
+ }
340
+ return identifier;
341
+ };
138
342
  return {
139
- init: createIdentifier(config.init),
140
- next: createIdentifier(config.next),
343
+ init: getOperator(config.init, "initial predicate"),
344
+ next: getOperator(config.next, "next state action"),
345
+ scope: undefined,
141
346
  temporals: [],
142
347
  };
143
348
  }
144
- const initConjuncts: Expression[] = [];
145
- const nextActions: Expression[] = [];
349
+ const initConjuncts: ScopedExpression[] = [];
350
+ const nextActions: ScopedExpression[] = [];
146
351
  const temporals: ScopedExpression[] = [];
147
- const body = getDefinitionBody(config.specification, environment);
148
- const getUnscoped = (expression: Expression, scope: Scope | undefined) => {
149
- const unscoped = toUnscopedExpression(expression, scope);
150
- if (!unscoped) {
151
- throw new TlaUnsupportedError(
152
- `The specification ${config.specification} has an initial predicate or next-state relation inside a quantified formula`,
352
+ const definition = getConfigOperator("name", config.specification, environment);
353
+ const value = getConstantValue(config.specification, definition, environment);
354
+ if (value !== undefined) {
355
+ throw new TlaConfigError(
356
+ `The value of ${config.specification} is equal to ${formatValue(value)}`,
357
+ );
358
+ }
359
+ expandTemporal(definition.body, undefined, environment, false).forEach((item) => {
360
+ const conjunct = item.expression;
361
+ if (isConstantTrue(item, environment, "spec")) return;
362
+ if (conjunct.kind === "UnboundedQuantifier" && conjunct.isTemporal) {
363
+ throw setExitCode(
364
+ new TlaConfigError(
365
+ "TLC does not support temporal existential, nor universal, quantification over state variables.",
366
+ ),
367
+ EXIT_STATUS.error,
153
368
  );
154
369
  }
155
- return unscoped;
156
- };
157
- expandTemporal(body, undefined, environment).forEach((item) => {
158
- const conjunct = item.expression;
159
370
  if (conjunct.kind === "Always" && conjunct.expression.kind === "BoxAction") {
160
- nextActions.push(getUnscoped(conjunct.expression.action, item.scope));
371
+ nextActions.push({ expression: conjunct.expression.action, scope: item.scope });
161
372
  return;
162
373
  }
163
374
  if (
@@ -178,21 +389,54 @@ export const getSpecification = (config: ModelConfig, environment: Environment):
178
389
  `TLC cannot handle the action-level conjunct of the specification ${config.specification}`,
179
390
  );
180
391
  }
181
- initConjuncts.push(getUnscoped(conjunct, item.scope));
392
+ initConjuncts.push(item);
182
393
  });
183
- if (nextActions.length !== 1) {
394
+ if (nextActions.length > 1) {
184
395
  throw new TlaConfigError(
185
- `The specification ${config.specification} must contain exactly one [][Next]_vars`,
396
+ `The specification ${config.specification} must contain at most one [][Next]_vars`,
186
397
  );
187
398
  }
399
+ const items = [...initConjuncts, ...nextActions];
400
+ const getName = (index: number) => `$specification${index}`;
401
+ const scope = items.reduce<Scope | undefined>(
402
+ (parent, item, index) =>
403
+ item.scope === undefined
404
+ ? parent
405
+ : {
406
+ name: getName(index),
407
+ binding: {
408
+ kind: "Thunk",
409
+ expression: item.expression,
410
+ scope: item.scope,
411
+ state: undefined,
412
+ next: undefined,
413
+ cache: undefined,
414
+ },
415
+ parent,
416
+ },
417
+ undefined,
418
+ );
419
+ const getReference = (item: ScopedExpression, index: number): Expression =>
420
+ item.scope === undefined
421
+ ? item.expression
422
+ : {
423
+ kind: "Identifier",
424
+ name: getName(index),
425
+ location: item.expression.location,
426
+ resolution: { kind: "Local" },
427
+ };
188
428
  return {
189
- init: { kind: "And", operands: initConjuncts, location: START },
190
- next: nextActions[0],
429
+ init:
430
+ initConjuncts.length === 0
431
+ ? undefined
432
+ : { kind: "And", operands: initConjuncts.map(getReference), location: START },
433
+ next: nextActions.length === 0 ? undefined : getReference(nextActions[0], initConjuncts.length),
434
+ scope,
191
435
  temporals,
192
436
  };
193
437
  };
194
438
 
195
- export const getProperties = (config: ModelConfig, environment: Environment): Properties => {
439
+ const getProperties = (config: ModelConfig, environment: Environment): Properties => {
196
440
  const properties: Properties = {
197
441
  initialPredicates: [],
198
442
  invariants: [],
@@ -200,12 +444,15 @@ export const getProperties = (config: ModelConfig, environment: Environment): Pr
200
444
  liveness: [],
201
445
  };
202
446
  config.properties.forEach((name) => {
203
- const body = getDefinitionBody(name, environment);
204
- expandTemporal(body, undefined, environment).forEach((item) => {
447
+ const definition = getConfigPredicate("property", name, environment);
448
+ if (!definition) return;
449
+ expandTemporal(definition.body, undefined, environment, true, name).forEach((item) => {
205
450
  const conjunct = item.expression;
451
+ if (isConstantTrue(item, environment, "property")) return;
206
452
  if (conjunct.kind === "Always" && conjunct.expression.kind === "BoxAction") {
207
453
  properties.actionProperties.push({
208
- name,
454
+ name: item.name,
455
+ box: conjunct.expression,
209
456
  action: conjunct.expression.action,
210
457
  subscript: conjunct.expression.subscript,
211
458
  scope: item.scope,
@@ -216,12 +463,22 @@ export const getProperties = (config: ModelConfig, environment: Environment): Pr
216
463
  conjunct.kind === "Always" &&
217
464
  getLevel(conjunct.expression, item.scope, environment) <= 1
218
465
  ) {
219
- properties.invariants.push({ name, expression: conjunct.expression, scope: item.scope });
466
+ // TLC names the invariant []P after P when P is an operator name.
467
+ const expression = conjunct.expression;
468
+ properties.invariants.push({
469
+ name: expression.kind === "Identifier" ? expression.name : item.name,
470
+ expression,
471
+ scope: item.scope,
472
+ });
220
473
  return;
221
474
  }
222
475
  const level = getLevel(conjunct, item.scope, environment);
223
476
  if (level < ACTION_LEVEL) {
224
- properties.initialPredicates.push({ name, expression: conjunct, scope: item.scope });
477
+ properties.initialPredicates.push({
478
+ name: item.name,
479
+ expression: conjunct,
480
+ scope: item.scope,
481
+ });
225
482
  return;
226
483
  }
227
484
  if (level === ACTION_LEVEL) {
@@ -233,27 +490,68 @@ export const getProperties = (config: ModelConfig, environment: Environment): Pr
233
490
  return properties;
234
491
  };
235
492
 
236
- export const getNamedExpressions = (names: string[], environment: Environment): NamedExpression[] =>
237
- names.map((name) => {
238
- getDefinitionBody(name, environment);
239
- return { name, expression: createIdentifier(name), scope: undefined };
493
+ const getNamedExpressions = (
494
+ kind: string,
495
+ names: string[],
496
+ environment: Environment,
497
+ ): NamedExpression[] =>
498
+ names.flatMap((name) =>
499
+ getConfigPredicate(kind, name, environment)
500
+ ? [{ name, expression: createIdentifier(name), scope: undefined }]
501
+ : [],
502
+ );
503
+
504
+ const getBodyRange = (name: string, environment: Environment) => {
505
+ const definition = getDefinition(name, environment);
506
+ return definition?.kind === "Operator" ? definition.bodyRange : undefined;
507
+ };
508
+
509
+ const getPossiblePredicates = (names: string[], environment: Environment) =>
510
+ names.map((name, index) => {
511
+ if (names.indexOf(name) !== index) {
512
+ throw new TlaConfigError(`_POSSIBLE lists ${name} more than once`);
513
+ }
514
+ getConfigDefinition("possible", name, environment);
515
+ const expression = createIdentifier(name);
516
+ if (getLevel(expression, undefined, environment) === TEMPORAL_LEVEL) {
517
+ throw new TlaConfigError(
518
+ `The possible of ${name} is equal to a temporal formula; only state- and action-level predicates are supported`,
519
+ );
520
+ }
521
+ return { name, expression, scope: undefined };
240
522
  });
241
523
 
242
- export const getStateChecks = (named: NamedExpression[], environment: Environment): StateCheck[] =>
524
+ const getMembership = (
525
+ expression: Expression,
526
+ variables: number[] | undefined,
527
+ environment: Environment,
528
+ ): Membership | undefined => {
529
+ if (expression.kind !== "Apply" || expression.operator !== "\\in" || variables?.length !== 1)
530
+ return undefined;
531
+ const element = expression.args[0];
532
+ if (element.kind !== "Identifier" || isLocallyResolved(element)) return undefined;
533
+ return environment.variableIndex.get(element.name) === variables[0]
534
+ ? { variable: variables[0], set: expression.args[1] }
535
+ : undefined;
536
+ };
537
+
538
+ const getStateChecks = (named: NamedExpression[], environment: Environment): StateCheck[] =>
243
539
  named.flatMap((item) =>
244
- getConjuncts(item.expression, environment).map((expression) => ({
245
- name: item.name,
246
- expression,
247
- scope: item.scope,
248
- variables: getReadVariables(expression, environment),
249
- })),
540
+ getConjuncts(item.expression, environment).map((expression) => {
541
+ // A LET or an argument in the scope can read variables the expression doesn't name.
542
+ const variables =
543
+ item.scope === undefined ? getReadVariables(expression, environment) : undefined;
544
+ return {
545
+ name: item.name,
546
+ expression,
547
+ scope: item.scope,
548
+ variables,
549
+ membership: getMembership(expression, variables, environment),
550
+ };
551
+ }),
250
552
  );
251
553
 
252
- export const isUnchangedFor = (
253
- stateCheck: StateCheck,
254
- state: Value[],
255
- parent: Value[] | undefined,
256
- ) => {
554
+ const isUnchangedFor = (stateCheck: StateCheck, state: Value[], parent: Value[] | undefined) => {
257
555
  const variables = stateCheck.variables;
258
556
  if (!parent || !variables) return false;
259
557
  for (let index = 0; index < variables.length; index++) {
@@ -262,10 +560,40 @@ export const isUnchangedFor = (
262
560
  return true;
263
561
  };
264
562
 
265
- export interface Search {
563
+ const WIDE_CHARACTER = /[\u0100-\uffff]/;
564
+
565
+ const DESERIALIZERS = new Set(["JsonDeserialize", "ndJsonDeserialize"]);
566
+
567
+ const isWideConfigValue = (value: ConfigValue): boolean =>
568
+ value.kind === "String"
569
+ ? WIDE_CHARACTER.test(value.value)
570
+ : value.kind === "Set" && value.elements.some(isWideConfigValue);
571
+
572
+ const isWideExpression = (expression: Expression): boolean =>
573
+ (expression.kind === "String" && WIDE_CHARACTER.test(expression.value)) ||
574
+ (expression.kind === "Apply" && DESERIALIZERS.has(expression.operator)) ||
575
+ getChildren(expression).some(isWideExpression);
576
+
577
+ // TLC fingerprints a string by the low byte of each character, so it merges states whose
578
+ // strings differ only above U+00FF. Strings reach a state from literals, the config, or files.
579
+ const hasWideString = (config: ModelConfig, environment: Environment) =>
580
+ config.constants.some(
581
+ (constant) =>
582
+ isWideConfigValue(constant.value) || (constant.args ?? []).some(isWideConfigValue),
583
+ ) ||
584
+ [...environment.definitions.values()].some(
585
+ (definition) =>
586
+ isWideExpression(definition.body) ||
587
+ (definition.kind === "Function" &&
588
+ definition.bounds.some((bound) => isWideExpression(bound.set))),
589
+ );
590
+
591
+ interface Search {
266
592
  properties: Properties;
267
593
  spec: Specification;
268
594
  getFingerprintState: (state: Value[]) => Value[];
595
+ getStoredFingerprints: (states: Value[][], fingerprintStates: Value[][]) => BigInt64Array;
596
+ getTlcOrder: () => number[];
269
597
  isSymmetric: boolean;
270
598
  findViolatedInvariant: (state: Value[], parent?: Value[]) => StateCheck | undefined;
271
599
  satisfiesConstraints: (state: Value[], parent?: Value[]) => boolean;
@@ -274,9 +602,8 @@ export interface Search {
274
602
  satisfiesActionConstraints: (state: Value[], next: Value[]) => boolean;
275
603
  trackStatePossible: (state: Value[]) => void;
276
604
  trackActionPossible: (state: Value[], next: Value[]) => void;
277
- findPostconditionViolation: (
278
- print: (text: string) => void,
279
- ) => Omit<Violation, "loopStart"> | undefined;
605
+ findUnwitnessedPossible: () => Postcondition | undefined;
606
+ findPostconditionViolation: () => Postcondition | undefined;
280
607
  }
281
608
 
282
609
  const getContext = (
@@ -284,11 +611,39 @@ const getContext = (
284
611
  state: Value[] | undefined,
285
612
  next: Value[] | undefined,
286
613
  scope?: Scope,
287
- ): Context => ({ environment, scope, state, next });
614
+ ) => ({ environment, scope, state, next });
288
615
 
289
616
  const holds = (expression: Expression, context: Context, description: string) =>
290
617
  expectBoolean(evaluate(expression, context), description);
291
618
 
619
+ // TLC names a check that is not a boolean by the location of the predicate it evaluates.
620
+ const holdsLikeTlc = (
621
+ expression: Expression,
622
+ context: Context,
623
+ getMessage = getExpectedBoolean,
624
+ ) => {
625
+ const value = evaluate(expression, context);
626
+ if (typeof value !== "boolean") {
627
+ throw new TlaEvaluationError(getMessage(expression, context.environment));
628
+ }
629
+ return value;
630
+ };
631
+
632
+ // SANY prints a number by its digits and any other expression by its location.
633
+ const getExpectedBoolean = (expression: Expression, environment: Environment) => {
634
+ const definition =
635
+ expression.kind === "Identifier" ? getDefinition(expression.name, environment) : undefined;
636
+ const body = definition?.kind === "Operator" ? definition.body : expression;
637
+ const range = definition?.kind === "Operator" ? definition.bodyRange : undefined;
638
+ const location =
639
+ body.kind === "Number"
640
+ ? (body.text ?? String(body.value))
641
+ : range
642
+ ? formatRange(range)
643
+ : describeRange(body);
644
+ return `TLC expected a boolean value, but did not find one. ${location}`;
645
+ };
646
+
292
647
  const ignorePossible = () => {};
293
648
 
294
649
  const trackPossible = (items: NamedExpression[], runtime: CheckerRuntime, context: Context) =>
@@ -320,36 +675,56 @@ export const findAssumptionViolation = (
320
675
  for (const assumption of assumptions.filter((candidate) => !candidate.isAxiom)) {
321
676
  const failure = getConstantFailure(assumption.expression, environment, "an assumption");
322
677
  if (failure) {
323
- const name =
324
- assumption.name ?? `line ${assumption.location.line}, column ${assumption.location.column}`;
325
- return { name, trace: [], message: failure.message };
678
+ return { name: describeRange(assumption.expression), trace: [], message: failure.message };
326
679
  }
327
680
  }
328
681
  return undefined;
329
682
  };
330
683
 
331
- export const createSearch = (config: ModelConfig, environment: Environment): Search | undefined => {
684
+ export const createSearch = (
685
+ config: ModelConfig,
686
+ environment: Environment,
687
+ getVariableOrder: () => string[],
688
+ ): Search | undefined => {
689
+ const configInvariants = getInvariants(config.invariants, environment);
690
+ const spec = getSpecification(config, environment);
332
691
  const properties = getProperties(config, environment);
333
- const invariants = getStateChecks(
334
- [...getNamedExpressions(config.invariants, environment), ...properties.invariants],
692
+ const invariants = getStateChecks([...configInvariants, ...properties.invariants], environment);
693
+ const isCheckingBehaviors =
694
+ invariants.length > 0 ||
695
+ properties.actionProperties.length > 0 ||
696
+ properties.liveness.length > 0;
697
+ if (
698
+ spec.init === undefined &&
699
+ (isCheckingBehaviors ||
700
+ properties.initialPredicates.length > 0 ||
701
+ environment.variables.length > 0)
702
+ ) {
703
+ throw new TlaConfigError("The configuration file did not specify the initial state predicate.");
704
+ }
705
+ if (spec.next === undefined && isCheckingBehaviors) {
706
+ throw new TlaConfigError("The configuration file did not specify the next state predicate.");
707
+ }
708
+ const constraints = getStateChecks(
709
+ getNamedExpressions("constraint", config.constraints, environment),
335
710
  environment,
336
711
  );
337
- const isConstantModel =
338
- config.specification === undefined &&
339
- config.init === undefined &&
340
- environment.variables.length === 0;
341
- if (isConstantModel) return undefined;
342
- const spec = getSpecification(config, environment);
712
+ const actionConstraints = getNamedExpressions(
713
+ "action constraint",
714
+ config.actionConstraints,
715
+ environment,
716
+ );
717
+ if (config.rlReward !== undefined) getConfigOperator("rlreward", config.rlReward, environment);
718
+ if (config.periodic !== undefined) getConfigOperator("periodic", config.periodic, environment);
719
+ const possible = getPossiblePredicates(config.possible, environment);
343
720
  if (environment.variables.length === 0) return undefined;
344
721
  const symmetryGroup =
345
722
  config.symmetry === undefined ? [] : getSymmetryGroup(config.symmetry, environment);
723
+ if (config.view !== undefined) getConfigOperator("view function", config.view, environment);
346
724
  const view =
347
- config.view === undefined ? undefined : getNamedExpressions([config.view], environment)[0];
348
- const constraints = getStateChecks(
349
- getNamedExpressions(config.constraints, environment),
350
- environment,
351
- );
352
- const actionConstraints = getNamedExpressions(config.actionConstraints, environment);
725
+ config.view === undefined
726
+ ? undefined
727
+ : { name: config.view, expression: createIdentifier(config.view), scope: undefined };
353
728
  const actionProperties = properties.actionProperties.map((property) => {
354
729
  const unchanged: Expression = {
355
730
  kind: "Unchanged",
@@ -358,72 +733,140 @@ export const createSearch = (config: ModelConfig, environment: Environment): Sea
358
733
  };
359
734
  return { ...property, unchanged };
360
735
  });
361
- const possible = getNamedExpressions(config.possible, environment);
362
736
  const isActionPossible = (item: NamedExpression) =>
363
737
  getLevel(item.expression, undefined, environment) >= ACTION_LEVEL;
364
738
  const statePossible = possible.filter((item) => !isActionPossible(item));
365
739
  const actionPossible = possible.filter(isActionPossible);
366
740
  const runtime = environment.runtime;
741
+ const tlcOrder = { indices: undefined as number[] | undefined };
742
+ const getTlcOrder = () => {
743
+ if (tlcOrder.indices) return tlcOrder.indices;
744
+ const variableOrder = getVariableOrder();
745
+ const getTlcPosition = (index: number) => {
746
+ const position = variableOrder.indexOf(environment.variables[index]);
747
+ return position === -1 ? environment.variables.length : position;
748
+ };
749
+ tlcOrder.indices = environment.variables
750
+ .map((_, index) => index)
751
+ .sort((left, right) => getTlcPosition(left) - getTlcPosition(right));
752
+ return tlcOrder.indices;
753
+ };
754
+ // A representative in TLC's variable order is the one whose fingerprint TLC reports.
755
+ const order = symmetryGroup.length > 0 ? getTlcOrder() : undefined;
756
+ const getViewValue = (expression: Expression, state: Value[]) =>
757
+ evaluate(expression, getContext(environment, state, undefined));
758
+ const getTlcStateFingerprint = (state: Value[]) => {
759
+ const indices = getTlcOrder();
760
+ const representative =
761
+ symmetryGroup.length === 0 ? state : getRepresentative(state, symmetryGroup, indices);
762
+ return getTlcFingerprint(
763
+ view === undefined
764
+ ? indices.map((index) => representative[index])
765
+ : [getViewValue(view.expression, representative)],
766
+ );
767
+ };
768
+ const isFingerprintedLikeTlc = hasWideString(config, environment);
769
+ runtime.getFingerprint = getTlcStateFingerprint;
770
+ const findUnwitnessedPossible = () => {
771
+ const unwitnessed = possible.find((item) => !runtime.possibleCounts.get(item.name));
772
+ if (!unwitnessed) return undefined;
773
+ const range = getBodyRange(unwitnessed.name, environment);
774
+ const location = range ? ` at ${formatRange(range)}` : "";
775
+ return {
776
+ name: unwitnessed.name,
777
+ message: `The _POSSIBLE predicate ${unwitnessed.name}${location} was never witnessed.\nOthers may be unwitnessed too; only witnessed predicates appear with a\nnon-zero count in the record printed above.\nSee https://explain.tlapl.us/possible-conditions for additional details.`,
778
+ counts: prettyPrint(formatValue(getPossibleCounts(runtime), true)),
779
+ };
780
+ };
367
781
  return {
368
782
  properties,
369
783
  spec,
370
784
  isSymmetric: symmetryGroup.length > 0,
785
+ getTlcOrder,
786
+ getStoredFingerprints: (states, fingerprintStates) => {
787
+ if (view !== undefined || isFingerprintedLikeTlc) {
788
+ return BigInt64Array.from(states, getTlcStateFingerprint);
789
+ }
790
+ const fingerprints = new BigInt64Array(fingerprintStates.length);
791
+ const fingerprint = createTlcFingerprinter(
792
+ getTlcOrder(),
793
+ new Int32Array(fingerprints.buffer),
794
+ );
795
+ fingerprintStates.forEach(fingerprint);
796
+ return fingerprints;
797
+ },
371
798
  getFingerprintState: (state) => {
799
+ if (isFingerprintedLikeTlc) return [String(getTlcStateFingerprint(state))];
372
800
  const representative =
373
- symmetryGroup.length === 0 ? state : getRepresentative(state, symmetryGroup);
374
- return view === undefined
375
- ? representative
376
- : [evaluate(view.expression, getContext(environment, representative, undefined))];
801
+ symmetryGroup.length === 0 ? state : getRepresentative(state, symmetryGroup, order);
802
+ return view === undefined ? representative : [getViewValue(view.expression, representative)];
377
803
  },
378
804
  findViolatedInvariant: (state, parent) =>
379
- invariants.find(
380
- (invariant) =>
381
- !isUnchangedFor(invariant, state, parent) &&
382
- !holds(
383
- invariant.expression,
384
- getContext(environment, state, undefined, invariant.scope),
385
- `invariant ${invariant.name}`,
386
- ),
387
- ),
805
+ invariants.find((invariant) => {
806
+ if (isUnchangedFor(invariant, state, parent)) return false;
807
+ try {
808
+ const context = getContext(environment, state, undefined, invariant.scope);
809
+ const membership = invariant.membership;
810
+ // The parent satisfies every invariant, so only the entries the step changed can fail.
811
+ return parent && membership
812
+ ? !isUpdatedElementOf(
813
+ state[membership.variable],
814
+ parent[membership.variable],
815
+ evaluate(membership.set, context),
816
+ )
817
+ : !holdsLikeTlc(invariant.expression, context);
818
+ } catch (error) {
819
+ // TLC reports a failure only on a state after the initial states as an invariant failure.
820
+ if (!parent) throw error;
821
+ throw withHeadline(
822
+ setExitCode(error, EXIT_STATUS.safetyEvaluationFailure),
823
+ `Evaluating invariant ${invariant.name} failed.`,
824
+ );
825
+ }
826
+ }),
388
827
  satisfiesConstraints: (state, parent) =>
389
828
  constraints.every(
390
829
  (constraint) =>
391
830
  isUnchangedFor(constraint, state, parent) ||
392
- holds(
393
- constraint.expression,
394
- getContext(environment, state, undefined),
395
- `constraint ${constraint.name}`,
396
- ),
831
+ holdsLikeTlc(constraint.expression, getContext(environment, state, undefined)),
397
832
  ),
398
833
  findFailedInitialPredicate: (state) =>
399
834
  properties.initialPredicates.find(
400
835
  (predicate) =>
401
- !holds(
836
+ !holdsLikeTlc(
402
837
  predicate.expression,
403
838
  getContext(environment, state, undefined, predicate.scope),
404
- `property ${predicate.name}`,
405
839
  ),
406
840
  ),
407
841
  findViolatedActionProperty: (state, next) =>
408
- actionProperties.find(
409
- (property) =>
410
- !holds(
411
- property.action,
412
- getContext(environment, state, next, property.scope),
413
- `property ${property.name}`,
414
- ) &&
415
- !holds(
416
- property.unchanged,
417
- getContext(environment, state, next, property.scope),
418
- "a subscript",
419
- ),
420
- ),
842
+ actionProperties.find((property) => {
843
+ try {
844
+ return (
845
+ !holdsLikeTlc(
846
+ property.action,
847
+ getContext(environment, state, next, property.scope),
848
+ () =>
849
+ `Attempted to evaluate an expression of form [A]_e, but A was not a boolean.\n${describeRange(property.box)}`,
850
+ ) &&
851
+ !holds(
852
+ property.unchanged,
853
+ getContext(environment, state, next, property.scope),
854
+ "a subscript",
855
+ )
856
+ );
857
+ } catch (error) {
858
+ throw withHeadline(
859
+ withNextStateExitCode(error),
860
+ `Evaluating action property ${property.name} failed.`,
861
+ );
862
+ }
863
+ }),
421
864
  satisfiesActionConstraints: (state, next) =>
422
865
  actionConstraints.every((constraint) =>
423
- holds(
866
+ holdsLikeTlc(
424
867
  constraint.expression,
425
868
  getContext(environment, state, next),
426
- `action constraint ${constraint.name}`,
869
+ (expression) => `${UNEXPECTED_EXCEPTION}${getExpectedBoolean(expression, environment)}`,
427
870
  ),
428
871
  ),
429
872
  trackStatePossible:
@@ -436,20 +879,14 @@ export const createSearch = (config: ModelConfig, environment: Environment): Sea
436
879
  ? ignorePossible
437
880
  : (state, next) =>
438
881
  trackPossible(actionPossible, runtime, getContext(environment, state, next)),
439
- findPostconditionViolation: (print) => {
440
- const unwitnessed = possible.find((item) => !runtime.possibleCounts.get(item.name));
441
- if (unwitnessed) {
442
- print(formatValue(getPossibleCounts(runtime), true));
443
- return {
444
- name: unwitnessed.name,
445
- trace: [],
446
- message: `The _POSSIBLE predicate ${unwitnessed.name} was never witnessed.`,
447
- };
448
- }
882
+ findUnwitnessedPossible,
883
+ findPostconditionViolation: () => {
884
+ const unwitnessed = findUnwitnessedPossible();
885
+ if (unwitnessed) return unwitnessed;
449
886
  for (const name of config.postconditions) {
450
887
  const failure = getConstantFailure(createIdentifier(name), environment, "a postcondition");
451
888
  if (failure) {
452
- return { name, trace: [], message: failure.message ?? `Postcondition ${name} is false.` };
889
+ return { name, message: failure.message ?? `Postcondition ${name} is false.` };
453
890
  }
454
891
  }
455
892
  return undefined;
@@ -457,37 +894,154 @@ export const createSearch = (config: ModelConfig, environment: Environment): Sea
457
894
  };
458
895
  };
459
896
 
460
- export const check = (options: CheckOptions): CheckResult => {
897
+ // TLC exits with the code of a standard module's failure only when the failure escapes the
898
+ // computation of next states. In every other phase, the phase decides the code.
899
+ const withNextStateExitCode = (error: unknown) =>
900
+ error instanceof TlaModuleError ? setExitCode(error, error.exitCode) : error;
901
+
902
+ const withHeadline = (error: unknown, headline: string) =>
903
+ error instanceof TlaEvaluationError
904
+ ? setExitCode(
905
+ new TlaEvaluationError(`${headline}\n${error.message}`, error),
906
+ getErrorExitCode(error),
907
+ )
908
+ : error;
909
+
910
+ // TLC finishes the -dump file whether or not the search finds a violation.
911
+ export const checkSequentially = (options: CheckOptions): CheckResult => {
912
+ const stateWriter = options.dump && createStateWriter(options.dump, options.writeFile);
913
+ const result = searchStates(options, stateWriter);
914
+ stateWriter?.close();
915
+ return result;
916
+ };
917
+
918
+ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefined): CheckResult => {
461
919
  const config = typeof options.config === "string" ? parseConfig(options.config) : options.config;
462
- const print = options.onPrint ?? console.log;
463
- const specification = createEnvironment(parseModule(options.source), config, {
920
+ const onPrint = options.onPrint ?? console.log;
921
+ // TLC prints again while it rebuilds a trace, between the states it prints. Printing those lines
922
+ // before the trace would misplace them, so rebuilding a trace prints nothing.
923
+ const output = { isMuted: false };
924
+ const print = (text: string) => {
925
+ if (!output.isMuted) onPrint(text);
926
+ };
927
+ const withoutOutput = <Result>(rebuild: () => Result) => {
928
+ output.isMuted = true;
929
+ const result = rebuild();
930
+ output.isMuted = false;
931
+ return result;
932
+ };
933
+ setStringOrder(getTlcStringOrder(options.source, config, options.loadModule));
934
+ const specification = createEnvironment(config, {
935
+ source: options.source,
464
936
  loadModule: options.loadModule,
937
+ loadClass: options.loadClass,
465
938
  print,
466
939
  files: { readFile: options.readFile, writeFile: options.writeFile },
940
+ seed: options.seed,
467
941
  });
468
942
  const environment = specification.environment;
469
943
  const runtime = environment.runtime;
944
+ runtime.pause = options.onPause ?? (() => {});
945
+ runtime.getSpecification = () =>
946
+ getSpecificationValue(
947
+ config,
948
+ environment,
949
+ specification.variableLocations,
950
+ specification.instanceActions,
951
+ );
470
952
  const statistics = { depth: 0 };
471
953
  const createResult = (
472
954
  status: CheckStatus,
473
955
  violation?: Omit<Violation, "loopStart"> & { loopStart?: number },
956
+ failure?: EvaluationFailure,
474
957
  ): CheckResult => ({
475
958
  status,
476
959
  violation: violation && { ...violation, loopStart: violation.loopStart },
960
+ failure,
477
961
  generatedStates: runtime.generatedStates,
478
962
  distinctStates: runtime.distinctStates,
479
- depth: statistics.depth,
963
+ queuedStates: runtime.queueSize,
964
+ depth: runtime.generatedStates === 0 ? 0 : Math.max(statistics.depth, 1),
965
+ outDegrees: undefined,
966
+ fingerprintDistance: undefined,
967
+ });
968
+ const outDegrees = Array.from({ length: OUT_DEGREE_BUCKETS }, () => 0);
969
+ const expansion = { newStates: 0 };
970
+ const getOutDegreeBucket = () => Math.min(expansion.newStates, OUT_DEGREE_BUCKETS - 1);
971
+ // TLC counts the state it was expanding when an evaluation failed.
972
+ const getPartialOutDegrees = () =>
973
+ outDegrees.map((count, degree) => (degree === getOutDegreeBucket() ? count + 1 : count));
974
+ const createSuccess = (): CheckResult => ({
975
+ ...createResult("success"),
976
+ outDegrees: [...outDegrees],
977
+ fingerprintDistance: getFingerprintDistance(
978
+ runtime.distinctStates,
979
+ runtime.generatedStates,
980
+ () =>
981
+ search
982
+ ? search.getStoredFingerprints(states, fingerprintStates)
983
+ : BigInt64Array.from(states, runtime.getFingerprint),
984
+ ),
480
985
  });
481
986
 
987
+ const search = createSearch(config, environment, () =>
988
+ getTlcVariableOrder(options.source, options.loadModule),
989
+ );
482
990
  const assumptionViolation = findAssumptionViolation(specification.assumptions, environment);
483
991
  if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
484
-
485
- const search = createSearch(config, environment);
486
- if (!search) return createResult("success");
487
- const properties = search.properties;
992
+ if (!search) return createSuccess();
993
+ const hasPostconditions = config.postconditions.length > 0 || config.possible.length > 0;
994
+ const reportViolation = (
995
+ status: CheckStatus,
996
+ violation: Omit<Violation, "loopStart"> & { loopStart?: number },
997
+ getLoopAction?: () => string | undefined,
998
+ ) => {
999
+ if (hasPostconditions) {
1000
+ const start = violation.loopStart;
1001
+ runtime.counterExample = createCounterExample(
1002
+ violation.trace,
1003
+ start === undefined || !getLoopAction ? undefined : { start, action: getLoopAction() },
1004
+ );
1005
+ }
1006
+ const unwitnessed = search.findUnwitnessedPossible();
1007
+ if (!unwitnessed) search.findPostconditionViolation();
1008
+ return createResult(status, unwitnessed ? { ...violation, unwitnessed } : violation);
1009
+ };
488
1010
  const spec = search.spec;
489
1011
  const getFingerprintState = search.getFingerprintState;
490
- const liveness = createLivenessChecker(properties.liveness, spec.temporals, environment);
1012
+ const nextActions = { value: undefined as SpecAction[] | undefined };
1013
+ const isReducing = config.view !== undefined || config.symmetry !== undefined;
1014
+ const tlcFingerprints: number[] = [];
1015
+ const liveness = withLivenessExitCode(() =>
1016
+ createLivenessChecker(search.properties.liveness, spec.temporals, environment, {
1017
+ getFingerprint: (index) =>
1018
+ (tlcFingerprints[index] ??= Number(
1019
+ BigInt.asIntN(32, runtime.getFingerprint(states[index])),
1020
+ )),
1021
+ getSuccessors: (state) => {
1022
+ const successors: LiveSuccessor[] = [];
1023
+ if (spec.next === undefined) return successors;
1024
+ forEachSuccessor(
1025
+ spec.next,
1026
+ state,
1027
+ environment,
1028
+ (successor) => {
1029
+ canonicalizeState(successor.state);
1030
+ const isInModel =
1031
+ search.satisfiesConstraints(successor.state, state) &&
1032
+ search.satisfiesActionConstraints(state, successor.state);
1033
+ if (!isInModel) return false;
1034
+ const fingerprintState = getFingerprintState(successor.state);
1035
+ const index = findStateIndex(getStateHash(fingerprintState), fingerprintState);
1036
+ successors.push({ index, state: successor.state });
1037
+ return false;
1038
+ },
1039
+ spec.scope,
1040
+ );
1041
+ return successors;
1042
+ },
1043
+ }),
1044
+ );
491
1045
  const isCanonicalizedFirst = search.isSymmetric || liveness !== undefined;
492
1046
 
493
1047
  const states: Value[][] = [];
@@ -495,33 +1049,156 @@ export const check = (options: CheckOptions): CheckResult => {
495
1049
  const parents: number[] = [];
496
1050
  const actions: (string | undefined)[] = [];
497
1051
  const depths: number[] = [];
498
- const buckets = new Map<number, number | number[]>();
1052
+ // A Map holds at most 2^24 entries, so an open-addressing table keeps each seen state's hash
1053
+ // and its index plus one side by side, probed by the hash.
1054
+ const seen = { slots: new Int32Array(1 << 17), size: 0, shift: 16 };
499
1055
  const canonicalizeState = createCanonicalizer();
500
1056
 
501
- const toRecord = (state: Value[]) =>
502
- Object.fromEntries(environment.variables.map((name, index) => [name, state[index]]));
503
- const getTrace = (
504
- index: number,
505
- last?: { state: Value[]; action: string | undefined },
506
- ): TraceStep[] => {
507
- const steps: TraceStep[] = last ? [{ action: last.action, state: toRecord(last.state) }] : [];
508
- for (let current = index; current !== -1; current = parents[current]) {
509
- steps.push({ action: actions[current], state: toRecord(states[current]) });
510
- }
511
- return steps.reverse();
512
- };
513
- const getPathTrace = (path: number[]) =>
514
- path.map((stateIndex, position): TraceStep => {
515
- if (position === 0) return { action: undefined, state: toRecord(states[stateIndex]) };
516
- const previous = path[position - 1];
517
- const action =
518
- previous === stateIndex
519
- ? "Stuttering"
520
- : getSuccessors(spec.next, states[previous], environment).find((successor) =>
521
- isSameState(successor.state, states[stateIndex]),
522
- )?.action;
523
- return { action, state: toRecord(states[stateIndex]) };
1057
+ const toRecord = (state: Value[]): Record<string, Value> =>
1058
+ Object.fromEntries(
1059
+ search.getTlcOrder().map((index) => [environment.variables[index], state[index]]),
1060
+ );
1061
+ const getAliasState = (
1062
+ alias: string,
1063
+ steps: Successor[],
1064
+ position: number,
1065
+ loopStart: number | undefined,
1066
+ ) => {
1067
+ // TLC evaluates TLCGet("level") and Trace in an alias at the state's position in the trace.
1068
+ runtime.getLevel = () => position + 1;
1069
+ runtime.getBehavior = () => steps.slice(0, position + 1).map((step) => step.state);
1070
+ return evaluateAlias(
1071
+ alias,
1072
+ steps[position].state,
1073
+ (steps[position + 1] ?? steps[loopStart ?? position]).state,
1074
+ );
1075
+ };
1076
+ const evaluateAlias = (alias: string, state: Value[], next: Value[] | undefined) => {
1077
+ try {
1078
+ const body = getConfigDefinition("alias", alias, environment).body;
1079
+ const value = evaluate(createIdentifier(alias), getContext(environment, state, next));
1080
+ const fieldOrder = body.kind === "Record" ? body.fields.map((field) => field.name) : [];
1081
+ return toAliasRecord(value, fieldOrder) ?? toRecord(state);
1082
+ } catch (error) {
1083
+ if (!(error instanceof TlaConfigError || error instanceof TlaEvaluationError)) throw error;
1084
+ return { ...toRecord(state), _ALIASEvalError: error.message };
1085
+ }
1086
+ };
1087
+ // TLC labels a step with the first action that takes it, evaluated as when the search expanded
1088
+ // the previous state.
1089
+ const getLabel = (index: number, previous: Value[], state: Value[]) => {
1090
+ nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
1091
+ const expanding = { ...current };
1092
+ Object.assign(current, { index, isExpanding: true, candidate: undefined });
1093
+ const fingerprintState = getFingerprintState(state);
1094
+ const action = nextActions.value.find((item) =>
1095
+ getSuccessors(item.expression, previous, environment, item.scope).some((successor) =>
1096
+ isSameState(getFingerprintState(successor.state), fingerprintState),
1097
+ ),
1098
+ );
1099
+ Object.assign(current, expanding);
1100
+ return action && getActionLabel(action);
1101
+ };
1102
+ const toTrace = (steps: Successor[], path: number[], loopStart?: number): TraceStep[] => {
1103
+ const alias = config.alias;
1104
+ const labels = withoutOutput(() => {
1105
+ // TLC rebuilds a trace from the initial predicate, which can reset what TLCSet stored.
1106
+ if (steps.length > 1 && isImpure(environment)) getSpecInitialStates();
1107
+ // TLC finds the action that takes each step before it evaluates the alias.
1108
+ return steps.map((step, position) =>
1109
+ position === 0 || step.action === "Stuttering"
1110
+ ? undefined
1111
+ : getLabel(path[position - 1], steps[position - 1].state, step.state),
1112
+ );
524
1113
  });
1114
+ return steps.map((step, position) => ({
1115
+ action: step.action,
1116
+ label: labels[position],
1117
+ state:
1118
+ alias === undefined
1119
+ ? toRecord(step.state)
1120
+ : getAliasState(alias, steps, position, loopStart),
1121
+ }));
1122
+ };
1123
+ const getSpecInitialStates = () =>
1124
+ spec.init === undefined ? [] : getInitialStates(spec.init, environment, spec.scope);
1125
+ const getTraceSuccessors = (state: Value[]) =>
1126
+ spec.next === undefined ? [] : getSuccessors(spec.next, state, environment, spec.scope);
1127
+ const hasFingerprint = (state: Value[], index: number) =>
1128
+ isSameState(getFingerprintState(state), fingerprintStates[index]);
1129
+ const findSuccessorWithFingerprint = (state: Value[], index: number) =>
1130
+ getTraceSuccessors(state).find((successor) => hasFingerprint(successor.state, index));
1131
+ const getPathStates = (path: number[], nextFailure: string) => {
1132
+ const initial =
1133
+ isReducing || isImpure(environment)
1134
+ ? getSpecInitialStates().find((state) => hasFingerprint(state, path[0]))
1135
+ : states[path[0]];
1136
+ if (!initial) throw new TlaEvaluationError(INITIAL_RECOVERY_FAILURE);
1137
+ const steps: Successor[] = [{ state: initial, action: undefined }];
1138
+ for (let position = 1; position < path.length; position++) {
1139
+ const previous = steps[position - 1].state;
1140
+ if (path[position - 1] === path[position]) {
1141
+ steps.push({ state: previous, action: "Stuttering" });
1142
+ continue;
1143
+ }
1144
+ const successor = findSuccessorWithFingerprint(previous, path[position]);
1145
+ if (!successor) throw new TlaEvaluationError(nextFailure);
1146
+ steps.push(successor);
1147
+ }
1148
+ return steps;
1149
+ };
1150
+ const getTrace = (index: number, last?: Successor) => {
1151
+ const path: number[] = [];
1152
+ for (let position = index; position !== -1; position = parents[position]) {
1153
+ path.unshift(position);
1154
+ }
1155
+ const steps =
1156
+ isReducing && path.length > 1
1157
+ ? getPathStates(path, INITIAL_RECOVERY_FAILURE)
1158
+ : path.map((position) => ({ state: states[position], action: actions[position] }));
1159
+ if (!last) return toTrace(steps, path);
1160
+ const action = isReducing
1161
+ ? getTraceSuccessors(states[index]).find((successor) =>
1162
+ isSameState(successor.state, last.state),
1163
+ )?.action
1164
+ : last.action;
1165
+ return toTrace([...steps, { state: last.state, action }], path);
1166
+ };
1167
+ // TLC prints an initial state on its own without evaluating the alias.
1168
+ const getStateTrace = (index: number) =>
1169
+ parents[index] === -1
1170
+ ? [{ action: undefined, label: undefined, state: toRecord(states[index]) }]
1171
+ : getTrace(index);
1172
+ // TLC names the initial state it was checking unless a standard module's Java code failed.
1173
+ const toFailure = (
1174
+ error: unknown,
1175
+ trace: TraceStep[],
1176
+ initialState?: Value[],
1177
+ failureOutDegrees?: number[],
1178
+ ) => {
1179
+ if (!(error instanceof TlaEvaluationError)) throw error;
1180
+ return {
1181
+ ...createResult("error", undefined, {
1182
+ message: error.message,
1183
+ trace,
1184
+ initialState:
1185
+ initialState && !(error instanceof TlaModuleError) ? toRecord(initialState) : undefined,
1186
+ exitCode: getErrorExitCode(error),
1187
+ }),
1188
+ outDegrees: failureOutDegrees,
1189
+ };
1190
+ };
1191
+ const getPathSteps = (path: number[], loopStart?: number) => {
1192
+ const steps = getPathStates(path, NEXT_RECOVERY_FAILURE);
1193
+ const last = steps[steps.length - 1].state;
1194
+ const isClosed =
1195
+ !isReducing ||
1196
+ loopStart === undefined ||
1197
+ loopStart === path.length - 1 ||
1198
+ findSuccessorWithFingerprint(last, path[loopStart]) !== undefined;
1199
+ if (!isClosed) throw new TlaEvaluationError(NEXT_RECOVERY_FAILURE);
1200
+ return steps;
1201
+ };
525
1202
  const getStateHash = (state: Value[]) => {
526
1203
  let hash = 0x811c9dc5;
527
1204
  for (let index = 0; index < state.length; index++)
@@ -534,19 +1211,35 @@ export const check = (options: CheckOptions): CheckResult => {
534
1211
  }
535
1212
  return true;
536
1213
  };
1214
+ const getSlot = (hash: number) => (Math.imul(hash, 0x9e3779b1) >>> seen.shift) << 1;
537
1215
  const findStateIndex = (hash: number, state: Value[]) => {
538
- const bucket = buckets.get(hash);
539
- if (bucket === undefined) return -1;
540
- if (typeof bucket === "number") {
541
- return isSameState(fingerprintStates[bucket], state) ? bucket : -1;
1216
+ const mask = seen.slots.length - 1;
1217
+ for (let slot = getSlot(hash); ; slot = (slot + 2) & mask) {
1218
+ const entry = seen.slots[slot + 1];
1219
+ if (entry === 0) return -1;
1220
+ if (seen.slots[slot] === hash && isSameState(fingerprintStates[entry - 1], state)) {
1221
+ return entry - 1;
1222
+ }
542
1223
  }
543
- return bucket.find((index) => isSameState(fingerprintStates[index], state)) ?? -1;
1224
+ };
1225
+ const insertSeen = (hash: number, entry: number) => {
1226
+ const mask = seen.slots.length - 1;
1227
+ let slot = getSlot(hash);
1228
+ while (seen.slots[slot + 1] !== 0) slot = (slot + 2) & mask;
1229
+ seen.slots[slot] = hash;
1230
+ seen.slots[slot + 1] = entry;
544
1231
  };
545
1232
  const markSeen = (hash: number, index: number) => {
546
- const bucket = buckets.get(hash);
547
- if (bucket === undefined) buckets.set(hash, index);
548
- else if (typeof bucket === "number") buckets.set(hash, [bucket, index]);
549
- else bucket.push(index);
1233
+ seen.size++;
1234
+ if (seen.size * 4 > seen.slots.length) {
1235
+ const slots = seen.slots;
1236
+ seen.slots = new Int32Array(slots.length * 2);
1237
+ seen.shift--;
1238
+ for (let slot = 0; slot < slots.length; slot += 2) {
1239
+ if (slots[slot + 1] !== 0) insertSeen(slots[slot], slots[slot + 1]);
1240
+ }
1241
+ }
1242
+ insertSeen(hash, index + 1);
550
1243
  };
551
1244
  const countDistinctState = (depth: number) => {
552
1245
  runtime.distinctStates = states.length + 1;
@@ -572,21 +1265,44 @@ export const check = (options: CheckOptions): CheckResult => {
572
1265
  isExpanding: false,
573
1266
  candidate: undefined as Value[] | undefined,
574
1267
  candidateLevel: 0,
1268
+ livenessSource: -1,
575
1269
  };
576
1270
  const getPath = (index: number): Value[][] =>
577
1271
  index === -1 ? [] : [...getPath(parents[index]), states[index]];
1272
+ runtime.isSeen = (state) => {
1273
+ const fingerprintState = getFingerprintState(state);
1274
+ return findStateIndex(getStateHash(fingerprintState), fingerprintState) !== -1;
1275
+ };
578
1276
  runtime.getBehavior = (state) => {
579
1277
  const index = state === current.candidate ? -1 : states.indexOf(state);
580
1278
  return index === -1 ? [...getPath(current.index), state] : getPath(index);
581
1279
  };
1280
+ runtime.getCurrentState = () => (current.index === -1 ? undefined : states[current.index]);
1281
+ runtime.setLivenessSource = (index) => {
1282
+ current.livenessSource = index ?? -1;
1283
+ };
582
1284
  runtime.getLevel = (state) => {
1285
+ const source = current.livenessSource;
1286
+ if (source !== -1) return state === states[source] ? depths[source] : depths[source] + 1;
583
1287
  if (state === current.candidate) return current.candidateLevel;
584
1288
  if (current.index === -1) return 0;
585
1289
  if (state === states[current.index]) return depths[current.index];
586
1290
  return current.isExpanding ? depths[current.index] + 1 : 0;
587
1291
  };
588
1292
 
589
- for (const state of getInitialStates(spec.init, environment)) {
1293
+ const getGraphState = (state: Value[], level: number): GraphState => ({
1294
+ fingerprint: BigInt.asIntN(64, runtime.getFingerprint(state)),
1295
+ level,
1296
+ getLabel: () =>
1297
+ formatState(
1298
+ config.alias === undefined
1299
+ ? toRecord(state)
1300
+ : evaluateAlias(config.alias, state, undefined),
1301
+ ),
1302
+ getText: () => formatState(toRecord(state)),
1303
+ });
1304
+
1305
+ const visitInitialState = (state: Value[]) => {
590
1306
  canonicalizeState(state);
591
1307
  runtime.generatedStates++;
592
1308
  runtime.initialStates++;
@@ -594,111 +1310,269 @@ export const check = (options: CheckOptions): CheckResult => {
594
1310
  current.candidateLevel = 1;
595
1311
  const fingerprintState = getFingerprintState(state);
596
1312
  const hash = getStateHash(fingerprintState);
597
- const isSeen = findStateIndex(hash, fingerprintState) !== -1;
598
- const isInModel = isSeen || search.satisfiesConstraints(state);
1313
+ const isInModel = search.satisfiesConstraints(state);
599
1314
  if (isInModel) search.trackStatePossible(state);
600
- if (isSeen) continue;
1315
+ const isSeen = isInModel && findStateIndex(hash, fingerprintState) !== -1;
1316
+ if (isSeen) return undefined;
601
1317
  if (isInModel) {
602
1318
  countDistinctState(1);
603
1319
  runtime.queueSize++;
604
1320
  liveness?.addInitialState(states.length, state);
1321
+ stateWriter?.writeInitialState(getGraphState(state, 1));
605
1322
  }
606
1323
  const violated = search.findViolatedInvariant(state);
607
1324
  if (violated) {
608
- return createResult("invariant-violation", {
1325
+ return reportViolation("invariant-violation", {
609
1326
  name: violated.name,
610
- trace: [{ action: undefined, state: toRecord(state) }],
1327
+ trace: toTrace([{ action: undefined, state }], []),
611
1328
  });
612
1329
  }
613
1330
  const failedPredicate = search.findFailedInitialPredicate(state);
614
1331
  if (failedPredicate) {
615
- return createResult("liveness-violation", {
1332
+ return reportViolation("liveness-violation", {
616
1333
  name: failedPredicate.name,
617
- trace: [{ action: undefined, state: toRecord(state) }],
1334
+ trace: toTrace([{ action: undefined, state }], []),
618
1335
  });
619
1336
  }
620
- if (!isInModel) continue;
1337
+ if (!isInModel) return undefined;
621
1338
  markSeen(hash, states.length);
622
1339
  addState(state, fingerprintState, -1, undefined);
623
- }
624
-
625
- for (let index = 0; index < states.length && !runtime.isStopped; index++) {
1340
+ return undefined;
1341
+ };
1342
+ const visitSuccessor = (
1343
+ index: number,
1344
+ successor: Successor,
1345
+ liveSuccessors: LiveSuccessor[],
1346
+ source: GraphState | undefined,
1347
+ action: SpecAction | undefined,
1348
+ ) => {
626
1349
  const state = states[index];
627
- current.index = index;
628
- runtime.queueSize = states.length - index - 1;
629
- current.isExpanding = true;
630
- const successors = getSuccessors(spec.next, state, environment);
631
- current.isExpanding = false;
632
- if (successors.length === 0 && config.checkDeadlock) {
633
- return createResult("deadlock", { name: "deadlock", trace: getTrace(index) });
1350
+ runtime.generatedStates++;
1351
+ current.candidate = successor.state;
1352
+ current.candidateLevel = depths[index] + 1;
1353
+ if (isCanonicalizedFirst) canonicalizeState(successor.state);
1354
+ const fingerprintState = getFingerprintState(successor.state);
1355
+ const hash = getStateHash(fingerprintState);
1356
+ const found = findStateIndex(hash, fingerprintState);
1357
+ const isStateInModel = search.satisfiesConstraints(successor.state, state);
1358
+ if (isStateInModel) search.trackStatePossible(successor.state);
1359
+ const isInModel = isStateInModel && search.satisfiesActionConstraints(state, successor.state);
1360
+ if (isInModel) search.trackActionPossible(state, successor.state);
1361
+ const existing = isInModel ? found : -1;
1362
+ if (source && isInModel) {
1363
+ stateWriter?.writeSuccessor(
1364
+ source,
1365
+ getGraphState(successor.state, depths[index] + 1),
1366
+ existing !== -1,
1367
+ action && { name: action.name, signature: getActionSignature(action) },
1368
+ );
634
1369
  }
635
- const liveSuccessors: LiveSuccessor[] = [];
636
- for (const successor of successors) {
637
- runtime.generatedStates++;
638
- current.candidate = successor.state;
639
- current.candidateLevel = depths[index] + 1;
640
- if (isCanonicalizedFirst) canonicalizeState(successor.state);
641
- const fingerprintState = getFingerprintState(successor.state);
642
- const hash = getStateHash(fingerprintState);
643
- const found = findStateIndex(hash, fingerprintState);
644
- const isStateInModel = found !== -1 || search.satisfiesConstraints(successor.state, state);
645
- if (isStateInModel) search.trackStatePossible(successor.state);
646
- const isInModel = isStateInModel && search.satisfiesActionConstraints(state, successor.state);
647
- if (isInModel) search.trackActionPossible(state, successor.state);
648
- const existing = isInModel ? found : -1;
649
- if (existing !== -1 && liveness) {
650
- const stored = states[existing];
651
- const isStored = stored.every((value, position) => value === successor.state[position]);
652
- liveSuccessors.push({ index: existing, state: isStored ? stored : successor.state });
653
- }
654
- const isNew = isInModel && existing === -1;
655
- if (isNew) countDistinctState(depths[index] + 1);
656
- if (existing === -1) {
1370
+ if (existing !== -1 && liveness) {
1371
+ const stored = states[existing];
1372
+ const isStored = stored.every((value, position) => value === successor.state[position]);
1373
+ liveSuccessors.push({ index: existing, state: isStored ? stored : successor.state });
1374
+ }
1375
+ const isNew = isInModel && existing === -1;
1376
+ if (isNew) {
1377
+ countDistinctState(depths[index] + 1);
1378
+ expansion.newStates++;
1379
+ }
1380
+ if (existing === -1) {
1381
+ try {
657
1382
  const violated = search.findViolatedInvariant(successor.state, state);
658
1383
  if (violated) {
659
- return createResult("invariant-violation", {
1384
+ return reportViolation("invariant-violation", {
660
1385
  name: violated.name,
661
1386
  trace: getTrace(index, successor),
662
1387
  });
663
1388
  }
1389
+ } catch (error) {
1390
+ // TLC prints the outdegree when it cannot reproduce the failure, as for an invariant here.
1391
+ return toFailure(error, getTrace(index, successor), undefined, getPartialOutDegrees());
664
1392
  }
665
- const violatedProperty = search.findViolatedActionProperty(state, successor.state);
666
- if (violatedProperty) {
667
- return createResult("liveness-violation", {
668
- name: violatedProperty.name,
669
- trace: getTrace(index, successor),
670
- });
1393
+ }
1394
+ const violatedProperty = search.findViolatedActionProperty(state, successor.state);
1395
+ if (violatedProperty) {
1396
+ return reportViolation("liveness-violation", {
1397
+ name: violatedProperty.name,
1398
+ trace: getTrace(index, successor),
1399
+ });
1400
+ }
1401
+ if (!isNew) return undefined;
1402
+ if (!isCanonicalizedFirst) canonicalizeState(successor.state);
1403
+ markSeen(hash, states.length);
1404
+ if (liveness) liveSuccessors.push({ index: states.length, state: successor.state });
1405
+ addState(successor.state, fingerprintState, index, successor.action);
1406
+ runtime.queueSize++;
1407
+ return undefined;
1408
+ };
1409
+
1410
+ const outcome: { result: CheckResult | undefined } = { result: undefined };
1411
+ if (spec.init !== undefined) {
1412
+ try {
1413
+ forEachInitialState(
1414
+ spec.init,
1415
+ environment,
1416
+ (state) => {
1417
+ try {
1418
+ outcome.result = visitInitialState(state);
1419
+ } catch (error) {
1420
+ outcome.result = toFailure(error, [], state);
1421
+ }
1422
+ return outcome.result !== undefined;
1423
+ },
1424
+ spec.scope,
1425
+ );
1426
+ } catch (error) {
1427
+ return toFailure(error, []);
1428
+ }
1429
+ }
1430
+ if (outcome.result) return outcome.result;
1431
+
1432
+ const next = spec.next;
1433
+ if (next === undefined) {
1434
+ if (states.length > 0) {
1435
+ throw new TlaEvaluationError(
1436
+ "No next state actions defined to generate successor states from.",
1437
+ );
1438
+ }
1439
+ return createSuccess();
1440
+ }
1441
+ // TLC labels and colors an edge of the -dump state graph by the action that generated it. When
1442
+ // the graph names its edges, the search generates successors action by action, as TLC does.
1443
+ const isNamingEdges = Boolean(
1444
+ options.dump?.dot && (options.dump.actionLabels || options.dump.colorize),
1445
+ );
1446
+ const forEachActionSuccessor = (
1447
+ state: Value[],
1448
+ onSuccessor: (successor: Successor, action: SpecAction | undefined) => boolean,
1449
+ ) => {
1450
+ if (!isNamingEdges) {
1451
+ return forEachSuccessor(
1452
+ next,
1453
+ state,
1454
+ environment,
1455
+ (successor) => onSuccessor(successor, undefined),
1456
+ spec.scope,
1457
+ );
1458
+ }
1459
+ nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
1460
+ const progress = { isStopped: false };
1461
+ return nextActions.value.reduce((count, action) => {
1462
+ if (progress.isStopped) return count;
1463
+ return (
1464
+ count +
1465
+ forEachSuccessor(
1466
+ action.expression,
1467
+ state,
1468
+ environment,
1469
+ (successor) => {
1470
+ progress.isStopped = onSuccessor(successor, action);
1471
+ return progress.isStopped;
1472
+ },
1473
+ action.scope,
1474
+ )
1475
+ );
1476
+ }, 0);
1477
+ };
1478
+ const expandState = (index: number) => {
1479
+ const state = states[index];
1480
+ const liveSuccessors: LiveSuccessor[] = [];
1481
+ const source = stateWriter && getGraphState(state, depths[index]);
1482
+ const successorCount = forEachActionSuccessor(state, (successor, action) => {
1483
+ try {
1484
+ outcome.result = visitSuccessor(index, successor, liveSuccessors, source, action);
1485
+ } catch (error) {
1486
+ outcome.result = toFailure(error, getTrace(index, successor));
671
1487
  }
672
- if (!isNew) continue;
673
- if (!isCanonicalizedFirst) canonicalizeState(successor.state);
674
- markSeen(hash, states.length);
675
- if (liveness) liveSuccessors.push({ index: states.length, state: successor.state });
676
- addState(successor.state, fingerprintState, index, successor.action);
677
- runtime.queueSize++;
1488
+ return outcome.result !== undefined;
1489
+ });
1490
+ current.isExpanding = false;
1491
+ if (outcome.result) return outcome.result;
1492
+ if (successorCount === 0 && config.checkDeadlock) {
1493
+ return reportViolation("deadlock", { name: "deadlock", trace: getStateTrace(index) });
678
1494
  }
679
- const accepted = liveness?.addState(index, state, liveSuccessors);
680
- if (accepted) {
681
- return createResult("property-violation", {
682
- name: accepted.name,
683
- trace: getPathTrace(accepted.path),
1495
+ try {
1496
+ const accepted = liveness?.addState(index, state, liveSuccessors);
1497
+ if (!liveness || !accepted) return undefined;
1498
+ const steps = getPathSteps(accepted);
1499
+ const properties = liveness.getViolatedProperties(
1500
+ steps.map((step) => step.state),
1501
+ steps.length - 1,
1502
+ );
1503
+ return reportViolation("property-violation", {
1504
+ name: properties[0],
1505
+ properties,
1506
+ trace: toTrace(steps, accepted),
684
1507
  });
1508
+ } catch (error) {
1509
+ return toFailure(error, getStateTrace(index), undefined, getPartialOutDegrees());
1510
+ }
1511
+ };
1512
+ // TLC names the properties and the step back into the cycle from the states it prints.
1513
+ const reportLasso = (checker: LivenessChecker, lasso: Lasso) => {
1514
+ const path = [...lasso.prefix, ...lasso.cycle];
1515
+ const loopStart = lasso.prefix.length;
1516
+ const steps = getPathSteps(path, loopStart);
1517
+ const trace = toTrace(steps, path, loopStart);
1518
+ const properties = checker.getViolatedProperties(
1519
+ steps.map((step) => step.state),
1520
+ loopStart,
1521
+ );
1522
+ const back = path[loopStart];
1523
+ const last = path[path.length - 1];
1524
+ const lastState = steps[steps.length - 1].state;
1525
+ const loopLabel =
1526
+ back === last ? undefined : withoutOutput(() => getLabel(last, lastState, states[back]));
1527
+ return reportViolation(
1528
+ "liveness-violation",
1529
+ { name: properties[0], properties, trace, loopStart, loopLabel },
1530
+ () =>
1531
+ back === last
1532
+ ? trace[trace.length - 1].action
1533
+ : findSuccessorWithFingerprint(lastState, back)?.action,
1534
+ );
1535
+ };
1536
+ const isPeriodic = liveness !== undefined && options.livenessCheck !== "final";
1537
+ const startedAt = performance.now();
1538
+ const periodic = { at: startedAt + PERIODIC_START, size: 1, time: 0 };
1539
+ const findPeriodicViolation = (expanded: number) => {
1540
+ const now = performance.now();
1541
+ periodic.at = now + PROGRESS_INTERVAL;
1542
+ const isGrown = (expanded - periodic.size) / periodic.size > LIVENESS_GROWTH;
1543
+ if (!isGrown || periodic.time > (now - startedAt) * LIVENESS_RATIO) return undefined;
1544
+ periodic.size = expanded;
1545
+ const lasso = liveness?.findViolation();
1546
+ periodic.time += performance.now() - now;
1547
+ return lasso;
1548
+ };
1549
+ for (let index = 0; index < states.length && !runtime.isStopped; index++) {
1550
+ current.index = index;
1551
+ current.candidate = undefined;
1552
+ runtime.queueSize = states.length - index - 1;
1553
+ current.isExpanding = true;
1554
+ try {
1555
+ outcome.result = expandState(index);
1556
+ } catch (error) {
1557
+ outcome.result = toFailure(withNextStateExitCode(error), getStateTrace(index));
1558
+ }
1559
+ if (outcome.result) return outcome.result;
1560
+ outDegrees[getOutDegreeBucket()]++;
1561
+ expansion.newStates = 0;
1562
+ if (isPeriodic && performance.now() >= periodic.at) {
1563
+ const lasso = findPeriodicViolation(index + 1);
1564
+ if (liveness && lasso) return reportLasso(liveness, lasso);
685
1565
  }
686
1566
  }
687
1567
 
688
1568
  current.index = -1;
689
1569
  current.candidate = undefined;
690
1570
  const lasso = liveness?.findViolation();
691
- if (lasso) {
692
- return createResult("liveness-violation", {
693
- name: lasso.name,
694
- trace: getPathTrace([...lasso.prefix, ...lasso.cycle]),
695
- loopStart: lasso.prefix.length,
696
- });
697
- }
1571
+ if (liveness && lasso) return reportLasso(liveness, lasso);
698
1572
 
699
- const postconditionViolation = search.findPostconditionViolation(print);
1573
+ const postconditionViolation = search.findPostconditionViolation();
700
1574
  if (postconditionViolation) {
701
- return createResult("postcondition-violation", postconditionViolation);
1575
+ return createResult("postcondition-violation", { ...postconditionViolation, trace: [] });
702
1576
  }
703
- return createResult("success");
1577
+ return createSuccess();
704
1578
  };