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

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 (586) hide show
  1. package/README.md +2 -1
  2. package/dist/compile.cjs +6 -6
  3. package/dist/compile.js +10 -10
  4. package/dist/deciders.cjs +41 -37
  5. package/dist/deciders.js +57 -53
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +37 -0
  8. package/dist/index.d.ts +37 -0
  9. package/dist/index.js +1 -1
  10. package/dist/parallel-worker.cjs +1 -1
  11. package/dist/parallel-worker.js +1 -1
  12. package/dist/prove.cjs +2683 -427
  13. package/dist/prove.js +2681 -425
  14. package/dist/run.cjs +47 -44
  15. package/dist/run.js +47 -44
  16. package/dist/tlapm.cjs +2 -2
  17. package/dist/tlapm.js +2 -2
  18. package/dist/transfer.cjs +44 -41
  19. package/dist/transfer.js +44 -41
  20. package/dist/worker.cjs +7 -7
  21. package/dist/worker.js +7 -7
  22. package/package.json +1 -1
  23. package/src/ast.ts +41 -41
  24. package/src/bags.ts +2 -5
  25. package/src/builtins.ts +5 -21
  26. package/src/check-failure.ts +116 -0
  27. package/src/check-trace.ts +268 -0
  28. package/src/check.ts +474 -718
  29. package/src/cli/options.ts +6 -31
  30. package/src/cli/run.ts +0 -2
  31. package/src/cli/runtime-invariants.ts +8 -7
  32. package/src/cli/shared.ts +1 -5
  33. package/src/cli/tlapm.ts +433 -70
  34. package/src/cli/tlc-arguments.ts +244 -238
  35. package/src/cli/tlc-output.ts +687 -0
  36. package/src/cli/tlc-usage.ts +3 -5
  37. package/src/cli/tlc.ts +49 -702
  38. package/src/cli/xml-exporter.ts +23 -33
  39. package/src/codegen.ts +5 -10
  40. package/src/coverage.ts +3 -10
  41. package/src/dependencies.ts +30 -14
  42. package/src/dfid.ts +16 -16
  43. package/src/environment-config.ts +315 -0
  44. package/src/environment.ts +55 -338
  45. package/src/errors.ts +33 -5
  46. package/src/evaluate.ts +31 -106
  47. package/src/exit-codes.ts +2 -0
  48. package/src/fingerprints.ts +65 -1
  49. package/src/instances.ts +47 -10
  50. package/src/java-hash.ts +7 -0
  51. package/src/java-overrides.ts +4 -9
  52. package/src/json-reader.ts +1 -2
  53. package/src/json.ts +8 -18
  54. package/src/levels.ts +46 -57
  55. package/src/lexer.ts +76 -85
  56. package/src/liveness-checker.ts +616 -306
  57. package/src/liveness.ts +104 -120
  58. package/src/obligations/action.ts +14 -17
  59. package/src/obligations/anonymize.ts +37 -16
  60. package/src/obligations/enabled-axioms.ts +218 -0
  61. package/src/obligations/equality.ts +1 -3
  62. package/src/obligations/expression.ts +36 -8
  63. package/src/obligations/format.ts +0 -2
  64. package/src/obligations/generate.ts +66 -54
  65. package/src/obligations/index.ts +38 -8
  66. package/src/obligations/levels.ts +24 -11
  67. package/src/obligations/module.ts +28 -41
  68. package/src/obligations/normalize.ts +26 -14
  69. package/src/obligations/operators.ts +0 -2
  70. package/src/obligations/pragma.ts +53 -16
  71. package/src/obligations/printer.ts +43 -13
  72. package/src/obligations/proof.ts +3 -2
  73. package/src/obligations/regroup.ts +0 -2
  74. package/src/obligations/simplify.ts +55 -50
  75. package/src/obligations/source.ts +118 -74
  76. package/src/obligations/subexpression.ts +45 -18
  77. package/src/obligations/substitution.ts +1 -3
  78. package/src/obligations/temporal.ts +5 -7
  79. package/src/obligations/tuples.ts +0 -2
  80. package/src/parallel-worker.ts +10 -30
  81. package/src/parallel.ts +50 -80
  82. package/src/parser.ts +722 -385
  83. package/src/pcal/ast.ts +53 -65
  84. package/src/pcal/parse.ts +144 -191
  85. package/src/pcal/tokenize.ts +91 -115
  86. package/src/pcal/translate.ts +83 -98
  87. package/src/pcal/validate.ts +48 -50
  88. package/src/pretty-print.ts +7 -7
  89. package/src/prover/decide-pool.ts +3 -3
  90. package/src/prover/deciders.ts +12 -9
  91. package/src/prover/isabelle/decide.ts +3 -25
  92. package/src/prover/isabelle/encode.ts +72 -42
  93. package/src/prover/isabelle/isar/attrib.ts +250 -0
  94. package/src/prover/isabelle/isar/context.ts +335 -0
  95. package/src/prover/isabelle/isar/induct.ts +382 -0
  96. package/src/prover/isabelle/isar/inner-syntax.ts +158 -7
  97. package/src/prover/isabelle/isar/method.ts +509 -212
  98. package/src/prover/isabelle/isar/proof.ts +570 -14
  99. package/src/prover/isabelle/isar/rule-cases.ts +224 -0
  100. package/src/prover/isabelle/isar/theory.ts +487 -76
  101. package/src/prover/isabelle/isar/toplevel.ts +331 -0
  102. package/src/prover/isabelle/isar/type-check.ts +89 -14
  103. package/src/prover/isabelle/provers/blast/blast.ts +7 -65
  104. package/src/prover/isabelle/provers/blast/branch.ts +0 -2
  105. package/src/prover/isabelle/provers/blast/prove.ts +0 -2
  106. package/src/prover/isabelle/provers/blast/rules.ts +0 -2
  107. package/src/prover/isabelle/provers/blast/state.ts +0 -2
  108. package/src/prover/isabelle/provers/blast/term.ts +0 -2
  109. package/src/prover/isabelle/provers/clasimp.ts +0 -2
  110. package/src/prover/isabelle/provers/classical.ts +45 -20
  111. package/src/prover/isabelle/provers/hypsubst.ts +17 -28
  112. package/src/prover/isabelle/pure/bicompose.ts +9 -27
  113. package/src/prover/isabelle/pure/consts.ts +0 -2
  114. package/src/prover/isabelle/pure/conv.ts +2 -10
  115. package/src/prover/isabelle/pure/drule.ts +72 -6
  116. package/src/prover/isabelle/pure/envir.ts +0 -2
  117. package/src/prover/isabelle/pure/goal.ts +1 -3
  118. package/src/prover/isabelle/pure/logic.ts +1 -3
  119. package/src/prover/isabelle/pure/name.ts +0 -2
  120. package/src/prover/isabelle/pure/net.ts +0 -2
  121. package/src/prover/isabelle/pure/object-logic.ts +13 -7
  122. package/src/prover/isabelle/pure/pattern.ts +0 -2
  123. package/src/prover/isabelle/pure/raw-simplifier.ts +4 -15
  124. package/src/prover/isabelle/pure/rewriter.ts +6 -17
  125. package/src/prover/isabelle/pure/search.ts +0 -2
  126. package/src/prover/isabelle/pure/seq.ts +0 -2
  127. package/src/prover/isabelle/pure/simplifier.ts +26 -7
  128. package/src/prover/isabelle/pure/table.ts +2 -3
  129. package/src/prover/isabelle/pure/tactic.ts +0 -2
  130. package/src/prover/isabelle/pure/tactical.ts +42 -37
  131. package/src/prover/isabelle/pure/term-ord.ts +0 -2
  132. package/src/prover/isabelle/pure/term.ts +0 -2
  133. package/src/prover/isabelle/pure/thm.ts +14 -13
  134. package/src/prover/isabelle/pure/type.ts +0 -2
  135. package/src/prover/isabelle/pure/unify.ts +0 -2
  136. package/src/prover/isabelle/pure/variable.ts +0 -2
  137. package/src/prover/isabelle/tla/classical-setup.ts +18 -16
  138. package/src/prover/isabelle/tla/context.ts +58 -11
  139. package/src/prover/isabelle/tla/logic-data.ts +1 -1
  140. package/src/prover/isabelle/tla/logic.ts +49 -21
  141. package/src/prover/isabelle/tla/simpdata.ts +1 -12
  142. package/src/prover/isabelle/tools/intuitionistic.ts +28 -12
  143. package/src/prover/ocaml.ts +4 -1
  144. package/src/prover/prep/action.ts +30 -31
  145. package/src/prover/prep/enabled-axioms.ts +11 -2
  146. package/src/prover/prep/fingerprint.ts +2 -5
  147. package/src/prover/prep/methods.ts +181 -51
  148. package/src/prover/prep/normalize.ts +38 -9
  149. package/src/prover/prove.ts +395 -94
  150. package/src/prover/ptl/decide.ts +95 -50
  151. package/src/prover/ptl/encode.ts +2 -3
  152. package/src/prover/ptl/tableau.ts +28 -2
  153. package/src/prover/smt/arithmetic.ts +310 -0
  154. package/src/prover/smt/axioms.ts +12 -8
  155. package/src/prover/smt/context.ts +43 -8
  156. package/src/prover/smt/data.ts +498 -379
  157. package/src/prover/smt/encode.ts +148 -57
  158. package/src/prover/smt/extensionality.ts +5 -3
  159. package/src/prover/smt/flatten.ts +4 -6
  160. package/src/prover/smt/format.ts +28 -4
  161. package/src/prover/smt/instances.ts +7 -1
  162. package/src/prover/smt/layout.ts +91 -0
  163. package/src/prover/smt/rewrite.ts +1021 -618
  164. package/src/prover/smt/simplify.ts +441 -0
  165. package/src/prover/smt/solver/ackermannize-bv-tactic.ts +61 -0
  166. package/src/prover/smt/solver/ackr-helper.ts +179 -0
  167. package/src/prover/smt/solver/ackr-model-converter.ts +105 -0
  168. package/src/prover/smt/solver/act-cache.ts +0 -1
  169. package/src/prover/smt/solver/add-bounds-tactic.ts +59 -0
  170. package/src/prover/smt/solver/aig-tactic.ts +52 -0
  171. package/src/prover/smt/solver/aig.ts +889 -0
  172. package/src/prover/smt/solver/arith-rewriter.ts +613 -6
  173. package/src/prover/smt/solver/arith-terms.ts +121 -0
  174. package/src/prover/smt/solver/array-decl-plugin.ts +175 -0
  175. package/src/prover/smt/solver/array-rewriter.ts +309 -0
  176. package/src/prover/smt/solver/asserted-formulas.ts +87 -16
  177. package/src/prover/smt/solver/ast-lt.ts +166 -12
  178. package/src/prover/smt/solver/ast-util.ts +160 -2
  179. package/src/prover/smt/solver/ast.ts +1427 -41
  180. package/src/prover/smt/solver/auf-solver.ts +2 -6
  181. package/src/prover/smt/solver/bit-blast-tactic.ts +582 -0
  182. package/src/prover/smt/solver/bit-blaster.ts +871 -0
  183. package/src/prover/smt/solver/bound-manager.ts +196 -0
  184. package/src/prover/smt/solver/bound-simplifier.ts +600 -0
  185. package/src/prover/smt/solver/bv-bound-chk.ts +492 -0
  186. package/src/prover/smt/solver/bv-decl-plugin.ts +338 -0
  187. package/src/prover/smt/solver/bv-divrem-bounds.ts +95 -0
  188. package/src/prover/smt/solver/bv-rewriter.ts +1901 -0
  189. package/src/prover/smt/solver/bv1-blast.ts +214 -0
  190. package/src/prover/smt/solver/bv2fpa-converter.ts +174 -0
  191. package/src/prover/smt/solver/bv2int-rewriter.ts +544 -0
  192. package/src/prover/smt/solver/bv2real-rewriter.ts +533 -0
  193. package/src/prover/smt/solver/card2bv.ts +110 -0
  194. package/src/prover/smt/solver/case-split-queue.ts +0 -2
  195. package/src/prover/smt/solver/cg-table.ts +39 -25
  196. package/src/prover/smt/solver/check-logic.ts +330 -0
  197. package/src/prover/smt/solver/clause.ts +0 -1
  198. package/src/prover/smt/solver/cofactor-elim-term-ite.ts +278 -0
  199. package/src/prover/smt/solver/conflict-resolution.ts +78 -2
  200. package/src/prover/smt/solver/context.ts +516 -115
  201. package/src/prover/smt/solver/ctx-simplify.ts +20 -10
  202. package/src/prover/smt/solver/ctx-solver-simplify.ts +122 -0
  203. package/src/prover/smt/solver/datatype-decl-plugin.ts +572 -0
  204. package/src/prover/smt/solver/datatype-rewriter.ts +82 -0
  205. package/src/prover/smt/solver/demodulator.ts +786 -0
  206. package/src/prover/smt/solver/dependent-expr-state.ts +81 -0
  207. package/src/prover/smt/solver/der.ts +38 -10
  208. package/src/prover/smt/solver/diff-neq.ts +206 -0
  209. package/src/prover/smt/solver/distribute-forall.ts +57 -0
  210. package/src/prover/smt/solver/dom-simplify.ts +511 -0
  211. package/src/prover/smt/solver/dt2bv-tactic.ts +260 -0
  212. package/src/prover/smt/solver/dyn-ack.ts +0 -1
  213. package/src/prover/smt/solver/e-matching.ts +7 -8
  214. package/src/prover/smt/solver/elim-small-bv-tactic.ts +129 -0
  215. package/src/prover/smt/solver/elim-uncnstr.ts +545 -0
  216. package/src/prover/smt/solver/enode.ts +100 -3
  217. package/src/prover/smt/solver/eq2bv-tactic.ts +218 -0
  218. package/src/prover/smt/solver/euf/arith-axioms.ts +403 -0
  219. package/src/prover/smt/solver/euf/arith-internalize.ts +653 -0
  220. package/src/prover/smt/solver/euf/arith-solver.ts +889 -0
  221. package/src/prover/smt/solver/euf/array-axioms.ts +527 -0
  222. package/src/prover/smt/solver/euf/array-internalize.ts +428 -0
  223. package/src/prover/smt/solver/euf/array-solver.ts +306 -0
  224. package/src/prover/smt/solver/euf/bv-ackerman.ts +162 -0
  225. package/src/prover/smt/solver/euf/bv-internalize.ts +748 -0
  226. package/src/prover/smt/solver/euf/bv-solver.ts +449 -0
  227. package/src/prover/smt/solver/euf/dt-solver.ts +618 -0
  228. package/src/prover/smt/solver/euf/egraph.ts +908 -0
  229. package/src/prover/smt/solver/euf/euf-solver.ts +1205 -0
  230. package/src/prover/smt/solver/euf/fpa-solver.ts +317 -0
  231. package/src/prover/smt/solver/euf/mam.ts +1050 -0
  232. package/src/prover/smt/solver/euf/q-ematch.ts +830 -0
  233. package/src/prover/smt/solver/euf/q-mbi.ts +587 -0
  234. package/src/prover/smt/solver/euf/q-model-fixer.ts +296 -0
  235. package/src/prover/smt/solver/euf/q-solver.ts +361 -0
  236. package/src/prover/smt/solver/euf/th-solver.ts +335 -0
  237. package/src/prover/smt/solver/euf/th-solvers.ts +30 -0
  238. package/src/prover/smt/solver/expr-ref.ts +0 -1
  239. package/src/prover/smt/solver/expr-safe-replace.ts +26 -2
  240. package/src/prover/smt/solver/expr2polynomial.ts +146 -0
  241. package/src/prover/smt/solver/factor.ts +141 -0
  242. package/src/prover/smt/solver/fd-solver.ts +265 -0
  243. package/src/prover/smt/solver/fingerprints.ts +15 -15
  244. package/src/prover/smt/solver/fix-dl-var.ts +148 -0
  245. package/src/prover/smt/solver/flat-literals.ts +0 -1
  246. package/src/prover/smt/solver/fm-tactic.ts +884 -0
  247. package/src/prover/smt/solver/fpa-decl-plugin.ts +618 -0
  248. package/src/prover/smt/solver/fpa-rewriter.ts +640 -0
  249. package/src/prover/smt/solver/fpa2bv-converter.ts +2249 -0
  250. package/src/prover/smt/solver/fpa2bv-rewriter.ts +348 -0
  251. package/src/prover/smt/solver/fpa2bv-tactic.ts +73 -0
  252. package/src/prover/smt/solver/goal.ts +175 -15
  253. package/src/prover/smt/solver/goal2nlsat.ts +189 -0
  254. package/src/prover/smt/solver/guard-set.ts +219 -0
  255. package/src/prover/smt/solver/hash.ts +0 -1
  256. package/src/prover/smt/solver/hashtable.ts +30 -16
  257. package/src/prover/smt/solver/inf-eps.ts +63 -0
  258. package/src/prover/smt/solver/inj-axiom.ts +101 -0
  259. package/src/prover/smt/solver/internalizer.ts +110 -38
  260. package/src/prover/smt/solver/lackr.ts +381 -0
  261. package/src/prover/smt/solver/lbool.ts +0 -1
  262. package/src/prover/smt/solver/lia2card.ts +268 -0
  263. package/src/prover/smt/solver/lia2pb.ts +154 -0
  264. package/src/prover/smt/solver/literal.ts +0 -1
  265. package/src/prover/smt/solver/logic-tactics.ts +345 -0
  266. package/src/prover/smt/solver/lp/bound-propagator.ts +0 -1
  267. package/src/prover/smt/solver/lp/constraints.ts +0 -1
  268. package/src/prover/smt/solver/lp/containers.ts +7 -2
  269. package/src/prover/smt/solver/lp/core-solver.ts +18 -3
  270. package/src/prover/smt/solver/lp/cross-nested.ts +1 -4
  271. package/src/prover/smt/solver/lp/dep-intervals.ts +0 -3
  272. package/src/prover/smt/solver/lp/dependency.ts +0 -2
  273. package/src/prover/smt/solver/lp/dioph-eq.ts +1 -10
  274. package/src/prover/smt/solver/lp/explanation.ts +0 -1
  275. package/src/prover/smt/solver/lp/gomory.ts +0 -1
  276. package/src/prover/smt/solver/lp/hnf-cutter.ts +1 -2
  277. package/src/prover/smt/solver/lp/hnf.ts +0 -3
  278. package/src/prover/smt/solver/lp/int-cube.ts +3 -4
  279. package/src/prover/smt/solver/lp/int-solver.ts +0 -2
  280. package/src/prover/smt/solver/lp/lar-solver.ts +40 -4
  281. package/src/prover/smt/solver/lp/lar-term.ts +0 -1
  282. package/src/prover/smt/solver/lp/lp-settings.ts +0 -1
  283. package/src/prover/smt/solver/lp/maximize-term.ts +59 -10
  284. package/src/prover/smt/solver/lp/nex-creator.ts +3 -3
  285. package/src/prover/smt/solver/lp/nex.ts +2 -2
  286. package/src/prover/smt/solver/lp/nla-backoff.ts +0 -2
  287. package/src/prover/smt/solver/lp/nla-basics.ts +46 -3
  288. package/src/prover/smt/solver/lp/nla-core.ts +67 -16
  289. package/src/prover/smt/solver/lp/nla-divisions.ts +0 -2
  290. package/src/prover/smt/solver/lp/nla-emonics.ts +0 -1
  291. package/src/prover/smt/solver/lp/nla-factorization.ts +0 -1
  292. package/src/prover/smt/solver/lp/nla-grobner.ts +9 -5
  293. package/src/prover/smt/solver/lp/nla-horner.ts +0 -2
  294. package/src/prover/smt/solver/lp/nla-intervals.ts +0 -1
  295. package/src/prover/smt/solver/lp/nla-monomial-bounds.ts +0 -2
  296. package/src/prover/smt/solver/lp/nla-monotone.ts +0 -1
  297. package/src/prover/smt/solver/lp/nla-order.ts +0 -2
  298. package/src/prover/smt/solver/lp/nla-patcher.ts +0 -1
  299. package/src/prover/smt/solver/lp/nla-powers.ts +220 -0
  300. package/src/prover/smt/solver/lp/nla-tangents.ts +0 -2
  301. package/src/prover/smt/solver/lp/nla-throttle.ts +0 -1
  302. package/src/prover/smt/solver/lp/nla-transcendentals.ts +324 -0
  303. package/src/prover/smt/solver/lp/nla-types.ts +0 -2
  304. package/src/prover/smt/solver/lp/nla-var-eqs.ts +0 -1
  305. package/src/prover/smt/solver/lp/nra-solver.ts +122 -64
  306. package/src/prover/smt/solver/lp/numeric-pair.ts +0 -1
  307. package/src/prover/smt/solver/lp/pdd-interval.ts +0 -1
  308. package/src/prover/smt/solver/lp/pdd-simplifier.ts +0 -1
  309. package/src/prover/smt/solver/lp/pdd-solver.ts +0 -2
  310. package/src/prover/smt/solver/lp/pdd.ts +2 -2
  311. package/src/prover/smt/solver/lp/random-updater.ts +0 -2
  312. package/src/prover/smt/solver/lp/static-matrix.ts +0 -1
  313. package/src/prover/smt/solver/lp/union-find.ts +7 -2
  314. package/src/prover/smt/solver/macro-finder.ts +530 -0
  315. package/src/prover/smt/solver/mam-compiler.ts +122 -90
  316. package/src/prover/smt/solver/mam-interpreter.ts +0 -1
  317. package/src/prover/smt/solver/max-bv-sharing-tactic.ts +17 -0
  318. package/src/prover/smt/solver/max-cliques.ts +105 -0
  319. package/src/prover/smt/solver/maxcore.ts +309 -0
  320. package/src/prover/smt/solver/maximize-ac-sharing.ts +8 -6
  321. package/src/prover/smt/solver/maxlex.ts +115 -0
  322. package/src/prover/smt/solver/maxsmt-base.ts +105 -0
  323. package/src/prover/smt/solver/maxsmt.ts +92 -0
  324. package/src/prover/smt/solver/mbp/mbp-arith.ts +467 -0
  325. package/src/prover/smt/solver/mbp/mbp-basic-tg.ts +101 -0
  326. package/src/prover/smt/solver/mbp/mbp-plugin.ts +287 -0
  327. package/src/prover/smt/solver/mbp/mbp-qel.ts +48 -0
  328. package/src/prover/smt/solver/mbp/mbp-solve-plugin.ts +271 -0
  329. package/src/prover/smt/solver/mbp/mbp-term-graph.ts +606 -0
  330. package/src/prover/smt/solver/model-based-opt.ts +844 -0
  331. package/src/prover/smt/solver/model-checker.ts +18 -27
  332. package/src/prover/smt/solver/model-evaluator.ts +188 -12
  333. package/src/prover/smt/solver/model-finder.ts +12 -18
  334. package/src/prover/smt/solver/model-generator.ts +56 -29
  335. package/src/prover/smt/solver/model-macro-solver.ts +49 -46
  336. package/src/prover/smt/solver/model-printer.ts +214 -0
  337. package/src/prover/smt/solver/mpf.ts +711 -0
  338. package/src/prover/smt/solver/mus.ts +51 -0
  339. package/src/prover/smt/solver/muz/dl-context.ts +404 -0
  340. package/src/prover/smt/solver/muz/dl-mk-bit-blast.ts +97 -0
  341. package/src/prover/smt/solver/muz/dl-mk-coi-filter.ts +167 -0
  342. package/src/prover/smt/solver/muz/dl-mk-elim-term-ite.ts +125 -0
  343. package/src/prover/smt/solver/muz/dl-mk-interp-tail-simplifier.ts +299 -0
  344. package/src/prover/smt/solver/muz/dl-mk-rule-inliner.ts +455 -0
  345. package/src/prover/smt/solver/muz/dl-mk-slice.ts +340 -0
  346. package/src/prover/smt/solver/muz/dl-mk-subsumption-checker.ts +163 -0
  347. package/src/prover/smt/solver/muz/dl-rule-set.ts +273 -0
  348. package/src/prover/smt/solver/muz/dl-rule-transformer.ts +123 -0
  349. package/src/prover/smt/solver/muz/dl-rule.ts +496 -0
  350. package/src/prover/smt/solver/muz/hnf.ts +201 -0
  351. package/src/prover/smt/solver/muz/horn-subsume-model-converter.ts +176 -0
  352. package/src/prover/smt/solver/muz/horn-tactic.ts +201 -0
  353. package/src/prover/smt/solver/muz/rule-properties.ts +337 -0
  354. package/src/prover/smt/solver/muz/spacer-context.ts +1406 -0
  355. package/src/prover/smt/solver/muz/spacer-dl-interface.ts +52 -0
  356. package/src/prover/smt/solver/muz/spacer-generalizers.ts +241 -0
  357. package/src/prover/smt/solver/muz/spacer-manager.ts +127 -0
  358. package/src/prover/smt/solver/muz/spacer-pdr.ts +218 -0
  359. package/src/prover/smt/solver/muz/spacer-prop-solver.ts +333 -0
  360. package/src/prover/smt/solver/muz/spacer-util.ts +282 -0
  361. package/src/prover/smt/solver/muz/substitution.ts +203 -0
  362. package/src/prover/smt/solver/nla2bv-tactic.ts +285 -0
  363. package/src/prover/smt/solver/nlqsat.ts +484 -0
  364. package/src/prover/smt/solver/nlsat/algebraic.ts +125 -12
  365. package/src/prover/smt/solver/nlsat/atoms.ts +20 -6
  366. package/src/prover/smt/solver/nlsat/evaluator.ts +0 -1
  367. package/src/prover/smt/solver/nlsat/explain.ts +63 -23
  368. package/src/prover/smt/solver/nlsat/interval-set.ts +1 -2
  369. package/src/prover/smt/solver/nlsat/levelwise.ts +3 -9
  370. package/src/prover/smt/solver/nlsat/mpbq.ts +45 -1
  371. package/src/prover/smt/solver/nlsat/polynomial.ts +13 -6
  372. package/src/prover/smt/solver/nlsat/solver.ts +236 -45
  373. package/src/prover/smt/solver/nlsat/transcendental-eval.ts +310 -0
  374. package/src/prover/smt/solver/nlsat/transcendentals.ts +367 -0
  375. package/src/prover/smt/solver/nlsat/types.ts +0 -2
  376. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +1 -4
  377. package/src/prover/smt/solver/nlsat/upolynomial.ts +0 -2
  378. package/src/prover/smt/solver/nlsat-tactic.ts +82 -0
  379. package/src/prover/smt/solver/nnf.ts +105 -23
  380. package/src/prover/smt/solver/normalize-bounds.ts +53 -0
  381. package/src/prover/smt/solver/occf.ts +97 -0
  382. package/src/prover/smt/solver/opt-context.ts +787 -0
  383. package/src/prover/smt/solver/opt-nlsat.ts +375 -0
  384. package/src/prover/smt/solver/opt-pareto.ts +282 -0
  385. package/src/prover/smt/solver/opt-preprocess.ts +101 -0
  386. package/src/prover/smt/solver/opt-solver.ts +308 -0
  387. package/src/prover/smt/solver/opt-value.ts +55 -0
  388. package/src/prover/smt/solver/optsmt.ts +692 -0
  389. package/src/prover/smt/solver/parallel-tactic.ts +299 -0
  390. package/src/prover/smt/solver/pattern-inference.ts +19 -11
  391. package/src/prover/smt/solver/pb-rewriter.ts +284 -0
  392. package/src/prover/smt/solver/pb2bv-tactic.ts +540 -0
  393. package/src/prover/smt/solver/poly-rewriter.ts +202 -57
  394. package/src/prover/smt/solver/probes.ts +512 -0
  395. package/src/prover/smt/solver/propagate-values.ts +37 -21
  396. package/src/prover/smt/solver/proto-model.ts +648 -19
  397. package/src/prover/smt/solver/pull-quant.ts +28 -12
  398. package/src/prover/smt/solver/purify-arith.ts +632 -0
  399. package/src/prover/smt/solver/qe-arith-plugin.ts +1098 -0
  400. package/src/prover/smt/solver/qe-lite-der.ts +2 -3
  401. package/src/prover/smt/solver/qe-lite-fm.ts +3 -4
  402. package/src/prover/smt/solver/qe-lite.ts +37 -17
  403. package/src/prover/smt/solver/qe-mbp.ts +270 -0
  404. package/src/prover/smt/solver/qe.ts +1498 -0
  405. package/src/prover/smt/solver/qel.ts +25 -0
  406. package/src/prover/smt/solver/qi-queue.ts +0 -1
  407. package/src/prover/smt/solver/qsat.ts +814 -0
  408. package/src/prover/smt/solver/quant-hoist.ts +196 -0
  409. package/src/prover/smt/solver/quant-tactics.ts +16 -56
  410. package/src/prover/smt/solver/quantifier-analyzer.ts +19 -20
  411. package/src/prover/smt/solver/quantifier-manager.ts +8 -16
  412. package/src/prover/smt/solver/quasi-macros.ts +243 -0
  413. package/src/prover/smt/solver/random-gen.ts +0 -1
  414. package/src/prover/smt/solver/rational.ts +45 -1
  415. package/src/prover/smt/solver/recfun-decl-plugin.ts +261 -0
  416. package/src/prover/smt/solver/recfun-rewriter.ts +107 -0
  417. package/src/prover/smt/solver/reduce-args.ts +225 -0
  418. package/src/prover/smt/solver/reduce-bv-size.ts +119 -0
  419. package/src/prover/smt/solver/ref-vector.ts +0 -1
  420. package/src/prover/smt/solver/relevancy.ts +1 -2
  421. package/src/prover/smt/solver/rewriter-tpl.ts +77 -10
  422. package/src/prover/smt/solver/rewriter.ts +475 -36
  423. package/src/prover/smt/solver/rlimit.ts +38 -2
  424. package/src/prover/smt/solver/sat/asymm-branch.ts +325 -0
  425. package/src/prover/smt/solver/sat/big.ts +177 -0
  426. package/src/prover/smt/solver/sat/clause-use-list.ts +71 -0
  427. package/src/prover/smt/solver/sat/clause.ts +203 -0
  428. package/src/prover/smt/solver/sat/cleaner.ts +94 -0
  429. package/src/prover/smt/solver/sat/config.ts +122 -0
  430. package/src/prover/smt/solver/sat/consequences.ts +203 -0
  431. package/src/prover/smt/solver/sat/elim-eqs.ts +142 -0
  432. package/src/prover/smt/solver/sat/goal2sat.ts +526 -0
  433. package/src/prover/smt/solver/sat/inc-sat-solver.ts +378 -0
  434. package/src/prover/smt/solver/sat/model-converter.ts +136 -0
  435. package/src/prover/smt/solver/sat/pb-constraint.ts +261 -0
  436. package/src/prover/smt/solver/sat/pb-solver.ts +1577 -0
  437. package/src/prover/smt/solver/sat/probing.ts +170 -0
  438. package/src/prover/smt/solver/sat/sat-tactic.ts +43 -0
  439. package/src/prover/smt/solver/sat/sat2goal.ts +165 -0
  440. package/src/prover/smt/solver/sat/scc.ts +142 -0
  441. package/src/prover/smt/solver/sat/simplifier.ts +1618 -0
  442. package/src/prover/smt/solver/sat/solver.ts +2127 -0
  443. package/src/prover/smt/solver/sat/var-queue.ts +117 -0
  444. package/src/prover/smt/solver/sat/watch-list.ts +140 -0
  445. package/src/prover/smt/solver/search-tree.ts +284 -0
  446. package/src/prover/smt/solver/seq-axioms.ts +1010 -0
  447. package/src/prover/smt/solver/seq-decl-plugin.ts +819 -0
  448. package/src/prover/smt/solver/seq-derive.ts +1298 -0
  449. package/src/prover/smt/solver/seq-eq-approx.ts +236 -0
  450. package/src/prover/smt/solver/seq-eq-solver.ts +439 -0
  451. package/src/prover/smt/solver/seq-factory.ts +89 -0
  452. package/src/prover/smt/solver/seq-monadic.ts +728 -0
  453. package/src/prover/smt/solver/seq-range-predicate.ts +235 -0
  454. package/src/prover/smt/solver/seq-re-rewriter.ts +1170 -0
  455. package/src/prover/smt/solver/seq-re-util.ts +758 -0
  456. package/src/prover/smt/solver/seq-regex-bisim.ts +144 -0
  457. package/src/prover/smt/solver/seq-regex-live.ts +200 -0
  458. package/src/prover/smt/solver/seq-rewriter.ts +2402 -0
  459. package/src/prover/smt/solver/seq-skolem.ts +317 -0
  460. package/src/prover/smt/solver/seq-subset.ts +165 -0
  461. package/src/prover/smt/solver/seq-view-witness.ts +353 -0
  462. package/src/prover/smt/solver/smt-consequences.ts +297 -0
  463. package/src/prover/smt/solver/smt-kernel.ts +83 -0
  464. package/src/prover/smt/solver/smt-logics.ts +66 -0
  465. package/src/prover/smt/solver/smt-setup.ts +496 -0
  466. package/src/prover/smt/solver/smt2-printer.ts +765 -0
  467. package/src/prover/smt/solver/smtlib-parser.ts +3126 -316
  468. package/src/prover/smt/solver/smtlib-script.ts +1631 -0
  469. package/src/prover/smt/solver/solve-eqs.ts +929 -0
  470. package/src/prover/smt/solver/solver.ts +113 -22
  471. package/src/prover/smt/solver/static-features.ts +314 -0
  472. package/src/prover/smt/solver/sticky-generations.ts +0 -1
  473. package/src/prover/smt/solver/tactic.ts +1986 -0
  474. package/src/prover/smt/solver/term-enumeration.ts +205 -0
  475. package/src/prover/smt/solver/theory-array.ts +1240 -0
  476. package/src/prover/smt/solver/theory-bv.ts +1200 -0
  477. package/src/prover/smt/solver/theory-char.ts +355 -0
  478. package/src/prover/smt/solver/theory-datatype.ts +598 -0
  479. package/src/prover/smt/solver/theory-finite-set.ts +30 -0
  480. package/src/prover/smt/solver/theory-fpa.ts +389 -0
  481. package/src/prover/smt/solver/theory-lra-axioms.ts +53 -2
  482. package/src/prover/smt/solver/theory-lra-bounds.ts +31 -6
  483. package/src/prover/smt/solver/theory-lra-final-check.ts +56 -70
  484. package/src/prover/smt/solver/theory-lra-internalize.ts +94 -27
  485. package/src/prover/smt/solver/theory-lra-model.ts +20 -35
  486. package/src/prover/smt/solver/theory-lra-propagate.ts +24 -26
  487. package/src/prover/smt/solver/theory-lra-state.ts +6 -22
  488. package/src/prover/smt/solver/theory-lra.ts +188 -1
  489. package/src/prover/smt/solver/theory-pb.ts +934 -0
  490. package/src/prover/smt/solver/theory-polymorphism.ts +58 -0
  491. package/src/prover/smt/solver/theory-recfun.ts +307 -0
  492. package/src/prover/smt/solver/theory-seq-regex.ts +867 -0
  493. package/src/prover/smt/solver/theory-seq-solve.ts +1373 -0
  494. package/src/prover/smt/solver/theory-seq-state.ts +871 -0
  495. package/src/prover/smt/solver/theory-seq.ts +961 -0
  496. package/src/prover/smt/solver/theory.ts +189 -0
  497. package/src/prover/smt/solver/tseitin-cnf.ts +485 -0
  498. package/src/prover/smt/solver/var-subst.ts +36 -14
  499. package/src/prover/smt/table.ts +3 -2
  500. package/src/prover/smt/types.ts +146 -0
  501. package/src/prover/tlapm/cache.ts +50 -19
  502. package/src/prover/tlapm/tlapm.ts +15 -9
  503. package/src/prover/tlapm-library.ts +3208 -0
  504. package/src/prover/verdict.ts +9 -0
  505. package/src/prover/zenon/check/check.ts +1 -2
  506. package/src/prover/zenon/check/records.ts +1 -1
  507. package/src/prover/zenon/check/relations.ts +2 -1
  508. package/src/prover/zenon/check/rewrites.ts +2 -15
  509. package/src/prover/zenon/check/sets.ts +40 -58
  510. package/src/prover/zenon/check/terms.ts +1 -2
  511. package/src/prover/zenon/decide.ts +10 -7
  512. package/src/prover/zenon/encode.ts +0 -2
  513. package/src/prover/zenon/eqrel.ts +2 -2
  514. package/src/prover/zenon/equality-rules.ts +24 -2
  515. package/src/prover/zenon/expr.ts +28 -2
  516. package/src/prover/zenon/index-table.ts +11 -21
  517. package/src/prover/zenon/isar-case.ts +0 -2
  518. package/src/prover/zenon/isar.ts +35 -37
  519. package/src/prover/zenon/llproof.ts +2 -13
  520. package/src/prover/zenon/mltoll.ts +12 -30
  521. package/src/prover/zenon/node.ts +20 -5
  522. package/src/prover/zenon/parse.ts +9 -8
  523. package/src/prover/zenon/phrase.ts +0 -2
  524. package/src/prover/zenon/proof.ts +0 -2
  525. package/src/prover/zenon/propositional-rules.ts +0 -2
  526. package/src/prover/zenon/rules.ts +2 -3
  527. package/src/prover/zenon/search.ts +11 -19
  528. package/src/prover/zenon/tla/functions.ts +2 -4
  529. package/src/prover/zenon/tla/llproof.ts +9 -13
  530. package/src/prover/zenon/tla/records.ts +1 -8
  531. package/src/prover/zenon/tla/rewrites.ts +0 -2
  532. package/src/prover/zenon/tla/sets.ts +22 -22
  533. package/src/prover/zenon/tla/terms.ts +0 -2
  534. package/src/prover/zenon/tla/tla.ts +7 -8
  535. package/src/randomization.ts +1 -4
  536. package/src/resolve.ts +67 -143
  537. package/src/runtime.ts +15 -18
  538. package/src/sany/builtins.ts +1 -3
  539. package/src/sany/generation.ts +394 -0
  540. package/src/sany/generator-def-entries.ts +210 -0
  541. package/src/sany/generator-definitions.ts +686 -0
  542. package/src/sany/generator-expressions.ts +1100 -0
  543. package/src/sany/generator-proofs.ts +662 -0
  544. package/src/sany/generator.ts +160 -2683
  545. package/src/sany/levels.ts +5 -11
  546. package/src/sany/lexer.ts +57 -60
  547. package/src/sany/linter.ts +0 -3
  548. package/src/sany/nodes.ts +6 -13
  549. package/src/sany/report.ts +3 -6
  550. package/src/sany/selectors.ts +35 -38
  551. package/src/sany/xml.ts +23 -55
  552. package/src/search.ts +206 -44
  553. package/src/simulate.ts +202 -184
  554. package/src/spec-description.ts +56 -82
  555. package/src/standard-definitions.ts +4 -3
  556. package/src/standard-modules.ts +17 -44
  557. package/src/state-graph.ts +3 -17
  558. package/src/subexpressions.ts +38 -47
  559. package/src/substitution-levels.ts +5 -4
  560. package/src/successors.ts +20 -43
  561. package/src/symmetry.ts +6 -21
  562. package/src/tableau.ts +2 -2
  563. package/src/tlc/fingerprint.ts +96 -30
  564. package/src/tlc/jar-data.ts +0 -1
  565. package/src/tlc/messages.ts +22 -36
  566. package/src/tlc/order.ts +22 -47
  567. package/src/tlc/random.ts +22 -34
  568. package/src/tlc/replay.ts +21 -48
  569. package/src/tlc/summary.ts +64 -58
  570. package/src/tlc/tlc-operators.ts +6 -17
  571. package/src/tlc/tlcext-operators.ts +54 -26
  572. package/src/tlc/trace-spec.ts +26 -51
  573. package/src/tlc/value-stream.ts +9 -13
  574. package/src/tlc/version.ts +0 -1
  575. package/src/typed-tier.ts +6535 -0
  576. package/src/typescript/actions.ts +2 -4
  577. package/src/typescript/collections.ts +34 -20
  578. package/src/typescript/compile.ts +1 -3
  579. package/src/typescript/formula.ts +5 -3
  580. package/src/typescript/model.ts +4 -5
  581. package/src/typescript/steps.ts +20 -18
  582. package/src/values.ts +136 -338
  583. package/src/prover/isabelle/isar/statement.ts +0 -52
  584. package/src/prover/smt/solver/z3-license.txt +0 -10
  585. package/src/prover/tlaps-module.ts +0 -510
  586. package/src/prover/zenon/LICENSE +0 -32
package/src/check.ts CHANGED
@@ -9,10 +9,8 @@ import {
9
9
  getCoverageReport,
10
10
  type CoverageReport,
11
11
  } from "./coverage";
12
- import { createEnvironment } from "./environment";
13
12
  import {
14
13
  createStackOverflowError,
15
- getErrorExitCode,
16
14
  isStackOverflow,
17
15
  TlaEvaluationError,
18
16
  TlaIllegalStateError,
@@ -21,24 +19,36 @@ import {
21
19
  TlaStackOverflowError,
22
20
  UNEXPECTED_EVAL_EXCEPTION,
23
21
  UNEXPECTED_EXCEPTION,
22
+ formatRange,
24
23
  } from "./errors";
25
24
  import {
26
- createTracingEnvironment,
27
25
  describeRange,
28
- formatRange,
29
26
  getDefinition,
30
- isImpure,
31
27
  type CallStack,
32
28
  type Environment,
33
29
  type FingerprintFailure,
34
30
  } from "./evaluate";
31
+ import { EXIT_STATUS, setExitCode, withLivenessExitCode } from "./exit-codes";
32
+ import {
33
+ fingerprintReplayed,
34
+ getFailureExitCode,
35
+ getReplayFailure,
36
+ type FailureOptions,
37
+ } from "./check-failure";
35
38
  import {
36
- EXIT_STATUS,
37
- getExitCode,
38
- getMessageExitStatus,
39
- setExitCode,
40
- withLivenessExitCode,
41
- } from "./exit-codes";
39
+ createTraceBuilder,
40
+ type Behavior,
41
+ type SearchPosition,
42
+ type TracedStep,
43
+ } from "./check-trace";
44
+ import {
45
+ createStateTable,
46
+ findStateIndex,
47
+ getStateHash,
48
+ isSameState,
49
+ markSeenState,
50
+ type StateTable,
51
+ } from "./fingerprints";
42
52
  import type { JavaOverride } from "./java-overrides";
43
53
  import {
44
54
  createLivenessChecker,
@@ -47,6 +57,7 @@ import {
47
57
  type LiveSuccessor,
48
58
  } from "./liveness-checker";
49
59
  import {
60
+ createCheckEnvironment,
50
61
  createMissingOperatorError,
51
62
  createSearch,
52
63
  getIncompleteSuccessorMessage,
@@ -58,11 +69,11 @@ import {
58
69
  import {
59
70
  getActionLabel,
60
71
  getActionSignature,
61
- getInitActions,
62
- getNextActions,
72
+ getSpecDescription,
63
73
  getSpecificationValue,
64
74
  toActionValue,
65
75
  type SpecAction,
76
+ type SpecDescription,
66
77
  } from "./spec-description";
67
78
  import {
68
79
  createStateWriter,
@@ -79,7 +90,6 @@ import {
79
90
  type Successor,
80
91
  } from "./successors";
81
92
  import {
82
- getCodedMessage,
83
93
  getFailureMessage,
84
94
  getWrappedException,
85
95
  isEvalException,
@@ -90,9 +100,7 @@ import {
90
100
  } from "./tlc/messages";
91
101
  import { createTautologyError } from "./liveness";
92
102
  import { KEY_SEPARATOR } from "./resolve";
93
- import { setFingerprintPolynomial } from "./tlc/fingerprint";
94
103
  import { writeTraceSpec } from "./tlc/trace-spec";
95
- import { createTlcOrder } from "./tlc/order";
96
104
  import {
97
105
  getPrimedRanges,
98
106
  replayInitialStates,
@@ -102,19 +110,15 @@ import {
102
110
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc/summary";
103
111
  import { createActionRecord, createCounterExample } from "./tlc/tlcext-operators";
104
112
  import type { TlcVersion } from "./tlc/version";
113
+ import { runTypedSearch, type TypedResult } from "./typed-tier";
105
114
  import {
106
- combineHash,
107
115
  createCanonicalizer,
108
116
  createModelValue,
109
117
  formatState,
110
118
  getFingerprintError,
111
- getHeldValues,
112
119
  getModelValues,
113
- getValueHash,
114
120
  isSameValue,
115
121
  markFingerprinted,
116
- setStringOrder,
117
- setValueOptions,
118
122
  type Value,
119
123
  } from "./values";
120
124
 
@@ -130,30 +134,32 @@ export interface CheckOptions {
130
134
  makeDirectory?: (path: string) => void;
131
135
  seed?: bigint;
132
136
  workers?: number;
133
- // TLC's -lncheck: "final" checks liveness only on the complete graph, "off" never looks for a cycle.
137
+ /** TLC's -lncheck: "final" checks liveness only on the complete graph, "off" never looks for a cycle. */
134
138
  livenessCheck?: "default" | "final" | "off";
135
- // TLC's -fp: the index of the polynomial in TLC's FP64.Polys that fingerprints states.
139
+ /** TLC's -fp: the index of the polynomial in TLC's FP64.Polys that fingerprints states. */
136
140
  fingerprintPolynomial?: number;
137
- // False for TLC's -terse, which prints a lazy value, such as SUBSET S, without enumerating it.
141
+ /** False for TLC's -terse, which prints a lazy value, such as SUBSET S, without enumerating it. */
138
142
  isLazyValueExpanded?: boolean;
139
- // TLC's -view: prints each state as the value of the configuration's VIEW.
143
+ /** TLC's -view: prints each state as the value of the configuration's VIEW. */
140
144
  isViewPrinted?: boolean;
141
- // TLC's -maxSetSize: the most elements TLC enumerates into a set, or states into a list of them.
145
+ /** TLC's -maxSetSize: the most elements TLC enumerates into a set, or states into a list of them. */
142
146
  maxSetSize?: number;
143
- // TLC's -dump: writes the reachable states, or with `dot` the state graph, through writeFile.
147
+ /** TLC's -dump: writes the reachable states, or with `dot` the state graph, through writeFile. */
144
148
  dump?: StateDump;
145
- // TLC's -tool, which changes the messages of TLC's errors.
149
+ /** TLC's -tool, which changes the messages of TLC's errors. */
146
150
  isTool?: boolean;
147
- // TLC's -continue: reports each violation through onProgress and goes on.
151
+ /** TLC's -continue: reports each violation through onProgress and goes on. */
148
152
  isContinued?: boolean;
153
+ /** Skips fingerprintDistance, which takes fingerprinting every state again after the search. */
154
+ isFingerprintDistanceSkipped?: boolean;
149
155
  moduleOperators?: ModuleOperator[];
150
- // TLC's trace exploration spec, and the binary trace TLC records for it unless -noTEBin.
156
+ /** TLC's trace exploration spec, and the binary trace TLC records for it unless -noTEBin. */
151
157
  traceSpec?: TraceSpecOptions;
152
- // Whether the caller printed SANY's report, its warnings included, before the check.
158
+ /** Whether the caller printed SANY's report, its warnings included, before the check. */
153
159
  isSanyReported?: boolean;
154
- // False for TLC's -nowarning, which changes how TLC computes some successors.
160
+ /** False for TLC's -nowarning, which changes how TLC computes some successors. */
155
161
  isWarningEnabled?: boolean;
156
- // TLC's -coverage, in minutes.
162
+ /** TLC's -coverage, in minutes. */
157
163
  coverage?: number;
158
164
  version?: TlcVersion;
159
165
  onProgress?: (progress: CheckProgress) => void;
@@ -176,7 +182,6 @@ export interface InitialStatesProgress {
176
182
  count: number;
177
183
  }
178
184
 
179
- // A check TLC reports as violated before it stops replaying the initial states.
180
185
  export interface InitialStateViolation {
181
186
  kind: "initial-state-violation";
182
187
  status: "invariant-violation" | "liveness-violation";
@@ -184,7 +189,6 @@ export interface InitialStateViolation {
184
189
  state: Record<string, Value>;
185
190
  }
186
191
 
187
- // A line the spec prints, or what TLC reports as it replays the initial states.
188
192
  export type OutputLine = string | InitialStatesProgress | InitialStateViolation;
189
193
 
190
194
  export type CheckProgress =
@@ -200,17 +204,16 @@ export type CheckProgress =
200
204
  | {
201
205
  kind: "liveness-started";
202
206
  branches: number;
203
- // Whether TLC checks the complete state graph, and how many states of it each branch has.
207
+ /** Whether TLC checks the complete state graph. */
204
208
  isComplete: boolean;
209
+ /** How many states of the graph each branch has. */
205
210
  states: number;
206
211
  statistics: SearchStatistics;
207
212
  }
208
213
  | { kind: "liveness-finished" }
209
214
  | { kind: "sequential-fallback"; string: string }
210
215
  | { kind: "warning"; code: number; text: string }
211
- // A violation that the search goes on past with -continue.
212
216
  | { 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
217
  | ({ kind: "java-override" } & JavaOverride);
215
218
 
216
219
  export interface SearchStatistics extends Pick<
@@ -230,30 +233,30 @@ export type CheckStatus =
230
233
 
231
234
  export interface TraceStep {
232
235
  action: string | undefined;
233
- // TLC's name, parameters and location for the action that took this step.
236
+ /** TLC's name, parameters and location for the action that took this step. */
234
237
  label: string | undefined;
235
238
  state: Record<string, Value>;
236
- // What the spec prints before this step as TLC rebuilds the trace, and before it for the first.
239
+ /** What the spec prints before this step as TLC rebuilds the trace, and before it for the first. */
237
240
  output?: OutputLine[];
238
241
  }
239
242
 
240
243
  export interface Violation {
241
244
  name: string;
242
- // Every temporal property that a liveness counterexample violates, in the configuration's order.
245
+ /** Every temporal property that a liveness counterexample violates, in the configuration's order. */
243
246
  properties?: string[];
244
247
  trace: TraceStep[];
245
- // What the spec prints after the trace, as TLC finds the lasso's step back or rebuilds the trace.
248
+ /** What the spec prints after the trace, as TLC finds the lasso's step back or rebuilds the trace. */
246
249
  traceOutput?: OutputLine[];
247
- // What the postconditions print, which TLC checks after the lasso's step back.
250
+ /** What the postconditions print, which TLC checks after the lasso's step back. */
248
251
  postconditionOutput?: OutputLine[];
249
252
  loopStart: number | undefined;
250
253
  loopLabel?: string;
251
254
  message?: string;
252
255
  counts?: string;
253
256
  unwitnessed?: Postcondition;
254
- // A POSTCONDITION that is false or fails, which TLC checks as it prints the counterexample.
257
+ /** A POSTCONDITION that is false or fails, which TLC checks as it prints the counterexample. */
255
258
  postcondition?: Postcondition;
256
- // What TLC warns about after a counterexample, with its code.
259
+ /** What TLC warns about after a counterexample, with its code. */
257
260
  warning?: { code: number; text: string };
258
261
  }
259
262
 
@@ -264,7 +267,7 @@ export interface Postcondition {
264
267
  counts?: string;
265
268
  }
266
269
 
267
- // An evaluation that failed during the search, with the behavior up to the state TLC was working on.
270
+ /** An evaluation that failed during the search, with the behavior up to the state TLC was working on. */
268
271
  export interface EvaluationFailure {
269
272
  code: number;
270
273
  message: string;
@@ -273,26 +276,20 @@ export interface EvaluationFailure {
273
276
  traceOutput?: OutputLine[];
274
277
  initialState: Record<string, Value> | undefined;
275
278
  exitCode: number;
276
- // The expressions TLC was evaluating, outermost first, when its replay finds them.
279
+ /** The expressions TLC was evaluating, outermost first, when its replay finds them. */
277
280
  callStack: Expression[] | undefined;
278
- // Whether TLC prints the call stack before the error, as it does for a failed liveness check.
281
+ /** Whether TLC prints the call stack before the error, as it does for a failed liveness check. */
279
282
  isCallStackFirst?: boolean;
280
- // The FingerprintException the replay raises, which TLC reports in place of the call stack.
283
+ /** The FingerprintException the replay raises, which TLC reports in place of the call stack. */
281
284
  fingerprint?: FingerprintFailure;
282
- // How TLC reports failing again as it prints the trace, since it can't fingerprint the state.
285
+ /** How TLC reports failing again as it prints the trace, since it can't fingerprint the state. */
283
286
  traceFailure?: FailureMessage;
284
- // A POSTCONDITION that is false or fails after the trace, which TLC checks as it prints one.
287
+ /** A POSTCONDITION that is false or fails after the trace, which TLC checks as it prints one. */
285
288
  postcondition?: Postcondition;
286
- // Whether TLC stops before it prints the statistics, as it does for an illegal initial state.
289
+ /** Whether TLC stops before it prints the statistics, as it does for an illegal initial state. */
287
290
  isWithoutStatistics?: boolean;
288
291
  }
289
292
 
290
- interface ReplayFailure {
291
- callStack: Expression[];
292
- fingerprint: FingerprintFailure | undefined;
293
- replayError?: TlaEvaluationError;
294
- }
295
-
296
293
  export interface InitialStates {
297
294
  generated: number;
298
295
  distinct: number;
@@ -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;
@@ -326,28 +323,8 @@ interface CoveredAction extends SpecAction {
326
323
  node: number;
327
324
  }
328
325
 
329
- interface Behavior {
330
- trace: TraceStep[];
331
- traceOutput?: OutputLine[];
332
- }
333
-
334
- interface TraceOptions {
326
+ interface ReportedViolation extends Omit<Violation, "loopStart"> {
335
327
  loopStart?: number;
336
- known?: number;
337
- }
338
-
339
- interface FailureOptions {
340
- initialState?: Value[];
341
- isInitial?: boolean;
342
- outDegrees?: number[];
343
- callStack?: Expression[];
344
- fingerprint?: FingerprintFailure;
345
- replayError?: TlaEvaluationError;
346
- isNextState?: boolean;
347
- isCallStackFirst?: boolean;
348
- traceFailure?: FailureMessage;
349
- // Whether TLC prints the call stack of adding the state to the behavior graph, not a replay.
350
- isLiveCallStack?: boolean;
351
328
  }
352
329
 
353
330
  const appendTraceOutput = <Traced extends Behavior>(behavior: Traced, lines: OutputLine[]) => ({
@@ -355,32 +332,9 @@ const appendTraceOutput = <Traced extends Behavior>(behavior: Traced, lines: Out
355
332
  traceOutput: [...(behavior.traceOutput ?? []), ...lines],
356
333
  });
357
334
 
358
- const INITIAL_RECOVERY_FAILURE = "Failed to recover the initial state from its fingerprint.";
359
- const NEXT_RECOVERY_FAILURE = "Failed to recover the next state from its fingerprint.";
360
-
361
- // Stops a replay where TLC stops it without a failure, as at a violated invariant.
362
335
  const STOP_REPLAY = new Error("The replay stopped");
363
336
  const STOP_WALK = new Error("The walk stopped");
364
337
 
365
- // When TLC's replay of the initial states doesn't fail again, it exits with the error's code.
366
- const getInitialExitCode = (error: TlaEvaluationError) => {
367
- const coded = getCodedMessage(error.message);
368
- return coded &&
369
- !coded.isEvalException &&
370
- getMessageExitStatus(coded.code) === EXIT_STATUS.configParseError
371
- ? EXIT_STATUS.configParseError
372
- : getErrorExitCode(error);
373
- };
374
-
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
- const getReplayExitCode = (error: TlaEvaluationError): number => {
378
- const inner = error.cause;
379
- if (inner instanceof TlaEvaluationError) return getReplayExitCode(inner);
380
- return error instanceof TlaModuleError ? error.exitCode : EXIT_STATUS.specEvaluationFailure;
381
- };
382
-
383
- // TLC finishes the -dump file whether or not the search finds a violation.
384
338
  export const checkSequentially = (options: CheckOptions): CheckResult => {
385
339
  const stateWriter =
386
340
  options.dump && createStateWriter(options.dump, options.writeFile, options.version);
@@ -393,8 +347,6 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
393
347
  }
394
348
  };
395
349
 
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
350
  const PERIODIC_START = 3000;
399
351
  const PROGRESS_INTERVAL = 60_000;
400
352
  const LIVENESS_GROWTH = 0.1;
@@ -406,45 +358,23 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
406
358
  ? parseConfig(options.config, options.version)
407
359
  : options.config;
408
360
  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 };
361
+ let capturedLines: OutputLine[] | undefined;
411
362
  const print = (text: string) => {
412
- if (capturedOutput.lines) capturedOutput.lines.push(text);
363
+ if (capturedLines) capturedLines.push(text);
413
364
  else onPrint(text);
414
365
  };
415
366
  const captureOutput = <Result>(rebuild: () => Result) => {
416
- const outer = capturedOutput.lines;
367
+ const outer = capturedLines;
417
368
  const lines: OutputLine[] = [];
418
- capturedOutput.lines = lines;
369
+ capturedLines = lines;
419
370
  try {
420
371
  return { result: rebuild(), lines };
421
372
  } finally {
422
- capturedOutput.lines = outer;
373
+ capturedLines = outer;
423
374
  }
424
375
  };
425
- const order = createTlcOrder(options.source, options.loadModule);
426
- setStringOrder(order.getStringOrder(config));
427
- setValueOptions(options);
428
- setFingerprintPolynomial(options.fingerprintPolynomial ?? 0);
429
- const specification = createEnvironment(config, {
430
- source: options.source,
431
- loadModule: options.loadModule,
432
- order,
433
- loadClass: options.loadClass,
434
- print,
435
- files: {
436
- readFile: options.readFile,
437
- writeFile: options.writeFile,
438
- makeDirectory: options.makeDirectory,
439
- },
440
- seed: options.seed,
441
- isTool: options.isTool,
442
- traceFile: options.traceSpec?.traceFile,
443
- isSanyReported: options.isSanyReported,
444
- isWarningEnabled: options.isWarningEnabled,
445
- version: options.version,
446
- moduleOperators: options.moduleOperators,
447
- });
376
+ const created = createCheckEnvironment(config, options, print);
377
+ const specification = created.specification;
448
378
  reportStartup(specification, config, options.onProgress);
449
379
  const coverage =
450
380
  options.coverage === undefined
@@ -462,14 +392,13 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
462
392
  const runtime = environment.runtime;
463
393
  const is174 = runtime.version === "1.7.4";
464
394
  runtime.pause = options.onPause ?? (() => {});
395
+ let description: SpecDescription | undefined;
396
+ const getDescription = () =>
397
+ (description ??= getSpecDescription(config, environment, specification.instanceActions));
465
398
  runtime.getSpecification = () =>
466
- getSpecificationValue(
467
- config,
468
- environment,
469
- specification.variableLocations,
470
- specification.instanceActions,
471
- );
472
- const statistics = { depth: 0, initialStates: undefined as InitialStates | undefined };
399
+ getSpecificationValue(getDescription(), config, environment, specification.variableLocations);
400
+ let searchDepth = 0;
401
+ let computedInitialStates: InitialStates | undefined;
473
402
  const getTraceSpec = (trace: TraceStep[], loopStart: number | undefined) =>
474
403
  options.traceSpec &&
475
404
  writeTraceSpec({
@@ -488,10 +417,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
488
417
  });
489
418
  const createResult = (
490
419
  status: CheckStatus,
491
- violation?: Omit<Violation, "loopStart"> & { loopStart?: number },
420
+ violation?: ReportedViolation,
492
421
  failure?: EvaluationFailure,
493
422
  ): CheckResult => {
494
- // TLC writes the trace it printed, and a safety property's counterexample doesn't loop back.
495
423
  const traceSpec = getTraceSpec(
496
424
  violation?.trace ?? failure?.trace ?? [],
497
425
  status === "property-violation" ? undefined : violation?.loopStart,
@@ -503,8 +431,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
503
431
  generatedStates: runtime.generatedStates,
504
432
  distinctStates: runtime.distinctStates,
505
433
  queuedStates: runtime.queueSize,
506
- depth: runtime.generatedStates === 0 ? 0 : Math.max(statistics.depth, 1),
507
- initialStates: statistics.initialStates,
434
+ depth: runtime.generatedStates === 0 ? 0 : Math.max(searchDepth, 1),
435
+ initialStates: computedInitialStates,
508
436
  outDegrees: undefined,
509
437
  fingerprintDistance: undefined,
510
438
  coverage: coverage?.relations.some((relation) => relation.kind === "next")
@@ -519,16 +447,13 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
519
447
  };
520
448
  };
521
449
  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.
450
+ let newStateCount = 0;
451
+ const getOutDegreeBucket = () => Math.min(newStateCount, OUT_DEGREE_BUCKETS - 1);
525
452
  const getPartialOutDegrees = () =>
526
453
  outDegrees.map((count, degree) => (degree === getOutDegreeBucket() ? count + 1 : count));
527
454
  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
455
  const getViolatedProperties = (checker: LivenessChecker, path: Value[][], cycleStart: number) =>
530
456
  is174 ? [] : checker.getViolatedProperties(path, cycleStart);
531
- // A violation in a successor ends the expansion of a state before TLC counts it.
532
457
  const withOutDegrees = (result: CheckResult, degrees = [...outDegrees]): CheckResult => ({
533
458
  ...result,
534
459
  violationOutDegrees: degrees,
@@ -536,21 +461,22 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
536
461
  const createSuccess = (): CheckResult => ({
537
462
  ...createResult("success"),
538
463
  outDegrees: [...outDegrees],
539
- fingerprintDistance: getFingerprintDistance(
540
- runtime.distinctStates,
541
- runtime.generatedStates,
542
- () =>
543
- search
544
- ? search.getStoredFingerprints(states, fingerprintStates)
545
- : BigInt64Array.from(states, runtime.getFingerprint),
546
- ),
464
+ fingerprintDistance: options.isFingerprintDistanceSkipped
465
+ ? undefined
466
+ : getFingerprintDistance(runtime.distinctStates, runtime.generatedStates, (visit) =>
467
+ visit(
468
+ search
469
+ ? search.getStoredFingerprints(states, fingerprintStates)
470
+ : BigInt64Array.from(states, runtime.getFingerprint),
471
+ ),
472
+ ),
547
473
  });
548
474
 
549
475
  const search = createSearch(
550
476
  config,
551
477
  environment,
552
478
  specification.variableLocations,
553
- () => order.getDeclarationOrder("variable"),
479
+ () => created.order.getDeclarationOrder("variable"),
554
480
  options.onProgress,
555
481
  specification.moduleOperators,
556
482
  );
@@ -560,12 +486,11 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
560
486
  runtime.isStarted = true;
561
487
  const assumptionViolation = findViolatedAssumption();
562
488
  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 };
489
+ computedInitialStates = { generated: 0, distinct: 0 };
565
490
  options.onProgress?.({ kind: "initial-states-started" });
566
491
  options.onProgress?.({
567
492
  kind: "initial-states-computed",
568
- initialStates: statistics.initialStates,
493
+ initialStates: computedInitialStates,
569
494
  });
570
495
  return createSuccess();
571
496
  }
@@ -573,17 +498,12 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
573
498
  config.postconditions.length > 0 ||
574
499
  config.possible.length > 0 ||
575
500
  specification.moduleOperators.some((operator) => operator.kind === "postcondition");
576
- // The state of each step without the alias, and its action, which CounterExample records.
577
- const traceSteps = new WeakMap<
578
- TraceStep,
579
- { state: Record<string, Value>; action: SpecAction | undefined }
580
- >();
581
- const getStepState = (step: TraceStep) => traceSteps.get(step)?.state ?? step.state;
501
+ const tracedSteps = new WeakMap<TraceStep, TracedStep>();
502
+ const getStepState = (step: TraceStep) => tracedSteps.get(step)?.state ?? step.state;
582
503
  const getStepAction = (step: TraceStep) => {
583
- const action = traceSteps.get(step)?.action;
504
+ const action = tracedSteps.get(step)?.action;
584
505
  return action ? toActionValue(action) : createActionRecord(step.action);
585
506
  };
586
- // TLC checks the postconditions on each trace it prints, so what they print follows the trace.
587
507
  const checkTracePostconditions = (
588
508
  trace: TraceStep[],
589
509
  loop: { start: number; action: Value } | undefined,
@@ -603,7 +523,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
603
523
  };
604
524
  const reportViolation = (
605
525
  status: CheckStatus,
606
- violation: Omit<Violation, "loopStart"> & { loopStart?: number },
526
+ violation: ReportedViolation,
607
527
  getLoopAction?: () => Value,
608
528
  ) => {
609
529
  const start = violation.loopStart;
@@ -618,15 +538,13 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
618
538
  ...(checked.postcondition && { postcondition: checked.postcondition }),
619
539
  });
620
540
  };
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 };
541
+ // Deviation from TLC: -continue ends with the status of the first violation, not a success.
542
+ let continuedStatus: CheckStatus | undefined;
625
543
  const reportContinuedViolation = (
626
544
  status: CheckStatus,
627
545
  violation: Omit<Violation, "loopStart">,
628
546
  ) => {
629
- continued.status ??= status;
547
+ continuedStatus ??= status;
630
548
  options.onProgress?.({
631
549
  kind: "violation",
632
550
  status,
@@ -635,13 +553,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
635
553
  };
636
554
  const spec = search.spec;
637
555
  const getFingerprintState = search.getFingerprintState;
638
- const specNextActions = { value: undefined as SpecAction[] | undefined };
639
- const getSpecNextActions = () =>
640
- (specNextActions.value ??= getNextActions(config, environment, specification.instanceActions));
641
556
  // Tool's constructor splits the next-state relation into actions before TLC checks anything.
642
- getSpecNextActions();
557
+ const nextActions = getDescription().actions;
643
558
  runtime.getSuccessorAction = (state, next) =>
644
- getSpecNextActions().find((action) =>
559
+ nextActions.find((action) =>
645
560
  getSuccessors(action.expression, state, environment, action.scope).some((successor) =>
646
561
  successor.state.every((value, index) => isSameValue(value, next[index])),
647
562
  ),
@@ -659,11 +574,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
659
574
  )
660
575
  : -1,
661
576
  }));
662
- const coverageInits = addCoverageRelations(
663
- "init",
664
- coverage ? getInitActions(config, environment, specification.instanceActions) : [],
665
- );
666
- const coverageActions = addCoverageRelations("next", coverage ? getSpecNextActions() : []);
577
+ const coverageInits = addCoverageRelations("init", coverage ? getDescription().inits : []);
578
+ const coverageActions = addCoverageRelations("next", coverage ? nextActions : []);
667
579
  if (coverage) buildCoverage(coverage, environment, getPrimedRanges(coverageActions, environment));
668
580
  const walkCoveredSuccessors = (
669
581
  action: CoveredAction,
@@ -680,7 +592,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
680
592
  onState(successor);
681
593
  },
682
594
  (partial) => {
683
- const missing = environment.variables.filter((_, index) => partial[index] === undefined);
595
+ const missing = environment.variables.filter(
596
+ (_variable, index) => partial[index] === undefined,
597
+ );
684
598
  throw new TlaIncompleteSuccessorError(
685
599
  `Successor state is not completely specified by action ${action.name}. The following variables are not assigned: ${missing.join(", ")}`,
686
600
  partial,
@@ -696,69 +610,26 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
696
610
  );
697
611
  return successors;
698
612
  };
613
+ const rejectIncompleteInitialState = (partial: (Value | undefined)[]) => {
614
+ throw setExitCode(new TlaIllegalStateError([...partial]), EXIT_STATUS.error);
615
+ };
699
616
  const getCoveredInitialStates = () => {
700
617
  const initialStates: Value[][] = [];
701
618
  replayInitialStates(
702
619
  coverageInits,
703
620
  environment,
704
621
  (state) => initialStates.push(state),
705
- (partial) => {
706
- throw setExitCode(new TlaIllegalStateError([...partial]), EXIT_STATUS.error);
707
- },
622
+ rejectIncompleteInitialState,
708
623
  );
709
624
  return initialStates;
710
625
  };
711
- const getReplayFailure = (replay: (tracing: Environment) => void): ReplayFailure | undefined => {
712
- const tracing = createTracingEnvironment(environment);
713
- const callStack = tracing.callStack;
714
- try {
715
- replay(tracing);
716
- return undefined;
717
- } catch (error) {
718
- // A replay that overflows the stack again has an empty call stack.
719
- if (isStackOverflow(error)) return { callStack: [], fingerprint: undefined };
720
- if (!(error instanceof TlaEvaluationError) || !callStack) return undefined;
721
- return {
722
- callStack: callStack.expressions,
723
- fingerprint: callStack.fingerprint,
724
- replayError: error,
725
- };
726
- }
727
- };
728
- // Outermost first: each value fails as it fingerprints a value it holds.
729
- const findFailedSources = (value: Value, sources: CallStack["sources"]): Expression[] => {
730
- if (typeof value !== "object") return [];
731
- const source = sources.get(value);
732
- const failed = getHeldValues(value).find((held) => getFingerprintError(held) !== undefined);
733
- return [
734
- ...(source ? [source] : []),
735
- ...(failed === undefined ? [] : findFailedSources(failed, sources)),
736
- ];
737
- };
738
- // A value the replay built raises a FingerprintException when TLC fails to fingerprint it.
739
- const fingerprintReplayed = (state: Value[], callStack: CallStack | undefined) => {
740
- for (const value of getFingerprintState(state)) {
741
- const error = getFingerprintError(value);
742
- if (!error) continue;
743
- const sources = callStack ? findFailedSources(value, callStack.sources) : [];
744
- // TLC fingerprints a state outside any evaluation, so its call stack is empty.
745
- if (callStack && sources.length > 0) {
746
- callStack.expressions.length = 0;
747
- callStack.isFrozen = true;
748
- callStack.fingerprint = { sources, reason: error.message };
749
- }
750
- throw error;
751
- }
752
- state.forEach(markFingerprinted);
753
- };
754
- // TLC's set of states already holds the state that failed.
755
626
  const createReplayedStates = () => {
756
- const replayed = unstoredState.fingerprint ? [unstoredState.fingerprint] : [];
627
+ const replayed = unstoredFingerprint ? [unstoredFingerprint] : [];
757
628
  return (state: Value[], callStack: CallStack | undefined) => {
758
- fingerprintReplayed(state, callStack);
629
+ fingerprintReplayed(state, getFingerprintState(state), callStack);
759
630
  const fingerprintState = getFingerprintState(state);
760
631
  const isSeen =
761
- findStateIndex(getStateHash(fingerprintState), fingerprintState) !== -1 ||
632
+ findStateIndex(seenStates, getStateHash(fingerprintState), fingerprintState) !== -1 ||
762
633
  replayed.some((seen) => isSameState(seen, fingerprintState));
763
634
  if (isSeen) return false;
764
635
  replayed.push(fingerprintState);
@@ -766,57 +637,48 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
766
637
  return true;
767
638
  };
768
639
  };
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
640
  const replayInit = () => {
772
- const replayed = { count: 0 };
641
+ let replayedCount = 0;
773
642
  const deferred: unknown[] = [];
774
643
  const addReplayed = createReplayedStates();
775
- return getReplayFailure((tracing) => {
776
- replayInitialStates(
777
- getInitActions(config, environment, specification.instanceActions),
778
- tracing,
779
- (state) => {
780
- reportInitialStatesProgress(replayed.count, (progress) =>
781
- capturedOutput.lines?.push(progress),
782
- );
783
- replayed.count++;
784
- runtime.generatedStates = replayed.count;
785
- if (deferred.length > 0) return;
786
- try {
787
- const addFingerprint = () => {
788
- if (!addReplayed(state, tracing.callStack)) return;
789
- runtime.queueSize++;
790
- liveness?.addInitialState(states.length, state, tracing);
791
- };
792
- const violation = search.checkReplayedInitialState(state, tracing, addFingerprint);
793
- if (violation) {
794
- const traced = toTrace([{ action: undefined, state }], []).trace[0].state;
795
- capturedOutput.lines?.push({
796
- kind: "initial-state-violation",
797
- ...violation,
798
- state: traced,
799
- });
800
- throw STOP_REPLAY;
801
- }
802
- } catch (error) {
803
- const isFingerprintFailure =
804
- error instanceof TlaEvaluationError && tracing.callStack?.fingerprint !== undefined;
805
- if (!isFingerprintFailure && !isStackOverflow(error)) throw error;
806
- deferred.push(error);
644
+ return getReplayFailure(environment, (tracing) => {
645
+ replayInitialStates(getDescription().inits, tracing, (state) => {
646
+ reportInitialStatesProgress(replayedCount, (progress) => capturedLines?.push(progress));
647
+ replayedCount++;
648
+ runtime.generatedStates = replayedCount;
649
+ if (deferred.length > 0) return;
650
+ try {
651
+ const addFingerprint = () => {
652
+ if (!addReplayed(state, tracing.callStack)) return;
653
+ runtime.queueSize++;
654
+ liveness?.addInitialState(states.length, state, tracing);
655
+ };
656
+ const violation = search.checkReplayedInitialState(state, tracing, addFingerprint);
657
+ if (violation) {
658
+ const traced = traces.toTrace([{ action: undefined, state }], []).trace[0].state;
659
+ capturedLines?.push({
660
+ kind: "initial-state-violation",
661
+ ...violation,
662
+ state: traced,
663
+ });
664
+ throw STOP_REPLAY;
807
665
  }
808
- },
809
- );
666
+ } catch (error) {
667
+ const isFingerprintFailure =
668
+ error instanceof TlaEvaluationError && tracing.callStack?.fingerprint !== undefined;
669
+ if (!isFingerprintFailure && !isStackOverflow(error)) throw error;
670
+ deferred.push(error);
671
+ }
672
+ });
810
673
  if (deferred.length > 0) throw deferred[0];
811
674
  });
812
675
  };
813
- // TLC's replay writes each successor in the model to the -dump state graph again.
814
676
  const replayNext = (index: number) =>
815
- getReplayFailure((tracing) => {
677
+ getReplayFailure(environment, (tracing) => {
816
678
  const state = states[index];
817
679
  const source = stateWriter && getGraphState(state, depths[index]);
818
680
  const addReplayed = createReplayedStates();
819
- replaySuccessors(getSpecNextActions(), state, tracing, (next, action) => {
681
+ replaySuccessors(nextActions, state, tracing, (next, action) => {
820
682
  const addFingerprint = () => {
821
683
  const isUnseen = addReplayed(next, tracing.callStack);
822
684
  if (source) {
@@ -834,9 +696,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
834
696
  }
835
697
  });
836
698
  });
837
- const isReducing = config.view !== undefined || config.symmetry !== undefined;
838
699
  const tlcFingerprints: number[] = [];
839
- // TLC warns about the liveness checker before it builds it.
840
700
  if (search.properties.liveness.length > 0) {
841
701
  options.onProgress?.({
842
702
  kind: "liveness-initializing",
@@ -847,12 +707,13 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
847
707
  const liveness = withLivenessExitCode(() =>
848
708
  withUnexpectedException(() =>
849
709
  createLivenessChecker(search.properties.liveness, spec.temporals, environment, {
850
- getFingerprint: ({ index, state }) =>
851
- (tlcFingerprints[index] ??= Number(BigInt.asIntN(32, runtime.getFingerprint(state)))),
710
+ getFingerprint: (successor) =>
711
+ (tlcFingerprints[successor.index] ??= Number(
712
+ BigInt.asIntN(32, runtime.getFingerprint(successor.state)),
713
+ )),
852
714
  getSuccessors: (source, state) => {
853
715
  const successors: LiveSuccessor[] = [];
854
716
  if (spec.next === undefined) return successors;
855
- // The constraints read the level of the state whose successors they check.
856
717
  const livenessSource = current.livenessSource;
857
718
  current.livenessSource = source;
858
719
  try {
@@ -867,8 +728,12 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
867
728
  search.satisfiesActionConstraints(state, successor.state);
868
729
  if (!isInModel) return false;
869
730
  const fingerprintState = getFingerprintState(successor.state);
870
- const index = findStateIndex(getStateHash(fingerprintState), fingerprintState);
871
- successors.push({ index, state: successor.state });
731
+ const hash = getStateHash(fingerprintState);
732
+ const index = findStateIndex(seenStates, hash, fingerprintState);
733
+ successors.push({
734
+ index: index === -1 ? getPendingIndex(hash, fingerprintState) : index,
735
+ state: successor.state,
736
+ });
872
737
  return false;
873
738
  },
874
739
  spec.scope,
@@ -881,9 +746,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
881
746
  }),
882
747
  ),
883
748
  );
884
- // ModelChecker rejects a temporal property whose negation has no solution.
885
749
  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
750
  runtime.isStarted = true;
888
751
  const isCanonicalizedFirst = search.isSymmetric || liveness !== undefined;
889
752
 
@@ -892,219 +755,26 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
892
755
  const parents: number[] = [];
893
756
  const actions: (string | undefined)[] = [];
894
757
  const depths: number[] = [];
895
- // A Map holds at most 2^24 entries, so an open-addressing table keeps each hash and index + 1.
896
- const seenStates = { slots: new Int32Array(1 << 17), size: 0, shift: 16 };
758
+ const seenStates = createStateTable(fingerprintStates);
759
+ const pendingFingerprintStates: Value[][] = [];
760
+ let pendingStates: StateTable | undefined;
761
+ const getPendingIndex = (hash: number, fingerprintState: Value[]) => {
762
+ pendingStates ??= createStateTable(pendingFingerprintStates);
763
+ const found = findStateIndex(pendingStates, hash, fingerprintState);
764
+ const position = found === -1 ? pendingFingerprintStates.length : found;
765
+ if (found === -1) {
766
+ markSeenState(pendingStates, hash, position);
767
+ pendingFingerprintStates.push(fingerprintState);
768
+ }
769
+ return -2 - position;
770
+ };
897
771
  const canonicalizeState = createCanonicalizer();
898
772
 
899
773
  const toRecord = search.toRecord;
900
- const getAliasState = (
901
- alias: string,
902
- steps: Successor[],
903
- position: number,
904
- loopStart: number | undefined,
905
- ) => {
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
- const searchLevel = runtime.getLevel;
909
- const searchBehavior = runtime.getBehavior;
910
- runtime.getLevel = () => position + 1;
911
- runtime.getBehavior = () => steps.slice(0, position + 1).map((step) => step.state);
912
- try {
913
- return evaluateAlias(
914
- alias,
915
- steps[position].state,
916
- (steps[position + 1] ?? steps[loopStart ?? position]).state,
917
- );
918
- } finally {
919
- runtime.getLevel = searchLevel;
920
- runtime.getBehavior = searchBehavior;
921
- }
922
- };
923
- const evaluateAlias = (alias: string, state: Value[], next: Value[] | undefined) =>
924
- 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
- const findStepAction = (index: number, previous: Value[], state: Value[], isHeld: boolean) => {
928
- const actions = getSpecNextActions();
929
- const expanding = { ...current };
930
- Object.assign(current, {
931
- index,
932
- isExpanding: true,
933
- candidate: undefined,
934
- rebuilt: { state: previous, level: depths[index] },
935
- });
936
- const getKey = isHeld ? (values: Value[]) => values : getFingerprintState;
937
- const key = getKey(state);
938
- try {
939
- return coverage
940
- ? coverageActions.find((item) =>
941
- getCoveredSuccessors(item, previous).some((successor) =>
942
- isSameState(getKey(successor.state), key),
943
- ),
944
- )
945
- : actions.find((item) =>
946
- getSuccessors(item.expression, previous, environment, item.scope).some((successor) =>
947
- isSameState(getKey(successor.state), key),
948
- ),
949
- );
950
- } finally {
951
- Object.assign(current, expanding);
952
- }
953
- };
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
- const toTrace = (
958
- steps: Successor[],
959
- path: number[],
960
- traceOptions: TraceOptions = {},
961
- ): Behavior => {
962
- const alias = config.alias;
963
- const known = traceOptions.known ?? 1;
964
- // Rebuilding the trace from the initial predicate can reset what TLCSet stored.
965
- const initialOutput = steps.length > 1 ? captureOutput(getSpecInitialStates).lines : [];
966
- // TLC finds the action that takes each step before it evaluates the alias.
967
- const stepActions = steps.map((step, position) =>
968
- position === 0 || step.action === "Stuttering"
969
- ? { result: undefined, lines: [] }
970
- : captureOutput(() =>
971
- findStepAction(
972
- path[position - 1],
973
- steps[position - 1].state,
974
- step.state,
975
- known === 2 && position === steps.length - 1,
976
- ),
977
- ),
978
- );
979
- const outputs = stepActions.map((step) => step.lines);
980
- 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
- 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
- if (coverage && steps.length > 1) {
985
- const isRebuiltAgain = known > 0 && !is174;
986
- if (rebuilt > 0 && isRebuiltAgain) captureOutput(getSpecInitialStates);
987
- if (isRebuiltAgain) {
988
- steps.slice(1).forEach((step, position) => {
989
- if (step.action === "Stuttering") return;
990
- captureOutput(() =>
991
- findStepAction(
992
- path[position],
993
- steps[position].state,
994
- step.state,
995
- known === 2 && position === steps.length - 2,
996
- ),
997
- );
998
- });
999
- }
1000
- }
1001
- const prefixOutput = rebuilt > 0 ? [initialOutput, ...outputs.slice(1, rebuilt)].flat() : [];
1002
- return {
1003
- trace: steps.map((step, position) => {
1004
- const action = stepActions[position].result;
1005
- const traceStep: TraceStep = {
1006
- action: step.action,
1007
- label: action && getActionLabel(action, options.version),
1008
- state:
1009
- alias === undefined
1010
- ? toRecord(step.state)
1011
- : getAliasState(alias, steps, position, loopStart),
1012
- output: position === 0 ? prefixOutput : position < rebuilt ? [] : outputs[position],
1013
- };
1014
- if (alias !== undefined || action) {
1015
- traceSteps.set(traceStep, { state: toRecord(step.state), action });
1016
- }
1017
- return traceStep;
1018
- }),
1019
- traceOutput: known > 0 && !is174 ? [initialOutput, ...outputs].flat() : [],
1020
- };
1021
- };
1022
774
  const getSpecInitialStates = () => {
1023
775
  if (coverage) return getCoveredInitialStates();
1024
776
  return spec.init === undefined ? [] : getInitialStates(spec.init, environment, spec.scope);
1025
777
  };
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
- const findTraceSuccessor = (state: Value[], isMatch: (successor: Successor) => boolean) =>
1029
- captureOutput(() => {
1030
- for (const action of getSpecNextActions()) {
1031
- const successor = getSuccessors(action.expression, state, environment, action.scope).find(
1032
- isMatch,
1033
- );
1034
- if (successor) return { ...successor, action: successor.action ?? action.name };
1035
- }
1036
- return undefined;
1037
- }).result;
1038
- const hasFingerprint = (state: Value[], index: number) =>
1039
- isSameState(getFingerprintState(state), fingerprintStates[index]);
1040
- const findSuccessorWithFingerprint = (state: Value[], index: number) =>
1041
- findTraceSuccessor(state, (successor) => hasFingerprint(successor.state, index));
1042
- const getPathStates = (path: number[], nextFailure: string) => {
1043
- const initial = captureOutput(() =>
1044
- isReducing || isImpure(environment)
1045
- ? getSpecInitialStates().find((state) => hasFingerprint(state, path[0]))
1046
- : states[path[0]],
1047
- ).result;
1048
- if (!initial) throw new TlaEvaluationError(INITIAL_RECOVERY_FAILURE);
1049
- const steps: Successor[] = [{ state: initial, action: undefined }];
1050
- for (let position = 1; position < path.length; position++) {
1051
- const previous = steps[position - 1].state;
1052
- if (path[position - 1] === path[position]) {
1053
- steps.push({ state: previous, action: "Stuttering" });
1054
- continue;
1055
- }
1056
- // TLC rebuilds each state at its level, which TLCGet reads.
1057
- const rebuilt = current.rebuilt;
1058
- current.rebuilt = { state: previous, level: depths[path[position - 1]] };
1059
- const successor = findSuccessorWithFingerprint(previous, path[position]);
1060
- current.rebuilt = rebuilt;
1061
- if (!successor) throw new TlaEvaluationError(nextFailure);
1062
- steps.push(successor);
1063
- }
1064
- return steps;
1065
- };
1066
- const getTrace = (index: number, lastSuccessor?: Successor) => {
1067
- const path: number[] = [];
1068
- for (let position = index; position !== -1; position = parents[position]) {
1069
- path.unshift(position);
1070
- }
1071
- const steps =
1072
- isReducing && path.length > 1
1073
- ? getPathStates(path, INITIAL_RECOVERY_FAILURE)
1074
- : path.map((position) => ({ state: states[position], action: actions[position] }));
1075
- if (!lastSuccessor) return toTrace(steps, path);
1076
- const action = isReducing
1077
- ? findTraceSuccessor(states[index], (successor) =>
1078
- isSameState(successor.state, lastSuccessor.state),
1079
- )?.action
1080
- : lastSuccessor.action;
1081
- return toTrace([...steps, { state: lastSuccessor.state, action }], path, { known: 2 });
1082
- };
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.
1085
- const getStateTrace = (index: number): Behavior =>
1086
- parents[index] === -1
1087
- ? {
1088
- trace: [
1089
- {
1090
- action: undefined,
1091
- label: undefined,
1092
- state:
1093
- config.alias === undefined
1094
- ? toRecord(states[index])
1095
- : getAliasState(
1096
- config.alias,
1097
- [{ state: states[index], action: undefined }],
1098
- 0,
1099
- undefined,
1100
- ),
1101
- },
1102
- ],
1103
- traceOutput: is174 ? [] : captureOutput(getSpecInitialStates).lines,
1104
- }
1105
- : 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
778
  const isUnfingerprintable = (state: Value[]) => {
1109
779
  try {
1110
780
  return getFingerprintState(state).some((value) => getFingerprintError(value) !== undefined);
@@ -1113,35 +783,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1113
783
  return true;
1114
784
  }
1115
785
  };
1116
- const getFailedTrace = (index: number, successor: Successor): Behavior => ({
1117
- trace: getTrace(index, successor).trace,
1118
- });
1119
- // TLC names the initial state it was checking unless a standard module's Java code failed.
1120
- 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
- if (
1123
- failureOptions.isInitial &&
1124
- !failureOptions.callStack &&
1125
- !failureOptions.fingerprint &&
1126
- is174
1127
- ) {
1128
- return EXIT_STATUS.success;
1129
- }
1130
- if (!failureOptions.callStack) {
1131
- return failureOptions.isInitial ? getInitialExitCode(error) : getErrorExitCode(error);
1132
- }
1133
- 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
- if (failureOptions.isLiveCallStack) {
1136
- return (
1137
- getExitCode(error) ?? (error instanceof TlaModuleError ? error.exitCode : EXIT_STATUS.error)
1138
- );
1139
- }
1140
- // TLC exits with the code of a failed initial replay whatever the error, as for a fingerprint.
1141
- return failureOptions.isInitial || failureOptions.fingerprint
1142
- ? EXIT_STATUS.specEvaluationFailure
1143
- : getReplayExitCode(failureOptions.replayError ?? error);
1144
- };
1145
786
  const createFailureResult = (
1146
787
  failed: unknown,
1147
788
  behavior: Behavior,
@@ -1157,7 +798,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1157
798
  const traceOutput = [...(behavior.traceOutput ?? []), ...(checked?.lines ?? [])];
1158
799
  return {
1159
800
  ...createResult("error", undefined, {
1160
- ...getFailureMessage(error, failureOptions.isNextState ?? false),
801
+ ...getFailureMessage(
802
+ error,
803
+ failureOptions.phase !== undefined && failureOptions.phase !== "initial",
804
+ ),
1161
805
  ...behavior,
1162
806
  ...(traceOutput.length > 0 && { traceOutput }),
1163
807
  ...(postcondition && { postcondition }),
@@ -1165,22 +809,21 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1165
809
  failureOptions.initialState && !(error instanceof TlaModuleError)
1166
810
  ? toRecord(failureOptions.initialState)
1167
811
  : undefined,
1168
- exitCode: getFailureExitCode(error, failureOptions),
812
+ exitCode: getFailureExitCode(error, failureOptions, is174),
1169
813
  callStack: failureOptions.callStack,
1170
- ...(failureOptions.isCallStackFirst && { isCallStackFirst: true }),
814
+ ...(failureOptions.phase === "liveness" && { isCallStackFirst: true }),
1171
815
  ...(failureOptions.fingerprint && { fingerprint: failureOptions.fingerprint }),
1172
816
  ...(failureOptions.traceFailure && { traceFailure: failureOptions.traceFailure }),
1173
817
  }),
1174
818
  outDegrees: failureOptions.outDegrees,
1175
819
  };
1176
820
  };
1177
- // TLC reports a partial successor with the trace to it, naming the action if there are several.
1178
821
  const reportIncompleteSuccessor = (index: number, error: TlaIncompleteSuccessorError) => {
1179
822
  runtime.generatedStates++;
1180
- const actions = getSpecNextActions();
1181
823
  const named =
1182
- 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.
824
+ nextActions.length === 1
825
+ ? nextActions
826
+ : nextActions.filter((item) => item.name === error.action);
1184
827
  const action =
1185
828
  named.length === 1
1186
829
  ? named[0]
@@ -1192,12 +835,12 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1192
835
  const message = getIncompleteSuccessorMessage(
1193
836
  error.variables,
1194
837
  error.action,
1195
- actions.length,
838
+ nextActions.length,
1196
839
  options.version,
1197
840
  );
1198
841
  const undefinedValue = createModelValue("null");
1199
842
  const partial = error.state.map((value) => value ?? undefinedValue);
1200
- const failure = createFailureResult(error, getStateTrace(index));
843
+ const failure = createFailureResult(error, traces.getStateTrace(index));
1201
844
  return withOutDegrees({
1202
845
  ...failure,
1203
846
  failure: failure.failure && {
@@ -1217,71 +860,16 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1217
860
  },
1218
861
  });
1219
862
  };
1220
- const getPathSteps = (path: number[], loopStart?: number) => {
1221
- const steps = getPathStates(path, NEXT_RECOVERY_FAILURE);
1222
- const lastState = steps[steps.length - 1].state;
1223
- const isClosed =
1224
- !isReducing ||
1225
- loopStart === undefined ||
1226
- loopStart === path.length - 1 ||
1227
- findSuccessorWithFingerprint(lastState, path[loopStart]) !== undefined;
1228
- if (!isClosed) throw new TlaEvaluationError(NEXT_RECOVERY_FAILURE);
1229
- return steps;
1230
- };
1231
- const getStateHash = (state: Value[]) => {
1232
- let hash = 0x811c9dc5;
1233
- for (let index = 0; index < state.length; index++)
1234
- hash = combineHash(hash, getValueHash(state[index]));
1235
- return hash & 0x3fffffff;
1236
- };
1237
- // TLC fingerprints a state once it finds the state in the model.
1238
863
  const fingerprintModelState = (state: Value[]) => {
1239
864
  for (const value of state) {
1240
865
  const error = getFingerprintError(value);
1241
866
  if (error) throw error;
1242
867
  }
1243
868
  };
1244
- const isSameState = (stored: Value[], state: Value[]) => {
1245
- for (let position = 0; position < state.length; position++) {
1246
- if (!isSameValue(stored[position], state[position])) return false;
1247
- }
1248
- return true;
1249
- };
1250
- const getSlot = (hash: number) => (Math.imul(hash, 0x9e3779b1) >>> seenStates.shift) << 1;
1251
- const findStateIndex = (hash: number, state: Value[]) => {
1252
- const mask = seenStates.slots.length - 1;
1253
- for (let slot = getSlot(hash); ; slot = (slot + 2) & mask) {
1254
- const entry = seenStates.slots[slot + 1];
1255
- if (entry === 0) return -1;
1256
- if (seenStates.slots[slot] === hash && isSameState(fingerprintStates[entry - 1], state)) {
1257
- return entry - 1;
1258
- }
1259
- }
1260
- };
1261
- const insertSeen = (hash: number, entry: number) => {
1262
- const mask = seenStates.slots.length - 1;
1263
- let slot = getSlot(hash);
1264
- while (seenStates.slots[slot + 1] !== 0) slot = (slot + 2) & mask;
1265
- seenStates.slots[slot] = hash;
1266
- seenStates.slots[slot + 1] = entry;
1267
- };
1268
- const markSeen = (hash: number, index: number) => {
1269
- seenStates.size++;
1270
- if (seenStates.size * 4 > seenStates.slots.length) {
1271
- const slots = seenStates.slots;
1272
- seenStates.slots = new Int32Array(slots.length * 2);
1273
- seenStates.shift--;
1274
- for (let slot = 0; slot < slots.length; slot += 2) {
1275
- if (slots[slot + 1] !== 0) insertSeen(slots[slot], slots[slot + 1]);
1276
- }
1277
- }
1278
- insertSeen(hash, index + 1);
1279
- };
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 };
869
+ let unstoredFingerprint: Value[] | undefined;
1282
870
  const countDistinctState = (depth: number) => {
1283
871
  runtime.distinctStates = states.length + 1;
1284
- statistics.depth = Math.max(statistics.depth, depth);
872
+ searchDepth = Math.max(searchDepth, depth);
1285
873
  runtime.diameter = Math.max(runtime.diameter, depth);
1286
874
  };
1287
875
  const addState = (
@@ -1298,19 +886,41 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1298
886
  depths.push(depth);
1299
887
  };
1300
888
 
1301
- const current = {
889
+ const current: SearchPosition = {
1302
890
  index: -1,
1303
891
  isExpanding: false,
1304
- candidate: undefined as Value[] | undefined,
892
+ candidate: undefined,
1305
893
  candidateLevel: 0,
1306
894
  livenessSource: -1,
1307
- rebuilt: undefined as { state: Value[]; level: number } | undefined,
895
+ rebuilt: undefined,
1308
896
  };
897
+ const traces = createTraceBuilder({
898
+ config,
899
+ options,
900
+ environment,
901
+ search,
902
+ nextActions,
903
+ current,
904
+ states,
905
+ fingerprintStates,
906
+ parents,
907
+ actions,
908
+ depths,
909
+ tracedSteps,
910
+ captureOutput,
911
+ getInitialStates: getSpecInitialStates,
912
+ findSuccessorAction: (state, isMatch) =>
913
+ coverage
914
+ ? coverageActions.find((item) => getCoveredSuccessors(item, state).some(isMatch))
915
+ : nextActions.find((item) =>
916
+ getSuccessors(item.expression, state, environment, item.scope).some(isMatch),
917
+ ),
918
+ });
1309
919
  const getPath = (index: number): Value[][] =>
1310
920
  index === -1 ? [] : [...getPath(parents[index]), states[index]];
1311
921
  runtime.isSeen = (state) => {
1312
922
  const fingerprintState = getFingerprintState(state);
1313
- return findStateIndex(getStateHash(fingerprintState), fingerprintState) !== -1;
923
+ return findStateIndex(seenStates, getStateHash(fingerprintState), fingerprintState) !== -1;
1314
924
  };
1315
925
  runtime.getBehavior = (state) => {
1316
926
  const index = state === current.candidate ? -1 : states.indexOf(state);
@@ -1322,7 +932,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1322
932
  };
1323
933
  runtime.getLevel = (state) => {
1324
934
  const source = current.livenessSource;
1325
- // TLC 1.7.4 reads the level of the state its worker explores, whichever state it evaluates.
1326
935
  if (is174) {
1327
936
  const explored = source !== -1 ? source : current.isExpanding ? current.index : -1;
1328
937
  return explored === -1 ? 0 : depths[explored];
@@ -1347,7 +956,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1347
956
  formatState(
1348
957
  config.alias === undefined
1349
958
  ? toRecord(state)
1350
- : evaluateAlias(config.alias, state, undefined),
959
+ : search.evaluateAlias(config.alias, state, undefined, options.isTool ?? false),
1351
960
  ),
1352
961
  getText: () => formatState(toRecord(state)),
1353
962
  });
@@ -1366,9 +975,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1366
975
  fingerprintModelState(fingerprintState);
1367
976
  state.forEach(markFingerprinted);
1368
977
  }
1369
- const isSeen = isInModel && findStateIndex(hash, fingerprintState) !== -1;
978
+ const isSeen = isInModel && findStateIndex(seenStates, hash, fingerprintState) !== -1;
1370
979
  if (isSeen) return undefined;
1371
- unstoredState.fingerprint = isInModel ? fingerprintState : undefined;
980
+ unstoredFingerprint = isInModel ? fingerprintState : undefined;
1372
981
  if (isInModel) {
1373
982
  countDistinctState(1);
1374
983
  runtime.queueSize++;
@@ -1379,7 +988,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1379
988
  search.getViolatedInvariants(state).forEach((invariant) =>
1380
989
  reportContinuedViolation("invariant-violation", {
1381
990
  name: invariant.name,
1382
- ...toTrace([{ action: undefined, state }], []),
991
+ ...traces.toTrace([{ action: undefined, state }], []),
1383
992
  }),
1384
993
  );
1385
994
  }
@@ -1387,21 +996,37 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1387
996
  if (violated) {
1388
997
  return reportViolation("invariant-violation", {
1389
998
  name: violated.name,
1390
- ...toTrace([{ action: undefined, state }], []),
999
+ ...traces.toTrace([{ action: undefined, state }], []),
1391
1000
  });
1392
1001
  }
1393
1002
  const failedPredicate = search.findFailedInitialPredicate(state);
1394
1003
  if (failedPredicate) {
1395
1004
  return reportViolation("liveness-violation", {
1396
1005
  name: failedPredicate.name,
1397
- ...toTrace([{ action: undefined, state }], []),
1006
+ ...traces.toTrace([{ action: undefined, state }], []),
1398
1007
  });
1399
1008
  }
1400
1009
  if (!isInModel) return undefined;
1401
- markSeen(hash, states.length);
1010
+ markSeenState(seenStates, hash, states.length);
1402
1011
  addState(state, fingerprintState, -1, undefined);
1403
1012
  return undefined;
1404
1013
  };
1014
+ // Looks a successor up, where the constraints keep it in the model, as the search does before it
1015
+ // checks the successor.
1016
+ const lookUpSuccessor = (state: Value[], successor: Successor) => {
1017
+ const fingerprintState = getFingerprintState(successor.state);
1018
+ const hash = getStateHash(fingerprintState);
1019
+ const foundIndex = findStateIndex(seenStates, hash, fingerprintState);
1020
+ const isStateInModel = search.satisfiesConstraints(successor.state, state);
1021
+ if (isStateInModel) search.trackStatePossible(successor.state);
1022
+ const isInModel = isStateInModel && search.satisfiesActionConstraints(state, successor.state);
1023
+ if (isInModel) {
1024
+ search.trackActionPossible(state, successor.state);
1025
+ fingerprintModelState(fingerprintState);
1026
+ successor.state.forEach(markFingerprinted);
1027
+ }
1028
+ return { fingerprintState, hash, isInModel, existing: isInModel ? foundIndex : -1 };
1029
+ };
1405
1030
  const visitSuccessor = (
1406
1031
  index: number,
1407
1032
  successor: Successor,
@@ -1414,27 +1039,16 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1414
1039
  current.candidate = successor.state;
1415
1040
  current.candidateLevel = depths[index] + 1;
1416
1041
  if (isCanonicalizedFirst) canonicalizeState(successor.state);
1417
- const fingerprintState = getFingerprintState(successor.state);
1418
- const hash = getStateHash(fingerprintState);
1419
- const foundIndex = findStateIndex(hash, fingerprintState);
1420
- const isStateInModel = search.satisfiesConstraints(successor.state, state);
1421
- if (isStateInModel) search.trackStatePossible(successor.state);
1422
- const isInModel = isStateInModel && search.satisfiesActionConstraints(state, successor.state);
1423
- if (isInModel) {
1424
- search.trackActionPossible(state, successor.state);
1425
- fingerprintModelState(fingerprintState);
1426
- successor.state.forEach(markFingerprinted);
1427
- }
1428
- const existing = isInModel ? foundIndex : -1;
1429
- if (source && isInModel) {
1042
+ const found = lookUpSuccessor(state, successor);
1043
+ if (source && found.isInModel) {
1430
1044
  stateWriter?.writeSuccessor(
1431
1045
  source,
1432
1046
  getGraphState(successor.state, depths[index] + 1),
1433
- existing !== -1,
1047
+ found.existing !== -1,
1434
1048
  action && getGraphAction(action),
1435
1049
  );
1436
1050
  }
1437
- if (source && !isInModel && options.dump?.constrained) {
1051
+ if (source && !found.isInModel && options.dump?.constrained) {
1438
1052
  const excluded = getGraphState(successor.state, depths[index] + 1);
1439
1053
  search
1440
1054
  .getExcludingConstraints(state, successor.state)
@@ -1447,36 +1061,33 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1447
1061
  ),
1448
1062
  );
1449
1063
  }
1450
- if (existing !== -1 && liveness) {
1451
- const stored = states[existing];
1064
+ if (found.existing !== -1 && liveness) {
1065
+ const stored = states[found.existing];
1452
1066
  const isStored = stored.every((value, position) => value === successor.state[position]);
1453
- liveSuccessors.push({ index: existing, state: isStored ? stored : successor.state });
1067
+ liveSuccessors.push({ index: found.existing, state: isStored ? stored : successor.state });
1454
1068
  }
1455
- const isNew = isInModel && existing === -1;
1456
- // TLC adds a new state to the behavior graph's successors before it checks the invariants.
1069
+ const isNew = found.isInModel && found.existing === -1;
1457
1070
  if (isNew && liveness) liveSuccessors.push({ index: states.length, state: successor.state });
1458
- unstoredState.fingerprint = isNew ? fingerprintState : undefined;
1071
+ unstoredFingerprint = isNew ? found.fingerprintState : undefined;
1459
1072
  if (isNew) {
1460
1073
  countDistinctState(depths[index] + 1);
1461
- expansion.newStates++;
1462
- if (coverage) coverage.secondary[coveredAction.node]++;
1074
+ newStateCount++;
1075
+ if (coverage) coverage.secondary[coveredNode]++;
1463
1076
  }
1464
- if (existing === -1) {
1077
+ if (found.existing === -1) {
1465
1078
  try {
1466
1079
  const violated = search.findViolatedInvariant(successor.state, state);
1467
- const violation = violated && { name: violated.name, ...getTrace(index, successor) };
1080
+ const violation = violated && { name: violated.name, ...traces.getTrace(index, successor) };
1468
1081
  if (violation && !options.isContinued) {
1469
1082
  return withOutDegrees(reportViolation("invariant-violation", violation));
1470
1083
  }
1471
1084
  if (violation) reportContinuedViolation("invariant-violation", violation);
1472
1085
  } catch (error) {
1473
1086
  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
1087
  const replay = captureOutput(() => replayNext(index));
1477
1088
  return createFailureResult(
1478
1089
  error,
1479
- appendTraceOutput(getFailedTrace(index, successor), replay.lines),
1090
+ appendTraceOutput(traces.getFailedTrace(index, successor), replay.lines),
1480
1091
  replay.result ?? { outDegrees: getFailureOutDegrees() },
1481
1092
  );
1482
1093
  }
@@ -1484,7 +1095,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1484
1095
  const violatedProperty = search.findViolatedActionProperty(state, successor.state);
1485
1096
  const propertyViolation = violatedProperty && {
1486
1097
  name: violatedProperty.name,
1487
- ...getTrace(index, successor),
1098
+ ...traces.getTrace(index, successor),
1488
1099
  };
1489
1100
  if (propertyViolation && !options.isContinued) {
1490
1101
  return withOutDegrees(reportViolation("liveness-violation", propertyViolation));
@@ -1493,47 +1104,100 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1493
1104
  if (!isNew) return undefined;
1494
1105
  if (coverage) countCoverageVariables(coverage, successor.state);
1495
1106
  if (!isCanonicalizedFirst) canonicalizeState(successor.state);
1496
- markSeen(hash, states.length);
1497
- addState(successor.state, fingerprintState, index, successor.action);
1107
+ markSeenState(seenStates, found.hash, states.length);
1108
+ if (pendingStates) {
1109
+ const pending = findStateIndex(pendingStates, found.hash, found.fingerprintState);
1110
+ if (pending !== -1) liveness?.storeState(-2 - pending, states.length);
1111
+ }
1112
+ addState(successor.state, found.fingerprintState, index, successor.action);
1498
1113
  runtime.queueSize++;
1499
1114
  return undefined;
1500
1115
  };
1501
1116
 
1502
- const outcome: { result: CheckResult | undefined } = { result: undefined };
1503
- const coveredAction = { node: -1 };
1117
+ let outcome: CheckResult | undefined;
1118
+ let coveredNode = -1;
1504
1119
  if (liveness) {
1505
1120
  options.onProgress?.({ kind: "liveness-prepared", branches: liveness.branches });
1506
1121
  }
1507
- // TLC checks the assumptions once it has built the liveness checker.
1508
1122
  const assumptionViolation = findViolatedAssumption();
1509
1123
  if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
1510
1124
  options.onProgress?.({ kind: "initial-states-started" });
1125
+ const typedChecks =
1126
+ !options.isContinued &&
1127
+ options.dump === undefined &&
1128
+ // A set of small integers on the tier is a 31-bit mask, which a lower bound could overflow.
1129
+ options.maxSetSize === undefined &&
1130
+ !hasPostconditions
1131
+ ? search.getTypedChecks(liveness?.solutions)
1132
+ : undefined;
1133
+ const typed =
1134
+ typedChecks &&
1135
+ runTypedSearch(environment, {
1136
+ ...typedChecks,
1137
+ isDeadlockChecked: config.checkDeadlock,
1138
+ isFingerprinted: !options.isFingerprintDistanceSkipped,
1139
+ livenessCheck: options.livenessCheck ?? "default",
1140
+ });
1141
+ if (typed && !typed.deadlock && !typed.violation && !typed.lasso) {
1142
+ for (let count = 2; count < typed.initialStates.generated; count *= 2) {
1143
+ reportInitialStatesProgress(count, options.onProgress);
1144
+ }
1145
+ options.onProgress?.({ kind: "initial-states-computed", initialStates: typed.initialStates });
1146
+ const statistics = {
1147
+ ...createResult("success"),
1148
+ generatedStates: typed.generatedStates,
1149
+ distinctStates: typed.distinctStates,
1150
+ queuedStates: 0,
1151
+ depth: typed.generatedStates === 0 ? 0 : Math.max(typed.depth, 1),
1152
+ initialStates: typed.initialStates,
1153
+ };
1154
+ if (liveness && options.livenessCheck !== "off") {
1155
+ options.onProgress?.({
1156
+ kind: "liveness-started",
1157
+ branches: liveness.branches,
1158
+ isComplete: true,
1159
+ states: typed.distinctStates,
1160
+ statistics,
1161
+ });
1162
+ options.onProgress?.({ kind: "liveness-finished" });
1163
+ }
1164
+ return {
1165
+ ...statistics,
1166
+ outDegrees: typed.outDegrees,
1167
+ fingerprintDistance: options.isFingerprintDistanceSkipped
1168
+ ? undefined
1169
+ : getFingerprintDistance(
1170
+ typed.distinctStates,
1171
+ typed.generatedStates,
1172
+ typed.forEachFingerprintRun,
1173
+ ),
1174
+ };
1175
+ }
1511
1176
  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 };
1177
+ let overflowState: Value[] | undefined;
1514
1178
  const reportInitialFailure = (error: unknown, state: Value[]) => {
1515
1179
  const replay = captureOutput(replayInit);
1516
1180
  return createFailureResult(
1517
1181
  error,
1518
1182
  { trace: [], traceOutput: replay.lines },
1519
- { initialState: state, ...replay.result, isInitial: true },
1183
+ { initialState: state, ...replay.result, phase: "initial" },
1520
1184
  );
1521
1185
  };
1522
1186
  try {
1523
1187
  const onInitialState = (state: Value[]) => {
1524
1188
  reportInitialStatesProgress(runtime.initialStates, options.onProgress);
1525
- if (overflow.state) {
1189
+ if (overflowState) {
1526
1190
  runtime.generatedStates++;
1527
1191
  runtime.initialStates++;
1528
1192
  return false;
1529
1193
  }
1530
1194
  try {
1531
- outcome.result = visitInitialState(state);
1195
+ outcome = visitInitialState(state);
1532
1196
  } catch (error) {
1533
- if (isStackOverflow(error)) overflow.state = state;
1534
- else outcome.result = reportInitialFailure(error, state);
1197
+ if (isStackOverflow(error)) overflowState = state;
1198
+ else outcome = reportInitialFailure(error, state);
1535
1199
  }
1536
- return outcome.result !== undefined;
1200
+ return outcome !== undefined;
1537
1201
  };
1538
1202
  if (coverage) {
1539
1203
  try {
@@ -1543,9 +1207,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1543
1207
  (state) => {
1544
1208
  if (onInitialState(state)) throw STOP_WALK;
1545
1209
  },
1546
- (partial) => {
1547
- throw setExitCode(new TlaIllegalStateError([...partial]), EXIT_STATUS.error);
1548
- },
1210
+ rejectIncompleteInitialState,
1549
1211
  );
1550
1212
  } catch (error) {
1551
1213
  if (error !== STOP_WALK) throw error;
@@ -1553,11 +1215,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1553
1215
  } else {
1554
1216
  forEachInitialState(spec.init, environment, onInitialState, spec.scope);
1555
1217
  }
1556
- if (overflow.state) {
1557
- outcome.result = reportInitialFailure(createStackOverflowError(), overflow.state);
1218
+ if (overflowState) {
1219
+ outcome = reportInitialFailure(createStackOverflowError(), overflowState);
1558
1220
  }
1559
1221
  } catch (error) {
1560
- // TLC prints null for each undefined variable and stops before the statistics.
1561
1222
  if (error instanceof TlaIllegalStateError) {
1562
1223
  const illegal = createFailureResult(
1563
1224
  error,
@@ -1569,23 +1230,22 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1569
1230
  failure: illegal.failure && { ...illegal.failure, isWithoutStatistics: true },
1570
1231
  };
1571
1232
  }
1572
- // TLC prints the error before it replays the initial predicate with its call stack.
1573
1233
  const replay = captureOutput(replayInit);
1574
1234
  return createFailureResult(
1575
1235
  error,
1576
1236
  { trace: [], traceOutput: replay.lines },
1577
- { ...replay.result, isInitial: true },
1237
+ { ...replay.result, phase: "initial" },
1578
1238
  );
1579
1239
  }
1580
1240
  }
1581
- if (outcome.result) return outcome.result;
1582
- statistics.initialStates = {
1241
+ if (outcome) return outcome;
1242
+ computedInitialStates = {
1583
1243
  generated: runtime.initialStates,
1584
1244
  distinct: runtime.distinctStates,
1585
1245
  };
1586
1246
  options.onProgress?.({
1587
1247
  kind: "initial-states-computed",
1588
- initialStates: statistics.initialStates,
1248
+ initialStates: computedInitialStates,
1589
1249
  });
1590
1250
 
1591
1251
  const next = spec.next;
@@ -1597,8 +1257,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1597
1257
  }
1598
1258
  return createSuccess();
1599
1259
  }
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
1260
  const isNamingEdges = Boolean(
1603
1261
  options.dump?.dot && (options.dump.actionLabels || options.dump.colorize),
1604
1262
  );
@@ -1610,19 +1268,19 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1610
1268
  onSuccessor: (successor: Successor, action: SpecAction | undefined) => boolean,
1611
1269
  ) => {
1612
1270
  if (coverage) {
1613
- const progress = { count: 0 };
1271
+ let successorCount = 0;
1614
1272
  try {
1615
1273
  coverageActions.forEach((action) => {
1616
- coveredAction.node = action.node;
1274
+ coveredNode = action.node;
1617
1275
  walkCoveredSuccessors(action, state, (successor) => {
1618
- progress.count++;
1276
+ successorCount++;
1619
1277
  if (onSuccessor({ state: successor, action: action.name }, action)) throw STOP_WALK;
1620
1278
  });
1621
1279
  });
1622
1280
  } catch (error) {
1623
1281
  if (error !== STOP_WALK) throw error;
1624
1282
  }
1625
- return progress.count;
1283
+ return successorCount;
1626
1284
  }
1627
1285
  if (!isNamingEdges) {
1628
1286
  return forEachSuccessor(
@@ -1635,9 +1293,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1635
1293
  onUnsatisfied,
1636
1294
  );
1637
1295
  }
1638
- const progress = { isStopped: false };
1639
- return getSpecNextActions().reduce((count, action) => {
1640
- if (progress.isStopped) return count;
1296
+ let isStopped = false;
1297
+ return nextActions.reduce((count, action) => {
1298
+ if (isStopped) return count;
1641
1299
  return (
1642
1300
  count +
1643
1301
  forEachSuccessor(
@@ -1645,8 +1303,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1645
1303
  state,
1646
1304
  environment,
1647
1305
  (successor) => {
1648
- progress.isStopped = onSuccessor(successor, action);
1649
- return progress.isStopped;
1306
+ isStopped = onSuccessor(successor, action);
1307
+ return isStopped;
1650
1308
  },
1651
1309
  action.scope,
1652
1310
  undefined,
@@ -1655,17 +1313,13 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1655
1313
  );
1656
1314
  }, 0);
1657
1315
  };
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
1316
  const getLiveCallStack = (index: number, liveSuccessors: LiveSuccessor[]) => {
1661
1317
  if (!liveness || is174) return undefined;
1662
- const replay = getReplayFailure((tracing) =>
1318
+ const replay = getReplayFailure(environment, (tracing) =>
1663
1319
  liveness.addState(index, states[index], liveSuccessors, tracing),
1664
1320
  );
1665
1321
  return replay?.callStack.length && !replay.fingerprint ? replay.callStack : undefined;
1666
1322
  };
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
1323
  const addFailedLiveState = (index: number, liveSuccessors: LiveSuccessor[]) => {
1670
1324
  try {
1671
1325
  liveness?.addState(index, states[index], liveSuccessors);
@@ -1678,16 +1332,14 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1678
1332
  const replayFailedNext = (index: number, liveSuccessors: LiveSuccessor[]) => {
1679
1333
  const live = captureOutput(() => addFailedLiveState(index, liveSuccessors));
1680
1334
  if (live.result) {
1681
- const result = { callStack: live.result, fingerprint: undefined, isLiveCallStack: true };
1335
+ const result: FailureOptions = { phase: "behavior-graph", callStack: live.result };
1682
1336
  return { result, lines: live.lines };
1683
1337
  }
1684
1338
  const replay = captureOutput(() => replayNext(index));
1685
1339
  return { result: replay.result, lines: [...live.lines, ...replay.lines] };
1686
1340
  };
1687
- // TLC reports a stack overflow in the next states without a replay, up to the state it expands.
1688
1341
  const reportNextStateOverflow = (index: number) =>
1689
- createFailureResult(createStackOverflowError(), getStateTrace(index), { isNextState: true });
1690
- // After the trace, TLC replays the next-state relation with its call stack, printing again.
1342
+ createFailureResult(createStackOverflowError(), traces.getStateTrace(index), { phase: "next" });
1691
1343
  const reportNextStateFailure = (
1692
1344
  error: unknown,
1693
1345
  index: number,
@@ -1697,8 +1349,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1697
1349
  const replay = replayFailedNext(index, liveSuccessors);
1698
1350
  return createFailureResult(
1699
1351
  withNextStateExitCode(error),
1700
- appendTraceOutput(getStateTrace(index), replay.lines),
1701
- { isNextState: true, ...replay.result },
1352
+ appendTraceOutput(traces.getStateTrace(index), replay.lines),
1353
+ { phase: "next", ...replay.result },
1702
1354
  );
1703
1355
  };
1704
1356
  const expandState = (index: number, liveSuccessors: LiveSuccessor[]) => {
@@ -1716,22 +1368,20 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1716
1368
  : undefined;
1717
1369
  const successorCount = forEachActionSuccessor(state, writeUnsatisfied, (successor, action) => {
1718
1370
  try {
1719
- outcome.result = visitSuccessor(index, successor, liveSuccessors, source, action);
1371
+ outcome = visitSuccessor(index, successor, liveSuccessors, source, action);
1720
1372
  } catch (error) {
1721
1373
  if (isStackOverflow(error)) {
1722
- outcome.result = reportNextStateOverflow(index);
1374
+ outcome = reportNextStateOverflow(index);
1723
1375
  return true;
1724
1376
  }
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
1377
  const replay = is174
1728
1378
  ? captureOutput(() => replayNext(index))
1729
1379
  : replayFailedNext(index, liveSuccessors);
1730
1380
  if (is174 && error instanceof TlaEvaluationError && !isHeadedError(error)) {
1731
- outcome.result = createFailureResult(
1381
+ outcome = createFailureResult(
1732
1382
  new TlaEvaluationError(`${getWrappedException(error)}${error.message}`, error),
1733
1383
  appendTraceOutput({ trace: [] }, replay.lines),
1734
- { isNextState: true, ...replay.result },
1384
+ { phase: "next", ...replay.result },
1735
1385
  );
1736
1386
  return true;
1737
1387
  }
@@ -1745,20 +1395,19 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1745
1395
  true,
1746
1396
  )
1747
1397
  : undefined;
1748
- outcome.result = createFailureResult(
1398
+ outcome = createFailureResult(
1749
1399
  error,
1750
1400
  appendTraceOutput(
1751
- traceFailure ? getStateTrace(index) : getFailedTrace(index, successor),
1401
+ traceFailure ? traces.getStateTrace(index) : traces.getFailedTrace(index, successor),
1752
1402
  replay.lines,
1753
1403
  ),
1754
- { isNextState: true, ...replay.result, traceFailure },
1404
+ { phase: "next", ...replay.result, traceFailure },
1755
1405
  );
1756
1406
  }
1757
- return outcome.result !== undefined;
1407
+ return outcome !== undefined;
1758
1408
  });
1759
1409
  current.isExpanding = false;
1760
- const result = outcome.result;
1761
- // TLC 1.7.4's worker stops at a violation.
1410
+ const result = outcome;
1762
1411
  if (result?.violation && !is174) {
1763
1412
  const live = captureOutput(() => addFailedLiveState(index, liveSuccessors));
1764
1413
  return {
@@ -1774,7 +1423,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1774
1423
  }
1775
1424
  const accepted = liveness?.addState(index, state, liveSuccessors);
1776
1425
  if (!liveness || !accepted) return undefined;
1777
- const steps = getPathSteps(accepted);
1426
+ const steps = traces.getPathSteps(accepted);
1778
1427
  const properties = getViolatedProperties(
1779
1428
  liveness,
1780
1429
  steps.map((step) => step.state),
@@ -1783,13 +1432,14 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1783
1432
  return reportViolation("property-violation", {
1784
1433
  name: properties[0],
1785
1434
  properties,
1786
- ...toTrace(steps, accepted, { known: 0 }),
1435
+ ...traces.toTrace(steps, accepted, { known: 0 }),
1787
1436
  });
1788
1437
  };
1789
1438
  if (successorCount === 0 && config.checkDeadlock) {
1790
- 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.
1439
+ const deadlock = reportViolation("deadlock", {
1440
+ name: "deadlock",
1441
+ ...traces.getStateTrace(index),
1442
+ });
1793
1443
  const live = captureOutput(() => {
1794
1444
  try {
1795
1445
  return { additional: addLiveState()?.violation };
@@ -1801,7 +1451,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1801
1451
  const reported = deadlock.violation
1802
1452
  ? { ...deadlock, violation: appendTraceOutput(deadlock.violation, live.lines) }
1803
1453
  : deadlock;
1804
- // An error in adding the state stops TLC 1.7.4's worker before it counts the state.
1805
1454
  const counted = withOutDegrees(
1806
1455
  reported,
1807
1456
  live.result.isFailed ? getFailureOutDegrees() : getPartialOutDegrees(),
@@ -1813,7 +1462,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1813
1462
  try {
1814
1463
  return addLiveState();
1815
1464
  } catch (error) {
1816
- // TLC 1.7.4 reports this as an unexpected exception, without the trace or a call stack.
1817
1465
  if (is174 && error instanceof TlaEvaluationError) {
1818
1466
  const unexpected = new TlaEvaluationError(
1819
1467
  `${isEvalException(error) ? UNEXPECTED_EVAL_EXCEPTION : UNEXPECTED_EXCEPTION}${error.message}`,
@@ -1824,15 +1472,13 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1824
1472
  { outDegrees: getFailureOutDegrees() },
1825
1473
  );
1826
1474
  }
1827
- // TLC adds the state again for the call stack, prints it first, and blames the next states.
1828
- const replay = getReplayFailure((tracing) =>
1475
+ const replay = getReplayFailure(environment, (tracing) =>
1829
1476
  liveness?.addState(index, state, liveSuccessors, tracing),
1830
1477
  );
1831
- return createFailureResult(error, getStateTrace(index), {
1478
+ return createFailureResult(error, traces.getStateTrace(index), {
1832
1479
  outDegrees: getFailureOutDegrees(),
1833
1480
  callStack: replay?.callStack.length ? replay.callStack : undefined,
1834
- isNextState: true,
1835
- isCallStackFirst: true,
1481
+ phase: "liveness",
1836
1482
  });
1837
1483
  }
1838
1484
  };
@@ -1853,12 +1499,11 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1853
1499
  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
1500
  };
1855
1501
  };
1856
- // TLC names the properties and the step back into the cycle from the states it prints.
1857
1502
  const reportLasso = (checker: LivenessChecker, lasso: Lasso) => {
1858
1503
  const path = [...lasso.prefix, ...lasso.cycle];
1859
1504
  const loopStart = lasso.prefix.length;
1860
- const steps = getPathSteps(path, loopStart);
1861
- const trace = toTrace(steps, path, { loopStart, known: 0 }).trace;
1505
+ const steps = traces.getPathSteps(path, loopStart);
1506
+ const trace = traces.toTrace(steps, path, { loopStart, known: 0 }).trace;
1862
1507
  const properties = getViolatedProperties(
1863
1508
  checker,
1864
1509
  steps.map((step) => step.state),
@@ -1870,7 +1515,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1870
1515
  const loop =
1871
1516
  cycleStart === cycleEnd
1872
1517
  ? { result: undefined, lines: [] }
1873
- : captureOutput(() => findStepAction(cycleEnd, lastState, states[cycleStart], false));
1518
+ : captureOutput(() =>
1519
+ traces.findStepAction(cycleEnd, lastState, states[cycleStart], false),
1520
+ );
1874
1521
  const isStutteringWarned = cycleStart === cycleEnd && lasso.isCycleConstrained;
1875
1522
  return reportViolation(
1876
1523
  "liveness-violation",
@@ -1888,7 +1535,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1888
1535
  ? getStepAction(trace[trace.length - 1])
1889
1536
  : loop.result
1890
1537
  ? toActionValue(loop.result)
1891
- : createActionRecord(findSuccessorWithFingerprint(lastState, cycleStart)?.action),
1538
+ : createActionRecord(
1539
+ traces.findSuccessorWithFingerprint(lastState, cycleStart)?.action,
1540
+ ),
1892
1541
  );
1893
1542
  };
1894
1543
  const isPeriodic = liveness !== undefined && (options.livenessCheck ?? "default") === "default";
@@ -1917,29 +1566,129 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1917
1566
  periodic.time += performance.now() - now;
1918
1567
  return lasso;
1919
1568
  };
1920
- for (let index = 0; index < states.length && !runtime.isStopped; index++) {
1569
+ const adoptTypedSearch = (searched: TypedResult) => {
1570
+ runtime.generatedStates = searched.generatedStates;
1571
+ runtime.distinctStates = searched.distinctStates;
1572
+ runtime.queueSize = searched.queuedStates;
1573
+ runtime.diameter = searched.depth;
1574
+ searchDepth = searched.depth;
1575
+ outDegrees.splice(0, outDegrees.length, ...searched.outDegrees);
1576
+ newStateCount = 0;
1577
+ };
1578
+ // The tier found a state without successors, or a successor that violates an invariant or an
1579
+ // action property. The interpreter rebuilds the tier's path to it and reports it, as it would after
1580
+ // its own search.
1581
+ const path = typed?.deadlock ?? typed?.violation;
1582
+ const initialIndex = path ? states.findIndex((state) => path.isPathState(0, state)) : -1;
1583
+ if (typed && path && initialIndex !== -1) {
1584
+ const steps: { successor: Successor; action: SpecAction | undefined }[] = [];
1585
+ const getLastState = () => steps.at(-1)?.successor.state ?? states[initialIndex];
1586
+ for (let position = 1; position === steps.length + 1 && position < path.length; position++) {
1587
+ // The interpreter expands only the states it stores, which it has canonicalized.
1588
+ canonicalizeState(getLastState());
1589
+ forEachActionSuccessor(getLastState(), undefined, (successor, action) => {
1590
+ if (!path.isPathState(position, successor.state)) return false;
1591
+ steps.push({ successor, action });
1592
+ return true;
1593
+ });
1594
+ }
1595
+ const isRebuilt = steps.length === path.length - 1;
1596
+ const violating = typed.violation && isRebuilt ? steps.pop() : undefined;
1597
+ if (violating && isCanonicalizedFirst) canonicalizeState(violating.successor.state);
1598
+ const violatedInvariant =
1599
+ violating && search.findViolatedInvariant(violating.successor.state, getLastState());
1600
+ const violatedProperty =
1601
+ violating &&
1602
+ !violatedInvariant &&
1603
+ search.findViolatedActionProperty(getLastState(), violating.successor.state);
1604
+ const violated = violatedInvariant ?? violatedProperty;
1605
+ const isDeadlocked =
1606
+ typed.deadlock !== undefined &&
1607
+ isRebuilt &&
1608
+ forEachActionSuccessor(getLastState(), undefined, () => true) === 0;
1609
+ if (isDeadlocked || violated) {
1610
+ const parent = { index: initialIndex };
1611
+ for (const step of steps) {
1612
+ visitSuccessor(parent.index, step.successor, [], undefined, step.action);
1613
+ parent.index = states.length - 1;
1614
+ }
1615
+ adoptTypedSearch(typed);
1616
+ Object.assign(current, { index: parent.index, candidate: undefined, isExpanding: true });
1617
+ if (violating && violated) {
1618
+ lookUpSuccessor(states[parent.index], violating.successor);
1619
+ current.candidate = violating.successor.state;
1620
+ current.candidateLevel = depths[parent.index] + 1;
1621
+ return withOutDegrees(
1622
+ reportViolation(violatedInvariant ? "invariant-violation" : "liveness-violation", {
1623
+ name: violated.name,
1624
+ ...traces.getTrace(parent.index, violating.successor),
1625
+ }),
1626
+ );
1627
+ }
1628
+ const result = expandState(parent.index, []);
1629
+ if (result) return result;
1630
+ }
1631
+ }
1632
+ // The tier found a behavior that violates a temporal property after its whole search. The
1633
+ // interpreter stores the paths to the lasso's states and reports it, as it would after its own.
1634
+ const lassoSteps = new Map<number, { successor: Successor; action: SpecAction | undefined }>();
1635
+ for (const entry of typed?.lasso?.states ?? []) {
1636
+ const initial = entry.parent === -1 ? states.find(entry.isState) : undefined;
1637
+ if (initial) {
1638
+ lassoSteps.set(entry.index, {
1639
+ successor: { state: initial, action: undefined },
1640
+ action: undefined,
1641
+ });
1642
+ }
1643
+ const parent = lassoSteps.get(entry.parent)?.successor.state;
1644
+ if (!parent) continue;
1645
+ // The interpreter expands only the states it stores, which it has canonicalized.
1646
+ canonicalizeState(parent);
1647
+ forEachActionSuccessor(parent, undefined, (successor, action) => {
1648
+ if (!entry.isState(successor.state)) return false;
1649
+ lassoSteps.set(entry.index, { successor, action });
1650
+ return true;
1651
+ });
1652
+ }
1653
+ const lassoIndexes = new Map<number, number>();
1654
+ const typedLasso =
1655
+ typed?.lasso && lassoSteps.size === typed.lasso.states.length ? typed.lasso : undefined;
1656
+ typedLasso?.states.forEach((entry) => {
1657
+ const step = lassoSteps.get(entry.index);
1658
+ const parent = lassoIndexes.get(entry.parent);
1659
+ if (step && parent !== undefined)
1660
+ visitSuccessor(parent, step.successor, [], undefined, step.action);
1661
+ lassoIndexes.set(
1662
+ entry.index,
1663
+ parent === undefined ? states.findIndex(entry.isState) : states.length - 1,
1664
+ );
1665
+ });
1666
+ if (typed && typedLasso) adoptTypedSearch(typed);
1667
+ for (
1668
+ let index = typedLasso ? states.length : 0;
1669
+ index < states.length && !runtime.isStopped;
1670
+ index++
1671
+ ) {
1921
1672
  current.index = index;
1922
1673
  current.candidate = undefined;
1923
1674
  runtime.queueSize = states.length - index - 1;
1924
1675
  current.isExpanding = true;
1925
1676
  const liveSuccessors: LiveSuccessor[] = [];
1926
1677
  try {
1927
- outcome.result = expandState(index, liveSuccessors);
1678
+ outcome = expandState(index, liveSuccessors);
1928
1679
  } catch (error) {
1929
- outcome.result =
1680
+ outcome =
1930
1681
  error instanceof TlaIncompleteSuccessorError
1931
1682
  ? reportIncompleteSuccessor(index, error)
1932
1683
  : reportNextStateFailure(error, index, liveSuccessors);
1933
1684
  }
1934
- if (outcome.result) return outcome.result;
1685
+ if (outcome) return outcome;
1935
1686
  outDegrees[getOutDegreeBucket()]++;
1936
- expansion.newStates = 0;
1937
- // TLC checks liveness on the graph so far, then reports how far the search got.
1687
+ newStateCount = 0;
1938
1688
  if ((isPeriodic || options.onProgress) && performance.now() >= periodic.at) {
1939
1689
  periodic.at = performance.now() + PROGRESS_INTERVAL;
1940
1690
  const lasso = isPeriodic ? findPeriodicViolation(index + 1) : undefined;
1941
1691
  if (liveness && lasso) return reportLasso(liveness, lasso);
1942
- // TLC reports the coverage with every report after the first `coverage` reports since the last.
1943
1692
  const isCoverageDue = options.coverage !== undefined && periodic.coverageCount === 0;
1944
1693
  periodic.coverageCount = isCoverageDue
1945
1694
  ? Math.trunc(options.coverage ?? 0)
@@ -1964,10 +1713,17 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1964
1713
  statistics: createResult("success"),
1965
1714
  });
1966
1715
  }
1967
- const lasso = finalLiveness?.findViolation();
1716
+ const getLassoIndexes = (indexes: number[]) =>
1717
+ indexes.map((index) => lassoIndexes.get(index) ?? -1);
1718
+ const lasso = typedLasso
1719
+ ? {
1720
+ prefix: getLassoIndexes(typedLasso.prefix),
1721
+ cycle: getLassoIndexes(typedLasso.cycle),
1722
+ isCycleConstrained: typedLasso.isCycleConstrained,
1723
+ }
1724
+ : finalLiveness?.findViolation();
1968
1725
  if (finalLiveness && lasso) return reportLasso(finalLiveness, lasso);
1969
1726
 
1970
- // TLC finishes the check of the temporal properties before it checks the postconditions.
1971
1727
  if (finalLiveness) options.onProgress?.({ kind: "liveness-finished" });
1972
1728
  const missingPostcondition = specification.moduleOperators.find(
1973
1729
  (operator) => operator.kind === "postcondition" && operator.key === undefined,
@@ -1985,5 +1741,5 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1985
1741
  postcondition,
1986
1742
  });
1987
1743
  }
1988
- return continued.status ? createResult(continued.status) : createSuccess();
1744
+ return continuedStatus ? createResult(continuedStatus) : createSuccess();
1989
1745
  };