tla-ts 0.0.10-dev.09e53c2a6 → 0.0.10-dev.1ebc153bd

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 (214) hide show
  1. package/dist/compile.cjs +3 -3
  2. package/dist/compile.js +1 -1
  3. package/dist/deciders.cjs +36 -36
  4. package/dist/deciders.js +54 -54
  5. package/dist/index.cjs +1 -1
  6. package/dist/index.d.cts +2 -1
  7. package/dist/index.d.ts +2 -1
  8. package/dist/index.js +1 -1
  9. package/dist/parallel-worker.cjs +1 -1
  10. package/dist/parallel-worker.js +1 -1
  11. package/dist/prove-worker.cjs +1 -1
  12. package/dist/prove-worker.js +1 -1
  13. package/dist/prove.cjs +43 -43
  14. package/dist/prove.js +78 -78
  15. package/dist/run.cjs +33 -35
  16. package/dist/run.js +44 -46
  17. package/dist/tlapm.cjs +1 -1
  18. package/dist/tlapm.js +2 -2
  19. package/dist/transfer.cjs +43 -43
  20. package/dist/transfer.js +38 -38
  21. package/dist/worker.cjs +6 -6
  22. package/dist/worker.js +6 -6
  23. package/package.json +1 -1
  24. package/src/ast.ts +1 -0
  25. package/src/bags.ts +46 -28
  26. package/src/check-trace.ts +2 -16
  27. package/src/check.ts +152 -64
  28. package/src/cli/runtime-invariants.ts +20 -56
  29. package/src/cli/tlc-arguments.ts +2 -2
  30. package/src/cli/tlc-output.ts +1 -2
  31. package/src/cli/tlc.ts +13 -8
  32. package/src/cli/xml-exporter.ts +1 -1
  33. package/src/codegen.ts +9 -5
  34. package/src/dependencies.ts +49 -9
  35. package/src/dfid.ts +9 -2
  36. package/src/environment.ts +57 -33
  37. package/src/errors.ts +7 -0
  38. package/src/evaluate.ts +92 -32
  39. package/src/exit-codes.ts +4 -2
  40. package/src/instances.ts +5 -5
  41. package/src/java-overrides.ts +2 -2
  42. package/src/levels.ts +138 -90
  43. package/src/liveness-checker.ts +43 -4
  44. package/src/liveness.ts +1 -1
  45. package/src/obligations/index.ts +1 -1
  46. package/src/obligations/normalize.ts +1 -4
  47. package/src/obligations/printer.ts +5 -5
  48. package/src/parallel-worker.ts +8 -2
  49. package/src/parallel.ts +5 -0
  50. package/src/parser.ts +106 -144
  51. package/src/prover/isabelle/isar/attrib.ts +4 -4
  52. package/src/prover/isabelle/isar/rule-cases.ts +8 -6
  53. package/src/prover/isabelle/provers/clasimp.ts +1 -1
  54. package/src/prover/isabelle/provers/hypsubst.ts +2 -2
  55. package/src/prover/isabelle/pure/rewriter.ts +3 -3
  56. package/src/prover/isabelle/pure/term.ts +3 -3
  57. package/src/prover/prep/md5.ts +26 -29
  58. package/src/prover/smt/rewrite.ts +2 -7
  59. package/src/prover/smt/simplify.ts +1 -1
  60. package/src/prover/smt/solver/asserted-formulas.ts +66 -1
  61. package/src/prover/smt/solver/ast-lt.ts +1 -1
  62. package/src/prover/smt/solver/ast.ts +58 -11
  63. package/src/prover/smt/solver/blast-term-ite.ts +47 -0
  64. package/src/prover/smt/solver/bound-simplifier.ts +2 -3
  65. package/src/prover/smt/solver/bv-decl-plugin.ts +13 -10
  66. package/src/prover/smt/solver/bv-rewriter.ts +1 -1
  67. package/src/prover/smt/solver/card2bv.ts +3 -5
  68. package/src/prover/smt/solver/cofactor-elim-term-ite.ts +2 -3
  69. package/src/prover/smt/solver/context.ts +24 -3
  70. package/src/prover/smt/solver/ctx-simplify.ts +1 -2
  71. package/src/prover/smt/solver/datatype-decl-plugin.ts +15 -7
  72. package/src/prover/smt/solver/dependent-expr-state.ts +9 -4
  73. package/src/prover/smt/solver/diff-neq.ts +1 -2
  74. package/src/prover/smt/solver/elim-term-ite-tactic.ts +48 -0
  75. package/src/prover/smt/solver/elim-uncnstr.ts +4 -7
  76. package/src/prover/smt/solver/euf/arith-internalize.ts +1 -1
  77. package/src/prover/smt/solver/euf/array-internalize.ts +1 -1
  78. package/src/prover/smt/solver/euf/bv-internalize.ts +1 -1
  79. package/src/prover/smt/solver/euf/egraph.ts +4 -10
  80. package/src/prover/smt/solver/euf/euf-solver.ts +1 -2
  81. package/src/prover/smt/solver/euf/mam.ts +1 -5
  82. package/src/prover/smt/solver/euf/q-ematch.ts +1 -2
  83. package/src/prover/smt/solver/euf/th-solver.ts +0 -7
  84. package/src/prover/smt/solver/expr2polynomial.ts +204 -79
  85. package/src/prover/smt/solver/factor.ts +36 -14
  86. package/src/prover/smt/solver/fd-solver.ts +2 -0
  87. package/src/prover/smt/solver/fix-dl-var.ts +1 -2
  88. package/src/prover/smt/solver/fpa-rewriter.ts +1 -2
  89. package/src/prover/smt/solver/fpa2bv-converter.ts +3 -1
  90. package/src/prover/smt/solver/fpa2bv-rewriter.ts +1 -0
  91. package/src/prover/smt/solver/goal.ts +6 -3
  92. package/src/prover/smt/solver/goal2nlsat.ts +57 -30
  93. package/src/prover/smt/solver/hashtable.ts +4 -0
  94. package/src/prover/smt/solver/logic-tactics.ts +9 -2
  95. package/src/prover/smt/solver/lp/containers.ts +7 -1
  96. package/src/prover/smt/solver/lp/cross-nested.ts +1 -3
  97. package/src/prover/smt/solver/lp/lp-settings.ts +1 -1
  98. package/src/prover/smt/solver/lp/nex-creator.ts +3 -2
  99. package/src/prover/smt/solver/lp/nex.ts +2 -1
  100. package/src/prover/smt/solver/lp/nla-core.ts +1 -1
  101. package/src/prover/smt/solver/lp/nla-grobner.ts +158 -80
  102. package/src/prover/smt/solver/lp/nra-solver.ts +45 -39
  103. package/src/prover/smt/solver/lp/pdd-interval.ts +6 -2
  104. package/src/prover/smt/solver/lp/pdd-simplifier.ts +60 -20
  105. package/src/prover/smt/solver/lp/pdd-solver.ts +72 -39
  106. package/src/prover/smt/solver/lp/pdd.ts +725 -290
  107. package/src/prover/smt/solver/lp/union-find.ts +1 -1
  108. package/src/prover/smt/solver/mam-compiler.ts +1 -1
  109. package/src/prover/smt/solver/model-based-opt.ts +1 -1
  110. package/src/prover/smt/solver/model-generator.ts +3 -1
  111. package/src/prover/smt/solver/mpf.ts +2 -4
  112. package/src/prover/smt/solver/mus.ts +2 -3
  113. package/src/prover/smt/solver/muz/dl-context.ts +10 -4
  114. package/src/prover/smt/solver/muz/dl-mk-slice.ts +3 -3
  115. package/src/prover/smt/solver/muz/dl-rule.ts +2 -2
  116. package/src/prover/smt/solver/muz/horn-subsume-model-converter.ts +1 -1
  117. package/src/prover/smt/solver/muz/horn-tactic.ts +1 -1
  118. package/src/prover/smt/solver/muz/spacer-context.ts +2 -4
  119. package/src/prover/smt/solver/muz/spacer-pdr.ts +1 -0
  120. package/src/prover/smt/solver/nlqsat.ts +1 -1
  121. package/src/prover/smt/solver/nlsat/algebraic.ts +196 -92
  122. package/src/prover/smt/solver/nlsat/atoms.ts +52 -33
  123. package/src/prover/smt/solver/nlsat/explain.ts +375 -217
  124. package/src/prover/smt/solver/nlsat/levelwise.ts +460 -240
  125. package/src/prover/smt/solver/nlsat/polynomial.ts +2366 -681
  126. package/src/prover/smt/solver/nlsat/solver.ts +74 -64
  127. package/src/prover/smt/solver/nlsat/transcendentals.ts +41 -17
  128. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +8 -4
  129. package/src/prover/smt/solver/nlsat/upolynomial.ts +41 -18
  130. package/src/prover/smt/solver/nlsat-tactic.ts +1 -1
  131. package/src/prover/smt/solver/nnf.ts +6 -2
  132. package/src/prover/smt/solver/opt-context.ts +9 -3
  133. package/src/prover/smt/solver/opt-nlsat.ts +29 -18
  134. package/src/prover/smt/solver/opt-preprocess.ts +1 -1
  135. package/src/prover/smt/solver/opt-solver.ts +6 -3
  136. package/src/prover/smt/solver/optsmt.ts +1 -1
  137. package/src/prover/smt/solver/pb-rewriter.ts +1 -4
  138. package/src/prover/smt/solver/poly-rewriter.ts +74 -18
  139. package/src/prover/smt/solver/probes.ts +88 -23
  140. package/src/prover/smt/solver/proto-model.ts +4 -6
  141. package/src/prover/smt/solver/qe-arith-plugin.ts +2 -4
  142. package/src/prover/smt/solver/qe-lite.ts +2 -2
  143. package/src/prover/smt/solver/qe.ts +3 -2
  144. package/src/prover/smt/solver/quantifier-manager.ts +14 -9
  145. package/src/prover/smt/solver/recfun-decl-plugin.ts +2 -1
  146. package/src/prover/smt/solver/rlimit.ts +4 -0
  147. package/src/prover/smt/solver/sat/config.ts +1 -1
  148. package/src/prover/smt/solver/sat/inc-sat-solver.ts +26 -1
  149. package/src/prover/smt/solver/sat/model-converter.ts +1 -1
  150. package/src/prover/smt/solver/sat/pb-solver.ts +1 -1
  151. package/src/prover/smt/solver/sat/sat-tactic.ts +4 -3
  152. package/src/prover/smt/solver/sat/simplifier.ts +1 -1
  153. package/src/prover/smt/solver/sat/solver.ts +25 -47
  154. package/src/prover/smt/solver/seq-axioms.ts +20 -35
  155. package/src/prover/smt/solver/seq-decl-plugin.ts +1 -1
  156. package/src/prover/smt/solver/seq-derive.ts +4 -7
  157. package/src/prover/smt/solver/seq-eq-solver.ts +2 -2
  158. package/src/prover/smt/solver/seq-monadic.ts +7 -5
  159. package/src/prover/smt/solver/seq-re-rewriter.ts +2 -1
  160. package/src/prover/smt/solver/seq-re-util.ts +1 -1
  161. package/src/prover/smt/solver/seq-regex-bisim.ts +1 -1
  162. package/src/prover/smt/solver/seq-regex-live.ts +2 -2
  163. package/src/prover/smt/solver/seq-rewriter.ts +31 -29
  164. package/src/prover/smt/solver/seq-skolem.ts +0 -23
  165. package/src/prover/smt/solver/seq-view-witness.ts +4 -4
  166. package/src/prover/smt/solver/smt-kernel.ts +9 -3
  167. package/src/prover/smt/solver/smt-setup.ts +68 -6
  168. package/src/prover/smt/solver/smtlib-parser.ts +558 -220
  169. package/src/prover/smt/solver/smtlib-script.ts +495 -153
  170. package/src/prover/smt/solver/solve-eqs.ts +13 -21
  171. package/src/prover/smt/solver/tactic.ts +219 -130
  172. package/src/prover/smt/solver/theory-bv.ts +2 -2
  173. package/src/prover/smt/solver/theory-lra-final-check.ts +1 -1
  174. package/src/prover/smt/solver/theory-lra-internalize.ts +1 -0
  175. package/src/prover/smt/solver/theory-lra-propagate.ts +6 -4
  176. package/src/prover/smt/solver/theory-lra.ts +0 -1
  177. package/src/prover/smt/solver/theory-pb.ts +24 -7
  178. package/src/prover/smt/solver/theory-seq-solve.ts +1 -1
  179. package/src/prover/smt/solver/theory-seq-state.ts +2 -21
  180. package/src/prover/tlapm/cache.ts +8 -8
  181. package/src/prover/zenon/equality-rules.ts +24 -0
  182. package/src/prover/zenon/expr.ts +21 -0
  183. package/src/prover/zenon/index-table.ts +7 -2
  184. package/src/prover/zenon/isar-case.ts +1 -1
  185. package/src/prover/zenon/isar.ts +2 -2
  186. package/src/prover/zenon/phrase.ts +1 -1
  187. package/src/prover/zenon/rules.ts +2 -1
  188. package/src/resolve.ts +624 -187
  189. package/src/runtime.ts +3 -1
  190. package/src/sany/builtins.ts +10 -10
  191. package/src/sany/generation.ts +2 -13
  192. package/src/sany/generator-definitions.ts +3 -1
  193. package/src/sany/generator-expressions.ts +36 -30
  194. package/src/sany/generator-proofs.ts +5 -3
  195. package/src/sany/generator.ts +2 -1
  196. package/src/sany/lexer.ts +3 -3
  197. package/src/sany/modules.ts +4 -2
  198. package/src/sany/nodes.ts +1 -1
  199. package/src/sany/selectors.ts +11 -6
  200. package/src/sany/xml.ts +2 -3
  201. package/src/search.ts +51 -22
  202. package/src/spec-description.ts +2 -2
  203. package/src/subexpressions.ts +265 -94
  204. package/src/successors.ts +1 -0
  205. package/src/symmetry.ts +1 -1
  206. package/src/tlc/jar-data.ts +10 -0
  207. package/src/tlc/messages.ts +3 -3
  208. package/src/tlc/order.ts +14 -3
  209. package/src/tlc/tlc-operators.ts +3 -1
  210. package/src/tlc/tlcext-operators.ts +18 -5
  211. package/src/tlc/trace-spec.ts +5 -5
  212. package/src/typed-tier.ts +29 -23
  213. package/src/typescript/types.ts +2 -2
  214. package/src/values.ts +46 -27
package/src/check.ts CHANGED
@@ -47,6 +47,7 @@ import {
47
47
  getStateHash,
48
48
  isSameState,
49
49
  markSeenState,
50
+ type StateTable,
50
51
  } from "./fingerprints";
51
52
  import type { JavaOverride } from "./java-overrides";
52
53
  import {
@@ -205,7 +206,7 @@ export type CheckProgress =
205
206
  branches: number;
206
207
  /** Whether TLC checks the complete state graph. */
207
208
  isComplete: boolean;
208
- /** How many states of the graph each branch has. */
209
+ /** How many states the graphs of all branches have together. */
209
210
  states: number;
210
211
  statistics: SearchStatistics;
211
212
  }
@@ -414,6 +415,15 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
414
415
  key.startsWith(`${name}${KEY_SEPARATOR}`),
415
416
  ),
416
417
  });
418
+ const getCoverage = () =>
419
+ coverage?.relations.some((relation) => relation.kind === "next")
420
+ ? getCoverageReport(
421
+ coverage,
422
+ environment,
423
+ specification.variableLocations,
424
+ search?.getTlcOrder() ?? [],
425
+ )
426
+ : undefined;
417
427
  const createResult = (
418
428
  status: CheckStatus,
419
429
  violation?: ReportedViolation,
@@ -434,14 +444,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
434
444
  initialStates: computedInitialStates,
435
445
  outDegrees: undefined,
436
446
  fingerprintDistance: undefined,
437
- coverage: coverage?.relations.some((relation) => relation.kind === "next")
438
- ? getCoverageReport(
439
- coverage,
440
- environment,
441
- specification.variableLocations,
442
- search?.getTlcOrder() ?? [],
443
- )
444
- : undefined,
447
+ coverage: getCoverage(),
445
448
  ...(traceSpec !== undefined && { traceSpec }),
446
449
  };
447
450
  };
@@ -465,7 +468,12 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
465
468
  : getFingerprintDistance(runtime.distinctStates, runtime.generatedStates, (visit) =>
466
469
  visit(
467
470
  search
468
- ? search.getStoredFingerprints(states, fingerprintStates)
471
+ ? search.getStoredFingerprints(
472
+ exploredStates.length === 0 ? states : states.concat(exploredStates),
473
+ exploredStates.length === 0
474
+ ? fingerprintStates
475
+ : fingerprintStates.concat(exploredFingerprintStates),
476
+ )
469
477
  : BigInt64Array.from(states, runtime.getFingerprint),
470
478
  ),
471
479
  ),
@@ -478,6 +486,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
478
486
  () => created.order.getDeclarationOrder("variable"),
479
487
  options.onProgress,
480
488
  specification.moduleOperators,
489
+ specification.runtimeInvariants,
481
490
  );
482
491
  const findViolatedAssumption = () =>
483
492
  findAssumptionViolation(specification.assumptions, environment);
@@ -554,12 +563,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
554
563
  const getFingerprintState = search.getFingerprintState;
555
564
  // Tool's constructor splits the next-state relation into actions before TLC checks anything.
556
565
  const nextActions = getDescription().actions;
557
- runtime.getSuccessorAction = (state, next) =>
558
- nextActions.find((action) =>
559
- getSuccessors(action.expression, state, environment, action.scope).some((successor) =>
560
- successor.state.every((value, index) => isSameValue(value, next[index])),
561
- ),
562
- );
563
566
  const addCoverageRelations = (kind: "init" | "next", actions: SpecAction[]) =>
564
567
  actions.map((action): CoveredAction => ({
565
568
  ...action,
@@ -609,6 +612,17 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
609
612
  );
610
613
  return successors;
611
614
  };
615
+ // TLC generates the successors of each action again, which its coverage counts.
616
+ const findSuccessorAction = (state: Value[], isMatch: (successor: Successor) => boolean) =>
617
+ coverage
618
+ ? coverageActions.find((item) => getCoveredSuccessors(item, state).some(isMatch))
619
+ : nextActions.find((item) =>
620
+ getSuccessors(item.expression, state, environment, item.scope).some(isMatch),
621
+ );
622
+ runtime.getSuccessorAction = (state, next) =>
623
+ findSuccessorAction(state, (successor) =>
624
+ successor.state.every((value, index) => isSameValue(value, next[index])),
625
+ );
612
626
  const rejectIncompleteInitialState = (partial: (Value | undefined)[]) => {
613
627
  throw setExitCode(new TlaIllegalStateError([...partial]), EXIT_STATUS.error);
614
628
  };
@@ -627,8 +641,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
627
641
  return (state: Value[], callStack: CallStack | undefined) => {
628
642
  fingerprintReplayed(state, getFingerprintState(state), callStack);
629
643
  const fingerprintState = getFingerprintState(state);
644
+ const hash = getStateHash(fingerprintState);
630
645
  const isSeen =
631
- findStateIndex(seenStates, getStateHash(fingerprintState), fingerprintState) !== -1 ||
646
+ findStateIndex(seenStates, hash, fingerprintState) !== -1 ||
647
+ isExplored(hash, fingerprintState) ||
632
648
  replayed.some((seen) => isSameState(seen, fingerprintState));
633
649
  if (isSeen) return false;
634
650
  replayed.push(fingerprintState);
@@ -715,28 +731,38 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
715
731
  if (spec.next === undefined) return successors;
716
732
  const livenessSource = current.livenessSource;
717
733
  current.livenessSource = source;
734
+ const addSuccessor = (successor: Value[]) => {
735
+ canonicalizeState(successor);
736
+ const isInModel =
737
+ search.satisfiesConstraints(successor, state) &&
738
+ search.satisfiesActionConstraints(state, successor);
739
+ if (!isInModel) return;
740
+ const fingerprintState = getFingerprintState(successor);
741
+ const hash = getStateHash(fingerprintState);
742
+ const index = findStateIndex(seenStates, hash, fingerprintState);
743
+ successors.push({
744
+ index: index === -1 ? getPendingIndex(hash, fingerprintState) : index,
745
+ state: successor,
746
+ });
747
+ };
718
748
  try {
719
- forEachSuccessor(
720
- spec.next,
721
- state,
722
- environment,
723
- (successor) => {
724
- canonicalizeState(successor.state);
725
- const isInModel =
726
- search.satisfiesConstraints(successor.state, state) &&
727
- search.satisfiesActionConstraints(state, successor.state);
728
- if (!isInModel) return false;
729
- const fingerprintState = getFingerprintState(successor.state);
730
- const index = findStateIndex(
731
- seenStates,
732
- getStateHash(fingerprintState),
733
- fingerprintState,
734
- );
735
- successors.push({ index, state: successor.state });
736
- return false;
737
- },
738
- spec.scope,
739
- );
749
+ // TLC's coverage counts the successors of each action the graph generates again.
750
+ if (coverage) {
751
+ coverageActions.forEach((action) =>
752
+ walkCoveredSuccessors(action, state, addSuccessor),
753
+ );
754
+ } else {
755
+ forEachSuccessor(
756
+ spec.next,
757
+ state,
758
+ environment,
759
+ (successor) => {
760
+ addSuccessor(successor.state);
761
+ return false;
762
+ },
763
+ spec.scope,
764
+ );
765
+ }
740
766
  } finally {
741
767
  current.livenessSource = livenessSource;
742
768
  }
@@ -755,6 +781,23 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
755
781
  const actions: (string | undefined)[] = [];
756
782
  const depths: number[] = [];
757
783
  const seenStates = createStateTable(fingerprintStates);
784
+ const exploredStates: Value[][] = [];
785
+ const exploredFingerprintStates: Value[][] = [];
786
+ let exploredTable: StateTable | undefined;
787
+ const isExplored = (hash: number, fingerprintState: Value[]) =>
788
+ exploredTable !== undefined && findStateIndex(exploredTable, hash, fingerprintState) !== -1;
789
+ const pendingFingerprintStates: Value[][] = [];
790
+ let pendingStates: StateTable | undefined;
791
+ const getPendingIndex = (hash: number, fingerprintState: Value[]) => {
792
+ pendingStates ??= createStateTable(pendingFingerprintStates);
793
+ const found = findStateIndex(pendingStates, hash, fingerprintState);
794
+ const position = found === -1 ? pendingFingerprintStates.length : found;
795
+ if (found === -1) {
796
+ markSeenState(pendingStates, hash, position);
797
+ pendingFingerprintStates.push(fingerprintState);
798
+ }
799
+ return -2 - position;
800
+ };
758
801
  const canonicalizeState = createCanonicalizer();
759
802
 
760
803
  const toRecord = search.toRecord;
@@ -805,7 +848,12 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
805
848
  outDegrees: failureOptions.outDegrees,
806
849
  };
807
850
  };
808
- const reportIncompleteSuccessor = (index: number, error: TlaIncompleteSuccessorError) => {
851
+ // Deviation from TLC: under -continue, TLC goes on past an incomplete successor and leaks an ArrayIndexOutOfBoundsException.
852
+ const reportIncompleteSuccessor = (
853
+ index: number,
854
+ error: TlaIncompleteSuccessorError,
855
+ liveSuccessors: LiveSuccessor[],
856
+ ) => {
809
857
  runtime.generatedStates++;
810
858
  const named =
811
859
  nextActions.length === 1
@@ -827,7 +875,12 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
827
875
  );
828
876
  const undefinedValue = createModelValue("null");
829
877
  const partial = error.state.map((value) => value ?? undefinedValue);
830
- const failure = createFailureResult(error, traces.getStateTrace(index));
878
+ const live = captureOutput(() => addFailedLiveState(index, liveSuccessors));
879
+ const failure = createFailureResult(
880
+ error,
881
+ appendTraceOutput(traces.getStateTrace(index), live.lines),
882
+ { callStack: live.result },
883
+ );
831
884
  return withOutDegrees({
832
885
  ...failure,
833
886
  failure: failure.failure && {
@@ -855,7 +908,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
855
908
  };
856
909
  let unstoredFingerprint: Value[] | undefined;
857
910
  const countDistinctState = (depth: number) => {
858
- runtime.distinctStates = states.length + 1;
911
+ runtime.distinctStates = states.length + exploredStates.length + 1;
859
912
  searchDepth = Math.max(searchDepth, depth);
860
913
  runtime.diameter = Math.max(runtime.diameter, depth);
861
914
  };
@@ -896,18 +949,27 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
896
949
  tracedSteps,
897
950
  captureOutput,
898
951
  getInitialStates: getSpecInitialStates,
899
- findSuccessorAction: (state, isMatch) =>
900
- coverage
901
- ? coverageActions.find((item) => getCoveredSuccessors(item, state).some(isMatch))
902
- : nextActions.find((item) =>
903
- getSuccessors(item.expression, state, environment, item.scope).some(isMatch),
904
- ),
952
+ findSuccessorAction,
905
953
  });
906
954
  const getPath = (index: number): Value[][] =>
907
955
  index === -1 ? [] : [...getPath(parents[index]), states[index]];
956
+ // TLC adds a successor's fingerprint to its set before it checks the invariants of the successor.
908
957
  runtime.isSeen = (state) => {
909
958
  const fingerprintState = getFingerprintState(state);
910
- return findStateIndex(seenStates, getStateHash(fingerprintState), fingerprintState) !== -1;
959
+ const hash = getStateHash(fingerprintState);
960
+ return (
961
+ findStateIndex(seenStates, hash, fingerprintState) !== -1 ||
962
+ isExplored(hash, fingerprintState) ||
963
+ (unstoredFingerprint !== undefined && isSameState(unstoredFingerprint, fingerprintState))
964
+ );
965
+ };
966
+ runtime.markExplored = (state) => {
967
+ const fingerprintState = getFingerprintState(state);
968
+ exploredTable ??= createStateTable(exploredFingerprintStates);
969
+ markSeenState(exploredTable, getStateHash(fingerprintState), exploredStates.length);
970
+ exploredStates.push(state);
971
+ exploredFingerprintStates.push(fingerprintState);
972
+ runtime.distinctStates++;
911
973
  };
912
974
  runtime.getBehavior = (state) => {
913
975
  const index = state === current.candidate ? -1 : states.indexOf(state);
@@ -1012,7 +1074,14 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1012
1074
  fingerprintModelState(fingerprintState);
1013
1075
  successor.state.forEach(markFingerprinted);
1014
1076
  }
1015
- return { fingerprintState, hash, isInModel, existing: isInModel ? foundIndex : -1 };
1077
+ const existing = isInModel ? foundIndex : -1;
1078
+ return {
1079
+ fingerprintState,
1080
+ hash,
1081
+ isInModel,
1082
+ existing,
1083
+ isSeen: existing !== -1 || (isInModel && isExplored(hash, fingerprintState)),
1084
+ };
1016
1085
  };
1017
1086
  const visitSuccessor = (
1018
1087
  index: number,
@@ -1031,7 +1100,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1031
1100
  stateWriter?.writeSuccessor(
1032
1101
  source,
1033
1102
  getGraphState(successor.state, depths[index] + 1),
1034
- found.existing !== -1,
1103
+ found.isSeen,
1035
1104
  action && getGraphAction(action),
1036
1105
  );
1037
1106
  }
@@ -1053,7 +1122,13 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1053
1122
  const isStored = stored.every((value, position) => value === successor.state[position]);
1054
1123
  liveSuccessors.push({ index: found.existing, state: isStored ? stored : successor.state });
1055
1124
  }
1056
- const isNew = found.isInModel && found.existing === -1;
1125
+ if (found.isSeen && found.existing === -1 && liveness) {
1126
+ liveSuccessors.push({
1127
+ index: getPendingIndex(found.hash, found.fingerprintState),
1128
+ state: successor.state,
1129
+ });
1130
+ }
1131
+ const isNew = found.isInModel && !found.isSeen;
1057
1132
  if (isNew && liveness) liveSuccessors.push({ index: states.length, state: successor.state });
1058
1133
  unstoredFingerprint = isNew ? found.fingerprintState : undefined;
1059
1134
  if (isNew) {
@@ -1061,7 +1136,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1061
1136
  newStateCount++;
1062
1137
  if (coverage) coverage.secondary[coveredNode]++;
1063
1138
  }
1064
- if (found.existing === -1) {
1139
+ if (!found.isSeen) {
1065
1140
  try {
1066
1141
  const violated = search.findViolatedInvariant(successor.state, state);
1067
1142
  const violation = violated && { name: violated.name, ...traces.getTrace(index, successor) };
@@ -1092,6 +1167,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1092
1167
  if (coverage) countCoverageVariables(coverage, successor.state);
1093
1168
  if (!isCanonicalizedFirst) canonicalizeState(successor.state);
1094
1169
  markSeenState(seenStates, found.hash, states.length);
1170
+ if (pendingStates) {
1171
+ const pending = findStateIndex(pendingStates, found.hash, found.fingerprintState);
1172
+ if (pending !== -1) liveness?.storeState(-2 - pending, states.length);
1173
+ }
1095
1174
  addState(successor.state, found.fingerprintState, index, successor.action);
1096
1175
  runtime.queueSize++;
1097
1176
  return undefined;
@@ -1139,7 +1218,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1139
1218
  kind: "liveness-started",
1140
1219
  branches: liveness.branches,
1141
1220
  isComplete: true,
1142
- states: typed.distinctStates,
1221
+ states: liveness.branches * typed.distinctStates,
1143
1222
  statistics,
1144
1223
  });
1145
1224
  options.onProgress?.({ kind: "liveness-finished" });
@@ -1396,6 +1475,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1396
1475
  return {
1397
1476
  ...result,
1398
1477
  violation: appendTraceOutput(result.violation, live.lines),
1478
+ // TLC adds the state to the behavior graph before it reports the coverage.
1479
+ coverage: getCoverage(),
1399
1480
  ...(live.result && { liveCallStack: live.result }),
1400
1481
  };
1401
1482
  }
@@ -1527,24 +1608,29 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1527
1608
  const startedAt = performance.now();
1528
1609
  const periodic = {
1529
1610
  at: startedAt + PERIODIC_START,
1530
- size: 1,
1611
+ checkedCounts: liveness?.getStateCounts().map(() => 1) ?? [],
1531
1612
  time: 0,
1532
1613
  coverageCount: Math.trunc(options.coverage ?? 0),
1533
1614
  };
1534
- const findPeriodicViolation = (expanded: number) => {
1615
+ const getGraphStates = (checker: LivenessChecker) =>
1616
+ checker.getStateCounts().reduce((sum, count) => sum + count, 0);
1617
+ const findPeriodicViolation = (checker: LivenessChecker) => {
1535
1618
  const now = performance.now();
1536
- const isGrown = (expanded - periodic.size) / periodic.size > LIVENESS_GROWTH;
1619
+ const counts = checker.getStateCounts();
1620
+ const isGrown = counts.some(
1621
+ (count, branch) =>
1622
+ (count - periodic.checkedCounts[branch]) / periodic.checkedCounts[branch] > LIVENESS_GROWTH,
1623
+ );
1537
1624
  if (!isGrown || periodic.time > (now - startedAt) * LIVENESS_RATIO) return undefined;
1538
- periodic.size = expanded;
1539
- if (!liveness) return undefined;
1625
+ periodic.checkedCounts = counts;
1540
1626
  options.onProgress?.({
1541
1627
  kind: "liveness-started",
1542
- branches: liveness.branches,
1628
+ branches: checker.branches,
1543
1629
  isComplete: false,
1544
- states: expanded,
1630
+ states: getGraphStates(checker),
1545
1631
  statistics: createResult("success"),
1546
1632
  });
1547
- const lasso = liveness.findViolation();
1633
+ const lasso = checker.findViolation();
1548
1634
  if (!lasso) options.onProgress?.({ kind: "liveness-finished" });
1549
1635
  periodic.time += performance.now() - now;
1550
1636
  return lasso;
@@ -1662,7 +1748,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1662
1748
  } catch (error) {
1663
1749
  outcome =
1664
1750
  error instanceof TlaIncompleteSuccessorError
1665
- ? reportIncompleteSuccessor(index, error)
1751
+ ? reportIncompleteSuccessor(index, error, liveSuccessors)
1666
1752
  : reportNextStateFailure(error, index, liveSuccessors);
1667
1753
  }
1668
1754
  if (outcome) return outcome;
@@ -1670,7 +1756,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1670
1756
  newStateCount = 0;
1671
1757
  if ((isPeriodic || options.onProgress) && performance.now() >= periodic.at) {
1672
1758
  periodic.at = performance.now() + PROGRESS_INTERVAL;
1673
- const lasso = isPeriodic ? findPeriodicViolation(index + 1) : undefined;
1759
+ const lasso = isPeriodic && liveness ? findPeriodicViolation(liveness) : undefined;
1674
1760
  if (liveness && lasso) return reportLasso(liveness, lasso);
1675
1761
  const isCoverageDue = options.coverage !== undefined && periodic.coverageCount === 0;
1676
1762
  periodic.coverageCount = isCoverageDue
@@ -1692,7 +1778,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1692
1778
  kind: "liveness-started",
1693
1779
  branches: finalLiveness.branches,
1694
1780
  isComplete: true,
1695
- states: runtime.distinctStates,
1781
+ states: typedLasso
1782
+ ? finalLiveness.branches * runtime.distinctStates
1783
+ : getGraphStates(finalLiveness),
1696
1784
  statistics: createResult("success"),
1697
1785
  });
1698
1786
  }
@@ -3,14 +3,9 @@ import { EXIT_STATUS, setExitCode } from "../exit-codes";
3
3
  import { parseModule } from "../parser";
4
4
  import { generateSanySpecification } from "../sany/generator";
5
5
  import { checkModuleLevels } from "../sany/levels";
6
- import {
7
- VARIABLE_DECL_KIND,
8
- type ModuleNode,
9
- type OpDefNode,
10
- type SymbolNode,
11
- } from "../sany/nodes";
6
+ import type { ModuleNode, OpDefNode, SymbolNode } from "../sany/nodes";
12
7
  import type { TlcVersion } from "../tlc/version";
13
- import type { RuntimeInvariant } from "./tlc-arguments";
8
+ import type { RuntimeInvariantTemplate } from "./tlc-arguments";
14
9
 
15
10
  const CONSTANT_LEVEL = 0;
16
11
  const TEMPORAL_LEVEL = 3;
@@ -31,21 +26,20 @@ const createParsingFailure = (detail: string) =>
31
26
  EXIT_STATUS.specParseError,
32
27
  );
33
28
 
34
- const getDebuggerExpressionLevel = (
35
- root: string,
29
+ const checkDebuggerExpression = (
30
+ source: string,
31
+ moduleName: string,
36
32
  name: string,
37
33
  expression: string,
38
34
  loadModule: (name: string) => string | undefined,
39
35
  version: TlcVersion,
40
36
  ) => {
41
- const moduleName = name.replace("__DebuggerExpr__", "__DebuggerModule__");
42
- const text = `---- MODULE ${moduleName} ----\nEXTENDS ${root}\n\n${name} == ${expression}\n====`;
43
37
  const createFailure = (message: string) =>
44
38
  createParsingFailure(
45
39
  `Unknown location\n\n${message} while parsing breakpoint expression "${expression}"`,
46
40
  );
47
41
  try {
48
- parseModule(text);
42
+ parseModule(source);
49
43
  } catch (error) {
50
44
  if (!(error instanceof TlaSyntaxError)) throw error;
51
45
  throw createParsingFailure(`Syntax error while parsing breakpoint expression "${expression}"`);
@@ -54,7 +48,7 @@ const getDebuggerExpressionLevel = (
54
48
  let isLevelCorrect = false;
55
49
  const specification = (() => {
56
50
  try {
57
- return generateSanySpecification(text, loadModule, {
51
+ return generateSanySpecification(source, loadModule, {
58
52
  version,
59
53
  onModule: (module, messages) => {
60
54
  const isCorrect = () => messages.every((message) => message.isWarning);
@@ -81,56 +75,26 @@ const getDebuggerExpressionLevel = (
81
75
  `Unknown location\n\nDebug expressions must be action-level or below; actual level: ${level} (Temporal)`,
82
76
  );
83
77
  }
84
- return level;
85
78
  };
86
79
 
87
- // Deviation from TLC: TLC puts a generated operator in a module that extends the root module.
88
- export const addRuntimeInvariants = (
80
+ export const getRuntimeInvariants = (
89
81
  source: string,
90
82
  root: ModuleNode,
91
- invariants: RuntimeInvariant[],
83
+ invariants: RuntimeInvariantTemplate[],
92
84
  loadModule: (name: string) => string | undefined,
93
85
  version: TlcVersion,
94
86
  ) => {
95
- const stamp = Date.now();
96
- const named = invariants.map((invariant, index) => ({
97
- expression: invariant.expression,
98
- name: findDefinition(root, invariant.expression)
99
- ? invariant.expression
100
- : `__DebuggerExpr__${stamp + index}`,
101
- }));
102
- const names = named.map((invariant) => invariant.name);
103
- const generated = named.filter((invariant) => invariant.name !== invariant.expression);
104
- if (generated.length === 0) return { names, source };
105
87
  const loadDependency = (name: string) => (name === root.name ? source : loadModule(name));
106
- const variable = root.context.symbols.find(
107
- (symbol) => symbol.kind === "OpDecl" && symbol.declKind === VARIABLE_DECL_KIND,
108
- );
109
- const definitions = generated.map((invariant) => {
110
- const head = `${invariant.name} == `;
111
- const level = getDebuggerExpressionLevel(
112
- root.name,
113
- invariant.name,
114
- invariant.expression,
115
- loadDependency,
116
- version,
117
- );
118
- // HACK: TLC checks a constant-level -inv in every state, so an unused LET makes it depend on one.
119
- return level === CONSTANT_LEVEL && variable
120
- ? `${invariant.name} ==\nLET ${invariant.name}State == ${variable.name} IN\n${" ".repeat(head.length)}${invariant.expression}`
121
- : `${head}${invariant.expression}`;
88
+ // Deviation from TLC: TLC reads the clock for each name, which no fixed output can match; one reading plus an index keeps the names apart.
89
+ const stamp = Date.now();
90
+ return invariants.map((invariant, index) => {
91
+ if (findDefinition(root, invariant.expression)) {
92
+ return { name: invariant.expression, module: undefined, source: undefined };
93
+ }
94
+ const module = `__DebuggerModule__${stamp + index}`;
95
+ const name = `__DebuggerExpr__${stamp + index}`;
96
+ const text = `---- MODULE ${module} ----\nEXTENDS ${root.name}\n\n${name} == ${invariant.expression}\n====`;
97
+ checkDebuggerExpression(text, module, name, invariant.expression, loadDependency, version);
98
+ return { name, module, source: text };
122
99
  });
123
- const lines = source.split("\n");
124
- const end = (parseModule(source).location.range?.end.line ?? lines.length) - 1;
125
- const terminator = lines[end].search(/={4,}/);
126
- return {
127
- names,
128
- source: [
129
- ...lines.slice(0, end),
130
- lines[end].slice(0, terminator),
131
- ...definitions,
132
- lines[end].slice(terminator),
133
- ...lines.slice(end + 1),
134
- ].join("\n"),
135
- };
136
100
  };
@@ -35,11 +35,11 @@ export interface TlcArguments {
35
35
  suppressedCodes: number[];
36
36
  errorCodes: number[];
37
37
  userFile: string | undefined;
38
- invariants: RuntimeInvariant[];
38
+ invariants: RuntimeInvariantTemplate[];
39
39
  moduleOperators: ModuleOperator[];
40
40
  }
41
41
 
42
- export interface RuntimeInvariant {
42
+ export interface RuntimeInvariantTemplate {
43
43
  modules: string[];
44
44
  expression: string;
45
45
  }
@@ -320,11 +320,10 @@ export const printCheckProgress = (
320
320
  timing.livenessStartTime = Date.now();
321
321
  if (progress.isComplete) printProgress(printer, progress.statistics);
322
322
  const branches = progress.branches > 1 ? `${progress.branches} branches of ` : "";
323
- const states = progress.branches * progress.states;
324
323
  print(
325
324
  MESSAGE_CODE.checkingTemporal,
326
325
  MESSAGE_LEVEL.none,
327
- `Checking ${branches}temporal properties for the ${progress.isComplete ? "complete" : "current"} state space with ${states} total distinct states at (${formatTlcDate(new Date())})`,
326
+ `Checking ${branches}temporal properties for the ${progress.isComplete ? "complete" : "current"} state space with ${progress.states} total distinct states at (${formatTlcDate(new Date())})`,
328
327
  );
329
328
  return;
330
329
  }
package/src/cli/tlc.ts CHANGED
@@ -29,7 +29,7 @@ import { EXIT_STATUS } from "../exit-codes";
29
29
  import { check } from "../parallel";
30
30
  import { extractModule, parseModule } from "../parser";
31
31
  import { simulate } from "../simulate";
32
- import type { StandardInput } from "../search";
32
+ import type { CliSettings } from "../search";
33
33
  import type { StateDump } from "../state-graph";
34
34
  import {
35
35
  getSanyStandardModules,
@@ -49,7 +49,7 @@ import {
49
49
  type MessagePrinter,
50
50
  zeroPad,
51
51
  } from "../tlc/messages";
52
- import { addRuntimeInvariants } from "./runtime-invariants";
52
+ import { getRuntimeInvariants } from "./runtime-invariants";
53
53
  import { parseTlcArguments, type TlcArguments } from "./tlc-arguments";
54
54
  import {
55
55
  getClassPath,
@@ -378,15 +378,14 @@ const checkSpec = async (
378
378
  }
379
379
  const userFile = args.userFile;
380
380
  const standardModules = getSanyStandardModules(version);
381
- const invariants = addRuntimeInvariants(
381
+ const runtimeInvariants = getRuntimeInvariants(
382
382
  source,
383
383
  specification.root,
384
384
  args.invariants,
385
385
  (name) => loadModule(name) ?? standardModules.get(name) ?? extractModule(source, name),
386
386
  version,
387
387
  );
388
- config.invariants.push(...invariants.names);
389
- const options: CheckOptions & StandardInput = {
388
+ const options: CheckOptions & CliSettings = {
390
389
  workers: args.workers,
391
390
  livenessCheck:
392
391
  livenessCheck === "off"
@@ -410,11 +409,17 @@ const checkSpec = async (
410
409
  version,
411
410
  onProgress: (progress) => printCheckProgress(printer, progress, timing, directory),
412
411
  onPrint: userFile === undefined ? undefined : (text) => appendFileSync(userFile, `${text}\n`),
413
- source: invariants.source,
412
+ source,
414
413
  config,
415
414
  onPause: () => readSync(0, Buffer.alloc(1)),
416
415
  readLine: readStandardInputLine,
417
- loadModule,
416
+ runtimeInvariants: runtimeInvariants.map((invariant) => ({
417
+ name: invariant.name,
418
+ module: invariant.module,
419
+ })),
420
+ loadModule: (name) =>
421
+ runtimeInvariants.find((invariant) => invariant.module === name)?.source ??
422
+ loadModule(name),
418
423
  loadClass: (name) => {
419
424
  const classPath = getClassPath(directory, name);
420
425
  return existsSync(classPath) ? readFileSync(classPath) : undefined;
@@ -586,7 +591,7 @@ export const checkSpecs = async (args: string[], java: JavaProperties) => {
586
591
  exitCodes.push(
587
592
  await reportErrors(async () => {
588
593
  const specPath = path.endsWith(".ts") ? await writeTypeScriptSpec(path) : path;
589
- // Deviation from TLC: TLC checks one spec, so tla-ts names each of several it checks.
594
+ // An extension: TLC refuses more than one spec, and tla-ts checks each one under its name.
590
595
  if (paths.length > 1) {
591
596
  console.log(`Checking ${basename(specPath)} with ${basename(specPath, ".tla")}.cfg`);
592
597
  }
@@ -52,7 +52,7 @@ const XML_EXPORT_USAGE = (() => {
52
52
  "",
53
53
  getBold("OPTIONS"),
54
54
  "",
55
- ...options.map(([flag, description]) => `\t${getBold(flag)}\n\t\t${description}`),
55
+ ...options.map((option) => `\t${getBold(option[0])}\n\t\t${option[1]}`),
56
56
  "",
57
57
  getBold("TIPS"),
58
58
  "",
package/src/codegen.ts CHANGED
@@ -167,13 +167,13 @@ const getFreeNames = (expression: Expression, names = new Set<string>()) => {
167
167
 
168
168
  const getDelegateContext = (generator: Generator, expression: Expression, frame: Frame) => {
169
169
  const freeNames = getFreeNames(expression);
170
- const captured = [...frame.locals].filter(([name]) => freeNames.has(name));
170
+ const captured = [...frame.locals].filter((entry) => freeNames.has(entry[0]));
171
171
  if (captured.length === 0) return frame.context;
172
172
  const names = addReference(
173
173
  generator,
174
- captured.map(([name]) => name),
174
+ captured.map((entry) => entry[0]),
175
175
  );
176
- return `extend(${frame.context}, ${names}, [${captured.map(([, local]) => local).join(", ")}])`;
176
+ return `extend(${frame.context}, ${names}, [${captured.map((entry) => entry[1]).join(", ")}])`;
177
177
  };
178
178
 
179
179
  const generateDelegate = (generator: Generator, expression: Expression, frame: Frame) =>
@@ -440,12 +440,16 @@ const generateExpression = (generator: Generator, expression: Expression, frame:
440
440
  generator,
441
441
  fields.map((field) => field.name),
442
442
  );
443
- const values = `[${fields.map((field) => generate(field.value)).join(", ")}]`;
443
+ const values = `[${expression.fields.map((field) => generate(field.value)).join(", ")}]`;
444
444
  const writtenNames = expression.fields.map((field) => field.name);
445
445
  if (writtenNames.every((name, index) => name === fields[index].name)) {
446
446
  return `record(${names}, ${values})`;
447
447
  }
448
- return `writtenRecord(${names}, ${values}, ${addReference(generator, writtenNames)})`;
448
+ const writtenIndexes = addReference(
449
+ generator,
450
+ fields.map((field) => expression.fields.indexOf(field)),
451
+ );
452
+ return `writtenRecord(${names}, ${writtenIndexes}, ${values}, ${addReference(generator, writtenNames)})`;
449
453
  }
450
454
  case "Tuple":
451
455
  return `tuple([${expression.elements.map((element) => generate(element)).join(", ")}])`;