tla-ts 0.0.9 → 0.0.10-dev.28c823e4b

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 (390) hide show
  1. package/README.md +29 -1
  2. package/dist/compile.cjs +23 -0
  3. package/dist/compile.js +23 -0
  4. package/dist/deciders.cjs +28 -28
  5. package/dist/deciders.js +43 -43
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +106 -10
  8. package/dist/index.d.ts +106 -10
  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-worker.cjs +1 -1
  13. package/dist/prove-worker.js +1 -1
  14. package/dist/prove.cjs +116 -36
  15. package/dist/prove.js +116 -36
  16. package/dist/run.cjs +143 -31
  17. package/dist/run.js +143 -31
  18. package/dist/tlapm.cjs +2 -2
  19. package/dist/tlapm.js +2 -2
  20. package/dist/transfer.cjs +129 -104
  21. package/dist/transfer.js +129 -104
  22. package/dist/worker.cjs +7 -7
  23. package/dist/worker.js +7 -7
  24. package/package.json +3 -1
  25. package/src/ast.ts +4 -23
  26. package/src/bags.ts +99 -102
  27. package/src/builtins.ts +40 -78
  28. package/src/bundled-modules.ts +1 -8
  29. package/src/check.ts +599 -388
  30. package/src/cli/options.ts +11 -6
  31. package/src/cli/run.ts +0 -2
  32. package/src/cli/runtime-invariants.ts +136 -0
  33. package/src/cli/shared.ts +18 -11
  34. package/src/cli/tlapm.ts +0 -12
  35. package/src/cli/tlc-arguments.ts +640 -0
  36. package/src/cli/tlc-usage.ts +361 -0
  37. package/src/cli/tlc.ts +538 -220
  38. package/src/cli/typescript.ts +23 -0
  39. package/src/cli/xml-exporter.ts +4 -16
  40. package/src/cli.ts +0 -1
  41. package/src/codegen.ts +191 -64
  42. package/src/config.ts +140 -109
  43. package/src/coverage.ts +837 -0
  44. package/src/dependencies.ts +6 -40
  45. package/src/dfid.ts +618 -0
  46. package/src/environment.ts +240 -118
  47. package/src/errors.ts +70 -55
  48. package/src/evaluate.ts +596 -339
  49. package/src/exit-codes.ts +37 -3
  50. package/src/fingerprints.ts +10 -10
  51. package/src/index.ts +3 -0
  52. package/src/instances.ts +79 -11
  53. package/src/java-overrides.ts +4 -19
  54. package/src/json-reader.ts +455 -0
  55. package/src/json.ts +255 -139
  56. package/src/levels.ts +8 -17
  57. package/src/lexer.ts +80 -100
  58. package/src/liveness-checker.ts +82 -119
  59. package/src/liveness.ts +112 -64
  60. package/src/obligations/action.ts +4 -28
  61. package/src/obligations/anonymize.ts +84 -80
  62. package/src/obligations/equality.ts +1 -1
  63. package/src/obligations/expression.ts +2 -19
  64. package/src/obligations/format.ts +1 -9
  65. package/src/obligations/generate.ts +1 -11
  66. package/src/obligations/index.ts +0 -11
  67. package/src/obligations/levels.ts +4 -8
  68. package/src/obligations/module.ts +1 -15
  69. package/src/obligations/normalize.ts +5 -24
  70. package/src/obligations/operators.ts +1 -2
  71. package/src/obligations/pragma.ts +1 -10
  72. package/src/obligations/printer.ts +47 -46
  73. package/src/obligations/proof.ts +1 -5
  74. package/src/obligations/regroup.ts +1 -4
  75. package/src/obligations/simplify.ts +3 -14
  76. package/src/obligations/source.ts +1 -21
  77. package/src/obligations/subexpression.ts +5 -11
  78. package/src/obligations/substitution.ts +1 -3
  79. package/src/obligations/temporal.ts +8 -14
  80. package/src/obligations/tuples.ts +3 -9
  81. package/src/parallel-worker.ts +29 -39
  82. package/src/parallel.ts +53 -44
  83. package/src/parser.ts +565 -282
  84. package/src/pcal/ast.ts +53 -86
  85. package/src/pcal/parse.ts +144 -219
  86. package/src/pcal/tokenize.ts +91 -131
  87. package/src/pcal/translate.ts +83 -130
  88. package/src/pcal/validate.ts +48 -68
  89. package/src/pretty-print.ts +7 -8
  90. package/src/prover/decide-pool.ts +5 -10
  91. package/src/prover/deciders.ts +0 -4
  92. package/src/prover/first-order.ts +0 -11
  93. package/src/prover/isabelle/decide.ts +0 -6
  94. package/src/prover/isabelle/encode.ts +11 -23
  95. package/src/prover/isabelle/isar/inner-syntax.ts +108 -114
  96. package/src/prover/isabelle/isar/method.ts +25 -38
  97. package/src/prover/isabelle/isar/proof.ts +1 -10
  98. package/src/prover/isabelle/isar/statement.ts +1 -6
  99. package/src/prover/isabelle/isar/theory.ts +15 -26
  100. package/src/prover/isabelle/isar/type-check.ts +11 -25
  101. package/src/prover/isabelle/provers/blast/blast.ts +10 -41
  102. package/src/prover/isabelle/provers/blast/branch.ts +1 -32
  103. package/src/prover/isabelle/provers/blast/prove.ts +1 -35
  104. package/src/prover/isabelle/provers/blast/rules.ts +6 -44
  105. package/src/prover/isabelle/provers/blast/state.ts +2 -28
  106. package/src/prover/isabelle/provers/blast/term.ts +9 -36
  107. package/src/prover/isabelle/provers/clasimp.ts +1 -13
  108. package/src/prover/isabelle/provers/classical.ts +14 -42
  109. package/src/prover/isabelle/provers/hypsubst.ts +11 -25
  110. package/src/prover/isabelle/pure/bicompose.ts +16 -13
  111. package/src/prover/isabelle/pure/consts.ts +1 -7
  112. package/src/prover/isabelle/pure/conv.ts +1 -9
  113. package/src/prover/isabelle/pure/drule.ts +24 -40
  114. package/src/prover/isabelle/pure/envir.ts +3 -52
  115. package/src/prover/isabelle/pure/goal.ts +1 -7
  116. package/src/prover/isabelle/pure/interrupt.ts +0 -5
  117. package/src/prover/isabelle/pure/list.ts +0 -3
  118. package/src/prover/isabelle/pure/logic.ts +1 -14
  119. package/src/prover/isabelle/pure/name.ts +2 -9
  120. package/src/prover/isabelle/pure/net.ts +3 -59
  121. package/src/prover/isabelle/pure/object-logic.ts +3 -10
  122. package/src/prover/isabelle/pure/pattern.ts +2 -19
  123. package/src/prover/isabelle/pure/raw-simplifier.ts +13 -49
  124. package/src/prover/isabelle/pure/rewriter.ts +26 -58
  125. package/src/prover/isabelle/pure/search.ts +3 -10
  126. package/src/prover/isabelle/pure/seq.ts +1 -10
  127. package/src/prover/isabelle/pure/simplifier.ts +4 -12
  128. package/src/prover/isabelle/pure/table.ts +1 -31
  129. package/src/prover/isabelle/pure/tactic.ts +12 -22
  130. package/src/prover/isabelle/pure/tactical.ts +6 -12
  131. package/src/prover/isabelle/pure/term-ord.ts +2 -6
  132. package/src/prover/isabelle/pure/term.ts +2 -43
  133. package/src/prover/isabelle/pure/thm.ts +13 -36
  134. package/src/prover/isabelle/pure/type.ts +2 -15
  135. package/src/prover/isabelle/pure/unify.ts +20 -30
  136. package/src/prover/isabelle/pure/variable.ts +3 -7
  137. package/src/prover/isabelle/tla/classical-setup.ts +9 -19
  138. package/src/prover/isabelle/tla/context.ts +8 -16
  139. package/src/prover/isabelle/tla/logic.ts +4 -11
  140. package/src/prover/isabelle/tla/simpdata.ts +46 -34
  141. package/src/prover/isabelle/tools/intuitionistic.ts +1 -10
  142. package/src/prover/ocaml.ts +0 -6
  143. package/src/prover/prep/action.ts +4 -36
  144. package/src/prover/prep/enabled-axioms.ts +12 -19
  145. package/src/prover/prep/fingerprint.ts +0 -16
  146. package/src/prover/prep/level-comparison.ts +8 -12
  147. package/src/prover/prep/md5.ts +0 -2
  148. package/src/prover/prep/methods.ts +9 -36
  149. package/src/prover/prep/normalize.ts +4 -28
  150. package/src/prover/prove-worker.ts +0 -2
  151. package/src/prover/prove.ts +0 -36
  152. package/src/prover/ptl/decide.ts +7 -12
  153. package/src/prover/ptl/encode.ts +14 -36
  154. package/src/prover/ptl/sat.ts +24 -32
  155. package/src/prover/ptl/tableau.ts +12 -26
  156. package/src/prover/smt/axioms.ts +0 -7
  157. package/src/prover/smt/context.ts +19 -26
  158. package/src/prover/smt/data.ts +51 -54
  159. package/src/prover/smt/encode.ts +14 -35
  160. package/src/prover/smt/extensionality.ts +0 -10
  161. package/src/prover/smt/flatten.ts +3 -22
  162. package/src/prover/smt/format.ts +5 -10
  163. package/src/prover/smt/instances.ts +0 -10
  164. package/src/prover/smt/rewrite.ts +66 -101
  165. package/src/prover/smt/solver/act-cache.ts +0 -15
  166. package/src/prover/smt/solver/arith-rewriter.ts +3 -48
  167. package/src/prover/smt/solver/array.ts +1 -3
  168. package/src/prover/smt/solver/asserted-formulas.ts +1 -43
  169. package/src/prover/smt/solver/ast-lt.ts +1 -11
  170. package/src/prover/smt/solver/ast-util.ts +1 -6
  171. package/src/prover/smt/solver/ast.ts +1 -143
  172. package/src/prover/smt/solver/auf-solver.ts +6 -39
  173. package/src/prover/smt/solver/case-split-queue.ts +1 -9
  174. package/src/prover/smt/solver/cg-table.ts +1 -18
  175. package/src/prover/smt/solver/clause.ts +1 -27
  176. package/src/prover/smt/solver/conflict-resolution.ts +0 -9
  177. package/src/prover/smt/solver/context.ts +4 -61
  178. package/src/prover/smt/solver/ctx-simplify.ts +14 -41
  179. package/src/prover/smt/solver/der.ts +2 -21
  180. package/src/prover/smt/solver/dyn-ack.ts +1 -11
  181. package/src/prover/smt/solver/e-matching.ts +3 -34
  182. package/src/prover/smt/solver/enode.ts +1 -21
  183. package/src/prover/smt/solver/expr-ref.ts +1 -5
  184. package/src/prover/smt/solver/expr-safe-replace.ts +0 -5
  185. package/src/prover/smt/solver/fingerprints.ts +1 -12
  186. package/src/prover/smt/solver/flat-literals.ts +1 -9
  187. package/src/prover/smt/solver/goal.ts +2 -14
  188. package/src/prover/smt/solver/hash.ts +0 -8
  189. package/src/prover/smt/solver/hashtable.ts +1 -12
  190. package/src/prover/smt/solver/internalizer.ts +6 -98
  191. package/src/prover/smt/solver/lbool.ts +1 -2
  192. package/src/prover/smt/solver/literal.ts +0 -3
  193. package/src/prover/smt/solver/lp/bound-propagator.ts +8 -26
  194. package/src/prover/smt/solver/lp/constraints.ts +2 -8
  195. package/src/prover/smt/solver/lp/containers.ts +12 -30
  196. package/src/prover/smt/solver/lp/core-solver.ts +10 -31
  197. package/src/prover/smt/solver/lp/cross-nested.ts +6 -20
  198. package/src/prover/smt/solver/lp/dep-intervals.ts +7 -22
  199. package/src/prover/smt/solver/lp/dependency.ts +1 -4
  200. package/src/prover/smt/solver/lp/dioph-eq.ts +12 -98
  201. package/src/prover/smt/solver/lp/explanation.ts +1 -6
  202. package/src/prover/smt/solver/lp/gomory.ts +9 -22
  203. package/src/prover/smt/solver/lp/hnf-cutter.ts +17 -23
  204. package/src/prover/smt/solver/lp/hnf.ts +11 -26
  205. package/src/prover/smt/solver/lp/int-cube.ts +15 -36
  206. package/src/prover/smt/solver/lp/int-solver.ts +4 -34
  207. package/src/prover/smt/solver/lp/lar-solver.ts +32 -81
  208. package/src/prover/smt/solver/lp/lar-term.ts +1 -5
  209. package/src/prover/smt/solver/lp/lp-settings.ts +1 -14
  210. package/src/prover/smt/solver/lp/maximize-term.ts +20 -45
  211. package/src/prover/smt/solver/lp/nex-creator.ts +5 -28
  212. package/src/prover/smt/solver/lp/nex.ts +1 -6
  213. package/src/prover/smt/solver/lp/nla-backoff.ts +1 -4
  214. package/src/prover/smt/solver/lp/nla-basics.ts +5 -30
  215. package/src/prover/smt/solver/lp/nla-core.ts +35 -130
  216. package/src/prover/smt/solver/lp/nla-divisions.ts +32 -42
  217. package/src/prover/smt/solver/lp/nla-emonics.ts +4 -21
  218. package/src/prover/smt/solver/lp/nla-factorization.ts +1 -4
  219. package/src/prover/smt/solver/lp/nla-grobner.ts +15 -69
  220. package/src/prover/smt/solver/lp/nla-horner.ts +3 -11
  221. package/src/prover/smt/solver/lp/nla-intervals.ts +2 -12
  222. package/src/prover/smt/solver/lp/nla-monomial-bounds.ts +16 -41
  223. package/src/prover/smt/solver/lp/nla-monotone.ts +2 -6
  224. package/src/prover/smt/solver/lp/nla-order.ts +2 -13
  225. package/src/prover/smt/solver/lp/nla-patcher.ts +4 -7
  226. package/src/prover/smt/solver/lp/nla-tangents.ts +1 -9
  227. package/src/prover/smt/solver/lp/nla-throttle.ts +1 -6
  228. package/src/prover/smt/solver/lp/nla-types.ts +1 -11
  229. package/src/prover/smt/solver/lp/nla-var-eqs.ts +4 -25
  230. package/src/prover/smt/solver/lp/nra-solver.ts +5 -52
  231. package/src/prover/smt/solver/lp/numeric-pair.ts +1 -4
  232. package/src/prover/smt/solver/lp/pdd-interval.ts +1 -3
  233. package/src/prover/smt/solver/lp/pdd-simplifier.ts +2 -14
  234. package/src/prover/smt/solver/lp/pdd-solver.ts +4 -33
  235. package/src/prover/smt/solver/lp/pdd.ts +7 -70
  236. package/src/prover/smt/solver/lp/random-updater.ts +1 -8
  237. package/src/prover/smt/solver/lp/static-matrix.ts +9 -19
  238. package/src/prover/smt/solver/lp/union-find.ts +1 -6
  239. package/src/prover/smt/solver/mam-compiler.ts +14 -56
  240. package/src/prover/smt/solver/mam-interpreter.ts +1 -21
  241. package/src/prover/smt/solver/maximize-ac-sharing.ts +2 -17
  242. package/src/prover/smt/solver/model-checker.ts +2 -36
  243. package/src/prover/smt/solver/model-evaluator.ts +3 -29
  244. package/src/prover/smt/solver/model-finder.ts +3 -15
  245. package/src/prover/smt/solver/model-generator.ts +1 -12
  246. package/src/prover/smt/solver/model-macro-solver.ts +12 -69
  247. package/src/prover/smt/solver/nlsat/algebraic.ts +55 -151
  248. package/src/prover/smt/solver/nlsat/atoms.ts +5 -19
  249. package/src/prover/smt/solver/nlsat/evaluator.ts +17 -22
  250. package/src/prover/smt/solver/nlsat/explain.ts +3 -47
  251. package/src/prover/smt/solver/nlsat/interval-set.ts +9 -50
  252. package/src/prover/smt/solver/nlsat/levelwise.ts +48 -129
  253. package/src/prover/smt/solver/nlsat/mpbq.ts +3 -14
  254. package/src/prover/smt/solver/nlsat/polynomial.ts +17 -156
  255. package/src/prover/smt/solver/nlsat/solver.ts +7 -67
  256. package/src/prover/smt/solver/nlsat/types.ts +1 -8
  257. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +1 -44
  258. package/src/prover/smt/solver/nlsat/upolynomial.ts +11 -92
  259. package/src/prover/smt/solver/nnf.ts +3 -38
  260. package/src/prover/smt/solver/pattern-inference.ts +2 -15
  261. package/src/prover/smt/solver/poly-rewriter.ts +3 -23
  262. package/src/prover/smt/solver/propagate-values.ts +1 -10
  263. package/src/prover/smt/solver/proto-model.ts +3 -48
  264. package/src/prover/smt/solver/pull-quant.ts +1 -12
  265. package/src/prover/smt/solver/qe-lite-der.ts +1 -29
  266. package/src/prover/smt/solver/qe-lite-fm.ts +2 -25
  267. package/src/prover/smt/solver/qe-lite.ts +3 -33
  268. package/src/prover/smt/solver/qi-queue.ts +1 -16
  269. package/src/prover/smt/solver/quant-tactics.ts +5 -22
  270. package/src/prover/smt/solver/quantifier-analyzer.ts +17 -37
  271. package/src/prover/smt/solver/quantifier-manager.ts +1 -8
  272. package/src/prover/smt/solver/random-gen.ts +1 -2
  273. package/src/prover/smt/solver/rational.ts +1 -8
  274. package/src/prover/smt/solver/ref-vector.ts +1 -6
  275. package/src/prover/smt/solver/relevancy.ts +2 -15
  276. package/src/prover/smt/solver/rewriter-tpl.ts +3 -147
  277. package/src/prover/smt/solver/rewriter.ts +3 -85
  278. package/src/prover/smt/solver/rlimit.ts +2 -20
  279. package/src/prover/smt/solver/smtlib-parser.ts +2 -37
  280. package/src/prover/smt/solver/solver.ts +23 -34
  281. package/src/prover/smt/solver/sort.ts +1 -5
  282. package/src/prover/smt/solver/sticky-generations.ts +0 -5
  283. package/src/prover/smt/solver/theory-lra-axioms.ts +3 -24
  284. package/src/prover/smt/solver/theory-lra-bounds.ts +0 -5
  285. package/src/prover/smt/solver/theory-lra-final-check.ts +4 -22
  286. package/src/prover/smt/solver/theory-lra-internalize.ts +1 -27
  287. package/src/prover/smt/solver/theory-lra-model.ts +4 -19
  288. package/src/prover/smt/solver/theory-lra-propagate.ts +1 -15
  289. package/src/prover/smt/solver/theory-lra-state.ts +3 -8
  290. package/src/prover/smt/solver/theory-lra.ts +1 -8
  291. package/src/prover/smt/solver/var-subst.ts +2 -26
  292. package/src/prover/smt/table.ts +0 -8
  293. package/src/prover/tlapm/cache.ts +20 -25
  294. package/src/prover/tlapm/ocaml-marshal.ts +19 -21
  295. package/src/prover/tlapm/tlapm.ts +12 -17
  296. package/src/prover/verdict.ts +0 -2
  297. package/src/prover/zenon/check/check.ts +0 -9
  298. package/src/prover/zenon/check/definitions.ts +5 -15
  299. package/src/prover/zenon/check/equality.ts +0 -8
  300. package/src/prover/zenon/check/functions.ts +0 -4
  301. package/src/prover/zenon/check/keys.ts +0 -7
  302. package/src/prover/zenon/check/propositional.ts +0 -3
  303. package/src/prover/zenon/check/records.ts +0 -5
  304. package/src/prover/zenon/check/relations.ts +0 -13
  305. package/src/prover/zenon/check/rewrites.ts +0 -6
  306. package/src/prover/zenon/check/sets.ts +0 -3
  307. package/src/prover/zenon/check/terms.ts +0 -17
  308. package/src/prover/zenon/check/tla.ts +0 -6
  309. package/src/prover/zenon/decide.ts +0 -12
  310. package/src/prover/zenon/encode.ts +1 -8
  311. package/src/prover/zenon/eqrel.ts +0 -13
  312. package/src/prover/zenon/equality-rules.ts +0 -4
  313. package/src/prover/zenon/expr.ts +1 -26
  314. package/src/prover/zenon/index-table.ts +17 -38
  315. package/src/prover/zenon/isar-case.ts +9 -19
  316. package/src/prover/zenon/isar.ts +1 -29
  317. package/src/prover/zenon/limits.ts +0 -4
  318. package/src/prover/zenon/llproof.ts +0 -9
  319. package/src/prover/zenon/mltoll.ts +54 -76
  320. package/src/prover/zenon/node.ts +1 -11
  321. package/src/prover/zenon/ocaml.ts +1 -17
  322. package/src/prover/zenon/parse.ts +2 -7
  323. package/src/prover/zenon/phrase.ts +1 -11
  324. package/src/prover/zenon/proof.ts +0 -9
  325. package/src/prover/zenon/propositional-rules.ts +0 -5
  326. package/src/prover/zenon/rules.ts +2 -6
  327. package/src/prover/zenon/search.ts +1 -17
  328. package/src/prover/zenon/tla/functions.ts +57 -29
  329. package/src/prover/zenon/tla/llproof.ts +63 -70
  330. package/src/prover/zenon/tla/records.ts +56 -27
  331. package/src/prover/zenon/tla/rewrites.ts +12 -19
  332. package/src/prover/zenon/tla/sets.ts +68 -39
  333. package/src/prover/zenon/tla/terms.ts +0 -6
  334. package/src/prover/zenon/tla/tla.ts +59 -58
  335. package/src/randomization.ts +81 -35
  336. package/src/resolve.ts +12 -112
  337. package/src/runtime.ts +22 -22
  338. package/src/sany/builtins.ts +2 -5
  339. package/src/sany/generator.ts +149 -252
  340. package/src/sany/levels.ts +6 -34
  341. package/src/sany/lexer.ts +41 -61
  342. package/src/sany/linter.ts +1 -9
  343. package/src/sany/modules.ts +1 -5
  344. package/src/sany/nodes.ts +0 -31
  345. package/src/sany/parse-error.ts +39 -117
  346. package/src/sany/report.ts +29 -63
  347. package/src/sany/selectors.ts +15 -39
  348. package/src/sany/source.ts +1 -17
  349. package/src/sany/xml.ts +13 -63
  350. package/src/search.ts +495 -155
  351. package/src/simulate.ts +685 -0
  352. package/src/spec-description.ts +176 -69
  353. package/src/standard-definitions.ts +0 -4
  354. package/src/standard-modules.ts +254 -69
  355. package/src/state-graph.ts +50 -24
  356. package/src/subexpressions.ts +69 -52
  357. package/src/substitution-levels.ts +2 -3
  358. package/src/successors.ts +263 -94
  359. package/src/symmetry.ts +33 -25
  360. package/src/tableau.ts +27 -24
  361. package/src/tlc/fingerprint.ts +183 -67
  362. package/src/tlc/jar-data.ts +112 -6
  363. package/src/tlc/messages.ts +110 -44
  364. package/src/tlc/order.ts +37 -60
  365. package/src/tlc/random.ts +33 -45
  366. package/src/tlc/replay.ts +549 -217
  367. package/src/tlc/summary.ts +36 -47
  368. package/src/tlc/tlc-operators.ts +76 -41
  369. package/src/tlc/tlcext-operators.ts +139 -122
  370. package/src/tlc/trace-spec.ts +269 -0
  371. package/src/tlc/value-stream.ts +139 -0
  372. package/src/tlc/version.ts +1 -4
  373. package/src/transfer.ts +22 -25
  374. package/src/typescript/actions.ts +481 -0
  375. package/src/typescript/collections.ts +600 -0
  376. package/src/typescript/compile.ts +65 -0
  377. package/src/typescript/context.ts +94 -0
  378. package/src/typescript/emit.ts +121 -0
  379. package/src/typescript/expressions.ts +496 -0
  380. package/src/typescript/formula.ts +152 -0
  381. package/src/typescript/functions.ts +284 -0
  382. package/src/typescript/model.ts +163 -0
  383. package/src/typescript/names.ts +114 -0
  384. package/src/typescript/program.ts +48 -0
  385. package/src/typescript/properties.ts +139 -0
  386. package/src/typescript/scope.ts +112 -0
  387. package/src/typescript/steps.ts +165 -0
  388. package/src/typescript/types.ts +171 -0
  389. package/src/values.ts +780 -337
  390. package/src/worker.ts +7 -8
package/src/check.ts CHANGED
@@ -1,11 +1,19 @@
1
1
  import type { Expression } from "./ast";
2
2
  import { parseConfig, type ModelConfig } from "./config";
3
+ import {
4
+ addCoverageRelation,
5
+ buildCoverage,
6
+ countCoverageVariables,
7
+ createCoverage,
8
+ getCoverageLabel,
9
+ getCoverageReport,
10
+ type CoverageReport,
11
+ } from "./coverage";
3
12
  import { createEnvironment } from "./environment";
4
13
  import {
5
14
  createStackOverflowError,
6
15
  getErrorExitCode,
7
16
  isStackOverflow,
8
- TlaConfigError,
9
17
  TlaEvaluationError,
10
18
  TlaIllegalStateError,
11
19
  TlaIncompleteSuccessorError,
@@ -13,18 +21,24 @@ import {
13
21
  TlaStackOverflowError,
14
22
  UNEXPECTED_EVAL_EXCEPTION,
15
23
  UNEXPECTED_EXCEPTION,
24
+ formatRange,
16
25
  } from "./errors";
17
26
  import {
18
27
  createTracingEnvironment,
19
- evaluate,
20
- formatRange,
28
+ describeRange,
21
29
  getDefinition,
22
30
  isImpure,
23
31
  type CallStack,
24
32
  type Environment,
25
33
  type FingerprintFailure,
26
34
  } from "./evaluate";
27
- import { EXIT_STATUS, getExitCode, setExitCode, withLivenessExitCode } from "./exit-codes";
35
+ import {
36
+ EXIT_STATUS,
37
+ getExitCode,
38
+ getMessageExitStatus,
39
+ setExitCode,
40
+ withLivenessExitCode,
41
+ } from "./exit-codes";
28
42
  import type { JavaOverride } from "./java-overrides";
29
43
  import {
30
44
  createLivenessChecker,
@@ -33,11 +47,10 @@ import {
33
47
  type LiveSuccessor,
34
48
  } from "./liveness-checker";
35
49
  import {
36
- createIdentifier,
50
+ createMissingOperatorError,
37
51
  createSearch,
52
+ getIncompleteSuccessorMessage,
38
53
  findAssumptionViolation,
39
- getConfigDefinition,
40
- getContext,
41
54
  reportInitialStatesProgress,
42
55
  reportStartup,
43
56
  withNextStateExitCode,
@@ -62,10 +75,10 @@ import {
62
75
  forEachSuccessor,
63
76
  getInitialStates,
64
77
  getSuccessors,
78
+ hasIncompleteSuccessor,
65
79
  type Successor,
66
80
  } from "./successors";
67
81
  import {
68
- formatNestedMessage,
69
82
  getCodedMessage,
70
83
  getFailureMessage,
71
84
  getWrappedException,
@@ -75,8 +88,17 @@ import {
75
88
  withUnexpectedException,
76
89
  type FailureMessage,
77
90
  } from "./tlc/messages";
91
+ import { createTautologyError } from "./liveness";
92
+ import { KEY_SEPARATOR } from "./resolve";
93
+ import { setFingerprintPolynomial } from "./tlc/fingerprint";
94
+ import { writeTraceSpec } from "./tlc/trace-spec";
78
95
  import { createTlcOrder } from "./tlc/order";
79
- import { replayInitialStates, replaySuccessors } from "./tlc/replay";
96
+ import {
97
+ getPrimedRanges,
98
+ replayInitialStates,
99
+ replaySuccessors,
100
+ walkSuccessors,
101
+ } from "./tlc/replay";
80
102
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc/summary";
81
103
  import { createActionRecord, createCounterExample } from "./tlc/tlcext-operators";
82
104
  import type { TlcVersion } from "./tlc/version";
@@ -87,13 +109,12 @@ import {
87
109
  formatState,
88
110
  getFingerprintError,
89
111
  getHeldValues,
112
+ getModelValues,
90
113
  getValueHash,
91
- isFunctionValue,
92
114
  isSameValue,
93
115
  markFingerprinted,
94
116
  setStringOrder,
95
- setValueVersion,
96
- toFiniteFunction,
117
+ setValueOptions,
97
118
  type Value,
98
119
  } from "./values";
99
120
 
@@ -105,37 +126,56 @@ export interface CheckOptions {
105
126
  onPrint?: (text: string) => void;
106
127
  onPause?: () => void;
107
128
  readFile?: (path: string) => string | undefined;
108
- writeFile?: (path: string, content: string) => void;
129
+ writeFile?: (path: string, content: string | Uint8Array) => void;
130
+ makeDirectory?: (path: string) => void;
109
131
  seed?: bigint;
110
132
  workers?: number;
111
- // TLC's -lncheck: "final" checks liveness only on the complete state graph.
112
- livenessCheck?: "default" | "final";
113
- // TLC's -dump: writes the reachable states, or with `dot` the state graph, through writeFile.
133
+ /** TLC's -lncheck: "final" checks liveness only on the complete graph, "off" never looks for a cycle. */
134
+ livenessCheck?: "default" | "final" | "off";
135
+ /** TLC's -fp: the index of the polynomial in TLC's FP64.Polys that fingerprints states. */
136
+ fingerprintPolynomial?: number;
137
+ /** False for TLC's -terse, which prints a lazy value, such as SUBSET S, without enumerating it. */
138
+ isLazyValueExpanded?: boolean;
139
+ /** TLC's -view: prints each state as the value of the configuration's VIEW. */
140
+ isViewPrinted?: boolean;
141
+ /** TLC's -maxSetSize: the most elements TLC enumerates into a set, or states into a list of them. */
142
+ maxSetSize?: number;
143
+ /** TLC's -dump: writes the reachable states, or with `dot` the state graph, through writeFile. */
114
144
  dump?: StateDump;
115
- // TLC's -tool, which changes the messages of TLC's errors.
145
+ /** TLC's -tool, which changes the messages of TLC's errors. */
116
146
  isTool?: boolean;
117
- // TLC's -continue: the search reports each violated invariant and action property through
118
- // onProgress and goes on.
147
+ /** TLC's -continue: reports each violation through onProgress and goes on. */
119
148
  isContinued?: boolean;
120
- // Whether TLC records a binary trace for its trace exploration spec, for which it loads Integers.
121
- isTraceRecorded?: boolean;
122
- // Whether the caller printed SANY's report, its warnings included, before the check.
149
+ moduleOperators?: ModuleOperator[];
150
+ /** TLC's trace exploration spec, and the binary trace TLC records for it unless -noTEBin. */
151
+ traceSpec?: TraceSpecOptions;
152
+ /** Whether the caller printed SANY's report, its warnings included, before the check. */
123
153
  isSanyReported?: boolean;
124
- // False for TLC's -nowarning, which changes how TLC computes the successors of some actions.
154
+ /** False for TLC's -nowarning, which changes how TLC computes some successors. */
125
155
  isWarningEnabled?: boolean;
126
- // The TLC whose output tla-ts reproduces, which changes how TLC labels an action.
156
+ /** TLC's -coverage, in minutes. */
157
+ coverage?: number;
127
158
  version?: TlcVersion;
128
- // Reports the points of the search at which TLC prints a message.
129
159
  onProgress?: (progress: CheckProgress) => void;
130
160
  }
131
161
 
162
+ export interface TraceSpecOptions {
163
+ module: string;
164
+ traceFile?: string;
165
+ }
166
+
167
+ export interface ModuleOperator {
168
+ kind: "postcondition" | "constraint" | "view";
169
+ module: string;
170
+ operator: string;
171
+ constants?: Record<string, string>;
172
+ }
173
+
132
174
  export interface InitialStatesProgress {
133
175
  kind: "initial-states-progress";
134
176
  count: number;
135
177
  }
136
178
 
137
- // A check that TLC's DoInitFunctor reports as violated before it stops its replay of the initial
138
- // states.
139
179
  export interface InitialStateViolation {
140
180
  kind: "initial-state-violation";
141
181
  status: "invariant-violation" | "liveness-violation";
@@ -143,10 +183,8 @@ export interface InitialStateViolation {
143
183
  state: Record<string, Value>;
144
184
  }
145
185
 
146
- // A line the spec prints, or what TLC reports as it replays the initial states.
147
186
  export type OutputLine = string | InitialStatesProgress | InitialStateViolation;
148
187
 
149
- // The points of the search at which TLC prints a message.
150
188
  export type CheckProgress =
151
189
  | { kind: "parsed" }
152
190
  | { kind: "constant-level-invariant"; name: string }
@@ -160,23 +198,21 @@ export type CheckProgress =
160
198
  | {
161
199
  kind: "liveness-started";
162
200
  branches: number;
163
- // Whether TLC checks the complete state graph, and how many states of it each branch has.
201
+ /** Whether TLC checks the complete state graph. */
164
202
  isComplete: boolean;
203
+ /** How many states of the graph each branch has. */
165
204
  states: number;
166
205
  statistics: SearchStatistics;
167
206
  }
168
207
  | { kind: "liveness-finished" }
169
208
  | { kind: "sequential-fallback"; string: string }
170
- // A warning TLC prints as it evaluates the spec, with its message code.
171
209
  | { kind: "warning"; code: number; text: string }
172
- // A violation that the search goes on past with -continue.
173
210
  | { kind: "violation"; status: CheckStatus; violation: Violation }
174
- // A method of the class named after a module, which TLC reports as it loads the class.
175
211
  | ({ kind: "java-override" } & JavaOverride);
176
212
 
177
213
  export interface SearchStatistics extends Pick<
178
214
  CheckResult,
179
- "generatedStates" | "distinctStates" | "queuedStates" | "depth"
215
+ "generatedStates" | "distinctStates" | "queuedStates" | "depth" | "coverage"
180
216
  > {}
181
217
 
182
218
  export type CheckStatus =
@@ -191,45 +227,42 @@ export type CheckStatus =
191
227
 
192
228
  export interface TraceStep {
193
229
  action: string | undefined;
194
- // TLC's name, parameters and location for the action that took this step.
230
+ /** TLC's name, parameters and location for the action that took this step. */
195
231
  label: string | undefined;
196
232
  state: Record<string, Value>;
197
- // What the spec prints, before TLC prints this step, as TLC evaluates it again to rebuild the
198
- // trace. The first step has what TLC prints before the trace.
233
+ /** What the spec prints before this step as TLC rebuilds the trace, and before it for the first. */
199
234
  output?: OutputLine[];
200
235
  }
201
236
 
202
237
  export interface Violation {
203
238
  name: string;
204
- // Every temporal property that a liveness counterexample violates, in the configuration's order.
239
+ /** Every temporal property that a liveness counterexample violates, in the configuration's order. */
205
240
  properties?: string[];
206
241
  trace: TraceStep[];
207
- // What the spec prints after TLC prints the states of the trace, as TLC finds the step back into
208
- // the cycle of a lasso or rebuilds the trace once more.
242
+ /** What the spec prints after the trace, as TLC finds the lasso's step back or rebuilds the trace. */
209
243
  traceOutput?: OutputLine[];
244
+ /** What the postconditions print, which TLC checks after the lasso's step back. */
245
+ postconditionOutput?: OutputLine[];
210
246
  loopStart: number | undefined;
211
247
  loopLabel?: string;
212
248
  message?: string;
213
249
  counts?: string;
214
250
  unwitnessed?: Postcondition;
215
- // A POSTCONDITION that is false or fails after the counterexample, which TLC checks as it
216
- // prints one.
251
+ /** A POSTCONDITION that is false or fails, which TLC checks as it prints the counterexample. */
217
252
  postcondition?: Postcondition;
218
- // What TLC warns about after a counterexample, with its code.
253
+ /** What TLC warns about after a counterexample, with its code. */
219
254
  warning?: { code: number; text: string };
220
255
  }
221
256
 
222
257
  export interface Postcondition {
223
258
  name: string;
224
- // TLC's message code.
225
259
  code: number;
226
260
  message: string;
227
261
  counts?: string;
228
262
  }
229
263
 
230
- // An evaluation that failed during the search, with the behavior up to the state TLC was working on.
264
+ /** An evaluation that failed during the search, with the behavior up to the state TLC was working on. */
231
265
  export interface EvaluationFailure {
232
- // TLC's code for the message, and its text with and without -tool.
233
266
  code: number;
234
267
  message: string;
235
268
  toolMessage: string;
@@ -237,26 +270,24 @@ export interface EvaluationFailure {
237
270
  traceOutput?: OutputLine[];
238
271
  initialState: Record<string, Value> | undefined;
239
272
  exitCode: number;
240
- // The expressions TLC was evaluating when the failure occurred, outermost first, when TLC finds
241
- // them by replaying the failure.
273
+ /** The expressions TLC was evaluating, outermost first, when its replay finds them. */
242
274
  callStack: Expression[] | undefined;
243
- // Whether TLC prints the call stack before the error, as it does for a failed liveness check.
275
+ /** Whether TLC prints the call stack before the error, as it does for a failed liveness check. */
244
276
  isCallStackFirst?: boolean;
245
- // The FingerprintException the replay raises, which TLC reports in place of the call stack.
277
+ /** The FingerprintException the replay raises, which TLC reports in place of the call stack. */
246
278
  fingerprint?: FingerprintFailure;
247
- // How TLC reports failing again as it prints the trace, since it can't fingerprint the state the
248
- // failure occurred in.
279
+ /** How TLC reports failing again as it prints the trace, since it can't fingerprint the state. */
249
280
  traceFailure?: FailureMessage;
250
- // A POSTCONDITION that is false or fails after the trace, which TLC checks as it prints one.
281
+ /** A POSTCONDITION that is false or fails after the trace, which TLC checks as it prints one. */
251
282
  postcondition?: Postcondition;
252
- // Whether TLC stops before it prints the statistics, as it does for an illegal initial state.
283
+ /** Whether TLC stops before it prints the statistics, as it does for an illegal initial state. */
253
284
  isWithoutStatistics?: boolean;
254
285
  }
255
286
 
256
- // Where TLC's replay of a failure fails.
257
287
  interface ReplayFailure {
258
288
  callStack: Expression[];
259
289
  fingerprint: FingerprintFailure | undefined;
290
+ replayError?: TlaEvaluationError;
260
291
  }
261
292
 
262
293
  export interface InitialStates {
@@ -272,23 +303,24 @@ export interface CheckResult {
272
303
  distinctStates: number;
273
304
  queuedStates: number;
274
305
  depth: number;
275
- // How many initial states TLC generated and how many of them were distinct, once it computed
276
- // them all without a violation or an error.
306
+ /** Once TLC computed all the initial states without a violation or an error. */
277
307
  initialStates: InitialStates | undefined;
278
- // How many states that TLC counts as expanded found each number of new states, when TLC prints
279
- // the outdegree of the state graph.
308
+ /** How many expanded states found each number of new states, when TLC prints the outdegree. */
280
309
  outDegrees: number[] | undefined;
281
- // The smallest distance between the fingerprints of two distinct states, when TLC estimates a
282
- // collision from the actual fingerprints.
310
+ /** The smallest distance between two fingerprints, when TLC estimates a collision from them. */
283
311
  fingerprintDistance: bigint | undefined;
284
- // A temporal property TLC finds violated as it adds a deadlocked state to the behavior graph,
285
- // which it reports after the deadlock.
312
+ /** A temporal property TLC finds violated as it adds a deadlocked state, reported after. */
286
313
  additionalViolation?: Violation;
287
- // 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. */
288
315
  liveCallStack?: Expression[];
289
- // How many states that TLC counts as expanded found each number of new states, when its workers
290
- // stop on a violation without an error code, which TLC 1.7.4 reports as a successful search.
316
+ /** The outdegrees when TLC's workers stop on a violation that TLC 1.7.4 reports as a success. */
291
317
  violationOutDegrees?: number[];
318
+ traceSpec?: string;
319
+ coverage?: CoverageReport;
320
+ }
321
+
322
+ interface CoveredAction extends SpecAction {
323
+ node: number;
292
324
  }
293
325
 
294
326
  interface Behavior {
@@ -301,21 +333,37 @@ interface TraceOptions {
301
333
  known?: number;
302
334
  }
303
335
 
336
+ interface ReportedViolation extends Omit<Violation, "loopStart"> {
337
+ loopStart?: number;
338
+ }
339
+
340
+ interface RebuiltState {
341
+ state: Value[];
342
+ level: number;
343
+ }
344
+
345
+ interface SearchPosition {
346
+ index: number;
347
+ isExpanding: boolean;
348
+ candidate: Value[] | undefined;
349
+ candidateLevel: number;
350
+ livenessSource: number;
351
+ rebuilt: RebuiltState | undefined;
352
+ }
353
+
304
354
  interface FailureOptions {
305
355
  initialState?: Value[];
306
356
  isInitial?: boolean;
307
357
  outDegrees?: number[];
308
358
  callStack?: Expression[];
309
359
  fingerprint?: FingerprintFailure;
360
+ replayError?: TlaEvaluationError;
310
361
  isNextState?: boolean;
311
362
  isCallStackFirst?: boolean;
312
363
  traceFailure?: FailureMessage;
313
- // Whether the call stack is of adding the state to the behavior graph, which TLC prints instead
314
- // of replaying the error.
315
364
  isLiveCallStack?: boolean;
316
365
  }
317
366
 
318
- // TLC prints what the spec prints as it replays a failure after the trace.
319
367
  const appendTraceOutput = <Traced extends Behavior>(behavior: Traced, lines: OutputLine[]) => ({
320
368
  ...behavior,
321
369
  traceOutput: [...(behavior.traceOutput ?? []), ...lines],
@@ -324,52 +372,24 @@ const appendTraceOutput = <Traced extends Behavior>(behavior: Traced, lines: Out
324
372
  const INITIAL_RECOVERY_FAILURE = "Failed to recover the initial state from its fingerprint.";
325
373
  const NEXT_RECOVERY_FAILURE = "Failed to recover the next state from its fingerprint.";
326
374
 
327
- const toAliasRecord = (value: Value, fieldOrder: string[]) => {
328
- if (!isFunctionValue(value)) return undefined;
329
- const record = toFiniteFunction(value);
330
- if (!record.domain.every((key) => typeof key === "string")) return undefined;
331
- const entries = record.domain.map((key, index): [string, Value] => [
332
- String(key),
333
- record.range[index],
334
- ]);
335
- return Object.fromEntries(
336
- entries.sort((left, right) => fieldOrder.indexOf(left[0]) - fieldOrder.indexOf(right[0])),
337
- );
338
- };
339
-
340
- // Stops a replay where TLC stops it without a failure, as at a violated invariant.
341
375
  const STOP_REPLAY = new Error("The replay stopped");
376
+ const STOP_WALK = new Error("The walk stopped");
342
377
 
343
- // The codes of the errors in the configuration and the spec that TLC's EC.ExitStatus maps to a
344
- // configuration error.
345
- const CONFIG_ERROR_CODES = new Set([
346
- ...Array.from({ length: 24 }, (_, index) => 2222 + index),
347
- 2272,
348
- 2273,
349
- 2274,
350
- 2280,
351
- 2281,
352
- ]);
353
-
354
- // When TLC's replay of the initial states doesn't fail again, it exits with the code of the
355
- // TLCRuntimeException it reported.
356
378
  const getInitialExitCode = (error: TlaEvaluationError) => {
357
379
  const coded = getCodedMessage(error.message);
358
- return coded && !coded.isEvalException && CONFIG_ERROR_CODES.has(coded.code)
380
+ return coded &&
381
+ !coded.isEvalException &&
382
+ getMessageExitStatus(coded.code) === EXIT_STATUS.configParseError
359
383
  ? EXIT_STATUS.configParseError
360
384
  : getErrorExitCode(error);
361
385
  };
362
386
 
363
- // When TLC's replay of an error fails again, an EvalException from a standard module's Java code
364
- // decides the exit status, and any other failure exits as a nested expression failure. An error
365
- // that heads or wraps another exits as the other.
366
387
  const getReplayExitCode = (error: TlaEvaluationError): number => {
367
388
  const inner = error.cause;
368
389
  if (inner instanceof TlaEvaluationError) return getReplayExitCode(inner);
369
390
  return error instanceof TlaModuleError ? error.exitCode : EXIT_STATUS.specEvaluationFailure;
370
391
  };
371
392
 
372
- // TLC finishes the -dump file whether or not the search finds a violation.
373
393
  export const checkSequentially = (options: CheckOptions): CheckResult => {
374
394
  const stateWriter =
375
395
  options.dump && createStateWriter(options.dump, options.writeFile, options.version);
@@ -382,8 +402,6 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
382
402
  }
383
403
  };
384
404
 
385
- // TLC checks liveness on the graph so far 3 seconds into the search and then every minute, once
386
- // the graph has grown by a tenth and liveness checking has taken at most a fifth of the time.
387
405
  const PERIODIC_START = 3000;
388
406
  const PROGRESS_INTERVAL = 60_000;
389
407
  const LIVENESS_GROWTH = 0.1;
@@ -395,42 +413,58 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
395
413
  ? parseConfig(options.config, options.version)
396
414
  : options.config;
397
415
  const onPrint = options.onPrint ?? console.log;
398
- // TLC prints again while it rebuilds a trace, between the states it prints, so rebuilding a trace
399
- // keeps what it prints for the trace.
400
- const capturedOutput = { lines: undefined as OutputLine[] | undefined };
416
+ let capturedLines: OutputLine[] | undefined;
401
417
  const print = (text: string) => {
402
- if (capturedOutput.lines) capturedOutput.lines.push(text);
418
+ if (capturedLines) capturedLines.push(text);
403
419
  else onPrint(text);
404
420
  };
405
421
  const captureOutput = <Result>(rebuild: () => Result) => {
406
- const outer = capturedOutput.lines;
422
+ const outer = capturedLines;
407
423
  const lines: OutputLine[] = [];
408
- capturedOutput.lines = lines;
424
+ capturedLines = lines;
409
425
  try {
410
426
  return { result: rebuild(), lines };
411
427
  } finally {
412
- capturedOutput.lines = outer;
428
+ capturedLines = outer;
413
429
  }
414
430
  };
415
431
  const order = createTlcOrder(options.source, options.loadModule);
416
432
  setStringOrder(order.getStringOrder(config));
417
- setValueVersion(options.version);
433
+ setValueOptions(options);
434
+ setFingerprintPolynomial(options.fingerprintPolynomial ?? 0);
418
435
  const specification = createEnvironment(config, {
419
436
  source: options.source,
420
437
  loadModule: options.loadModule,
421
438
  order,
422
439
  loadClass: options.loadClass,
423
440
  print,
424
- files: { readFile: options.readFile, writeFile: options.writeFile },
441
+ files: {
442
+ readFile: options.readFile,
443
+ writeFile: options.writeFile,
444
+ makeDirectory: options.makeDirectory,
445
+ },
425
446
  seed: options.seed,
426
447
  isTool: options.isTool,
427
- isTraceRecorded: options.isTraceRecorded,
448
+ traceFile: options.traceSpec?.traceFile,
428
449
  isSanyReported: options.isSanyReported,
429
450
  isWarningEnabled: options.isWarningEnabled,
430
451
  version: options.version,
452
+ moduleOperators: options.moduleOperators,
431
453
  });
432
454
  reportStartup(specification, config, options.onProgress);
433
- const environment = specification.environment;
455
+ const coverage =
456
+ options.coverage === undefined
457
+ ? undefined
458
+ : createCoverage(specification.environment.variables.length);
459
+ const environment: Environment = coverage
460
+ ? {
461
+ ...specification.environment,
462
+ evaluators: new WeakMap(),
463
+ entryEvaluators: new WeakMap(),
464
+ definitionEvaluators: new WeakMap(),
465
+ coverage,
466
+ }
467
+ : specification.environment;
434
468
  const runtime = environment.runtime;
435
469
  const is174 = runtime.version === "1.7.4";
436
470
  runtime.pause = options.onPause ?? (() => {});
@@ -441,35 +475,63 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
441
475
  specification.variableLocations,
442
476
  specification.instanceActions,
443
477
  );
444
- const statistics = { depth: 0, initialStates: undefined as InitialStates | undefined };
478
+ let searchDepth = 0;
479
+ let computedInitialStates: InitialStates | undefined;
480
+ const getTraceSpec = (trace: TraceStep[], loopStart: number | undefined) =>
481
+ options.traceSpec &&
482
+ writeTraceSpec({
483
+ module: options.traceSpec.module,
484
+ specName: specification.rootName,
485
+ rawConstants: config.rawConstants,
486
+ states: trace.map((step) => getStepState(step)),
487
+ loopStart,
488
+ modelValues: getModelValues().map((value) => value.name),
489
+ isDefined: (name) =>
490
+ environment.definitions.has(name) ||
491
+ environment.constants.has(name) ||
492
+ [...environment.definitions.keys()].some((key) =>
493
+ key.startsWith(`${name}${KEY_SEPARATOR}`),
494
+ ),
495
+ });
445
496
  const createResult = (
446
497
  status: CheckStatus,
447
- violation?: Omit<Violation, "loopStart"> & { loopStart?: number },
498
+ violation?: ReportedViolation,
448
499
  failure?: EvaluationFailure,
449
- ): CheckResult => ({
450
- status,
451
- violation: violation && { ...violation, loopStart: violation.loopStart },
452
- failure,
453
- generatedStates: runtime.generatedStates,
454
- distinctStates: runtime.distinctStates,
455
- queuedStates: runtime.queueSize,
456
- depth: runtime.generatedStates === 0 ? 0 : Math.max(statistics.depth, 1),
457
- initialStates: statistics.initialStates,
458
- outDegrees: undefined,
459
- fingerprintDistance: undefined,
460
- });
500
+ ): CheckResult => {
501
+ const traceSpec = getTraceSpec(
502
+ violation?.trace ?? failure?.trace ?? [],
503
+ status === "property-violation" ? undefined : violation?.loopStart,
504
+ );
505
+ return {
506
+ status,
507
+ violation: violation && { ...violation, loopStart: violation.loopStart },
508
+ failure,
509
+ generatedStates: runtime.generatedStates,
510
+ distinctStates: runtime.distinctStates,
511
+ queuedStates: runtime.queueSize,
512
+ depth: runtime.generatedStates === 0 ? 0 : Math.max(searchDepth, 1),
513
+ initialStates: computedInitialStates,
514
+ outDegrees: undefined,
515
+ fingerprintDistance: undefined,
516
+ coverage: coverage?.relations.some((relation) => relation.kind === "next")
517
+ ? getCoverageReport(
518
+ coverage,
519
+ environment,
520
+ specification.variableLocations,
521
+ search?.getTlcOrder() ?? [],
522
+ )
523
+ : undefined,
524
+ ...(traceSpec !== undefined && { traceSpec }),
525
+ };
526
+ };
461
527
  const outDegrees = Array.from({ length: OUT_DEGREE_BUCKETS }, () => 0);
462
- const expansion = { newStates: 0 };
463
- const getOutDegreeBucket = () => Math.min(expansion.newStates, OUT_DEGREE_BUCKETS - 1);
464
- // TLC counts the state it was expanding when an evaluation failed, except TLC 1.7.4, whose
465
- // worker stops before it counts the state.
528
+ let newStateCount = 0;
529
+ const getOutDegreeBucket = () => Math.min(newStateCount, OUT_DEGREE_BUCKETS - 1);
466
530
  const getPartialOutDegrees = () =>
467
531
  outDegrees.map((count, degree) => (degree === getOutDegreeBucket() ? count + 1 : count));
468
532
  const getFailureOutDegrees = () => (is174 ? [...outDegrees] : getPartialOutDegrees());
469
- // TLC 1.7.4 doesn't name the properties a counterexample violates, so it evaluates none of them.
470
533
  const getViolatedProperties = (checker: LivenessChecker, path: Value[][], cycleStart: number) =>
471
534
  is174 ? [] : checker.getViolatedProperties(path, cycleStart);
472
- // A violation in a successor ends the expansion of a state before TLC counts it.
473
535
  const withOutDegrees = (result: CheckResult, degrees = [...outDegrees]): CheckResult => ({
474
536
  ...result,
475
537
  violationOutDegrees: degrees,
@@ -490,8 +552,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
490
552
  const search = createSearch(
491
553
  config,
492
554
  environment,
555
+ specification.variableLocations,
493
556
  () => order.getDeclarationOrder("variable"),
494
557
  options.onProgress,
558
+ specification.moduleOperators,
495
559
  );
496
560
  const findViolatedAssumption = () =>
497
561
  findAssumptionViolation(specification.assumptions, environment);
@@ -499,18 +563,18 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
499
563
  runtime.isStarted = true;
500
564
  const assumptionViolation = findViolatedAssumption();
501
565
  if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
502
- // TLC computes the initial states of a spec without variables, of which there are none.
503
- statistics.initialStates = { generated: 0, distinct: 0 };
566
+ computedInitialStates = { generated: 0, distinct: 0 };
504
567
  options.onProgress?.({ kind: "initial-states-started" });
505
568
  options.onProgress?.({
506
569
  kind: "initial-states-computed",
507
- initialStates: statistics.initialStates,
570
+ initialStates: computedInitialStates,
508
571
  });
509
572
  return createSuccess();
510
573
  }
511
- const hasPostconditions = config.postconditions.length > 0 || config.possible.length > 0;
512
- // The state of each step of a trace without the alias, and the action TLC finds for the step,
513
- // which CounterExample records.
574
+ const hasPostconditions =
575
+ config.postconditions.length > 0 ||
576
+ config.possible.length > 0 ||
577
+ specification.moduleOperators.some((operator) => operator.kind === "postcondition");
514
578
  const traceSteps = new WeakMap<
515
579
  TraceStep,
516
580
  { state: Record<string, Value>; action: SpecAction | undefined }
@@ -520,8 +584,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
520
584
  const action = traceSteps.get(step)?.action;
521
585
  return action ? toActionValue(action) : createActionRecord(step.action);
522
586
  };
523
- // Worker#printTrace checks the postconditions on the CounterExample of each trace it prints, so
524
- // what they print follows the trace.
525
587
  const checkTracePostconditions = (
526
588
  trace: TraceStep[],
527
589
  loop: { start: number; action: Value } | undefined,
@@ -541,7 +603,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
541
603
  };
542
604
  const reportViolation = (
543
605
  status: CheckStatus,
544
- violation: Omit<Violation, "loopStart"> & { loopStart?: number },
606
+ violation: ReportedViolation,
545
607
  getLoopAction?: () => Value,
546
608
  ) => {
547
609
  const start = violation.loopStart;
@@ -549,26 +611,103 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
549
611
  violation.trace,
550
612
  start === undefined || !getLoopAction ? undefined : { start, action: getLoopAction() },
551
613
  );
552
- const traceOutput = [...(violation.traceOutput ?? []), ...checked.lines];
553
614
  return createResult(status, {
554
615
  ...violation,
555
- ...(traceOutput.length > 0 && { traceOutput }),
616
+ ...(checked.lines.length > 0 && { postconditionOutput: checked.lines }),
556
617
  ...(checked.unwitnessed && { unwitnessed: checked.unwitnessed }),
557
618
  ...(checked.postcondition && { postcondition: checked.postcondition }),
558
619
  });
559
620
  };
560
- // With -continue, TLC prints the trace of a violation without checking the postconditions.
561
- const reportContinuedViolation = (status: CheckStatus, violation: Omit<Violation, "loopStart">) =>
621
+ // Deviation from TLC: -continue ends with the status of the first violation, not a success.
622
+ let continuedStatus: CheckStatus | undefined;
623
+ const reportContinuedViolation = (
624
+ status: CheckStatus,
625
+ violation: Omit<Violation, "loopStart">,
626
+ ) => {
627
+ continuedStatus ??= status;
562
628
  options.onProgress?.({
563
629
  kind: "violation",
564
630
  status,
565
631
  violation: { ...violation, loopStart: undefined },
566
632
  });
633
+ };
567
634
  const spec = search.spec;
568
635
  const getFingerprintState = search.getFingerprintState;
569
- const specNextActions = { value: undefined as SpecAction[] | undefined };
636
+ let specNextActions: SpecAction[] | undefined;
570
637
  const getSpecNextActions = () =>
571
- (specNextActions.value ??= getNextActions(config, environment, specification.instanceActions));
638
+ (specNextActions ??= getNextActions(config, environment, specification.instanceActions));
639
+ // Tool's constructor splits the next-state relation into actions before TLC checks anything.
640
+ getSpecNextActions();
641
+ runtime.getSuccessorAction = (state, next) =>
642
+ getSpecNextActions().find((action) =>
643
+ getSuccessors(action.expression, state, environment, action.scope).some((successor) =>
644
+ successor.state.every((value, index) => isSameValue(value, next[index])),
645
+ ),
646
+ );
647
+ const addCoverageRelations = (kind: "init" | "next", actions: SpecAction[]) =>
648
+ actions.map((action): CoveredAction => ({
649
+ ...action,
650
+ node: coverage
651
+ ? addCoverageRelation(
652
+ coverage,
653
+ kind,
654
+ getCoverageLabel(action.name, action.expression, environment),
655
+ action.expression,
656
+ action.scope,
657
+ )
658
+ : -1,
659
+ }));
660
+ const coverageInits = addCoverageRelations(
661
+ "init",
662
+ coverage ? getInitActions(config, environment, specification.instanceActions) : [],
663
+ );
664
+ const coverageActions = addCoverageRelations("next", coverage ? getSpecNextActions() : []);
665
+ if (coverage) buildCoverage(coverage, environment, getPrimedRanges(coverageActions, environment));
666
+ const walkCoveredSuccessors = (
667
+ action: CoveredAction,
668
+ state: Value[],
669
+ onState: (successor: Value[]) => void,
670
+ ) =>
671
+ walkSuccessors(
672
+ action,
673
+ action.node,
674
+ state,
675
+ environment,
676
+ (successor) => {
677
+ if (coverage) coverage.primary[action.node]++;
678
+ onState(successor);
679
+ },
680
+ (partial) => {
681
+ const missing = environment.variables.filter(
682
+ (_variable, index) => partial[index] === undefined,
683
+ );
684
+ throw new TlaIncompleteSuccessorError(
685
+ `Successor state is not completely specified by action ${action.name}. The following variables are not assigned: ${missing.join(", ")}`,
686
+ partial,
687
+ action.name,
688
+ missing,
689
+ );
690
+ },
691
+ );
692
+ const getCoveredSuccessors = (action: CoveredAction, state: Value[]) => {
693
+ const successors: Successor[] = [];
694
+ walkCoveredSuccessors(action, state, (successor) =>
695
+ successors.push({ state: successor, action: action.name }),
696
+ );
697
+ return successors;
698
+ };
699
+ const getCoveredInitialStates = () => {
700
+ const initialStates: Value[][] = [];
701
+ replayInitialStates(
702
+ coverageInits,
703
+ environment,
704
+ (state) => initialStates.push(state),
705
+ (partial) => {
706
+ throw setExitCode(new TlaIllegalStateError([...partial]), EXIT_STATUS.error);
707
+ },
708
+ );
709
+ return initialStates;
710
+ };
572
711
  const getReplayFailure = (replay: (tracing: Environment) => void): ReplayFailure | undefined => {
573
712
  const tracing = createTracingEnvironment(environment);
574
713
  const callStack = tracing.callStack;
@@ -576,14 +715,15 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
576
715
  replay(tracing);
577
716
  return undefined;
578
717
  } catch (error) {
579
- // A replay that overflows the stack again has an empty call stack.
580
718
  if (isStackOverflow(error)) return { callStack: [], fingerprint: undefined };
581
719
  if (!(error instanceof TlaEvaluationError) || !callStack) return undefined;
582
- return { callStack: callStack.expressions, fingerprint: callStack.fingerprint };
720
+ return {
721
+ callStack: callStack.expressions,
722
+ fingerprint: callStack.fingerprint,
723
+ replayError: error,
724
+ };
583
725
  }
584
726
  };
585
- // The sources of the values a fingerprint fails inside, outermost first: each value fails as it
586
- // fingerprints a value it holds.
587
727
  const findFailedSources = (value: Value, sources: CallStack["sources"]): Expression[] => {
588
728
  if (typeof value !== "object") return [];
589
729
  const source = sources.get(value);
@@ -593,14 +733,11 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
593
733
  ...(failed === undefined ? [] : findFailedSources(failed, sources)),
594
734
  ];
595
735
  };
596
- // TLC's replay fingerprints the states it finds, and a value the replay built raises a
597
- // FingerprintException when it fails to.
598
736
  const fingerprintReplayed = (state: Value[], callStack: CallStack | undefined) => {
599
737
  for (const value of getFingerprintState(state)) {
600
738
  const error = getFingerprintError(value);
601
739
  if (!error) continue;
602
740
  const sources = callStack ? findFailedSources(value, callStack.sources) : [];
603
- // TLC fingerprints a state outside any evaluation, so its call stack is empty.
604
741
  if (callStack && sources.length > 0) {
605
742
  callStack.expressions.length = 0;
606
743
  callStack.isFrozen = true;
@@ -610,10 +747,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
610
747
  }
611
748
  state.forEach(markFingerprinted);
612
749
  };
613
- // The replay adds the states it hasn't seen to TLC's set of states, which already holds the state
614
- // that failed after TLC added it.
615
750
  const createReplayedStates = () => {
616
- const replayed = unstoredState.fingerprint ? [unstoredState.fingerprint] : [];
751
+ const replayed = unstoredFingerprint ? [unstoredFingerprint] : [];
617
752
  return (state: Value[], callStack: CallStack | undefined) => {
618
753
  fingerprintReplayed(state, callStack);
619
754
  const fingerprintState = getFingerprintState(state);
@@ -626,23 +761,18 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
626
761
  return true;
627
762
  };
628
763
  };
629
- // TLC's DoInitFunctor reports its progress again as it replays the initial states, and adds each
630
- // one it hasn't seen to the behavior graph. After a FingerprintException, it only counts the
631
- // states left, then throws the exception.
632
764
  const replayInit = () => {
633
- const replayed = { count: 0 };
634
- const deferred: TlaEvaluationError[] = [];
765
+ let replayedCount = 0;
766
+ const deferred: unknown[] = [];
635
767
  const addReplayed = createReplayedStates();
636
768
  return getReplayFailure((tracing) => {
637
769
  replayInitialStates(
638
770
  getInitActions(config, environment, specification.instanceActions),
639
771
  tracing,
640
772
  (state) => {
641
- reportInitialStatesProgress(replayed.count, (progress) =>
642
- capturedOutput.lines?.push(progress),
643
- );
644
- replayed.count++;
645
- runtime.generatedStates = replayed.count;
773
+ reportInitialStatesProgress(replayedCount, (progress) => capturedLines?.push(progress));
774
+ replayedCount++;
775
+ runtime.generatedStates = replayedCount;
646
776
  if (deferred.length > 0) return;
647
777
  try {
648
778
  const addFingerprint = () => {
@@ -653,7 +783,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
653
783
  const violation = search.checkReplayedInitialState(state, tracing, addFingerprint);
654
784
  if (violation) {
655
785
  const traced = toTrace([{ action: undefined, state }], []).trace[0].state;
656
- capturedOutput.lines?.push({
786
+ capturedLines?.push({
657
787
  kind: "initial-state-violation",
658
788
  ...violation,
659
789
  state: traced,
@@ -661,9 +791,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
661
791
  throw STOP_REPLAY;
662
792
  }
663
793
  } catch (error) {
664
- if (!(error instanceof TlaEvaluationError) || !tracing.callStack?.fingerprint) {
665
- throw error;
666
- }
794
+ const isFingerprintFailure =
795
+ error instanceof TlaEvaluationError && tracing.callStack?.fingerprint !== undefined;
796
+ if (!isFingerprintFailure && !isStackOverflow(error)) throw error;
667
797
  deferred.push(error);
668
798
  }
669
799
  },
@@ -671,8 +801,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
671
801
  if (deferred.length > 0) throw deferred[0];
672
802
  });
673
803
  };
674
- // TLC replays the expansion of a state with ModelChecker.doNext, which writes each successor in
675
- // the model to the -dump state graph again.
676
804
  const replayNext = (index: number) =>
677
805
  getReplayFailure((tracing) => {
678
806
  const state = states[index];
@@ -686,9 +814,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
686
814
  source,
687
815
  getGraphState(next, depths[index] + 1),
688
816
  !isUnseen,
689
- isNamingEdges
690
- ? { name: action.name, signature: getActionSignature(action) }
691
- : undefined,
817
+ isNamingEdges ? getGraphAction(action) : undefined,
692
818
  );
693
819
  }
694
820
  return isUnseen;
@@ -700,7 +826,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
700
826
  });
701
827
  const isReducing = config.view !== undefined || config.symmetry !== undefined;
702
828
  const tlcFingerprints: number[] = [];
703
- // TLC warns about the liveness checker before it builds it.
704
829
  if (search.properties.liveness.length > 0) {
705
830
  options.onProgress?.({
706
831
  kind: "liveness-initializing",
@@ -711,39 +836,42 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
711
836
  const liveness = withLivenessExitCode(() =>
712
837
  withUnexpectedException(() =>
713
838
  createLivenessChecker(search.properties.liveness, spec.temporals, environment, {
714
- getFingerprint: ({ index, state }) =>
715
- (tlcFingerprints[index] ??= Number(BigInt.asIntN(32, runtime.getFingerprint(state)))),
839
+ getFingerprint: (successor) =>
840
+ (tlcFingerprints[successor.index] ??= Number(
841
+ BigInt.asIntN(32, runtime.getFingerprint(successor.state)),
842
+ )),
716
843
  getSuccessors: (source, state) => {
717
844
  const successors: LiveSuccessor[] = [];
718
845
  if (spec.next === undefined) return successors;
719
- // The constraints read the level of the state whose successors they check, as when TLC
720
- // explored it.
721
846
  const livenessSource = current.livenessSource;
722
847
  current.livenessSource = source;
723
- forEachSuccessor(
724
- spec.next,
725
- state,
726
- environment,
727
- (successor) => {
728
- canonicalizeState(successor.state);
729
- const isInModel =
730
- search.satisfiesConstraints(successor.state, state) &&
731
- search.satisfiesActionConstraints(state, successor.state);
732
- if (!isInModel) return false;
733
- const fingerprintState = getFingerprintState(successor.state);
734
- const index = findStateIndex(getStateHash(fingerprintState), fingerprintState);
735
- successors.push({ index, state: successor.state });
736
- return false;
737
- },
738
- spec.scope,
739
- );
740
- current.livenessSource = livenessSource;
848
+ try {
849
+ forEachSuccessor(
850
+ spec.next,
851
+ state,
852
+ environment,
853
+ (successor) => {
854
+ canonicalizeState(successor.state);
855
+ const isInModel =
856
+ search.satisfiesConstraints(successor.state, state) &&
857
+ search.satisfiesActionConstraints(state, successor.state);
858
+ if (!isInModel) return false;
859
+ const fingerprintState = getFingerprintState(successor.state);
860
+ const index = findStateIndex(getStateHash(fingerprintState), fingerprintState);
861
+ successors.push({ index, state: successor.state });
862
+ return false;
863
+ },
864
+ spec.scope,
865
+ );
866
+ } finally {
867
+ current.livenessSource = livenessSource;
868
+ }
741
869
  return successors;
742
870
  },
743
871
  }),
744
872
  ),
745
873
  );
746
- // TLC 1.7.4 creates its model checker, which TLCGet reads, once it has built the liveness checker.
874
+ if (liveness?.branches === 0) throw createTautologyError();
747
875
  runtime.isStarted = true;
748
876
  const isCanonicalizedFirst = search.isSymmetric || liveness !== undefined;
749
877
 
@@ -752,64 +880,61 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
752
880
  const parents: number[] = [];
753
881
  const actions: (string | undefined)[] = [];
754
882
  const depths: number[] = [];
755
- // A Map holds at most 2^24 entries, so an open-addressing table keeps each seen state's hash
756
- // and its index plus one side by side, probed by the hash.
883
+ // A Map holds at most 2^24 entries, so an open-addressing table keeps each hash and index + 1.
757
884
  const seenStates = { slots: new Int32Array(1 << 17), size: 0, shift: 16 };
758
885
  const canonicalizeState = createCanonicalizer();
759
886
 
760
- const toRecord = (state: Value[]): Record<string, Value> =>
761
- Object.fromEntries(
762
- search.getTlcOrder().map((index) => [environment.variables[index], state[index]]),
763
- );
887
+ const toRecord = search.toRecord;
764
888
  const getAliasState = (
765
889
  alias: string,
766
890
  steps: Successor[],
767
891
  position: number,
768
892
  loopStart: number | undefined,
769
893
  ) => {
770
- // TLC evaluates TLCGet("level") and Trace in an alias at the state's position in the trace.
894
+ const searchLevel = runtime.getLevel;
895
+ const searchBehavior = runtime.getBehavior;
771
896
  runtime.getLevel = () => position + 1;
772
897
  runtime.getBehavior = () => steps.slice(0, position + 1).map((step) => step.state);
773
- return evaluateAlias(
774
- alias,
775
- steps[position].state,
776
- (steps[position + 1] ?? steps[loopStart ?? position]).state,
777
- );
778
- };
779
- const evaluateAlias = (alias: string, state: Value[], next: Value[] | undefined) => {
780
898
  try {
781
- const body = getConfigDefinition("alias", alias, environment).body;
782
- const value = evaluate(createIdentifier(alias), getContext(environment, state, next));
783
- const fieldOrder = body.kind === "Record" ? body.fields.map((field) => field.name) : [];
784
- return toAliasRecord(value, fieldOrder) ?? toRecord(state);
785
- } catch (error) {
786
- if (!(error instanceof TlaConfigError || error instanceof TlaEvaluationError)) throw error;
787
- return {
788
- ...toRecord(state),
789
- _ALIASEvalError: formatNestedMessage(error.message, options.isTool ?? false),
790
- };
899
+ return evaluateAlias(
900
+ alias,
901
+ steps[position].state,
902
+ (steps[position + 1] ?? steps[loopStart ?? position]).state,
903
+ );
904
+ } finally {
905
+ runtime.getLevel = searchLevel;
906
+ runtime.getBehavior = searchBehavior;
791
907
  }
792
908
  };
793
- // TLC finds the action of a step as the first action that takes it, evaluated as when the search
794
- // expanded the previous state, by the values of a successor it holds and otherwise by fingerprint.
909
+ const evaluateAlias = (alias: string, state: Value[], next: Value[] | undefined) =>
910
+ search.evaluateAlias(alias, state, next, options.isTool ?? false);
795
911
  const findStepAction = (index: number, previous: Value[], state: Value[], isHeld: boolean) => {
796
912
  const actions = getSpecNextActions();
797
913
  const expanding = { ...current };
798
- Object.assign(current, { index, isExpanding: true, candidate: undefined });
914
+ Object.assign(current, {
915
+ index,
916
+ isExpanding: true,
917
+ candidate: undefined,
918
+ rebuilt: { state: previous, level: depths[index] },
919
+ });
799
920
  const getKey = isHeld ? (values: Value[]) => values : getFingerprintState;
800
921
  const key = getKey(state);
801
- const action = actions.find((item) =>
802
- getSuccessors(item.expression, previous, environment, item.scope).some((successor) =>
803
- isSameState(getKey(successor.state), key),
804
- ),
805
- );
806
- Object.assign(current, expanding);
807
- return action;
922
+ try {
923
+ return coverage
924
+ ? coverageActions.find((item) =>
925
+ getCoveredSuccessors(item, previous).some((successor) =>
926
+ isSameState(getKey(successor.state), key),
927
+ ),
928
+ )
929
+ : actions.find((item) =>
930
+ getSuccessors(item.expression, previous, environment, item.scope).some((successor) =>
931
+ isSameState(getKey(successor.state), key),
932
+ ),
933
+ );
934
+ } finally {
935
+ Object.assign(current, expanding);
936
+ }
808
937
  };
809
- // Before TLC prints a trace, it rebuilds from the initial predicate the states it does not keep,
810
- // all but the last `known` ones. As it prints each later step, it finds the action that takes
811
- // the step. Then it rebuilds the trace once more, unless the trace is a liveness counterexample
812
- // or TLC is 1.7.4.
813
938
  const toTrace = (
814
939
  steps: Successor[],
815
940
  path: number[],
@@ -817,9 +942,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
817
942
  ): Behavior => {
818
943
  const alias = config.alias;
819
944
  const known = traceOptions.known ?? 1;
820
- // Rebuilding the trace from the initial predicate can reset what TLCSet stored.
821
945
  const initialOutput = steps.length > 1 ? captureOutput(getSpecInitialStates).lines : [];
822
- // TLC finds the action that takes each step before it evaluates the alias.
823
946
  const stepActions = steps.map((step, position) =>
824
947
  position === 0 || step.action === "Stuttering"
825
948
  ? { result: undefined, lines: [] }
@@ -834,9 +957,24 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
834
957
  );
835
958
  const outputs = stepActions.map((step) => step.lines);
836
959
  const loopStart = traceOptions.loopStart;
837
- // 1.7.4's LiveWorker#printTrace rebuilds a lasso up to the start of its cycle at once, and then
838
- // each state of the cycle as it prints it.
839
960
  const rebuilt = is174 && loopStart !== undefined ? loopStart + 1 : steps.length - known;
961
+ if (coverage && steps.length > 1) {
962
+ const isRebuiltAgain = known > 0 && !is174;
963
+ if (rebuilt > 0 && isRebuiltAgain) captureOutput(getSpecInitialStates);
964
+ if (isRebuiltAgain) {
965
+ steps.slice(1).forEach((step, position) => {
966
+ if (step.action === "Stuttering") return;
967
+ captureOutput(() =>
968
+ findStepAction(
969
+ path[position],
970
+ steps[position].state,
971
+ step.state,
972
+ known === 2 && position === steps.length - 2,
973
+ ),
974
+ );
975
+ });
976
+ }
977
+ }
840
978
  const prefixOutput = rebuilt > 0 ? [initialOutput, ...outputs.slice(1, rebuilt)].flat() : [];
841
979
  return {
842
980
  trace: steps.map((step, position) => {
@@ -858,11 +996,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
858
996
  traceOutput: known > 0 && !is174 ? [initialOutput, ...outputs].flat() : [],
859
997
  };
860
998
  };
861
- const getSpecInitialStates = () =>
862
- spec.init === undefined ? [] : getInitialStates(spec.init, environment, spec.scope);
863
- // TLC's Tool#getState rebuilds a successor action by action, up to the first action that
864
- // generates it. A trace keeps what the spec prints as TLC rebuilds it, so finding its states
865
- // prints nothing.
999
+ const getSpecInitialStates = () => {
1000
+ if (coverage) return getCoveredInitialStates();
1001
+ return spec.init === undefined ? [] : getInitialStates(spec.init, environment, spec.scope);
1002
+ };
866
1003
  const findTraceSuccessor = (state: Value[], isMatch: (successor: Successor) => boolean) =>
867
1004
  captureOutput(() => {
868
1005
  for (const action of getSpecNextActions()) {
@@ -891,7 +1028,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
891
1028
  steps.push({ state: previous, action: "Stuttering" });
892
1029
  continue;
893
1030
  }
1031
+ const rebuilt = current.rebuilt;
1032
+ current.rebuilt = { state: previous, level: depths[path[position - 1]] };
894
1033
  const successor = findSuccessorWithFingerprint(previous, path[position]);
1034
+ current.rebuilt = rebuilt;
895
1035
  if (!successor) throw new TlaEvaluationError(nextFailure);
896
1036
  steps.push(successor);
897
1037
  }
@@ -914,24 +1054,40 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
914
1054
  : lastSuccessor.action;
915
1055
  return toTrace([...steps, { state: lastSuccessor.state, action }], path, { known: 2 });
916
1056
  };
917
- // TLC prints a lone initial state without the alias. TLCTrace#getTrace still recovers it from the
918
- // initial predicate, printing again, though TLC 1.7.4 doesn't.
1057
+ // Deviation from TLC: TLCTrace#printTrace prints a lone initial state without the alias.
919
1058
  const getStateTrace = (index: number): Behavior =>
920
1059
  parents[index] === -1
921
1060
  ? {
922
- trace: [{ action: undefined, label: undefined, state: toRecord(states[index]) }],
1061
+ trace: [
1062
+ {
1063
+ action: undefined,
1064
+ label: undefined,
1065
+ state:
1066
+ config.alias === undefined
1067
+ ? toRecord(states[index])
1068
+ : getAliasState(
1069
+ config.alias,
1070
+ [{ state: states[index], action: undefined }],
1071
+ 0,
1072
+ undefined,
1073
+ ),
1074
+ },
1075
+ ],
923
1076
  traceOutput: is174 ? [] : captureOutput(getSpecInitialStates).lines,
924
1077
  }
925
1078
  : getTrace(index);
926
- // TLC rebuilds the trace again for the postcondition after it prints a violation, but not after
927
- // an evaluation fails.
1079
+ const isUnfingerprintable = (state: Value[]) => {
1080
+ try {
1081
+ return getFingerprintState(state).some((value) => getFingerprintError(value) !== undefined);
1082
+ } catch (error) {
1083
+ if (!(error instanceof TlaEvaluationError)) throw error;
1084
+ return true;
1085
+ }
1086
+ };
928
1087
  const getFailedTrace = (index: number, successor: Successor): Behavior => ({
929
1088
  trace: getTrace(index, successor).trace,
930
1089
  });
931
- // TLC names the initial state it was checking unless a standard module's Java code failed.
932
1090
  const getFailureExitCode = (error: TlaEvaluationError, failureOptions: FailureOptions) => {
933
- // TLC 1.7.4 exits with the result of its replay of the initial states, which only fails again
934
- // when the error isn't in adding a state it has already seen to the behavior graph.
935
1091
  if (
936
1092
  failureOptions.isInitial &&
937
1093
  !failureOptions.callStack &&
@@ -944,17 +1100,14 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
944
1100
  return failureOptions.isInitial ? getInitialExitCode(error) : getErrorExitCode(error);
945
1101
  }
946
1102
  if (failureOptions.isCallStackFirst) return getErrorExitCode(error);
947
- // Without a replay, TLC exits with the code of the error, as for any error it didn't expect.
948
1103
  if (failureOptions.isLiveCallStack) {
949
1104
  return (
950
1105
  getExitCode(error) ?? (error instanceof TlaModuleError ? error.exitCode : EXIT_STATUS.error)
951
1106
  );
952
1107
  }
953
- // TLC exits with the code of a failed replay of the initial states regardless of the error, as
954
- // it does for a replay that fails to fingerprint.
955
1108
  return failureOptions.isInitial || failureOptions.fingerprint
956
1109
  ? EXIT_STATUS.specEvaluationFailure
957
- : getReplayExitCode(error);
1110
+ : getReplayExitCode(failureOptions.replayError ?? error);
958
1111
  };
959
1112
  const createFailureResult = (
960
1113
  failed: unknown,
@@ -988,21 +1141,25 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
988
1141
  outDegrees: failureOptions.outDegrees,
989
1142
  };
990
1143
  };
991
- // TLC reports a successor state that an action leaves incomplete with the trace to it, which ends
992
- // with the partial state. It names the action when the next-state relation has several.
993
1144
  const reportIncompleteSuccessor = (index: number, error: TlaIncompleteSuccessorError) => {
994
1145
  runtime.generatedStates++;
995
1146
  const actions = getSpecNextActions();
1147
+ const named =
1148
+ actions.length === 1 ? actions : actions.filter((item) => item.name === error.action);
996
1149
  const action =
997
- actions.length === 1 ? actions[0] : actions.find((item) => item.name === error.action);
998
- const missing = error.variables;
999
- const subject =
1000
- actions.length === 1
1001
- ? "the next-state action"
1002
- : `action ${error.action} of the next-state relation`;
1003
- // TLC 1.7.4 says a variable is not assigned rather than not defined.
1004
- const verb = is174 ? "assigned" : "defined";
1005
- const message = `Successor state is not completely specified by ${subject}. The following variable${missing.length > 1 ? "s are" : " is"} not ${verb}: ${missing.join(", ")}.\n`;
1150
+ named.length === 1
1151
+ ? named[0]
1152
+ : captureOutput(() =>
1153
+ named.find((item) =>
1154
+ hasIncompleteSuccessor(item.expression, states[index], environment, item.scope),
1155
+ ),
1156
+ ).result;
1157
+ const message = getIncompleteSuccessorMessage(
1158
+ error.variables,
1159
+ error.action,
1160
+ actions.length,
1161
+ options.version,
1162
+ );
1006
1163
  const undefinedValue = createModelValue("null");
1007
1164
  const partial = error.state.map((value) => value ?? undefinedValue);
1008
1165
  const failure = createFailureResult(error, getStateTrace(index));
@@ -1042,7 +1199,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1042
1199
  hash = combineHash(hash, getValueHash(state[index]));
1043
1200
  return hash & 0x3fffffff;
1044
1201
  };
1045
- // TLC fingerprints a state once it finds the state in the model.
1046
1202
  const fingerprintModelState = (state: Value[]) => {
1047
1203
  for (const value of state) {
1048
1204
  const error = getFingerprintError(value);
@@ -1085,12 +1241,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1085
1241
  }
1086
1242
  insertSeen(hash, index + 1);
1087
1243
  };
1088
- // A new successor that TLC has added to its set of states before it checks the successor, which
1089
- // the check stores after.
1090
- const unstoredState = { fingerprint: undefined as Value[] | undefined };
1244
+ let unstoredFingerprint: Value[] | undefined;
1091
1245
  const countDistinctState = (depth: number) => {
1092
1246
  runtime.distinctStates = states.length + 1;
1093
- statistics.depth = Math.max(statistics.depth, depth);
1247
+ searchDepth = Math.max(searchDepth, depth);
1094
1248
  runtime.diameter = Math.max(runtime.diameter, depth);
1095
1249
  };
1096
1250
  const addState = (
@@ -1107,12 +1261,13 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1107
1261
  depths.push(depth);
1108
1262
  };
1109
1263
 
1110
- const current = {
1264
+ const current: SearchPosition = {
1111
1265
  index: -1,
1112
1266
  isExpanding: false,
1113
- candidate: undefined as Value[] | undefined,
1267
+ candidate: undefined,
1114
1268
  candidateLevel: 0,
1115
1269
  livenessSource: -1,
1270
+ rebuilt: undefined,
1116
1271
  };
1117
1272
  const getPath = (index: number): Value[][] =>
1118
1273
  index === -1 ? [] : [...getPath(parents[index]), states[index]];
@@ -1130,11 +1285,12 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1130
1285
  };
1131
1286
  runtime.getLevel = (state) => {
1132
1287
  const source = current.livenessSource;
1133
- // TLC 1.7.4 reads the level of the state its worker explores, whichever state it evaluates.
1134
1288
  if (is174) {
1135
1289
  const explored = source !== -1 ? source : current.isExpanding ? current.index : -1;
1136
1290
  return explored === -1 ? 0 : depths[explored];
1137
1291
  }
1292
+ const rebuilt = current.rebuilt;
1293
+ if (rebuilt) return state === rebuilt.state ? rebuilt.level : rebuilt.level + 1;
1138
1294
  if (source !== -1) return state === states[source] ? depths[source] : depths[source] + 1;
1139
1295
  if (state === current.candidate) return current.candidateLevel;
1140
1296
  if (current.index === -1) return 0;
@@ -1142,6 +1298,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1142
1298
  return current.isExpanding ? depths[current.index] + 1 : 0;
1143
1299
  };
1144
1300
 
1301
+ const getGraphAction = (action: SpecAction) => ({
1302
+ name: action.name,
1303
+ signature: getActionSignature(action),
1304
+ });
1145
1305
  const getGraphState = (state: Value[], level: number): GraphState => ({
1146
1306
  fingerprint: BigInt.asIntN(64, runtime.getFingerprint(state)),
1147
1307
  level,
@@ -1170,7 +1330,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1170
1330
  }
1171
1331
  const isSeen = isInModel && findStateIndex(hash, fingerprintState) !== -1;
1172
1332
  if (isSeen) return undefined;
1173
- unstoredState.fingerprint = isInModel ? fingerprintState : undefined;
1333
+ unstoredFingerprint = isInModel ? fingerprintState : undefined;
1174
1334
  if (isInModel) {
1175
1335
  countDistinctState(1);
1176
1336
  runtime.queueSize++;
@@ -1233,21 +1393,34 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1233
1393
  source,
1234
1394
  getGraphState(successor.state, depths[index] + 1),
1235
1395
  existing !== -1,
1236
- action && { name: action.name, signature: getActionSignature(action) },
1396
+ action && getGraphAction(action),
1237
1397
  );
1238
1398
  }
1399
+ if (source && !isInModel && options.dump?.constrained) {
1400
+ const excluded = getGraphState(successor.state, depths[index] + 1);
1401
+ search
1402
+ .getExcludingConstraints(state, successor.state)
1403
+ .forEach((constraint) =>
1404
+ stateWriter?.writeConstrained(
1405
+ source,
1406
+ excluded,
1407
+ action && getGraphAction(action),
1408
+ constraint,
1409
+ ),
1410
+ );
1411
+ }
1239
1412
  if (existing !== -1 && liveness) {
1240
1413
  const stored = states[existing];
1241
1414
  const isStored = stored.every((value, position) => value === successor.state[position]);
1242
1415
  liveSuccessors.push({ index: existing, state: isStored ? stored : successor.state });
1243
1416
  }
1244
1417
  const isNew = isInModel && existing === -1;
1245
- // TLC adds a new state to the behavior graph's successors before it checks the invariants.
1246
1418
  if (isNew && liveness) liveSuccessors.push({ index: states.length, state: successor.state });
1247
- unstoredState.fingerprint = isNew ? fingerprintState : undefined;
1419
+ unstoredFingerprint = isNew ? fingerprintState : undefined;
1248
1420
  if (isNew) {
1249
1421
  countDistinctState(depths[index] + 1);
1250
- expansion.newStates++;
1422
+ newStateCount++;
1423
+ if (coverage) coverage.secondary[coveredNode]++;
1251
1424
  }
1252
1425
  if (existing === -1) {
1253
1426
  try {
@@ -1259,9 +1432,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1259
1432
  if (violation) reportContinuedViolation("invariant-violation", violation);
1260
1433
  } catch (error) {
1261
1434
  if (isStackOverflow(error)) throw error;
1262
- // TLC replays the expansion and skips the invariants of a state it has seen, the failed one
1263
- // included unless the constraints exclude it. When the replay fails, TLC reports where and
1264
- // leaves out the outdegree.
1265
1435
  const replay = captureOutput(() => replayNext(index));
1266
1436
  return createFailureResult(
1267
1437
  error,
@@ -1280,6 +1450,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1280
1450
  }
1281
1451
  if (propertyViolation) reportContinuedViolation("liveness-violation", propertyViolation);
1282
1452
  if (!isNew) return undefined;
1453
+ if (coverage) countCoverageVariables(coverage, successor.state);
1283
1454
  if (!isCanonicalizedFirst) canonicalizeState(successor.state);
1284
1455
  markSeen(hash, states.length);
1285
1456
  addState(successor.state, fingerprintState, index, successor.action);
@@ -1287,39 +1458,62 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1287
1458
  return undefined;
1288
1459
  };
1289
1460
 
1290
- const outcome: { result: CheckResult | undefined } = { result: undefined };
1461
+ let outcome: CheckResult | undefined;
1462
+ let coveredNode = -1;
1291
1463
  if (liveness) {
1292
1464
  options.onProgress?.({ kind: "liveness-prepared", branches: liveness.branches });
1293
1465
  }
1294
- // TLC checks the assumptions once it has built the liveness checker in ModelChecker's
1295
- // constructor.
1296
1466
  const assumptionViolation = findViolatedAssumption();
1297
1467
  if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
1298
1468
  options.onProgress?.({ kind: "initial-states-started" });
1299
1469
  if (spec.init !== undefined) {
1300
- try {
1301
- forEachInitialState(
1302
- spec.init,
1303
- environment,
1304
- (state) => {
1305
- reportInitialStatesProgress(runtime.initialStates, options.onProgress);
1306
- try {
1307
- outcome.result = visitInitialState(state);
1308
- } catch (error) {
1309
- const replay = captureOutput(replayInit);
1310
- outcome.result = createFailureResult(
1311
- error,
1312
- { trace: [], traceOutput: replay.lines },
1313
- { initialState: state, ...replay.result, isInitial: true },
1314
- );
1315
- }
1316
- return outcome.result !== undefined;
1317
- },
1318
- spec.scope,
1470
+ let overflowState: Value[] | undefined;
1471
+ const reportInitialFailure = (error: unknown, state: Value[]) => {
1472
+ const replay = captureOutput(replayInit);
1473
+ return createFailureResult(
1474
+ error,
1475
+ { trace: [], traceOutput: replay.lines },
1476
+ { initialState: state, ...replay.result, isInitial: true },
1319
1477
  );
1478
+ };
1479
+ try {
1480
+ const onInitialState = (state: Value[]) => {
1481
+ reportInitialStatesProgress(runtime.initialStates, options.onProgress);
1482
+ if (overflowState) {
1483
+ runtime.generatedStates++;
1484
+ runtime.initialStates++;
1485
+ return false;
1486
+ }
1487
+ try {
1488
+ outcome = visitInitialState(state);
1489
+ } catch (error) {
1490
+ if (isStackOverflow(error)) overflowState = state;
1491
+ else outcome = reportInitialFailure(error, state);
1492
+ }
1493
+ return outcome !== undefined;
1494
+ };
1495
+ if (coverage) {
1496
+ try {
1497
+ replayInitialStates(
1498
+ coverageInits,
1499
+ environment,
1500
+ (state) => {
1501
+ if (onInitialState(state)) throw STOP_WALK;
1502
+ },
1503
+ (partial) => {
1504
+ throw setExitCode(new TlaIllegalStateError([...partial]), EXIT_STATUS.error);
1505
+ },
1506
+ );
1507
+ } catch (error) {
1508
+ if (error !== STOP_WALK) throw error;
1509
+ }
1510
+ } else {
1511
+ forEachInitialState(spec.init, environment, onInitialState, spec.scope);
1512
+ }
1513
+ if (overflowState) {
1514
+ outcome = reportInitialFailure(createStackOverflowError(), overflowState);
1515
+ }
1320
1516
  } catch (error) {
1321
- // TLC prints an illegal initial state with null for each variable it leaves undefined, and
1322
- // stops before it prints the statistics.
1323
1517
  if (error instanceof TlaIllegalStateError) {
1324
1518
  const illegal = createFailureResult(
1325
1519
  error,
@@ -1331,7 +1525,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1331
1525
  failure: illegal.failure && { ...illegal.failure, isWithoutStatistics: true },
1332
1526
  };
1333
1527
  }
1334
- // TLC prints the error before it replays the initial predicate with its call stack.
1335
1528
  const replay = captureOutput(replayInit);
1336
1529
  return createFailureResult(
1337
1530
  error,
@@ -1340,14 +1533,14 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1340
1533
  );
1341
1534
  }
1342
1535
  }
1343
- if (outcome.result) return outcome.result;
1344
- statistics.initialStates = {
1536
+ if (outcome) return outcome;
1537
+ computedInitialStates = {
1345
1538
  generated: runtime.initialStates,
1346
1539
  distinct: runtime.distinctStates,
1347
1540
  };
1348
1541
  options.onProgress?.({
1349
1542
  kind: "initial-states-computed",
1350
- initialStates: statistics.initialStates,
1543
+ initialStates: computedInitialStates,
1351
1544
  });
1352
1545
 
1353
1546
  const next = spec.next;
@@ -1359,15 +1552,31 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1359
1552
  }
1360
1553
  return createSuccess();
1361
1554
  }
1362
- // TLC labels and colors an edge of the -dump state graph by the action that generated it. When
1363
- // the graph names its edges, the search generates successors action by action, as TLC does.
1364
1555
  const isNamingEdges = Boolean(
1365
1556
  options.dump?.dot && (options.dump.actionLabels || options.dump.colorize),
1366
1557
  );
1367
1558
  const forEachActionSuccessor = (
1368
1559
  state: Value[],
1560
+ onUnsatisfied:
1561
+ | ((successor: Value[], conjunct: Expression, action?: SpecAction) => void)
1562
+ | undefined,
1369
1563
  onSuccessor: (successor: Successor, action: SpecAction | undefined) => boolean,
1370
1564
  ) => {
1565
+ if (coverage) {
1566
+ let successorCount = 0;
1567
+ try {
1568
+ coverageActions.forEach((action) => {
1569
+ coveredNode = action.node;
1570
+ walkCoveredSuccessors(action, state, (successor) => {
1571
+ successorCount++;
1572
+ if (onSuccessor({ state: successor, action: action.name }, action)) throw STOP_WALK;
1573
+ });
1574
+ });
1575
+ } catch (error) {
1576
+ if (error !== STOP_WALK) throw error;
1577
+ }
1578
+ return successorCount;
1579
+ }
1371
1580
  if (!isNamingEdges) {
1372
1581
  return forEachSuccessor(
1373
1582
  next,
@@ -1375,11 +1584,13 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1375
1584
  environment,
1376
1585
  (successor) => onSuccessor(successor, undefined),
1377
1586
  spec.scope,
1587
+ undefined,
1588
+ onUnsatisfied,
1378
1589
  );
1379
1590
  }
1380
- const progress = { isStopped: false };
1591
+ let isStopped = false;
1381
1592
  return getSpecNextActions().reduce((count, action) => {
1382
- if (progress.isStopped) return count;
1593
+ if (isStopped) return count;
1383
1594
  return (
1384
1595
  count +
1385
1596
  forEachSuccessor(
@@ -1387,17 +1598,16 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1387
1598
  state,
1388
1599
  environment,
1389
1600
  (successor) => {
1390
- progress.isStopped = onSuccessor(successor, action);
1391
- return progress.isStopped;
1601
+ isStopped = onSuccessor(successor, action);
1602
+ return isStopped;
1392
1603
  },
1393
1604
  action.scope,
1605
+ undefined,
1606
+ onUnsatisfied && ((successor, conjunct) => onUnsatisfied(successor, conjunct, action)),
1394
1607
  )
1395
1608
  );
1396
1609
  }, 0);
1397
1610
  };
1398
- // TLC's worker adds a state to the behavior graph even after its next states fail or violate a
1399
- // property, and prints the call stack of an error in that, unless the error is a
1400
- // FingerprintException, which the worker doesn't catch. TLC 1.7.4 prints none.
1401
1611
  const getLiveCallStack = (index: number, liveSuccessors: LiveSuccessor[]) => {
1402
1612
  if (!liveness || is174) return undefined;
1403
1613
  const replay = getReplayFailure((tracing) =>
@@ -1405,9 +1615,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1405
1615
  );
1406
1616
  return replay?.callStack.length && !replay.fingerprint ? replay.callStack : undefined;
1407
1617
  };
1408
- // TLC's worker adds the state to the behavior graph after it prints the trace. On an error in that,
1409
- // it adds the state again to print the call stack instead of replaying the next-state relation,
1410
- // which TLC 1.7.4 doesn't.
1411
1618
  const addFailedLiveState = (index: number, liveSuccessors: LiveSuccessor[]) => {
1412
1619
  try {
1413
1620
  liveness?.addState(index, states[index], liveSuccessors);
@@ -1426,11 +1633,8 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1426
1633
  const replay = captureOutput(() => replayNext(index));
1427
1634
  return { result: replay.result, lines: [...live.lines, ...replay.lines] };
1428
1635
  };
1429
- // TLC reports a stack overflow while it computes next states without replaying it, with the
1430
- // behavior up to the state it expands.
1431
1636
  const reportNextStateOverflow = (index: number) =>
1432
- createFailureResult(createStackOverflowError(), getStateTrace(index));
1433
- // After the trace, TLC replays the next-state relation with its call stack, printing again.
1637
+ createFailureResult(createStackOverflowError(), getStateTrace(index), { isNextState: true });
1434
1638
  const reportNextStateFailure = (
1435
1639
  error: unknown,
1436
1640
  index: number,
@@ -1447,33 +1651,36 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1447
1651
  const expandState = (index: number, liveSuccessors: LiveSuccessor[]) => {
1448
1652
  const state = states[index];
1449
1653
  const source = stateWriter && getGraphState(state, depths[index]);
1450
- const successorCount = forEachActionSuccessor(state, (successor, action) => {
1654
+ const writeUnsatisfied =
1655
+ source && options.dump?.constrained
1656
+ ? (successor: Value[], conjunct: Expression, action?: SpecAction) =>
1657
+ stateWriter?.writeConstrained(
1658
+ source,
1659
+ getGraphState(successor, depths[index] + 1),
1660
+ action && getGraphAction(action),
1661
+ describeRange(conjunct),
1662
+ )
1663
+ : undefined;
1664
+ const successorCount = forEachActionSuccessor(state, writeUnsatisfied, (successor, action) => {
1451
1665
  try {
1452
- outcome.result = visitSuccessor(index, successor, liveSuccessors, source, action);
1666
+ outcome = visitSuccessor(index, successor, liveSuccessors, source, action);
1453
1667
  } catch (error) {
1454
1668
  if (isStackOverflow(error)) {
1455
- outcome.result = reportNextStateOverflow(index);
1669
+ outcome = reportNextStateOverflow(index);
1456
1670
  return true;
1457
1671
  }
1458
- // TLC 1.7.4 reports the wrapped error without the trace, except for a failed property,
1459
- // which it reports with the trace before it rethrows. The error stops its worker before it
1460
- // adds the state to the behavior graph.
1461
1672
  const replay = is174
1462
1673
  ? captureOutput(() => replayNext(index))
1463
1674
  : replayFailedNext(index, liveSuccessors);
1464
1675
  if (is174 && error instanceof TlaEvaluationError && !isHeadedError(error)) {
1465
- outcome.result = createFailureResult(
1676
+ outcome = createFailureResult(
1466
1677
  new TlaEvaluationError(`${getWrappedException(error)}${error.message}`, error),
1467
1678
  appendTraceOutput({ trace: [] }, replay.lines),
1468
1679
  { isNextState: true, ...replay.result },
1469
1680
  );
1470
1681
  return true;
1471
1682
  }
1472
- // A successor TLC can't fingerprint fails again as TLC prints it in the trace, which TLC
1473
- // reports as an exception it didn't expect.
1474
- const isTraceFailed = getFingerprintState(successor.state).some(
1475
- (value) => getFingerprintError(value) !== undefined,
1476
- );
1683
+ const isTraceFailed = isUnfingerprintable(successor.state);
1477
1684
  const traceFailure =
1478
1685
  isTraceFailed && error instanceof TlaEvaluationError
1479
1686
  ? getFailureMessage(
@@ -1483,7 +1690,7 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1483
1690
  true,
1484
1691
  )
1485
1692
  : undefined;
1486
- outcome.result = createFailureResult(
1693
+ outcome = createFailureResult(
1487
1694
  error,
1488
1695
  appendTraceOutput(
1489
1696
  traceFailure ? getStateTrace(index) : getFailedTrace(index, successor),
@@ -1492,11 +1699,10 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1492
1699
  { isNextState: true, ...replay.result, traceFailure },
1493
1700
  );
1494
1701
  }
1495
- return outcome.result !== undefined;
1702
+ return outcome !== undefined;
1496
1703
  });
1497
1704
  current.isExpanding = false;
1498
- const result = outcome.result;
1499
- // TLC 1.7.4's worker stops at a violation.
1705
+ const result = outcome;
1500
1706
  if (result?.violation && !is174) {
1501
1707
  const live = captureOutput(() => addFailedLiveState(index, liveSuccessors));
1502
1708
  return {
@@ -1507,7 +1713,9 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1507
1713
  }
1508
1714
  if (result) return result;
1509
1715
  const addLiveState = () => {
1510
- if (liveness && source && is174) stateWriter?.writeStuttering(source);
1716
+ if (liveness && source && (is174 || options.dump?.stuttering)) {
1717
+ stateWriter?.writeStuttering(source);
1718
+ }
1511
1719
  const accepted = liveness?.addState(index, state, liveSuccessors);
1512
1720
  if (!liveness || !accepted) return undefined;
1513
1721
  const steps = getPathSteps(accepted);
@@ -1524,9 +1732,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1524
1732
  };
1525
1733
  if (successorCount === 0 && config.checkDeadlock) {
1526
1734
  const deadlock = reportViolation("deadlock", { name: "deadlock", ...getStateTrace(index) });
1527
- // TLC's worker still adds the deadlocked state to the behavior graph after it reports the
1528
- // deadlock, and reports a temporal property that this violates. Then it counts the state as
1529
- // expanded.
1530
1735
  const live = captureOutput(() => {
1531
1736
  try {
1532
1737
  return { additional: addLiveState()?.violation };
@@ -1538,7 +1743,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1538
1743
  const reported = deadlock.violation
1539
1744
  ? { ...deadlock, violation: appendTraceOutput(deadlock.violation, live.lines) }
1540
1745
  : deadlock;
1541
- // An error in adding the state stops TLC 1.7.4's worker before it counts the state.
1542
1746
  const counted = withOutDegrees(
1543
1747
  reported,
1544
1748
  live.result.isFailed ? getFailureOutDegrees() : getPartialOutDegrees(),
@@ -1550,8 +1754,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1550
1754
  try {
1551
1755
  return addLiveState();
1552
1756
  } catch (error) {
1553
- // TLC 1.7.4's worker reports an error in adding a state to the behavior graph as an exception
1554
- // it didn't expect, without the trace or a call stack, and exits as for any general error.
1555
1757
  if (is174 && error instanceof TlaEvaluationError) {
1556
1758
  const unexpected = new TlaEvaluationError(
1557
1759
  `${isEvalException(error) ? UNEXPECTED_EVAL_EXCEPTION : UNEXPECTED_EXCEPTION}${error.message}`,
@@ -1562,8 +1764,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1562
1764
  { outDegrees: getFailureOutDegrees() },
1563
1765
  );
1564
1766
  }
1565
- // TLC's Worker#doNextCheckLiveness adds the state again to find the call stack, prints it
1566
- // before the error, and reports the error as one in computing next states.
1567
1767
  const replay = getReplayFailure((tracing) =>
1568
1768
  liveness?.addState(index, state, liveSuccessors, tracing),
1569
1769
  );
@@ -1575,7 +1775,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1575
1775
  });
1576
1776
  }
1577
1777
  };
1578
- // TLC's Liveness#printStutteringCounterExampleWarning.
1579
1778
  const getStutteringWarning = () => {
1580
1779
  const name = config.specification;
1581
1780
  const book =
@@ -1593,7 +1792,6 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1593
1792
  text: `The stuttering counterexample above may be caused by the absence of a fairness constraint in the behavior specification ${name} defined at ${formatRange(range)}. To rule out such counterexamples, conjoin a suitable fairness constraint to ${name} ${book}`,
1594
1793
  };
1595
1794
  };
1596
- // TLC names the properties and the step back into the cycle from the states it prints.
1597
1795
  const reportLasso = (checker: LivenessChecker, lasso: Lasso) => {
1598
1796
  const path = [...lasso.prefix, ...lasso.cycle];
1599
1797
  const loopStart = lasso.prefix.length;
@@ -1631,9 +1829,14 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1631
1829
  : createActionRecord(findSuccessorWithFingerprint(lastState, cycleStart)?.action),
1632
1830
  );
1633
1831
  };
1634
- const isPeriodic = liveness !== undefined && options.livenessCheck !== "final";
1832
+ const isPeriodic = liveness !== undefined && (options.livenessCheck ?? "default") === "default";
1635
1833
  const startedAt = performance.now();
1636
- const periodic = { at: startedAt + PERIODIC_START, size: 1, time: 0 };
1834
+ const periodic = {
1835
+ at: startedAt + PERIODIC_START,
1836
+ size: 1,
1837
+ time: 0,
1838
+ coverageCount: Math.trunc(options.coverage ?? 0),
1839
+ };
1637
1840
  const findPeriodicViolation = (expanded: number) => {
1638
1841
  const now = performance.now();
1639
1842
  const isGrown = (expanded - periodic.size) / periodic.size > LIVENESS_GROWTH;
@@ -1659,55 +1862,63 @@ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefine
1659
1862
  current.isExpanding = true;
1660
1863
  const liveSuccessors: LiveSuccessor[] = [];
1661
1864
  try {
1662
- outcome.result = expandState(index, liveSuccessors);
1865
+ outcome = expandState(index, liveSuccessors);
1663
1866
  } catch (error) {
1664
- outcome.result =
1867
+ outcome =
1665
1868
  error instanceof TlaIncompleteSuccessorError
1666
1869
  ? reportIncompleteSuccessor(index, error)
1667
1870
  : reportNextStateFailure(error, index, liveSuccessors);
1668
1871
  }
1669
- if (outcome.result) return outcome.result;
1872
+ if (outcome) return outcome;
1670
1873
  outDegrees[getOutDegreeBucket()]++;
1671
- expansion.newStates = 0;
1672
- // TLC's AbstractChecker#runTLC checks the liveness properties on the state graph so far, then
1673
- // reports how far the search got.
1874
+ newStateCount = 0;
1674
1875
  if ((isPeriodic || options.onProgress) && performance.now() >= periodic.at) {
1675
1876
  periodic.at = performance.now() + PROGRESS_INTERVAL;
1676
1877
  const lasso = isPeriodic ? findPeriodicViolation(index + 1) : undefined;
1677
1878
  if (liveness && lasso) return reportLasso(liveness, lasso);
1678
- options.onProgress?.({ kind: "progress", statistics: createResult("success") });
1879
+ const isCoverageDue = options.coverage !== undefined && periodic.coverageCount === 0;
1880
+ periodic.coverageCount = isCoverageDue
1881
+ ? Math.trunc(options.coverage ?? 0)
1882
+ : periodic.coverageCount - 1;
1883
+ const progress = createResult("success");
1884
+ options.onProgress?.({
1885
+ kind: "progress",
1886
+ statistics: { ...progress, coverage: isCoverageDue ? progress.coverage : undefined },
1887
+ });
1679
1888
  }
1680
1889
  }
1681
1890
 
1682
1891
  current.index = -1;
1683
1892
  current.candidate = undefined;
1684
- if (liveness) {
1893
+ const finalLiveness = options.livenessCheck === "off" ? undefined : liveness;
1894
+ if (finalLiveness) {
1685
1895
  options.onProgress?.({
1686
1896
  kind: "liveness-started",
1687
- branches: liveness.branches,
1897
+ branches: finalLiveness.branches,
1688
1898
  isComplete: true,
1689
1899
  states: runtime.distinctStates,
1690
1900
  statistics: createResult("success"),
1691
1901
  });
1692
1902
  }
1693
- const lasso = liveness?.findViolation();
1694
- if (liveness && lasso) return reportLasso(liveness, lasso);
1903
+ const lasso = finalLiveness?.findViolation();
1904
+ if (finalLiveness && lasso) return reportLasso(finalLiveness, lasso);
1695
1905
 
1696
- // TLC finishes the check of the temporal properties before it checks the postconditions.
1697
- if (liveness) options.onProgress?.({ kind: "liveness-finished" });
1698
- try {
1699
- const postcondition = search.findPostconditionViolation();
1700
- if (postcondition) {
1701
- return createResult("postcondition-violation", {
1702
- name: postcondition.name,
1703
- message: postcondition.message,
1704
- counts: postcondition.counts,
1705
- trace: [],
1706
- postcondition,
1707
- });
1708
- }
1709
- } catch (error) {
1710
- return createFailureResult(error, { trace: [] });
1906
+ if (finalLiveness) options.onProgress?.({ kind: "liveness-finished" });
1907
+ const missingPostcondition = specification.moduleOperators.find(
1908
+ (operator) => operator.kind === "postcondition" && operator.key === undefined,
1909
+ );
1910
+ if (missingPostcondition) {
1911
+ return createFailureResult(createMissingOperatorError(missingPostcondition), { trace: [] });
1912
+ }
1913
+ const postcondition = search.findPostconditionViolation();
1914
+ if (postcondition) {
1915
+ return createResult("postcondition-violation", {
1916
+ name: postcondition.name,
1917
+ message: postcondition.message,
1918
+ counts: postcondition.counts,
1919
+ trace: [],
1920
+ postcondition,
1921
+ });
1711
1922
  }
1712
- return createSuccess();
1923
+ return continuedStatus ? createResult(continuedStatus) : createSuccess();
1713
1924
  };