tla-ts 0.0.10-dev.b4a856304 → 0.0.10-dev.f16792fed

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 (72) hide show
  1. package/dist/index.cjs +1 -1
  2. package/dist/index.d.cts +34 -0
  3. package/dist/index.d.ts +34 -0
  4. package/dist/index.js +1 -1
  5. package/dist/parallel-worker.cjs +1 -1
  6. package/dist/parallel-worker.js +1 -1
  7. package/dist/prove.cjs +48 -48
  8. package/dist/prove.js +29 -29
  9. package/dist/run.cjs +40 -40
  10. package/dist/run.js +31 -31
  11. package/dist/transfer.cjs +36 -36
  12. package/dist/transfer.js +40 -40
  13. package/package.json +1 -1
  14. package/src/ast.ts +0 -5
  15. package/src/bags.ts +2 -5
  16. package/src/builtins.ts +1 -8
  17. package/src/check.ts +128 -193
  18. package/src/cli/options.ts +1 -1
  19. package/src/cli/run.ts +0 -2
  20. package/src/cli/runtime-invariants.ts +8 -7
  21. package/src/cli/shared.ts +0 -4
  22. package/src/cli/tlc-arguments.ts +24 -30
  23. package/src/cli/tlc-usage.ts +2 -3
  24. package/src/coverage.ts +3 -8
  25. package/src/evaluate.ts +26 -102
  26. package/src/java-hash.ts +7 -0
  27. package/src/java-overrides.ts +4 -9
  28. package/src/json-reader.ts +1 -2
  29. package/src/json.ts +4 -11
  30. package/src/levels.ts +7 -15
  31. package/src/lexer.ts +72 -83
  32. package/src/liveness-checker.ts +77 -106
  33. package/src/liveness.ts +10 -34
  34. package/src/parallel.ts +26 -33
  35. package/src/parser.ts +163 -226
  36. package/src/pcal/ast.ts +53 -65
  37. package/src/pcal/parse.ts +144 -191
  38. package/src/pcal/tokenize.ts +91 -115
  39. package/src/pcal/translate.ts +83 -98
  40. package/src/pcal/validate.ts +48 -50
  41. package/src/pretty-print.ts +6 -6
  42. package/src/randomization.ts +1 -4
  43. package/src/resolve.ts +12 -70
  44. package/src/runtime.ts +11 -18
  45. package/src/sany/builtins.ts +1 -3
  46. package/src/sany/generator.ts +74 -127
  47. package/src/sany/levels.ts +5 -9
  48. package/src/sany/lexer.ts +40 -44
  49. package/src/sany/linter.ts +0 -1
  50. package/src/sany/nodes.ts +4 -10
  51. package/src/search.ts +1 -1
  52. package/src/simulate.ts +50 -59
  53. package/src/spec-description.ts +23 -34
  54. package/src/standard-definitions.ts +0 -3
  55. package/src/standard-modules.ts +1 -12
  56. package/src/state-graph.ts +3 -15
  57. package/src/subexpressions.ts +38 -47
  58. package/src/successors.ts +14 -35
  59. package/src/symmetry.ts +4 -19
  60. package/src/tlc/fingerprint.ts +15 -21
  61. package/src/tlc/jar-data.ts +0 -1
  62. package/src/tlc/messages.ts +2 -21
  63. package/src/tlc/order.ts +22 -47
  64. package/src/tlc/random.ts +18 -30
  65. package/src/tlc/replay.ts +13 -33
  66. package/src/tlc/summary.ts +36 -45
  67. package/src/tlc/tlc-operators.ts +4 -14
  68. package/src/tlc/tlcext-operators.ts +11 -15
  69. package/src/tlc/trace-spec.ts +4 -9
  70. package/src/tlc/value-stream.ts +9 -13
  71. package/src/tlc/version.ts +0 -1
  72. package/src/values.ts +74 -186
package/src/check.ts CHANGED
@@ -21,11 +21,11 @@ import {
21
21
  TlaStackOverflowError,
22
22
  UNEXPECTED_EVAL_EXCEPTION,
23
23
  UNEXPECTED_EXCEPTION,
24
+ formatRange,
24
25
  } from "./errors";
25
26
  import {
26
27
  createTracingEnvironment,
27
28
  describeRange,
28
- formatRange,
29
29
  getDefinition,
30
30
  isImpure,
31
31
  type CallStack,
@@ -130,30 +130,30 @@ export interface CheckOptions {
130
130
  makeDirectory?: (path: string) => void;
131
131
  seed?: bigint;
132
132
  workers?: number;
133
- // TLC's -lncheck: "final" checks liveness only on the complete graph, "off" never looks for a cycle.
133
+ /** TLC's -lncheck: "final" checks liveness only on the complete graph, "off" never looks for a cycle. */
134
134
  livenessCheck?: "default" | "final" | "off";
135
- // TLC's -fp: the index of the polynomial in TLC's FP64.Polys that fingerprints states.
135
+ /** TLC's -fp: the index of the polynomial in TLC's FP64.Polys that fingerprints states. */
136
136
  fingerprintPolynomial?: number;
137
- // False for TLC's -terse, which prints a lazy value, such as SUBSET S, without enumerating it.
137
+ /** False for TLC's -terse, which prints a lazy value, such as SUBSET S, without enumerating it. */
138
138
  isLazyValueExpanded?: boolean;
139
- // TLC's -view: prints each state as the value of the configuration's VIEW.
139
+ /** TLC's -view: prints each state as the value of the configuration's VIEW. */
140
140
  isViewPrinted?: boolean;
141
- // TLC's -maxSetSize: the most elements TLC enumerates into a set, or states into a list of them.
141
+ /** TLC's -maxSetSize: the most elements TLC enumerates into a set, or states into a list of them. */
142
142
  maxSetSize?: number;
143
- // TLC's -dump: writes the reachable states, or with `dot` the state graph, through writeFile.
143
+ /** TLC's -dump: writes the reachable states, or with `dot` the state graph, through writeFile. */
144
144
  dump?: StateDump;
145
- // TLC's -tool, which changes the messages of TLC's errors.
145
+ /** TLC's -tool, which changes the messages of TLC's errors. */
146
146
  isTool?: boolean;
147
- // TLC's -continue: reports each violation through onProgress and goes on.
147
+ /** TLC's -continue: reports each violation through onProgress and goes on. */
148
148
  isContinued?: boolean;
149
149
  moduleOperators?: ModuleOperator[];
150
- // TLC's trace exploration spec, and the binary trace TLC records for it unless -noTEBin.
150
+ /** TLC's trace exploration spec, and the binary trace TLC records for it unless -noTEBin. */
151
151
  traceSpec?: TraceSpecOptions;
152
- // Whether the caller printed SANY's report, its warnings included, before the check.
152
+ /** Whether the caller printed SANY's report, its warnings included, before the check. */
153
153
  isSanyReported?: boolean;
154
- // False for TLC's -nowarning, which changes how TLC computes some successors.
154
+ /** False for TLC's -nowarning, which changes how TLC computes some successors. */
155
155
  isWarningEnabled?: boolean;
156
- // TLC's -coverage, in minutes.
156
+ /** TLC's -coverage, in minutes. */
157
157
  coverage?: number;
158
158
  version?: TlcVersion;
159
159
  onProgress?: (progress: CheckProgress) => void;
@@ -176,7 +176,6 @@ export interface InitialStatesProgress {
176
176
  count: number;
177
177
  }
178
178
 
179
- // A check TLC reports as violated before it stops replaying the initial states.
180
179
  export interface InitialStateViolation {
181
180
  kind: "initial-state-violation";
182
181
  status: "invariant-violation" | "liveness-violation";
@@ -184,7 +183,6 @@ export interface InitialStateViolation {
184
183
  state: Record<string, Value>;
185
184
  }
186
185
 
187
- // A line the spec prints, or what TLC reports as it replays the initial states.
188
186
  export type OutputLine = string | InitialStatesProgress | InitialStateViolation;
189
187
 
190
188
  export type CheckProgress =
@@ -200,17 +198,16 @@ export type CheckProgress =
200
198
  | {
201
199
  kind: "liveness-started";
202
200
  branches: number;
203
- // Whether TLC checks the complete state graph, and how many states of it each branch has.
201
+ /** Whether TLC checks the complete state graph. */
204
202
  isComplete: boolean;
203
+ /** How many states of the graph each branch has. */
205
204
  states: number;
206
205
  statistics: SearchStatistics;
207
206
  }
208
207
  | { kind: "liveness-finished" }
209
208
  | { kind: "sequential-fallback"; string: string }
210
209
  | { kind: "warning"; code: number; text: string }
211
- // A violation that the search goes on past with -continue.
212
210
  | { kind: "violation"; status: CheckStatus; violation: Violation }
213
- // A method of the class named after a module, which TLC reports as it loads the class.
214
211
  | ({ kind: "java-override" } & JavaOverride);
215
212
 
216
213
  export interface SearchStatistics extends Pick<
@@ -230,30 +227,30 @@ export type CheckStatus =
230
227
 
231
228
  export interface TraceStep {
232
229
  action: string | undefined;
233
- // TLC's name, parameters and location for the action that took this step.
230
+ /** TLC's name, parameters and location for the action that took this step. */
234
231
  label: string | undefined;
235
232
  state: Record<string, Value>;
236
- // What the spec prints before this step as TLC rebuilds the trace, and before it for the first.
233
+ /** What the spec prints before this step as TLC rebuilds the trace, and before it for the first. */
237
234
  output?: OutputLine[];
238
235
  }
239
236
 
240
237
  export interface Violation {
241
238
  name: string;
242
- // Every temporal property that a liveness counterexample violates, in the configuration's order.
239
+ /** Every temporal property that a liveness counterexample violates, in the configuration's order. */
243
240
  properties?: string[];
244
241
  trace: TraceStep[];
245
- // What the spec prints after the trace, as TLC finds the lasso's step back or rebuilds the trace.
242
+ /** What the spec prints after the trace, as TLC finds the lasso's step back or rebuilds the trace. */
246
243
  traceOutput?: OutputLine[];
247
- // What the postconditions print, which TLC checks after the lasso's step back.
244
+ /** What the postconditions print, which TLC checks after the lasso's step back. */
248
245
  postconditionOutput?: OutputLine[];
249
246
  loopStart: number | undefined;
250
247
  loopLabel?: string;
251
248
  message?: string;
252
249
  counts?: string;
253
250
  unwitnessed?: Postcondition;
254
- // A POSTCONDITION that is false or fails, which TLC checks as it prints the counterexample.
251
+ /** A POSTCONDITION that is false or fails, which TLC checks as it prints the counterexample. */
255
252
  postcondition?: Postcondition;
256
- // What TLC warns about after a counterexample, with its code.
253
+ /** What TLC warns about after a counterexample, with its code. */
257
254
  warning?: { code: number; text: string };
258
255
  }
259
256
 
@@ -264,7 +261,7 @@ export interface Postcondition {
264
261
  counts?: string;
265
262
  }
266
263
 
267
- // An evaluation that failed during the search, with the behavior up to the state TLC was working on.
264
+ /** An evaluation that failed during the search, with the behavior up to the state TLC was working on. */
268
265
  export interface EvaluationFailure {
269
266
  code: number;
270
267
  message: string;
@@ -273,17 +270,17 @@ export interface EvaluationFailure {
273
270
  traceOutput?: OutputLine[];
274
271
  initialState: Record<string, Value> | undefined;
275
272
  exitCode: number;
276
- // The expressions TLC was evaluating, outermost first, when its replay finds them.
273
+ /** The expressions TLC was evaluating, outermost first, when its replay finds them. */
277
274
  callStack: Expression[] | undefined;
278
- // Whether TLC prints the call stack before the error, as it does for a failed liveness check.
275
+ /** Whether TLC prints the call stack before the error, as it does for a failed liveness check. */
279
276
  isCallStackFirst?: boolean;
280
- // The FingerprintException the replay raises, which TLC reports in place of the call stack.
277
+ /** The FingerprintException the replay raises, which TLC reports in place of the call stack. */
281
278
  fingerprint?: FingerprintFailure;
282
- // How TLC reports failing again as it prints the trace, since it can't fingerprint the state.
279
+ /** How TLC reports failing again as it prints the trace, since it can't fingerprint the state. */
283
280
  traceFailure?: FailureMessage;
284
- // A POSTCONDITION that is false or fails after the trace, which TLC checks as it prints one.
281
+ /** A POSTCONDITION that is false or fails after the trace, which TLC checks as it prints one. */
285
282
  postcondition?: Postcondition;
286
- // Whether TLC stops before it prints the statistics, as it does for an illegal initial state.
283
+ /** Whether TLC stops before it prints the statistics, as it does for an illegal initial state. */
287
284
  isWithoutStatistics?: boolean;
288
285
  }
289
286
 
@@ -306,17 +303,17 @@ export interface CheckResult {
306
303
  distinctStates: number;
307
304
  queuedStates: number;
308
305
  depth: number;
309
- // Once TLC computed all the initial states without a violation or an error.
306
+ /** Once TLC computed all the initial states without a violation or an error. */
310
307
  initialStates: InitialStates | undefined;
311
- // How many expanded states found each number of new states, when TLC prints the outdegree.
308
+ /** How many expanded states found each number of new states, when TLC prints the outdegree. */
312
309
  outDegrees: number[] | undefined;
313
- // The smallest distance between two fingerprints, when TLC estimates a collision from them.
310
+ /** The smallest distance between two fingerprints, when TLC estimates a collision from them. */
314
311
  fingerprintDistance: bigint | undefined;
315
- // A temporal property TLC finds violated as it adds a deadlocked state, reported after.
312
+ /** A temporal property TLC finds violated as it adds a deadlocked state, reported after. */
316
313
  additionalViolation?: Violation;
317
- // Where TLC's worker fails to add the state to the behavior graph after it reports a violation.
314
+ /** Where TLC's worker fails to add the state to the behavior graph after it reports a violation. */
318
315
  liveCallStack?: Expression[];
319
- // The outdegrees when TLC's workers stop on a violation that TLC 1.7.4 reports as a success.
316
+ /** The outdegrees when TLC's workers stop on a violation that TLC 1.7.4 reports as a success. */
320
317
  violationOutDegrees?: number[];
321
318
  traceSpec?: string;
322
319
  coverage?: CoverageReport;
@@ -336,6 +333,24 @@ interface TraceOptions {
336
333
  known?: number;
337
334
  }
338
335
 
336
+ interface ReportedViolation extends Omit<Violation, "loopStart"> {
337
+ loopStart?: number;
338
+ }
339
+
340
+ interface RebuiltState {
341
+ state: Value[];
342
+ level: number;
343
+ }
344
+
345
+ interface SearchPosition {
346
+ index: number;
347
+ isExpanding: boolean;
348
+ candidate: Value[] | undefined;
349
+ candidateLevel: number;
350
+ livenessSource: number;
351
+ rebuilt: RebuiltState | undefined;
352
+ }
353
+
339
354
  interface FailureOptions {
340
355
  initialState?: Value[];
341
356
  isInitial?: boolean;
@@ -346,7 +361,6 @@ interface FailureOptions {
346
361
  isNextState?: boolean;
347
362
  isCallStackFirst?: boolean;
348
363
  traceFailure?: FailureMessage;
349
- // Whether TLC prints the call stack of adding the state to the behavior graph, not a replay.
350
364
  isLiveCallStack?: boolean;
351
365
  }
352
366
 
@@ -358,11 +372,9 @@ const appendTraceOutput = <Traced extends Behavior>(behavior: Traced, lines: Out
358
372
  const INITIAL_RECOVERY_FAILURE = "Failed to recover the initial state from its fingerprint.";
359
373
  const NEXT_RECOVERY_FAILURE = "Failed to recover the next state from its fingerprint.";
360
374
 
361
- // Stops a replay where TLC stops it without a failure, as at a violated invariant.
362
375
  const STOP_REPLAY = new Error("The replay stopped");
363
376
  const STOP_WALK = new Error("The walk stopped");
364
377
 
365
- // When TLC's replay of the initial states doesn't fail again, it exits with the error's code.
366
378
  const getInitialExitCode = (error: TlaEvaluationError) => {
367
379
  const coded = getCodedMessage(error.message);
368
380
  return coded &&
@@ -372,15 +384,12 @@ const getInitialExitCode = (error: TlaEvaluationError) => {
372
384
  : getErrorExitCode(error);
373
385
  };
374
386
 
375
- // When the replay fails again, a standard module's EvalException decides the exit status, and
376
- // any other failure exits as a nested expression failure. A heading or wrapping error defers.
377
387
  const getReplayExitCode = (error: TlaEvaluationError): number => {
378
388
  const inner = error.cause;
379
389
  if (inner instanceof TlaEvaluationError) return getReplayExitCode(inner);
380
390
  return error instanceof TlaModuleError ? error.exitCode : EXIT_STATUS.specEvaluationFailure;
381
391
  };
382
392
 
383
- // TLC finishes the -dump file whether or not the search finds a violation.
384
393
  export const checkSequentially = (options: CheckOptions): CheckResult => {
385
394
  const stateWriter =
386
395
  options.dump && createStateWriter(options.dump, options.writeFile, options.version);
@@ -393,8 +402,6 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
393
402
  }
394
403
  };
395
404
 
396
- // TLC checks liveness on the graph so far after 3 seconds and then every minute, once the graph
397
- // has grown by a tenth and liveness checking has taken at most a fifth of the time.
398
405
  const PERIODIC_START = 3000;
399
406
  const PROGRESS_INTERVAL = 60_000;
400
407
  const LIVENESS_GROWTH = 0.1;
@@ -406,20 +413,19 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
406
413
  ? parseConfig(options.config, options.version)
407
414
  : options.config;
408
415
  const onPrint = options.onPrint ?? console.log;
409
- // TLC prints again while it rebuilds a trace, so rebuilding keeps what it prints for the trace.
410
- const capturedOutput = { lines: undefined as OutputLine[] | undefined };
416
+ let capturedLines: OutputLine[] | undefined;
411
417
  const print = (text: string) => {
412
- if (capturedOutput.lines) capturedOutput.lines.push(text);
418
+ if (capturedLines) capturedLines.push(text);
413
419
  else onPrint(text);
414
420
  };
415
421
  const captureOutput = <Result>(rebuild: () => Result) => {
416
- const outer = capturedOutput.lines;
422
+ const outer = capturedLines;
417
423
  const lines: OutputLine[] = [];
418
- capturedOutput.lines = lines;
424
+ capturedLines = lines;
419
425
  try {
420
426
  return { result: rebuild(), lines };
421
427
  } finally {
422
- capturedOutput.lines = outer;
428
+ capturedLines = outer;
423
429
  }
424
430
  };
425
431
  const order = createTlcOrder(options.source, options.loadModule);
@@ -469,7 +475,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
469
475
  specification.variableLocations,
470
476
  specification.instanceActions,
471
477
  );
472
- const statistics = { depth: 0, initialStates: undefined as InitialStates | undefined };
478
+ let searchDepth = 0;
479
+ let computedInitialStates: InitialStates | undefined;
473
480
  const getTraceSpec = (trace: TraceStep[], loopStart: number | undefined) =>
474
481
  options.traceSpec &&
475
482
  writeTraceSpec({
@@ -488,10 +495,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
488
495
  });
489
496
  const createResult = (
490
497
  status: CheckStatus,
491
- violation?: Omit<Violation, "loopStart"> & { loopStart?: number },
498
+ violation?: ReportedViolation,
492
499
  failure?: EvaluationFailure,
493
500
  ): CheckResult => {
494
- // TLC writes the trace it printed, and a safety property's counterexample doesn't loop back.
495
501
  const traceSpec = getTraceSpec(
496
502
  violation?.trace ?? failure?.trace ?? [],
497
503
  status === "property-violation" ? undefined : violation?.loopStart,
@@ -503,8 +509,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
503
509
  generatedStates: runtime.generatedStates,
504
510
  distinctStates: runtime.distinctStates,
505
511
  queuedStates: runtime.queueSize,
506
- depth: runtime.generatedStates === 0 ? 0 : Math.max(statistics.depth, 1),
507
- initialStates: statistics.initialStates,
512
+ depth: runtime.generatedStates === 0 ? 0 : Math.max(searchDepth, 1),
513
+ initialStates: computedInitialStates,
508
514
  outDegrees: undefined,
509
515
  fingerprintDistance: undefined,
510
516
  coverage: coverage?.relations.some((relation) => relation.kind === "next")
@@ -519,16 +525,13 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
519
525
  };
520
526
  };
521
527
  const outDegrees = Array.from({ length: OUT_DEGREE_BUCKETS }, () => 0);
522
- const expansion = { newStates: 0 };
523
- const getOutDegreeBucket = () => Math.min(expansion.newStates, OUT_DEGREE_BUCKETS - 1);
524
- // TLC counts the state it was expanding when an evaluation failed, except TLC 1.7.4.
528
+ let newStateCount = 0;
529
+ const getOutDegreeBucket = () => Math.min(newStateCount, OUT_DEGREE_BUCKETS - 1);
525
530
  const getPartialOutDegrees = () =>
526
531
  outDegrees.map((count, degree) => (degree === getOutDegreeBucket() ? count + 1 : count));
527
532
  const getFailureOutDegrees = () => (is174 ? [...outDegrees] : getPartialOutDegrees());
528
- // TLC 1.7.4 doesn't name the properties a counterexample violates, so it evaluates none of them.
529
533
  const getViolatedProperties = (checker: LivenessChecker, path: Value[][], cycleStart: number) =>
530
534
  is174 ? [] : checker.getViolatedProperties(path, cycleStart);
531
- // A violation in a successor ends the expansion of a state before TLC counts it.
532
535
  const withOutDegrees = (result: CheckResult, degrees = [...outDegrees]): CheckResult => ({
533
536
  ...result,
534
537
  violationOutDegrees: degrees,
@@ -560,12 +563,11 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
560
563
  runtime.isStarted = true;
561
564
  const assumptionViolation = findViolatedAssumption();
562
565
  if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
563
- // TLC computes the initial states of a spec without variables, of which there are none.
564
- statistics.initialStates = { generated: 0, distinct: 0 };
566
+ computedInitialStates = { generated: 0, distinct: 0 };
565
567
  options.onProgress?.({ kind: "initial-states-started" });
566
568
  options.onProgress?.({
567
569
  kind: "initial-states-computed",
568
- initialStates: statistics.initialStates,
570
+ initialStates: computedInitialStates,
569
571
  });
570
572
  return createSuccess();
571
573
  }
@@ -573,7 +575,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
573
575
  config.postconditions.length > 0 ||
574
576
  config.possible.length > 0 ||
575
577
  specification.moduleOperators.some((operator) => operator.kind === "postcondition");
576
- // The state of each step without the alias, and its action, which CounterExample records.
577
578
  const traceSteps = new WeakMap<
578
579
  TraceStep,
579
580
  { state: Record<string, Value>; action: SpecAction | undefined }
@@ -583,7 +584,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
583
584
  const action = traceSteps.get(step)?.action;
584
585
  return action ? toActionValue(action) : createActionRecord(step.action);
585
586
  };
586
- // TLC checks the postconditions on each trace it prints, so what they print follows the trace.
587
587
  const checkTracePostconditions = (
588
588
  trace: TraceStep[],
589
589
  loop: { start: number; action: Value } | undefined,
@@ -603,7 +603,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
603
603
  };
604
604
  const reportViolation = (
605
605
  status: CheckStatus,
606
- violation: Omit<Violation, "loopStart"> & { loopStart?: number },
606
+ violation: ReportedViolation,
607
607
  getLoopAction?: () => Value,
608
608
  ) => {
609
609
  const start = violation.loopStart;
@@ -618,15 +618,13 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
618
618
  ...(checked.postcondition && { postcondition: checked.postcondition }),
619
619
  });
620
620
  };
621
- // With -continue, TLC prints the trace of a violation without checking the postconditions. It
622
- // never records the violation, and reports a success at the end, where tla-ts ends with the
623
- // status of the first violation, as -dfid and -simulate do.
624
- const continued = { status: undefined as CheckStatus | undefined };
621
+ // Deviation from TLC: -continue ends with the status of the first violation, not a success.
622
+ let continuedStatus: CheckStatus | undefined;
625
623
  const reportContinuedViolation = (
626
624
  status: CheckStatus,
627
625
  violation: Omit<Violation, "loopStart">,
628
626
  ) => {
629
- continued.status ??= status;
627
+ continuedStatus ??= status;
630
628
  options.onProgress?.({
631
629
  kind: "violation",
632
630
  status,
@@ -635,9 +633,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
635
633
  };
636
634
  const spec = search.spec;
637
635
  const getFingerprintState = search.getFingerprintState;
638
- const specNextActions = { value: undefined as SpecAction[] | undefined };
636
+ let specNextActions: SpecAction[] | undefined;
639
637
  const getSpecNextActions = () =>
640
- (specNextActions.value ??= getNextActions(config, environment, specification.instanceActions));
638
+ (specNextActions ??= getNextActions(config, environment, specification.instanceActions));
641
639
  // Tool's constructor splits the next-state relation into actions before TLC checks anything.
642
640
  getSpecNextActions();
643
641
  runtime.getSuccessorAction = (state, next) =>
@@ -680,7 +678,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
680
678
  onState(successor);
681
679
  },
682
680
  (partial) => {
683
- const missing = environment.variables.filter((_, index) => partial[index] === undefined);
681
+ const missing = environment.variables.filter(
682
+ (_variable, index) => partial[index] === undefined,
683
+ );
684
684
  throw new TlaIncompleteSuccessorError(
685
685
  `Successor state is not completely specified by action ${action.name}. The following variables are not assigned: ${missing.join(", ")}`,
686
686
  partial,
@@ -715,7 +715,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
715
715
  replay(tracing);
716
716
  return undefined;
717
717
  } catch (error) {
718
- // A replay that overflows the stack again has an empty call stack.
719
718
  if (isStackOverflow(error)) return { callStack: [], fingerprint: undefined };
720
719
  if (!(error instanceof TlaEvaluationError) || !callStack) return undefined;
721
720
  return {
@@ -725,7 +724,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
725
724
  };
726
725
  }
727
726
  };
728
- // Outermost first: each value fails as it fingerprints a value it holds.
729
727
  const findFailedSources = (value: Value, sources: CallStack["sources"]): Expression[] => {
730
728
  if (typeof value !== "object") return [];
731
729
  const source = sources.get(value);
@@ -735,13 +733,11 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
735
733
  ...(failed === undefined ? [] : findFailedSources(failed, sources)),
736
734
  ];
737
735
  };
738
- // A value the replay built raises a FingerprintException when TLC fails to fingerprint it.
739
736
  const fingerprintReplayed = (state: Value[], callStack: CallStack | undefined) => {
740
737
  for (const value of getFingerprintState(state)) {
741
738
  const error = getFingerprintError(value);
742
739
  if (!error) continue;
743
740
  const sources = callStack ? findFailedSources(value, callStack.sources) : [];
744
- // TLC fingerprints a state outside any evaluation, so its call stack is empty.
745
741
  if (callStack && sources.length > 0) {
746
742
  callStack.expressions.length = 0;
747
743
  callStack.isFrozen = true;
@@ -751,9 +747,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
751
747
  }
752
748
  state.forEach(markFingerprinted);
753
749
  };
754
- // TLC's set of states already holds the state that failed.
755
750
  const createReplayedStates = () => {
756
- const replayed = unstoredState.fingerprint ? [unstoredState.fingerprint] : [];
751
+ const replayed = unstoredFingerprint ? [unstoredFingerprint] : [];
757
752
  return (state: Value[], callStack: CallStack | undefined) => {
758
753
  fingerprintReplayed(state, callStack);
759
754
  const fingerprintState = getFingerprintState(state);
@@ -766,10 +761,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
766
761
  return true;
767
762
  };
768
763
  };
769
- // TLC reports its progress again as it replays the initial states. After a FingerprintException
770
- // or a StackOverflowError, it only counts the states left, then throws the error.
771
764
  const replayInit = () => {
772
- const replayed = { count: 0 };
765
+ let replayedCount = 0;
773
766
  const deferred: unknown[] = [];
774
767
  const addReplayed = createReplayedStates();
775
768
  return getReplayFailure((tracing) => {
@@ -777,11 +770,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
777
770
  getInitActions(config, environment, specification.instanceActions),
778
771
  tracing,
779
772
  (state) => {
780
- reportInitialStatesProgress(replayed.count, (progress) =>
781
- capturedOutput.lines?.push(progress),
782
- );
783
- replayed.count++;
784
- runtime.generatedStates = replayed.count;
773
+ reportInitialStatesProgress(replayedCount, (progress) => capturedLines?.push(progress));
774
+ replayedCount++;
775
+ runtime.generatedStates = replayedCount;
785
776
  if (deferred.length > 0) return;
786
777
  try {
787
778
  const addFingerprint = () => {
@@ -792,7 +783,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
792
783
  const violation = search.checkReplayedInitialState(state, tracing, addFingerprint);
793
784
  if (violation) {
794
785
  const traced = toTrace([{ action: undefined, state }], []).trace[0].state;
795
- capturedOutput.lines?.push({
786
+ capturedLines?.push({
796
787
  kind: "initial-state-violation",
797
788
  ...violation,
798
789
  state: traced,
@@ -810,7 +801,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
810
801
  if (deferred.length > 0) throw deferred[0];
811
802
  });
812
803
  };
813
- // TLC's replay writes each successor in the model to the -dump state graph again.
814
804
  const replayNext = (index: number) =>
815
805
  getReplayFailure((tracing) => {
816
806
  const state = states[index];
@@ -836,7 +826,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
836
826
  });
837
827
  const isReducing = config.view !== undefined || config.symmetry !== undefined;
838
828
  const tlcFingerprints: number[] = [];
839
- // TLC warns about the liveness checker before it builds it.
840
829
  if (search.properties.liveness.length > 0) {
841
830
  options.onProgress?.({
842
831
  kind: "liveness-initializing",
@@ -847,12 +836,13 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
847
836
  const liveness = withLivenessExitCode(() =>
848
837
  withUnexpectedException(() =>
849
838
  createLivenessChecker(search.properties.liveness, spec.temporals, environment, {
850
- getFingerprint: ({ index, state }) =>
851
- (tlcFingerprints[index] ??= Number(BigInt.asIntN(32, runtime.getFingerprint(state)))),
839
+ getFingerprint: (successor) =>
840
+ (tlcFingerprints[successor.index] ??= Number(
841
+ BigInt.asIntN(32, runtime.getFingerprint(successor.state)),
842
+ )),
852
843
  getSuccessors: (source, state) => {
853
844
  const successors: LiveSuccessor[] = [];
854
845
  if (spec.next === undefined) return successors;
855
- // The constraints read the level of the state whose successors they check.
856
846
  const livenessSource = current.livenessSource;
857
847
  current.livenessSource = source;
858
848
  try {
@@ -881,9 +871,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
881
871
  }),
882
872
  ),
883
873
  );
884
- // ModelChecker rejects a temporal property whose negation has no solution.
885
874
  if (liveness?.branches === 0) throw createTautologyError();
886
- // TLC 1.7.4 creates its model checker, which TLCGet reads, once it has built the liveness checker.
887
875
  runtime.isStarted = true;
888
876
  const isCanonicalizedFirst = search.isSymmetric || liveness !== undefined;
889
877
 
@@ -903,8 +891,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
903
891
  position: number,
904
892
  loopStart: number | undefined,
905
893
  ) => {
906
- // TLC evaluates TLCGet("level") and Trace in an alias at the state's position in the trace. The
907
- // search reads them again once the alias is evaluated, as it goes on with -continue.
908
894
  const searchLevel = runtime.getLevel;
909
895
  const searchBehavior = runtime.getBehavior;
910
896
  runtime.getLevel = () => position + 1;
@@ -922,8 +908,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
922
908
  };
923
909
  const evaluateAlias = (alias: string, state: Value[], next: Value[] | undefined) =>
924
910
  search.evaluateAlias(alias, state, next, options.isTool ?? false);
925
- // TLC finds the action of a step as the first that takes it, evaluated as when the search
926
- // expanded the previous state, by a held successor's values and otherwise by fingerprint.
927
911
  const findStepAction = (index: number, previous: Value[], state: Value[], isHeld: boolean) => {
928
912
  const actions = getSpecNextActions();
929
913
  const expanding = { ...current };
@@ -951,9 +935,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
951
935
  Object.assign(current, expanding);
952
936
  }
953
937
  };
954
- // TLC rebuilds the states it doesn't keep, all but the last `known`, from the initial predicate,
955
- // finds the action of each later step, and then rebuilds the trace once more, unless it is a
956
- // liveness counterexample or TLC is 1.7.4.
957
938
  const toTrace = (
958
939
  steps: Successor[],
959
940
  path: number[],
@@ -961,9 +942,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
961
942
  ): Behavior => {
962
943
  const alias = config.alias;
963
944
  const known = traceOptions.known ?? 1;
964
- // Rebuilding the trace from the initial predicate can reset what TLCSet stored.
965
945
  const initialOutput = steps.length > 1 ? captureOutput(getSpecInitialStates).lines : [];
966
- // TLC finds the action that takes each step before it evaluates the alias.
967
946
  const stepActions = steps.map((step, position) =>
968
947
  position === 0 || step.action === "Stuttering"
969
948
  ? { result: undefined, lines: [] }
@@ -978,9 +957,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
978
957
  );
979
958
  const outputs = stepActions.map((step) => step.lines);
980
959
  const loopStart = traceOptions.loopStart;
981
- // TLC 1.7.4 rebuilds a lasso up to its cycle at once, then each cycle state as it prints it.
982
960
  const rebuilt = is174 && loopStart !== undefined ? loopStart + 1 : steps.length - known;
983
- // What the trace prints once comes from each time TLC rebuilds it, which coverage counts.
984
961
  if (coverage && steps.length > 1) {
985
962
  const isRebuiltAgain = known > 0 && !is174;
986
963
  if (rebuilt > 0 && isRebuiltAgain) captureOutput(getSpecInitialStates);
@@ -1023,8 +1000,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1023
1000
  if (coverage) return getCoveredInitialStates();
1024
1001
  return spec.init === undefined ? [] : getInitialStates(spec.init, environment, spec.scope);
1025
1002
  };
1026
- // TLC rebuilds a successor action by action, up to the first that generates it. A trace keeps
1027
- // what the spec prints as TLC rebuilds it, so finding its states prints nothing.
1028
1003
  const findTraceSuccessor = (state: Value[], isMatch: (successor: Successor) => boolean) =>
1029
1004
  captureOutput(() => {
1030
1005
  for (const action of getSpecNextActions()) {
@@ -1053,7 +1028,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1053
1028
  steps.push({ state: previous, action: "Stuttering" });
1054
1029
  continue;
1055
1030
  }
1056
- // TLC rebuilds each state at its level, which TLCGet reads.
1057
1031
  const rebuilt = current.rebuilt;
1058
1032
  current.rebuilt = { state: previous, level: depths[path[position - 1]] };
1059
1033
  const successor = findSuccessorWithFingerprint(previous, path[position]);
@@ -1080,8 +1054,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1080
1054
  : lastSuccessor.action;
1081
1055
  return toTrace([...steps, { state: lastSuccessor.state, action }], path, { known: 2 });
1082
1056
  };
1083
- // TLC rebuilds a lone initial state, unlike TLC 1.7.4. TLCTrace#printTrace prints it without the
1084
- // alias, where tla-ts applies the alias as it does to every other trace.
1057
+ // Deviation from TLC: TLCTrace#printTrace prints a lone initial state without the alias.
1085
1058
  const getStateTrace = (index: number): Behavior =>
1086
1059
  parents[index] === -1
1087
1060
  ? {
@@ -1103,8 +1076,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1103
1076
  traceOutput: is174 ? [] : captureOutput(getSpecInitialStates).lines,
1104
1077
  }
1105
1078
  : getTrace(index);
1106
- // TLC rebuilds the trace for the postcondition after a violation, but not after a failure.
1107
- // TLC fails again to fingerprint the successor in the trace, as an unexpected exception.
1108
1079
  const isUnfingerprintable = (state: Value[]) => {
1109
1080
  try {
1110
1081
  return getFingerprintState(state).some((value) => getFingerprintError(value) !== undefined);
@@ -1116,9 +1087,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1116
1087
  const getFailedTrace = (index: number, successor: Successor): Behavior => ({
1117
1088
  trace: getTrace(index, successor).trace,
1118
1089
  });
1119
- // TLC names the initial state it was checking unless a standard module's Java code failed.
1120
1090
  const getFailureExitCode = (error: TlaEvaluationError, failureOptions: FailureOptions) => {
1121
- // TLC 1.7.4 exits with the result of replaying the initial states, which fails again only here.
1122
1091
  if (
1123
1092
  failureOptions.isInitial &&
1124
1093
  !failureOptions.callStack &&
@@ -1131,13 +1100,11 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1131
1100
  return failureOptions.isInitial ? getInitialExitCode(error) : getErrorExitCode(error);
1132
1101
  }
1133
1102
  if (failureOptions.isCallStackFirst) return getErrorExitCode(error);
1134
- // Without a replay, TLC exits with the code of the error, as for any error it didn't expect.
1135
1103
  if (failureOptions.isLiveCallStack) {
1136
1104
  return (
1137
1105
  getExitCode(error) ?? (error instanceof TlaModuleError ? error.exitCode : EXIT_STATUS.error)
1138
1106
  );
1139
1107
  }
1140
- // TLC exits with the code of a failed initial replay whatever the error, as for a fingerprint.
1141
1108
  return failureOptions.isInitial || failureOptions.fingerprint
1142
1109
  ? EXIT_STATUS.specEvaluationFailure
1143
1110
  : getReplayExitCode(failureOptions.replayError ?? error);
@@ -1174,13 +1141,11 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1174
1141
  outDegrees: failureOptions.outDegrees,
1175
1142
  };
1176
1143
  };
1177
- // TLC reports a partial successor with the trace to it, naming the action if there are several.
1178
1144
  const reportIncompleteSuccessor = (index: number, error: TlaIncompleteSuccessorError) => {
1179
1145
  runtime.generatedStates++;
1180
1146
  const actions = getSpecNextActions();
1181
1147
  const named =
1182
1148
  actions.length === 1 ? actions : actions.filter((item) => item.name === error.action);
1183
- // Inline disjuncts of the next-state relation share its name, so TLC's is the one that failed.
1184
1149
  const action =
1185
1150
  named.length === 1
1186
1151
  ? named[0]
@@ -1234,7 +1199,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1234
1199
  hash = combineHash(hash, getValueHash(state[index]));
1235
1200
  return hash & 0x3fffffff;
1236
1201
  };
1237
- // TLC fingerprints a state once it finds the state in the model.
1238
1202
  const fingerprintModelState = (state: Value[]) => {
1239
1203
  for (const value of state) {
1240
1204
  const error = getFingerprintError(value);
@@ -1277,11 +1241,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1277
1241
  }
1278
1242
  insertSeen(hash, index + 1);
1279
1243
  };
1280
- // TLC adds a new successor to its states before it checks it, which the check stores after.
1281
- const unstoredState = { fingerprint: undefined as Value[] | undefined };
1244
+ let unstoredFingerprint: Value[] | undefined;
1282
1245
  const countDistinctState = (depth: number) => {
1283
1246
  runtime.distinctStates = states.length + 1;
1284
- statistics.depth = Math.max(statistics.depth, depth);
1247
+ searchDepth = Math.max(searchDepth, depth);
1285
1248
  runtime.diameter = Math.max(runtime.diameter, depth);
1286
1249
  };
1287
1250
  const addState = (
@@ -1298,13 +1261,13 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1298
1261
  depths.push(depth);
1299
1262
  };
1300
1263
 
1301
- const current = {
1264
+ const current: SearchPosition = {
1302
1265
  index: -1,
1303
1266
  isExpanding: false,
1304
- candidate: undefined as Value[] | undefined,
1267
+ candidate: undefined,
1305
1268
  candidateLevel: 0,
1306
1269
  livenessSource: -1,
1307
- rebuilt: undefined as { state: Value[]; level: number } | undefined,
1270
+ rebuilt: undefined,
1308
1271
  };
1309
1272
  const getPath = (index: number): Value[][] =>
1310
1273
  index === -1 ? [] : [...getPath(parents[index]), states[index]];
@@ -1322,7 +1285,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1322
1285
  };
1323
1286
  runtime.getLevel = (state) => {
1324
1287
  const source = current.livenessSource;
1325
- // TLC 1.7.4 reads the level of the state its worker explores, whichever state it evaluates.
1326
1288
  if (is174) {
1327
1289
  const explored = source !== -1 ? source : current.isExpanding ? current.index : -1;
1328
1290
  return explored === -1 ? 0 : depths[explored];
@@ -1368,7 +1330,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1368
1330
  }
1369
1331
  const isSeen = isInModel && findStateIndex(hash, fingerprintState) !== -1;
1370
1332
  if (isSeen) return undefined;
1371
- unstoredState.fingerprint = isInModel ? fingerprintState : undefined;
1333
+ unstoredFingerprint = isInModel ? fingerprintState : undefined;
1372
1334
  if (isInModel) {
1373
1335
  countDistinctState(1);
1374
1336
  runtime.queueSize++;
@@ -1453,13 +1415,12 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1453
1415
  liveSuccessors.push({ index: existing, state: isStored ? stored : successor.state });
1454
1416
  }
1455
1417
  const isNew = isInModel && existing === -1;
1456
- // TLC adds a new state to the behavior graph's successors before it checks the invariants.
1457
1418
  if (isNew && liveness) liveSuccessors.push({ index: states.length, state: successor.state });
1458
- unstoredState.fingerprint = isNew ? fingerprintState : undefined;
1419
+ unstoredFingerprint = isNew ? fingerprintState : undefined;
1459
1420
  if (isNew) {
1460
1421
  countDistinctState(depths[index] + 1);
1461
- expansion.newStates++;
1462
- if (coverage) coverage.secondary[coveredAction.node]++;
1422
+ newStateCount++;
1423
+ if (coverage) coverage.secondary[coveredNode]++;
1463
1424
  }
1464
1425
  if (existing === -1) {
1465
1426
  try {
@@ -1471,8 +1432,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1471
1432
  if (violation) reportContinuedViolation("invariant-violation", violation);
1472
1433
  } catch (error) {
1473
1434
  if (isStackOverflow(error)) throw error;
1474
- // TLC replays the expansion and skips the invariants of a seen state, the failed one
1475
- // included unless the constraints exclude it. A failed replay leaves out the outdegree.
1476
1435
  const replay = captureOutput(() => replayNext(index));
1477
1436
  return createFailureResult(
1478
1437
  error,
@@ -1499,18 +1458,16 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1499
1458
  return undefined;
1500
1459
  };
1501
1460
 
1502
- const outcome: { result: CheckResult | undefined } = { result: undefined };
1503
- const coveredAction = { node: -1 };
1461
+ let outcome: CheckResult | undefined;
1462
+ let coveredNode = -1;
1504
1463
  if (liveness) {
1505
1464
  options.onProgress?.({ kind: "liveness-prepared", branches: liveness.branches });
1506
1465
  }
1507
- // TLC checks the assumptions once it has built the liveness checker.
1508
1466
  const assumptionViolation = findViolatedAssumption();
1509
1467
  if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
1510
1468
  options.onProgress?.({ kind: "initial-states-started" });
1511
1469
  if (spec.init !== undefined) {
1512
- // TLC keeps an initial state's StackOverflowError, counts the states after it, then reports it.
1513
- const overflow: { state: Value[] | undefined } = { state: undefined };
1470
+ let overflowState: Value[] | undefined;
1514
1471
  const reportInitialFailure = (error: unknown, state: Value[]) => {
1515
1472
  const replay = captureOutput(replayInit);
1516
1473
  return createFailureResult(
@@ -1522,18 +1479,18 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1522
1479
  try {
1523
1480
  const onInitialState = (state: Value[]) => {
1524
1481
  reportInitialStatesProgress(runtime.initialStates, options.onProgress);
1525
- if (overflow.state) {
1482
+ if (overflowState) {
1526
1483
  runtime.generatedStates++;
1527
1484
  runtime.initialStates++;
1528
1485
  return false;
1529
1486
  }
1530
1487
  try {
1531
- outcome.result = visitInitialState(state);
1488
+ outcome = visitInitialState(state);
1532
1489
  } catch (error) {
1533
- if (isStackOverflow(error)) overflow.state = state;
1534
- else outcome.result = reportInitialFailure(error, state);
1490
+ if (isStackOverflow(error)) overflowState = state;
1491
+ else outcome = reportInitialFailure(error, state);
1535
1492
  }
1536
- return outcome.result !== undefined;
1493
+ return outcome !== undefined;
1537
1494
  };
1538
1495
  if (coverage) {
1539
1496
  try {
@@ -1553,11 +1510,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1553
1510
  } else {
1554
1511
  forEachInitialState(spec.init, environment, onInitialState, spec.scope);
1555
1512
  }
1556
- if (overflow.state) {
1557
- outcome.result = reportInitialFailure(createStackOverflowError(), overflow.state);
1513
+ if (overflowState) {
1514
+ outcome = reportInitialFailure(createStackOverflowError(), overflowState);
1558
1515
  }
1559
1516
  } catch (error) {
1560
- // TLC prints null for each undefined variable and stops before the statistics.
1561
1517
  if (error instanceof TlaIllegalStateError) {
1562
1518
  const illegal = createFailureResult(
1563
1519
  error,
@@ -1569,7 +1525,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1569
1525
  failure: illegal.failure && { ...illegal.failure, isWithoutStatistics: true },
1570
1526
  };
1571
1527
  }
1572
- // TLC prints the error before it replays the initial predicate with its call stack.
1573
1528
  const replay = captureOutput(replayInit);
1574
1529
  return createFailureResult(
1575
1530
  error,
@@ -1578,14 +1533,14 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1578
1533
  );
1579
1534
  }
1580
1535
  }
1581
- if (outcome.result) return outcome.result;
1582
- statistics.initialStates = {
1536
+ if (outcome) return outcome;
1537
+ computedInitialStates = {
1583
1538
  generated: runtime.initialStates,
1584
1539
  distinct: runtime.distinctStates,
1585
1540
  };
1586
1541
  options.onProgress?.({
1587
1542
  kind: "initial-states-computed",
1588
- initialStates: statistics.initialStates,
1543
+ initialStates: computedInitialStates,
1589
1544
  });
1590
1545
 
1591
1546
  const next = spec.next;
@@ -1597,8 +1552,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1597
1552
  }
1598
1553
  return createSuccess();
1599
1554
  }
1600
- // TLC labels and colors a -dump edge by its action, so a graph that names its edges generates
1601
- // successors action by action.
1602
1555
  const isNamingEdges = Boolean(
1603
1556
  options.dump?.dot && (options.dump.actionLabels || options.dump.colorize),
1604
1557
  );
@@ -1610,19 +1563,19 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1610
1563
  onSuccessor: (successor: Successor, action: SpecAction | undefined) => boolean,
1611
1564
  ) => {
1612
1565
  if (coverage) {
1613
- const progress = { count: 0 };
1566
+ let successorCount = 0;
1614
1567
  try {
1615
1568
  coverageActions.forEach((action) => {
1616
- coveredAction.node = action.node;
1569
+ coveredNode = action.node;
1617
1570
  walkCoveredSuccessors(action, state, (successor) => {
1618
- progress.count++;
1571
+ successorCount++;
1619
1572
  if (onSuccessor({ state: successor, action: action.name }, action)) throw STOP_WALK;
1620
1573
  });
1621
1574
  });
1622
1575
  } catch (error) {
1623
1576
  if (error !== STOP_WALK) throw error;
1624
1577
  }
1625
- return progress.count;
1578
+ return successorCount;
1626
1579
  }
1627
1580
  if (!isNamingEdges) {
1628
1581
  return forEachSuccessor(
@@ -1635,9 +1588,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1635
1588
  onUnsatisfied,
1636
1589
  );
1637
1590
  }
1638
- const progress = { isStopped: false };
1591
+ let isStopped = false;
1639
1592
  return getSpecNextActions().reduce((count, action) => {
1640
- if (progress.isStopped) return count;
1593
+ if (isStopped) return count;
1641
1594
  return (
1642
1595
  count +
1643
1596
  forEachSuccessor(
@@ -1645,8 +1598,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1645
1598
  state,
1646
1599
  environment,
1647
1600
  (successor) => {
1648
- progress.isStopped = onSuccessor(successor, action);
1649
- return progress.isStopped;
1601
+ isStopped = onSuccessor(successor, action);
1602
+ return isStopped;
1650
1603
  },
1651
1604
  action.scope,
1652
1605
  undefined,
@@ -1655,8 +1608,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1655
1608
  );
1656
1609
  }, 0);
1657
1610
  };
1658
- // TLC's worker adds a state to the behavior graph even after its next states fail, and prints
1659
- // the call stack of an error in that, unless it is a FingerprintException. TLC 1.7.4 prints none.
1660
1611
  const getLiveCallStack = (index: number, liveSuccessors: LiveSuccessor[]) => {
1661
1612
  if (!liveness || is174) return undefined;
1662
1613
  const replay = getReplayFailure((tracing) =>
@@ -1664,8 +1615,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1664
1615
  );
1665
1616
  return replay?.callStack.length && !replay.fingerprint ? replay.callStack : undefined;
1666
1617
  };
1667
- // On an error in adding the state after the trace, TLC adds it again to print the call stack
1668
- // instead of replaying the next-state relation, which TLC 1.7.4 doesn't.
1669
1618
  const addFailedLiveState = (index: number, liveSuccessors: LiveSuccessor[]) => {
1670
1619
  try {
1671
1620
  liveness?.addState(index, states[index], liveSuccessors);
@@ -1684,10 +1633,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1684
1633
  const replay = captureOutput(() => replayNext(index));
1685
1634
  return { result: replay.result, lines: [...live.lines, ...replay.lines] };
1686
1635
  };
1687
- // TLC reports a stack overflow in the next states without a replay, up to the state it expands.
1688
1636
  const reportNextStateOverflow = (index: number) =>
1689
1637
  createFailureResult(createStackOverflowError(), getStateTrace(index), { isNextState: true });
1690
- // After the trace, TLC replays the next-state relation with its call stack, printing again.
1691
1638
  const reportNextStateFailure = (
1692
1639
  error: unknown,
1693
1640
  index: number,
@@ -1716,19 +1663,17 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1716
1663
  : undefined;
1717
1664
  const successorCount = forEachActionSuccessor(state, writeUnsatisfied, (successor, action) => {
1718
1665
  try {
1719
- outcome.result = visitSuccessor(index, successor, liveSuccessors, source, action);
1666
+ outcome = visitSuccessor(index, successor, liveSuccessors, source, action);
1720
1667
  } catch (error) {
1721
1668
  if (isStackOverflow(error)) {
1722
- outcome.result = reportNextStateOverflow(index);
1669
+ outcome = reportNextStateOverflow(index);
1723
1670
  return true;
1724
1671
  }
1725
- // TLC 1.7.4 reports the wrapped error without the trace, except for a failed property, and
1726
- // stops its worker before it adds the state to the behavior graph.
1727
1672
  const replay = is174
1728
1673
  ? captureOutput(() => replayNext(index))
1729
1674
  : replayFailedNext(index, liveSuccessors);
1730
1675
  if (is174 && error instanceof TlaEvaluationError && !isHeadedError(error)) {
1731
- outcome.result = createFailureResult(
1676
+ outcome = createFailureResult(
1732
1677
  new TlaEvaluationError(`${getWrappedException(error)}${error.message}`, error),
1733
1678
  appendTraceOutput({ trace: [] }, replay.lines),
1734
1679
  { isNextState: true, ...replay.result },
@@ -1745,7 +1690,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1745
1690
  true,
1746
1691
  )
1747
1692
  : undefined;
1748
- outcome.result = createFailureResult(
1693
+ outcome = createFailureResult(
1749
1694
  error,
1750
1695
  appendTraceOutput(
1751
1696
  traceFailure ? getStateTrace(index) : getFailedTrace(index, successor),
@@ -1754,11 +1699,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1754
1699
  { isNextState: true, ...replay.result, traceFailure },
1755
1700
  );
1756
1701
  }
1757
- return outcome.result !== undefined;
1702
+ return outcome !== undefined;
1758
1703
  });
1759
1704
  current.isExpanding = false;
1760
- const result = outcome.result;
1761
- // TLC 1.7.4's worker stops at a violation.
1705
+ const result = outcome;
1762
1706
  if (result?.violation && !is174) {
1763
1707
  const live = captureOutput(() => addFailedLiveState(index, liveSuccessors));
1764
1708
  return {
@@ -1788,8 +1732,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1788
1732
  };
1789
1733
  if (successorCount === 0 && config.checkDeadlock) {
1790
1734
  const deadlock = reportViolation("deadlock", { name: "deadlock", ...getStateTrace(index) });
1791
- // TLC's worker still adds the deadlocked state to the behavior graph, reports a temporal
1792
- // property that violates, and then counts the state as expanded.
1793
1735
  const live = captureOutput(() => {
1794
1736
  try {
1795
1737
  return { additional: addLiveState()?.violation };
@@ -1801,7 +1743,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1801
1743
  const reported = deadlock.violation
1802
1744
  ? { ...deadlock, violation: appendTraceOutput(deadlock.violation, live.lines) }
1803
1745
  : deadlock;
1804
- // An error in adding the state stops TLC 1.7.4's worker before it counts the state.
1805
1746
  const counted = withOutDegrees(
1806
1747
  reported,
1807
1748
  live.result.isFailed ? getFailureOutDegrees() : getPartialOutDegrees(),
@@ -1813,7 +1754,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1813
1754
  try {
1814
1755
  return addLiveState();
1815
1756
  } catch (error) {
1816
- // TLC 1.7.4 reports this as an unexpected exception, without the trace or a call stack.
1817
1757
  if (is174 && error instanceof TlaEvaluationError) {
1818
1758
  const unexpected = new TlaEvaluationError(
1819
1759
  `${isEvalException(error) ? UNEXPECTED_EVAL_EXCEPTION : UNEXPECTED_EXCEPTION}${error.message}`,
@@ -1824,7 +1764,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1824
1764
  { outDegrees: getFailureOutDegrees() },
1825
1765
  );
1826
1766
  }
1827
- // TLC adds the state again for the call stack, prints it first, and blames the next states.
1828
1767
  const replay = getReplayFailure((tracing) =>
1829
1768
  liveness?.addState(index, state, liveSuccessors, tracing),
1830
1769
  );
@@ -1853,7 +1792,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1853
1792
  text: `The stuttering counterexample above may be caused by the absence of a fairness constraint in the behavior specification ${name} defined at ${formatRange(range)}. To rule out such counterexamples, conjoin a suitable fairness constraint to ${name} ${book}`,
1854
1793
  };
1855
1794
  };
1856
- // TLC names the properties and the step back into the cycle from the states it prints.
1857
1795
  const reportLasso = (checker: LivenessChecker, lasso: Lasso) => {
1858
1796
  const path = [...lasso.prefix, ...lasso.cycle];
1859
1797
  const loopStart = lasso.prefix.length;
@@ -1924,22 +1862,20 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1924
1862
  current.isExpanding = true;
1925
1863
  const liveSuccessors: LiveSuccessor[] = [];
1926
1864
  try {
1927
- outcome.result = expandState(index, liveSuccessors);
1865
+ outcome = expandState(index, liveSuccessors);
1928
1866
  } catch (error) {
1929
- outcome.result =
1867
+ outcome =
1930
1868
  error instanceof TlaIncompleteSuccessorError
1931
1869
  ? reportIncompleteSuccessor(index, error)
1932
1870
  : reportNextStateFailure(error, index, liveSuccessors);
1933
1871
  }
1934
- if (outcome.result) return outcome.result;
1872
+ if (outcome) return outcome;
1935
1873
  outDegrees[getOutDegreeBucket()]++;
1936
- expansion.newStates = 0;
1937
- // TLC checks liveness on the graph so far, then reports how far the search got.
1874
+ newStateCount = 0;
1938
1875
  if ((isPeriodic || options.onProgress) && performance.now() >= periodic.at) {
1939
1876
  periodic.at = performance.now() + PROGRESS_INTERVAL;
1940
1877
  const lasso = isPeriodic ? findPeriodicViolation(index + 1) : undefined;
1941
1878
  if (liveness && lasso) return reportLasso(liveness, lasso);
1942
- // TLC reports the coverage with every report after the first `coverage` reports since the last.
1943
1879
  const isCoverageDue = options.coverage !== undefined && periodic.coverageCount === 0;
1944
1880
  periodic.coverageCount = isCoverageDue
1945
1881
  ? Math.trunc(options.coverage ?? 0)
@@ -1967,7 +1903,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1967
1903
  const lasso = finalLiveness?.findViolation();
1968
1904
  if (finalLiveness && lasso) return reportLasso(finalLiveness, lasso);
1969
1905
 
1970
- // TLC finishes the check of the temporal properties before it checks the postconditions.
1971
1906
  if (finalLiveness) options.onProgress?.({ kind: "liveness-finished" });
1972
1907
  const missingPostcondition = specification.moduleOperators.find(
1973
1908
  (operator) => operator.kind === "postcondition" && operator.key === undefined,
@@ -1985,5 +1920,5 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1985
1920
  postcondition,
1986
1921
  });
1987
1922
  }
1988
- return continued.status ? createResult(continued.status) : createSuccess();
1923
+ return continuedStatus ? createResult(continuedStatus) : createSuccess();
1989
1924
  };