tla-ts 0.0.3 → 0.0.4-dev.1a3acf6

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 (381) hide show
  1. package/README.md +46 -115
  2. package/dist/cli.cjs +1 -1
  3. package/dist/cli.js +1 -1
  4. package/dist/deciders.cjs +366 -0
  5. package/dist/deciders.js +366 -0
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +194 -8
  8. package/dist/index.d.ts +194 -8
  9. package/dist/index.js +1 -1
  10. package/dist/parallel-worker.cjs +1 -4
  11. package/dist/parallel-worker.js +1 -4
  12. package/dist/prove-worker.cjs +9 -0
  13. package/dist/prove-worker.d.cts +9 -0
  14. package/dist/prove-worker.d.ts +9 -0
  15. package/dist/prove-worker.js +9 -0
  16. package/dist/prove.cjs +1006 -0
  17. package/dist/prove.js +1006 -0
  18. package/dist/run.cjs +45 -0
  19. package/dist/run.js +45 -0
  20. package/dist/tlapm.cjs +10 -0
  21. package/dist/tlapm.js +10 -0
  22. package/dist/transfer.cjs +1377 -18
  23. package/dist/transfer.js +1377 -18
  24. package/dist/worker.cjs +21 -0
  25. package/dist/worker.js +21 -0
  26. package/package.json +24 -11
  27. package/src/ast.ts +149 -8
  28. package/src/bags.ts +26 -30
  29. package/src/builtins.ts +45 -19
  30. package/src/bundled-modules.ts +3 -3
  31. package/src/check.ts +1182 -900
  32. package/src/cli/options.ts +109 -0
  33. package/src/cli/run.ts +63 -0
  34. package/src/cli/shared.ts +106 -0
  35. package/src/cli/tlapm.ts +374 -0
  36. package/src/cli/tlc.ts +941 -0
  37. package/src/cli/xml-exporter.ts +221 -0
  38. package/src/cli.ts +9 -2
  39. package/src/codegen.ts +112 -51
  40. package/src/config.ts +254 -181
  41. package/src/dependencies.ts +5 -7
  42. package/src/environment.ts +579 -184
  43. package/src/errors.ts +287 -4
  44. package/src/evaluate.ts +1095 -365
  45. package/src/exit-codes.ts +22 -43
  46. package/src/fingerprints.ts +49 -14
  47. package/src/index.ts +11 -0
  48. package/src/instances.ts +73 -60
  49. package/src/java-overrides.ts +183 -66
  50. package/src/json.ts +31 -36
  51. package/src/levels.ts +197 -54
  52. package/src/lexer.ts +127 -30
  53. package/src/liveness-checker.ts +894 -0
  54. package/src/liveness.ts +246 -596
  55. package/src/{obligation-action.ts → obligations/action.ts} +248 -74
  56. package/src/{obligation-anon.ts → obligations/anonymize.ts} +55 -57
  57. package/src/obligations/equality.ts +260 -0
  58. package/src/obligations/expression.ts +618 -0
  59. package/src/{obligation-format.ts → obligations/format.ts} +7 -8
  60. package/src/obligations/generate.ts +457 -0
  61. package/src/{obligations.ts → obligations/index.ts} +46 -32
  62. package/src/{obligation-levels.ts → obligations/levels.ts} +44 -40
  63. package/src/obligations/module.ts +445 -0
  64. package/src/obligations/normalize.ts +554 -0
  65. package/src/obligations/operators.ts +176 -0
  66. package/src/obligations/pragma.ts +195 -0
  67. package/src/{obligation-printer.ts → obligations/printer.ts} +65 -230
  68. package/src/{obligation-proof.ts → obligations/proof.ts} +7 -2
  69. package/src/obligations/regroup.ts +100 -0
  70. package/src/{obligation-generate.ts → obligations/simplify.ts} +130 -536
  71. package/src/{obligation-source.ts → obligations/source.ts} +174 -216
  72. package/src/{obligation-deref.ts → obligations/subexpression.ts} +84 -115
  73. package/src/obligations/substitution.ts +261 -0
  74. package/src/obligations/temporal.ts +321 -0
  75. package/src/{obligation-tuples.ts → obligations/tuples.ts} +38 -54
  76. package/src/parallel-worker.ts +184 -235
  77. package/src/parallel.ts +156 -91
  78. package/src/parser.ts +490 -188
  79. package/src/pcal/ast.ts +755 -0
  80. package/src/pcal/parse.ts +1487 -0
  81. package/src/pcal/tokenize.ts +487 -0
  82. package/src/pcal/translate.ts +1151 -0
  83. package/src/pcal/validate.ts +444 -0
  84. package/src/prover/decide-pool.ts +95 -0
  85. package/src/prover/deciders.ts +33 -0
  86. package/src/prover/first-order.ts +175 -0
  87. package/src/prover/isabelle/LICENSE +36 -0
  88. package/src/prover/isabelle/LICENSE-tlapm +26 -0
  89. package/src/prover/isabelle/decide.ts +44 -0
  90. package/src/prover/isabelle/encode.ts +445 -0
  91. package/src/prover/isabelle/isar/inner-syntax.ts +579 -0
  92. package/src/prover/isabelle/isar/method.ts +367 -0
  93. package/src/prover/isabelle/isar/proof.ts +28 -0
  94. package/src/prover/isabelle/isar/statement.ts +57 -0
  95. package/src/prover/isabelle/isar/theory.ts +192 -0
  96. package/src/prover/isabelle/isar/type-check.ts +278 -0
  97. package/src/prover/isabelle/provers/blast/blast.ts +258 -0
  98. package/src/prover/isabelle/provers/blast/branch.ts +322 -0
  99. package/src/prover/isabelle/provers/blast/prove.ts +347 -0
  100. package/src/prover/isabelle/provers/blast/rules.ts +330 -0
  101. package/src/prover/isabelle/provers/blast/state.ts +180 -0
  102. package/src/prover/isabelle/provers/blast/term.ts +546 -0
  103. package/src/prover/isabelle/provers/clasimp.ts +150 -0
  104. package/src/prover/isabelle/provers/classical.ts +389 -0
  105. package/src/prover/isabelle/provers/hypsubst.ts +433 -0
  106. package/src/prover/isabelle/pure/bicompose.ts +174 -0
  107. package/src/prover/isabelle/pure/consts.ts +32 -0
  108. package/src/prover/isabelle/pure/conv.ts +79 -0
  109. package/src/prover/isabelle/pure/drule.ts +264 -0
  110. package/src/prover/isabelle/pure/envir.ts +331 -0
  111. package/src/prover/isabelle/pure/goal.ts +53 -0
  112. package/src/prover/isabelle/pure/interrupt.ts +16 -0
  113. package/src/prover/isabelle/pure/list.ts +12 -0
  114. package/src/prover/isabelle/pure/logic.ts +330 -0
  115. package/src/prover/isabelle/pure/name.ts +98 -0
  116. package/src/prover/isabelle/pure/net.ts +215 -0
  117. package/src/prover/isabelle/pure/object-logic.ts +41 -0
  118. package/src/prover/isabelle/pure/pattern.ts +631 -0
  119. package/src/prover/isabelle/pure/raw-simplifier.ts +338 -0
  120. package/src/prover/isabelle/pure/rewriter.ts +602 -0
  121. package/src/prover/isabelle/pure/search.ts +68 -0
  122. package/src/prover/isabelle/pure/seq.ts +133 -0
  123. package/src/prover/isabelle/pure/simplifier.ts +106 -0
  124. package/src/prover/isabelle/pure/table.ts +201 -0
  125. package/src/prover/isabelle/pure/tactic.ts +168 -0
  126. package/src/prover/isabelle/pure/tactical.ts +264 -0
  127. package/src/prover/isabelle/pure/term-ord.ts +105 -0
  128. package/src/prover/isabelle/pure/term.ts +688 -0
  129. package/src/prover/isabelle/pure/thm.ts +783 -0
  130. package/src/prover/isabelle/pure/type.ts +121 -0
  131. package/src/prover/isabelle/pure/unify.ts +753 -0
  132. package/src/prover/isabelle/pure/variable.ts +25 -0
  133. package/src/prover/isabelle/tla/classical-setup.ts +101 -0
  134. package/src/prover/isabelle/tla/context.ts +74 -0
  135. package/src/prover/isabelle/tla/logic-data.ts +5 -0
  136. package/src/prover/isabelle/tla/logic.ts +215 -0
  137. package/src/prover/isabelle/tla/simpdata.ts +241 -0
  138. package/src/prover/isabelle/tools/intuitionistic.ts +132 -0
  139. package/src/prover/ocaml.ts +22 -0
  140. package/src/prover/prep/action.ts +508 -0
  141. package/src/prover/prep/enabled-axioms.ts +189 -0
  142. package/src/prover/prep/fingerprint.ts +388 -0
  143. package/src/prover/prep/level-comparison.ts +529 -0
  144. package/src/prover/prep/md5.ts +60 -0
  145. package/src/prover/prep/methods.ts +221 -0
  146. package/src/prover/prep/normalize.ts +309 -0
  147. package/src/prover/prove-worker.ts +22 -0
  148. package/src/prover/prove.ts +492 -0
  149. package/src/prover/ptl/decide.ts +68 -0
  150. package/src/prover/ptl/encode.ts +244 -0
  151. package/src/prover/ptl/sat.ts +151 -0
  152. package/src/prover/ptl/tableau.ts +276 -0
  153. package/src/prover/smt/axioms.ts +209 -0
  154. package/src/prover/smt/context.ts +108 -0
  155. package/src/prover/smt/data.ts +636 -0
  156. package/src/prover/smt/encode.ts +275 -0
  157. package/src/prover/smt/extensionality.ts +65 -0
  158. package/src/prover/smt/flatten.ts +112 -0
  159. package/src/prover/smt/format.ts +154 -0
  160. package/src/prover/smt/instances.ts +181 -0
  161. package/src/prover/smt/rewrite.ts +766 -0
  162. package/src/prover/smt/solver/act-cache.ts +265 -0
  163. package/src/prover/smt/solver/arith-rewriter.ts +962 -0
  164. package/src/prover/smt/solver/array.ts +22 -0
  165. package/src/prover/smt/solver/asserted-formulas.ts +469 -0
  166. package/src/prover/smt/solver/ast-lt.ts +157 -0
  167. package/src/prover/smt/solver/ast-util.ts +91 -0
  168. package/src/prover/smt/solver/ast.ts +1315 -0
  169. package/src/prover/smt/solver/auf-solver.ts +572 -0
  170. package/src/prover/smt/solver/case-split-queue.ts +178 -0
  171. package/src/prover/smt/solver/cg-table.ts +175 -0
  172. package/src/prover/smt/solver/clause.ts +276 -0
  173. package/src/prover/smt/solver/conflict-resolution.ts +343 -0
  174. package/src/prover/smt/solver/context.ts +1292 -0
  175. package/src/prover/smt/solver/ctx-simplify.ts +334 -0
  176. package/src/prover/smt/solver/der.ts +224 -0
  177. package/src/prover/smt/solver/dyn-ack.ts +141 -0
  178. package/src/prover/smt/solver/e-matching.ts +659 -0
  179. package/src/prover/smt/solver/enode.ts +259 -0
  180. package/src/prover/smt/solver/expr-ref.ts +21 -0
  181. package/src/prover/smt/solver/expr-safe-replace.ts +172 -0
  182. package/src/prover/smt/solver/fingerprints.ts +92 -0
  183. package/src/prover/smt/solver/flat-literals.ts +51 -0
  184. package/src/prover/smt/solver/goal.ts +138 -0
  185. package/src/prover/smt/solver/hash.ts +173 -0
  186. package/src/prover/smt/solver/hashtable.ts +166 -0
  187. package/src/prover/smt/solver/internalizer.ts +1381 -0
  188. package/src/prover/smt/solver/lbool.ts +5 -0
  189. package/src/prover/smt/solver/literal.ts +24 -0
  190. package/src/prover/smt/solver/lp/bound-propagator.ts +391 -0
  191. package/src/prover/smt/solver/lp/constraints.ts +78 -0
  192. package/src/prover/smt/solver/lp/containers.ts +296 -0
  193. package/src/prover/smt/solver/lp/core-solver.ts +504 -0
  194. package/src/prover/smt/solver/lp/cross-nested.ts +224 -0
  195. package/src/prover/smt/solver/lp/dep-intervals.ts +642 -0
  196. package/src/prover/smt/solver/lp/dependency.ts +51 -0
  197. package/src/prover/smt/solver/lp/dioph-eq.ts +1181 -0
  198. package/src/prover/smt/solver/lp/explanation.ts +46 -0
  199. package/src/prover/smt/solver/lp/gomory.ts +255 -0
  200. package/src/prover/smt/solver/lp/hnf-cutter.ts +125 -0
  201. package/src/prover/smt/solver/lp/hnf.ts +281 -0
  202. package/src/prover/smt/solver/lp/int-cube.ts +295 -0
  203. package/src/prover/smt/solver/lp/int-solver.ts +514 -0
  204. package/src/prover/smt/solver/lp/lar-solver.ts +816 -0
  205. package/src/prover/smt/solver/lp/lar-term.ts +62 -0
  206. package/src/prover/smt/solver/lp/lp-settings.ts +91 -0
  207. package/src/prover/smt/solver/lp/maximize-term.ts +347 -0
  208. package/src/prover/smt/solver/lp/nex-creator.ts +381 -0
  209. package/src/prover/smt/solver/lp/nex.ts +120 -0
  210. package/src/prover/smt/solver/lp/nla-backoff.ts +43 -0
  211. package/src/prover/smt/solver/lp/nla-basics.ts +398 -0
  212. package/src/prover/smt/solver/lp/nla-core.ts +968 -0
  213. package/src/prover/smt/solver/lp/nla-divisions.ts +332 -0
  214. package/src/prover/smt/solver/lp/nla-emonics.ts +373 -0
  215. package/src/prover/smt/solver/lp/nla-factorization.ts +30 -0
  216. package/src/prover/smt/solver/lp/nla-grobner.ts +904 -0
  217. package/src/prover/smt/solver/lp/nla-horner.ts +126 -0
  218. package/src/prover/smt/solver/lp/nla-intervals.ts +265 -0
  219. package/src/prover/smt/solver/lp/nla-monomial-bounds.ts +715 -0
  220. package/src/prover/smt/solver/lp/nla-monotone.ts +59 -0
  221. package/src/prover/smt/solver/lp/nla-order.ts +307 -0
  222. package/src/prover/smt/solver/lp/nla-patcher.ts +112 -0
  223. package/src/prover/smt/solver/lp/nla-tangents.ts +251 -0
  224. package/src/prover/smt/solver/lp/nla-throttle.ts +85 -0
  225. package/src/prover/smt/solver/lp/nla-types.ts +124 -0
  226. package/src/prover/smt/solver/lp/nla-var-eqs.ts +141 -0
  227. package/src/prover/smt/solver/lp/nra-solver.ts +440 -0
  228. package/src/prover/smt/solver/lp/numeric-pair.ts +65 -0
  229. package/src/prover/smt/solver/lp/pdd-interval.ts +31 -0
  230. package/src/prover/smt/solver/lp/pdd-simplifier.ts +184 -0
  231. package/src/prover/smt/solver/lp/pdd-solver.ts +408 -0
  232. package/src/prover/smt/solver/lp/pdd.ts +971 -0
  233. package/src/prover/smt/solver/lp/random-updater.ts +138 -0
  234. package/src/prover/smt/solver/lp/static-matrix.ts +246 -0
  235. package/src/prover/smt/solver/lp/union-find.ts +96 -0
  236. package/src/prover/smt/solver/mam-compiler.ts +847 -0
  237. package/src/prover/smt/solver/mam-interpreter.ts +400 -0
  238. package/src/prover/smt/solver/maximize-ac-sharing.ts +118 -0
  239. package/src/prover/smt/solver/model-checker.ts +347 -0
  240. package/src/prover/smt/solver/model-evaluator.ts +262 -0
  241. package/src/prover/smt/solver/model-finder.ts +155 -0
  242. package/src/prover/smt/solver/model-generator.ts +97 -0
  243. package/src/prover/smt/solver/model-macro-solver.ts +728 -0
  244. package/src/prover/smt/solver/nlsat/algebraic.ts +1161 -0
  245. package/src/prover/smt/solver/nlsat/atoms.ts +238 -0
  246. package/src/prover/smt/solver/nlsat/evaluator.ts +303 -0
  247. package/src/prover/smt/solver/nlsat/explain.ts +607 -0
  248. package/src/prover/smt/solver/nlsat/interval-set.ts +351 -0
  249. package/src/prover/smt/solver/nlsat/levelwise.ts +737 -0
  250. package/src/prover/smt/solver/nlsat/mpbq.ts +161 -0
  251. package/src/prover/smt/solver/nlsat/polynomial.ts +1722 -0
  252. package/src/prover/smt/solver/nlsat/solver.ts +911 -0
  253. package/src/prover/smt/solver/nlsat/types.ts +43 -0
  254. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +648 -0
  255. package/src/prover/smt/solver/nlsat/upolynomial.ts +996 -0
  256. package/src/prover/smt/solver/nnf.ts +469 -0
  257. package/src/prover/smt/solver/pattern-inference.ts +351 -0
  258. package/src/prover/smt/solver/poly-rewriter.ts +477 -0
  259. package/src/prover/smt/solver/propagate-values.ts +83 -0
  260. package/src/prover/smt/solver/proto-model.ts +551 -0
  261. package/src/prover/smt/solver/pull-quant.ts +139 -0
  262. package/src/prover/smt/solver/qe-lite-der.ts +526 -0
  263. package/src/prover/smt/solver/qe-lite-fm.ts +576 -0
  264. package/src/prover/smt/solver/qe-lite.ts +381 -0
  265. package/src/prover/smt/solver/qi-queue.ts +362 -0
  266. package/src/prover/smt/solver/quant-tactics.ts +117 -0
  267. package/src/prover/smt/solver/quantifier-analyzer.ts +562 -0
  268. package/src/prover/smt/solver/quantifier-manager.ts +186 -0
  269. package/src/prover/smt/solver/random-gen.ts +10 -0
  270. package/src/prover/smt/solver/rational.ts +165 -0
  271. package/src/prover/smt/solver/ref-vector.ts +62 -0
  272. package/src/prover/smt/solver/relevancy.ts +247 -0
  273. package/src/prover/smt/solver/rewriter-tpl.ts +1159 -0
  274. package/src/prover/smt/solver/rewriter.ts +843 -0
  275. package/src/prover/smt/solver/rlimit.ts +79 -0
  276. package/src/prover/smt/solver/smtlib-parser.ts +526 -0
  277. package/src/prover/smt/solver/solver.ts +71 -0
  278. package/src/prover/smt/solver/sort.ts +35 -0
  279. package/src/prover/smt/solver/sticky-generations.ts +69 -0
  280. package/src/prover/smt/solver/theory-lra-axioms.ts +340 -0
  281. package/src/prover/smt/solver/theory-lra-bounds.ts +226 -0
  282. package/src/prover/smt/solver/theory-lra-final-check.ts +252 -0
  283. package/src/prover/smt/solver/theory-lra-internalize.ts +476 -0
  284. package/src/prover/smt/solver/theory-lra-model.ts +243 -0
  285. package/src/prover/smt/solver/theory-lra-propagate.ts +405 -0
  286. package/src/prover/smt/solver/theory-lra-state.ts +43 -0
  287. package/src/prover/smt/solver/theory-lra.ts +56 -0
  288. package/src/prover/smt/solver/var-subst.ts +258 -0
  289. package/src/prover/smt/solver/z3-license.txt +10 -0
  290. package/src/prover/smt/table.ts +170 -0
  291. package/src/prover/tlapm/cache.ts +236 -0
  292. package/src/prover/tlapm/ocaml-marshal.ts +166 -0
  293. package/src/prover/tlapm/tlapm.ts +96 -0
  294. package/src/prover/tlaps-module.ts +510 -0
  295. package/src/prover/verdict.ts +13 -0
  296. package/src/prover/zenon/LICENSE +32 -0
  297. package/src/prover/zenon/check/check.ts +105 -0
  298. package/src/prover/zenon/check/definitions.ts +144 -0
  299. package/src/prover/zenon/check/equality.ts +182 -0
  300. package/src/prover/zenon/check/functions.ts +62 -0
  301. package/src/prover/zenon/check/keys.ts +125 -0
  302. package/src/prover/zenon/check/propositional.ts +104 -0
  303. package/src/prover/zenon/check/records.ts +188 -0
  304. package/src/prover/zenon/check/relations.ts +121 -0
  305. package/src/prover/zenon/check/rewrites.ts +224 -0
  306. package/src/prover/zenon/check/sets.ts +302 -0
  307. package/src/prover/zenon/check/terms.ts +127 -0
  308. package/src/prover/zenon/check/tla.ts +126 -0
  309. package/src/prover/zenon/decide.ts +107 -0
  310. package/src/prover/zenon/encode.ts +378 -0
  311. package/src/prover/zenon/eqrel.ts +300 -0
  312. package/src/prover/zenon/equality-rules.ts +435 -0
  313. package/src/prover/zenon/expr.ts +551 -0
  314. package/src/prover/zenon/index-table.ts +350 -0
  315. package/src/prover/zenon/isar-case.ts +513 -0
  316. package/src/prover/zenon/isar.ts +1249 -0
  317. package/src/prover/zenon/limits.ts +15 -0
  318. package/src/prover/zenon/llproof.ts +173 -0
  319. package/src/prover/zenon/mltoll.ts +1566 -0
  320. package/src/prover/zenon/node.ts +297 -0
  321. package/src/prover/zenon/ocaml.ts +169 -0
  322. package/src/prover/zenon/parse.ts +247 -0
  323. package/src/prover/zenon/phrase.ts +191 -0
  324. package/src/prover/zenon/proof.ts +198 -0
  325. package/src/prover/zenon/propositional-rules.ts +387 -0
  326. package/src/prover/zenon/rules.ts +94 -0
  327. package/src/prover/zenon/search.ts +288 -0
  328. package/src/prover/zenon/tla/functions.ts +151 -0
  329. package/src/prover/zenon/tla/llproof.ts +480 -0
  330. package/src/prover/zenon/tla/records.ts +225 -0
  331. package/src/prover/zenon/tla/rewrites.ts +447 -0
  332. package/src/prover/zenon/tla/sets.ts +304 -0
  333. package/src/prover/zenon/tla/terms.ts +162 -0
  334. package/src/prover/zenon/tla/tla.ts +506 -0
  335. package/src/randomization.ts +39 -27
  336. package/src/resolve.ts +1474 -426
  337. package/src/runtime.ts +25 -7
  338. package/src/sany/builtins.ts +147 -0
  339. package/src/sany/generator.ts +3111 -0
  340. package/src/sany/levels.ts +1205 -0
  341. package/src/sany/lexer.ts +544 -0
  342. package/src/sany/linter.ts +122 -0
  343. package/src/sany/modules.ts +1398 -0
  344. package/src/sany/nodes.ts +463 -0
  345. package/src/sany/parse-error.ts +2161 -0
  346. package/src/sany/report.ts +355 -0
  347. package/src/sany/selectors.ts +736 -0
  348. package/src/sany/source.ts +247 -0
  349. package/src/sany/xml.ts +1016 -0
  350. package/src/search.ts +969 -0
  351. package/src/spec-description.ts +66 -29
  352. package/src/{standard-levels.ts → standard-definitions.ts} +118 -2
  353. package/src/standard-modules.ts +215 -164
  354. package/src/state-graph.ts +181 -0
  355. package/src/subexpressions.ts +231 -171
  356. package/src/substitution-levels.ts +40 -19
  357. package/src/successors.ts +253 -125
  358. package/src/symmetry.ts +194 -54
  359. package/src/tableau.ts +60 -32
  360. package/src/tlc/fingerprint.ts +214 -0
  361. package/src/{tlc-modules.ts → tlc/jar-data.ts} +4 -0
  362. package/src/tlc/messages.ts +441 -0
  363. package/src/{tlc-order.ts → tlc/order.ts} +84 -16
  364. package/src/{tlc-random.ts → tlc/random.ts} +30 -189
  365. package/src/tlc/replay.ts +659 -0
  366. package/src/{tlc-summary.ts → tlc/summary.ts} +20 -5
  367. package/src/{tlc-module.ts → tlc/tlc-operators.ts} +59 -50
  368. package/src/{tlc-ext.ts → tlc/tlcext-operators.ts} +63 -45
  369. package/src/tlc/version.ts +19 -0
  370. package/src/transfer.ts +44 -32
  371. package/src/values.ts +843 -241
  372. package/src/worker.ts +62 -0
  373. package/dist/parallel.cjs +0 -12
  374. package/dist/parallel.js +0 -12
  375. package/dist/run-cli.cjs +0 -28
  376. package/dist/run-cli.js +0 -28
  377. package/src/canonical.ts +0 -39
  378. package/src/cli-options.ts +0 -58
  379. package/src/obligation-expression.ts +0 -1060
  380. package/src/obligation-module.ts +0 -1042
  381. package/src/run-cli.ts +0 -478
package/src/check.ts CHANGED
@@ -1,34 +1,62 @@
1
- import type { Assumption, Definition, Expression, SourceLocation } from "./ast";
2
- import { parseConfig, type ConfigValue, type ModelConfig } from "./config";
3
- import { getReadVariables } from "./dependencies";
1
+ import type { Expression } from "./ast";
2
+ import { parseConfig, type ModelConfig } from "./config";
4
3
  import { createEnvironment } from "./environment";
5
- import { getErrorExitCode, TlaConfigError, TlaEvaluationError, TlaModuleError } from "./errors";
6
- import { EXIT_STATUS, setExitCode, setNextStatePhase, withLivenessExitCode } from "./exit-codes";
7
4
  import {
8
- describeRange,
5
+ createStackOverflowError,
6
+ getErrorExitCode,
7
+ isStackOverflow,
8
+ TlaConfigError,
9
+ TlaEvaluationError,
10
+ TlaIllegalStateError,
11
+ TlaIncompleteSuccessorError,
12
+ TlaModuleError,
13
+ TlaStackOverflowError,
14
+ UNEXPECTED_EVAL_EXCEPTION,
15
+ UNEXPECTED_EXCEPTION,
16
+ } from "./errors";
17
+ import {
18
+ createTracingEnvironment,
9
19
  evaluate,
10
- expectBoolean,
11
20
  formatRange,
12
- getChildren,
13
21
  getDefinition,
14
- isConstantLevel,
15
22
  isImpure,
16
- isLocallyResolved,
17
- type Context,
23
+ type CallStack,
18
24
  type Environment,
19
- type Scope,
25
+ type FingerprintFailure,
20
26
  } from "./evaluate";
27
+ import { EXIT_STATUS, getExitCode, setExitCode, withLivenessExitCode } from "./exit-codes";
28
+ import type { JavaOverride } from "./java-overrides";
21
29
  import {
22
30
  createLivenessChecker,
23
- expandTemporal,
24
- getLevel,
25
31
  type Lasso,
32
+ type LivenessChecker,
26
33
  type LiveSuccessor,
27
- type ScopedExpression,
28
- type TemporalProperty,
29
- } from "./liveness";
30
- import { ACTION_LEVEL, createLevelAnalyzer, TEMPORAL_LEVEL } from "./levels";
31
- import { prettyPrint } from "./pretty-print";
34
+ } from "./liveness-checker";
35
+ import {
36
+ createIdentifier,
37
+ createSearch,
38
+ findAssumptionViolation,
39
+ getConfigDefinition,
40
+ getContext,
41
+ reportInitialStatesProgress,
42
+ reportStartup,
43
+ withNextStateExitCode,
44
+ } from "./search";
45
+ import {
46
+ getActionLabel,
47
+ getActionSignature,
48
+ getInitActions,
49
+ getNextActions,
50
+ getSpecificationValue,
51
+ toActionValue,
52
+ type SpecAction,
53
+ } from "./spec-description";
54
+ import {
55
+ createStateWriter,
56
+ type GraphState,
57
+ type StateDump,
58
+ type StateWriter,
59
+ } from "./state-graph";
32
60
  import {
33
61
  forEachInitialState,
34
62
  forEachSuccessor,
@@ -37,26 +65,34 @@ import {
37
65
  type Successor,
38
66
  } from "./successors";
39
67
  import {
40
- getActionLabel,
41
- getNextActions,
42
- getSpecificationValue,
43
- type SpecAction,
44
- } from "./spec-description";
45
- import { getRepresentative, getSymmetryGroup } from "./symmetry";
46
- import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
47
- import { createTlcFingerprinter, getTlcFingerprint } from "./tlc-random";
48
- import { createCanonicalizer } from "./canonical";
49
- import { getPossibleCounts, type CheckerRuntime } from "./runtime";
50
- import { createCounterExample } from "./tlc-ext";
51
- import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc-summary";
68
+ formatNestedMessage,
69
+ getCodedMessage,
70
+ getFailureMessage,
71
+ getWrappedException,
72
+ isEvalException,
73
+ isHeadedError,
74
+ MESSAGE_CODE,
75
+ withUnexpectedException,
76
+ type FailureMessage,
77
+ } from "./tlc/messages";
78
+ import { getTlcStringOrder, getTlcVariableOrder } from "./tlc/order";
79
+ import { replayInitialStates, replaySuccessors } from "./tlc/replay";
80
+ import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc/summary";
81
+ import { createActionRecord, createCounterExample } from "./tlc/tlcext-operators";
82
+ import type { TlcVersion } from "./tlc/version";
52
83
  import {
53
84
  combineHash,
54
- formatValue,
85
+ createCanonicalizer,
86
+ createModelValue,
87
+ formatState,
88
+ getFingerprintError,
89
+ getHeldValues,
55
90
  getValueHash,
56
91
  isFunctionValue,
57
92
  isSameValue,
58
- isUpdatedElementOf,
93
+ markFingerprinted,
59
94
  setStringOrder,
95
+ setValueVersion,
60
96
  toFiniteFunction,
61
97
  type Value,
62
98
  } from "./values";
@@ -74,8 +110,69 @@ export interface CheckOptions {
74
110
  workers?: number;
75
111
  // TLC's -lncheck: "final" checks liveness only on the complete state graph.
76
112
  livenessCheck?: "default" | "final";
113
+ // TLC's -dump: writes the reachable states, or with `dot` the state graph, through writeFile.
114
+ dump?: StateDump;
115
+ // TLC's -tool, which changes the messages of TLC's errors.
116
+ isTool?: boolean;
117
+ // Whether TLC records a binary trace for its trace exploration spec, for which it loads Integers.
118
+ isTraceRecorded?: boolean;
119
+ // Whether the caller printed SANY's report, its warnings included, before the check.
120
+ isSanyReported?: boolean;
121
+ // False for TLC's -nowarning, which changes how TLC computes the successors of some actions.
122
+ isWarningEnabled?: boolean;
123
+ // The TLC whose output tla-ts reproduces, which changes how TLC labels an action.
124
+ version?: TlcVersion;
125
+ // Reports the points of the search at which TLC prints a message.
126
+ onProgress?: (progress: CheckProgress) => void;
127
+ }
128
+
129
+ export interface InitialStatesProgress {
130
+ kind: "initial-states-progress";
131
+ count: number;
132
+ }
133
+
134
+ // A check that TLC's DoInitFunctor reports as violated before it stops its replay of the initial
135
+ // states.
136
+ export interface InitialStateViolation {
137
+ kind: "initial-state-violation";
138
+ status: "invariant-violation" | "liveness-violation";
139
+ name: string;
140
+ state: Record<string, Value>;
77
141
  }
78
142
 
143
+ // A line the spec prints, or what TLC reports as it replays the initial states.
144
+ export type OutputLine = string | InitialStatesProgress | InitialStateViolation;
145
+
146
+ // The points of the search at which TLC prints a message.
147
+ export type CheckProgress =
148
+ | { kind: "parsed" }
149
+ | { kind: "constant-level-invariant"; name: string }
150
+ | { kind: "state-level-property"; name: string }
151
+ | { kind: "liveness-initializing"; isSymmetric: boolean; isConstrained: boolean }
152
+ | { kind: "liveness-prepared"; branches: number }
153
+ | { kind: "initial-states-started" }
154
+ | InitialStatesProgress
155
+ | { kind: "initial-states-computed"; initialStates: InitialStates }
156
+ | { kind: "progress"; statistics: SearchStatistics }
157
+ | {
158
+ kind: "liveness-started";
159
+ branches: number;
160
+ // Whether TLC checks the complete state graph, and how many states of it each branch has.
161
+ isComplete: boolean;
162
+ states: number;
163
+ statistics: SearchStatistics;
164
+ }
165
+ | { kind: "liveness-finished" }
166
+ // A warning TLC prints as it evaluates the spec, with its message code.
167
+ | { kind: "warning"; code: number; text: string }
168
+ // A method of the class named after a module, which TLC reports as it loads the class.
169
+ | ({ kind: "java-override" } & JavaOverride);
170
+
171
+ export interface SearchStatistics extends Pick<
172
+ CheckResult,
173
+ "generatedStates" | "distinctStates" | "queuedStates" | "depth"
174
+ > {}
175
+
79
176
  export type CheckStatus =
80
177
  | "success"
81
178
  | "assumption-violation"
@@ -91,30 +188,74 @@ export interface TraceStep {
91
188
  // TLC's name, parameters and location for the action that took this step.
92
189
  label: string | undefined;
93
190
  state: Record<string, Value>;
191
+ // What the spec prints, before TLC prints this step, as TLC evaluates it again to rebuild the
192
+ // trace. The first step has what TLC prints before the trace.
193
+ output?: OutputLine[];
94
194
  }
95
195
 
96
196
  export interface Violation {
97
197
  name: string;
198
+ // Every temporal property that a liveness counterexample violates, in the configuration's order.
199
+ properties?: string[];
98
200
  trace: TraceStep[];
201
+ // What the spec prints after TLC prints the states of the trace, as TLC finds the step back into
202
+ // the cycle of a lasso or rebuilds the trace once more.
203
+ traceOutput?: OutputLine[];
99
204
  loopStart: number | undefined;
100
205
  loopLabel?: string;
101
206
  message?: string;
102
207
  counts?: string;
103
208
  unwitnessed?: Postcondition;
209
+ // A POSTCONDITION that is false or fails after the counterexample, which TLC checks as it
210
+ // prints one.
211
+ postcondition?: Postcondition;
212
+ // What TLC warns about after a counterexample, with its code.
213
+ warning?: { code: number; text: string };
104
214
  }
105
215
 
106
- interface Postcondition {
216
+ export interface Postcondition {
107
217
  name: string;
218
+ // TLC's message code.
219
+ code: number;
108
220
  message: string;
109
221
  counts?: string;
110
222
  }
111
223
 
112
224
  // An evaluation that failed during the search, with the behavior up to the state TLC was working on.
113
225
  export interface EvaluationFailure {
226
+ // TLC's code for the message, and its text with and without -tool.
227
+ code: number;
114
228
  message: string;
229
+ toolMessage: string;
115
230
  trace: TraceStep[];
231
+ traceOutput?: OutputLine[];
116
232
  initialState: Record<string, Value> | undefined;
117
233
  exitCode: number;
234
+ // The expressions TLC was evaluating when the failure occurred, outermost first, when TLC finds
235
+ // them by replaying the failure.
236
+ callStack: Expression[] | undefined;
237
+ // Whether TLC prints the call stack before the error, as it does for a failed liveness check.
238
+ isCallStackFirst?: boolean;
239
+ // The FingerprintException the replay raises, which TLC reports in place of the call stack.
240
+ fingerprint?: FingerprintFailure;
241
+ // How TLC reports failing again as it prints the trace, since it can't fingerprint the state the
242
+ // failure occurred in.
243
+ traceFailure?: FailureMessage;
244
+ // A POSTCONDITION that is false or fails after the trace, which TLC checks as it prints one.
245
+ postcondition?: Postcondition;
246
+ // Whether TLC stops before it prints the statistics, as it does for an illegal initial state.
247
+ isWithoutStatistics?: boolean;
248
+ }
249
+
250
+ // Where TLC's replay of a failure fails.
251
+ interface ReplayFailure {
252
+ callStack: Expression[];
253
+ fingerprint: FingerprintFailure | undefined;
254
+ }
255
+
256
+ export interface InitialStates {
257
+ generated: number;
258
+ distinct: number;
118
259
  }
119
260
 
120
261
  export interface CheckResult {
@@ -125,144 +266,58 @@ export interface CheckResult {
125
266
  distinctStates: number;
126
267
  queuedStates: number;
127
268
  depth: number;
269
+ // How many initial states TLC generated and how many of them were distinct, once it computed
270
+ // them all without a violation or an error.
271
+ initialStates: InitialStates | undefined;
128
272
  // How many states that TLC counts as expanded found each number of new states, when TLC prints
129
273
  // the outdegree of the state graph.
130
274
  outDegrees: number[] | undefined;
131
275
  // The smallest distance between the fingerprints of two distinct states, when TLC estimates a
132
276
  // collision from the actual fingerprints.
133
277
  fingerprintDistance: bigint | undefined;
278
+ // A temporal property TLC finds violated as it adds a deadlocked state to the behavior graph,
279
+ // which it reports after the deadlock.
280
+ additionalViolation?: Violation;
281
+ // Where TLC's worker fails to add the state to the behavior graph after it reports a violation.
282
+ liveCallStack?: Expression[];
283
+ // How many states that TLC counts as expanded found each number of new states, when its workers
284
+ // stop on a violation without an error code, which TLC 1.7.4 reports as a successful search.
285
+ violationOutDegrees?: number[];
134
286
  }
135
287
 
136
- interface NamedExpression {
137
- name: string;
138
- expression: Expression;
139
- scope: Scope | undefined;
140
- }
141
-
142
- interface StateCheck extends NamedExpression {
143
- variables: number[] | undefined;
144
- membership: Membership | undefined;
145
- }
146
-
147
- // A conjunct `x \in S` whose S reads no variables.
148
- interface Membership {
149
- variable: number;
150
- set: Expression;
151
- }
152
-
153
- interface ActionProperty {
154
- name: string;
155
- box: Expression;
156
- action: Expression;
157
- subscript: Expression;
158
- scope: Scope | undefined;
288
+ interface Behavior {
289
+ trace: TraceStep[];
290
+ traceOutput?: OutputLine[];
159
291
  }
160
292
 
161
- interface Specification {
162
- init: Expression | undefined;
163
- next: Expression | undefined;
164
- scope: Scope | undefined;
165
- temporals: ScopedExpression[];
293
+ interface TraceOptions {
294
+ loopStart?: number;
295
+ known?: number;
166
296
  }
167
297
 
168
- interface Properties {
169
- initialPredicates: NamedExpression[];
170
- invariants: NamedExpression[];
171
- actionProperties: ActionProperty[];
172
- liveness: TemporalProperty[];
298
+ interface FailureOptions {
299
+ initialState?: Value[];
300
+ isInitial?: boolean;
301
+ outDegrees?: number[];
302
+ callStack?: Expression[];
303
+ fingerprint?: FingerprintFailure;
304
+ isNextState?: boolean;
305
+ isCallStackFirst?: boolean;
306
+ traceFailure?: FailureMessage;
307
+ // Whether the call stack is of adding the state to the behavior graph, which TLC prints instead
308
+ // of replaying the error.
309
+ isLiveCallStack?: boolean;
173
310
  }
174
311
 
175
- const START: SourceLocation = { line: 0, column: 0 };
312
+ // TLC prints what the spec prints as it replays a failure after the trace.
313
+ const appendTraceOutput = <Traced extends Behavior>(behavior: Traced, lines: OutputLine[]) => ({
314
+ ...behavior,
315
+ traceOutput: [...(behavior.traceOutput ?? []), ...lines],
316
+ });
176
317
 
177
318
  const INITIAL_RECOVERY_FAILURE = "Failed to recover the initial state from its fingerprint.";
178
319
  const NEXT_RECOVERY_FAILURE = "Failed to recover the next state from its fingerprint.";
179
320
 
180
- const createIdentifier = (name: string): Expression => ({
181
- kind: "Identifier",
182
- name,
183
- location: START,
184
- });
185
-
186
- // TLC leaves the kind out when it rejects arguments to the specification or a property.
187
- const UNNAMED_ARGUMENT_KINDS = new Set(["name", "property"]);
188
-
189
- // TLC checks liveness on the graph so far 3 seconds into the search and then every minute, once
190
- // the graph has grown by a tenth and liveness checking has taken at most a fifth of the time.
191
- const PERIODIC_START = 3000;
192
- const PROGRESS_INTERVAL = 60_000;
193
- const LIVENESS_GROWTH = 0.1;
194
- const LIVENESS_RATIO = 0.2;
195
-
196
- const getConfigOperator = (kind: string, name: string, environment: Environment) => {
197
- const definition = getDefinition(name, environment);
198
- if (!definition) {
199
- throw new TlaConfigError(
200
- `The ${kind} ${name} specified in the configuration file\nis not defined in the specification.`,
201
- );
202
- }
203
- if (definition.kind === "Operator" && definition.params.length > 0) {
204
- throw new TlaConfigError(
205
- UNNAMED_ARGUMENT_KINDS.has(kind)
206
- ? `TLC requires ${name} not to take any argument.`
207
- : `TLC requires ${kind} not to take any argument, but one was given: ${name}`,
208
- );
209
- }
210
- return definition;
211
- };
212
-
213
- const getConfigDefinition = (kind: string, name: string, environment: Environment) => {
214
- const definition = getConfigOperator(kind, name, environment);
215
- if (isConstantLevel(definition, environment)) {
216
- throw new TlaConfigError(`The ${kind} ${name} cannot be a constant.`);
217
- }
218
- return definition;
219
- };
220
-
221
- // TLC evaluates every constant definition before it reads the configuration. It keeps a literal
222
- // number or string, and a definition that fails to evaluate, as an operator.
223
- const getConstantValue = (name: string, definition: Definition, environment: Environment) => {
224
- if (!isConstantLevel(definition, environment)) return undefined;
225
- if (definition.body.kind === "Number" || definition.body.kind === "String") return undefined;
226
- try {
227
- return evaluate(createIdentifier(name), getContext(environment, undefined, undefined));
228
- } catch (error) {
229
- if (error instanceof TlaEvaluationError) return undefined;
230
- throw error;
231
- }
232
- };
233
-
234
- const getConfigPredicate = (kind: string, name: string, environment: Environment) => {
235
- const definition = getConfigOperator(kind, name, environment);
236
- const value = getConstantValue(name, definition, environment);
237
- if (value !== undefined && value !== true) {
238
- throw new TlaConfigError(`The ${kind} of ${name} is equal to ${formatValue(value)}`);
239
- }
240
- return value === undefined ? definition : undefined;
241
- };
242
-
243
- const getInvariants = (names: string[], environment: Environment) => {
244
- const analyzer = createLevelAnalyzer({
245
- constants: new Set(environment.constants.keys()),
246
- variables: new Set(environment.variables),
247
- getDefinition: (name) => getDefinition(name, environment),
248
- });
249
- return names.flatMap((name) => {
250
- const definition = getConfigPredicate("invariant", name, environment);
251
- if (!definition) return [];
252
- const levels = analyzer.analyzeDefinition(definition, new Map());
253
- if (levels.level >= ACTION_LEVEL) {
254
- const note =
255
- levels.params.size === 0
256
- ? ""
257
- : "\nNote that a bug can cause TLC to incorrectly report this error.\nIf you believe your TLA+ or PlusCal specification to be correct,\nplease check if this bug described in LevelNode.java starting at line 590ff affects you.";
258
- throw new TlaConfigError(
259
- `The invariant ${name} is not a state predicate (one with no primes or temporal operators).${note}`,
260
- );
261
- }
262
- return [{ name, expression: createIdentifier(name), scope: undefined }];
263
- });
264
- };
265
-
266
321
  const toAliasRecord = (value: Value, fieldOrder: string[]) => {
267
322
  if (!isFunctionValue(value)) return undefined;
268
323
  const record = toFiniteFunction(value);
@@ -276,612 +331,83 @@ const toAliasRecord = (value: Value, fieldOrder: string[]) => {
276
331
  );
277
332
  };
278
333
 
279
- const getConjuncts = (expression: Expression, environment: Environment): Expression[] => {
280
- if (expression.kind === "And")
281
- return expression.operands.flatMap((operand) => getConjuncts(operand, environment));
282
- if (expression.kind === "Identifier" && !environment.constants.has(expression.name)) {
283
- const definition = getDefinition(expression.name, environment);
284
- if (definition?.kind === "Operator" && definition.params.length === 0) {
285
- return getConjuncts(definition.body, environment);
286
- }
287
- }
288
- return [expression];
289
- };
334
+ // Stops a replay where TLC stops it without a failure, as at a violated invariant.
335
+ const STOP_REPLAY = new Error("The replay stopped");
290
336
 
291
- const isConstantTrue = (item: ScopedExpression, environment: Environment, usage: string) => {
292
- const conjunct = item.expression;
293
- if (conjunct.kind !== "Identifier" || getLevel(conjunct, item.scope, environment) > 0) {
294
- return false;
295
- }
296
- const value = evaluate(conjunct, getContext(environment, undefined, undefined, item.scope));
297
- if (value === false) {
298
- throw new TlaConfigError(`The spec is trivially false because ${conjunct.name} is false.`);
299
- }
300
- if (value !== true) {
301
- throw new TlaConfigError(
302
- `The operator ${conjunct.name}, which equals ${formatValue(value)},\ncannot be used as a ${usage}`,
303
- );
304
- }
305
- return true;
306
- };
337
+ // The codes of the errors in the configuration and the spec that TLC's EC.ExitStatus maps to a
338
+ // configuration error.
339
+ const CONFIG_ERROR_CODES = new Set([
340
+ ...Array.from({ length: 24 }, (_, index) => 2222 + index),
341
+ 2272,
342
+ 2273,
343
+ 2274,
344
+ 2280,
345
+ 2281,
346
+ ]);
307
347
 
308
- const getSpecification = (config: ModelConfig, environment: Environment): Specification => {
309
- if (config.specification === undefined) {
310
- const getOperator = (name: string | undefined, description: string) => {
311
- if (name === undefined) return undefined;
312
- const body = getConfigOperator(description, name, environment).body;
313
- const identifier = createIdentifier(name);
314
- // TLC evaluates a literal body later and reports that it is not a boolean.
315
- const isLiteral = body.kind === "Number" || body.kind === "String";
316
- if (!isLiteral && getLevel(identifier, undefined, environment) === 0) {
317
- throw new TlaConfigError(`The ${description} ${name} cannot be a constant.`);
318
- }
319
- return identifier;
320
- };
321
- return {
322
- init: getOperator(config.init, "initial predicate"),
323
- next: getOperator(config.next, "next state action"),
324
- scope: undefined,
325
- temporals: [],
326
- };
327
- }
328
- const initConjuncts: ScopedExpression[] = [];
329
- const nextActions: ScopedExpression[] = [];
330
- const temporals: ScopedExpression[] = [];
331
- const definition = getConfigOperator("name", config.specification, environment);
332
- const value = getConstantValue(config.specification, definition, environment);
333
- if (value !== undefined) {
334
- throw new TlaConfigError(
335
- `The value of ${config.specification} is equal to ${formatValue(value)}`,
336
- );
337
- }
338
- expandTemporal(definition.body, undefined, environment, false).forEach((item) => {
339
- const conjunct = item.expression;
340
- if (isConstantTrue(item, environment, "spec")) return;
341
- if (conjunct.kind === "UnboundedQuantifier" && conjunct.isTemporal) {
342
- throw setExitCode(
343
- new TlaConfigError(
344
- "TLC does not support temporal existential, nor universal, quantification over state variables.",
345
- ),
346
- EXIT_STATUS.error,
347
- );
348
- }
349
- if (conjunct.kind === "Always" && conjunct.expression.kind === "BoxAction") {
350
- nextActions.push({ expression: conjunct.expression.action, scope: item.scope });
351
- return;
352
- }
353
- if (
354
- conjunct.kind === "Always" &&
355
- getLevel(conjunct.expression, item.scope, environment) < ACTION_LEVEL
356
- ) {
357
- throw new TlaConfigError(
358
- `TLC cannot handle []P in the specification ${config.specification} when P is a state predicate`,
359
- );
360
- }
361
- const level = getLevel(conjunct, item.scope, environment);
362
- if (level === TEMPORAL_LEVEL) {
363
- temporals.push(item);
364
- return;
365
- }
366
- if (level === ACTION_LEVEL) {
367
- throw new TlaConfigError(
368
- `TLC cannot handle the action-level conjunct of the specification ${config.specification}`,
369
- );
370
- }
371
- initConjuncts.push(item);
372
- });
373
- if (nextActions.length > 1) {
374
- throw new TlaConfigError(
375
- `The specification ${config.specification} must contain at most one [][Next]_vars`,
376
- );
377
- }
378
- const items = [...initConjuncts, ...nextActions];
379
- const getName = (index: number) => `$specification${index}`;
380
- const scope = items.reduce<Scope | undefined>(
381
- (parent, item, index) =>
382
- item.scope === undefined
383
- ? parent
384
- : {
385
- name: getName(index),
386
- binding: {
387
- kind: "Thunk",
388
- expression: item.expression,
389
- scope: item.scope,
390
- state: undefined,
391
- next: undefined,
392
- cache: undefined,
393
- },
394
- parent,
395
- },
396
- undefined,
397
- );
398
- const getReference = (item: ScopedExpression, index: number): Expression =>
399
- item.scope === undefined
400
- ? item.expression
401
- : {
402
- kind: "Identifier",
403
- name: getName(index),
404
- location: item.expression.location,
405
- resolution: { kind: "Local" },
406
- };
407
- return {
408
- init:
409
- initConjuncts.length === 0
410
- ? undefined
411
- : { kind: "And", operands: initConjuncts.map(getReference), location: START },
412
- next: nextActions.length === 0 ? undefined : getReference(nextActions[0], initConjuncts.length),
413
- scope,
414
- temporals,
415
- };
416
- };
417
-
418
- const getProperties = (config: ModelConfig, environment: Environment): Properties => {
419
- const properties: Properties = {
420
- initialPredicates: [],
421
- invariants: [],
422
- actionProperties: [],
423
- liveness: [],
424
- };
425
- config.properties.forEach((name) => {
426
- const definition = getConfigPredicate("property", name, environment);
427
- if (!definition) return;
428
- expandTemporal(definition.body, undefined, environment, true).forEach((item) => {
429
- const conjunct = item.expression;
430
- if (isConstantTrue(item, environment, "property")) return;
431
- if (conjunct.kind === "Always" && conjunct.expression.kind === "BoxAction") {
432
- properties.actionProperties.push({
433
- name,
434
- box: conjunct.expression,
435
- action: conjunct.expression.action,
436
- subscript: conjunct.expression.subscript,
437
- scope: item.scope,
438
- });
439
- return;
440
- }
441
- if (
442
- conjunct.kind === "Always" &&
443
- getLevel(conjunct.expression, item.scope, environment) <= 1
444
- ) {
445
- properties.invariants.push({ name, expression: conjunct.expression, scope: item.scope });
446
- return;
447
- }
448
- const level = getLevel(conjunct, item.scope, environment);
449
- if (level < ACTION_LEVEL) {
450
- properties.initialPredicates.push({ name, expression: conjunct, scope: item.scope });
451
- return;
452
- }
453
- if (level === ACTION_LEVEL) {
454
- throw new TlaConfigError(`The property ${name} is an action-level formula`);
455
- }
456
- properties.liveness.push({ name, expression: conjunct, scope: item.scope });
457
- });
458
- });
459
- return properties;
460
- };
461
-
462
- const getNamedExpressions = (
463
- kind: string,
464
- names: string[],
465
- environment: Environment,
466
- ): NamedExpression[] =>
467
- names.flatMap((name) =>
468
- getConfigPredicate(kind, name, environment)
469
- ? [{ name, expression: createIdentifier(name), scope: undefined }]
470
- : [],
471
- );
472
-
473
- const getBodyRange = (name: string, environment: Environment) => {
474
- const definition = getDefinition(name, environment);
475
- return definition?.kind === "Operator" ? definition.bodyRange : undefined;
476
- };
477
-
478
- const getPossiblePredicates = (names: string[], environment: Environment) =>
479
- names.map((name, index) => {
480
- if (names.indexOf(name) !== index) {
481
- throw new TlaConfigError(`_POSSIBLE lists ${name} more than once`);
482
- }
483
- getConfigDefinition("possible", name, environment);
484
- const expression = createIdentifier(name);
485
- if (getLevel(expression, undefined, environment) === TEMPORAL_LEVEL) {
486
- throw new TlaConfigError(
487
- `The possible of ${name} is equal to a temporal formula; only state- and action-level predicates are supported`,
488
- );
489
- }
490
- return { name, expression, scope: undefined };
491
- });
492
-
493
- const getMembership = (
494
- expression: Expression,
495
- variables: number[] | undefined,
496
- environment: Environment,
497
- ): Membership | undefined => {
498
- if (expression.kind !== "Apply" || expression.operator !== "\\in" || variables?.length !== 1)
499
- return undefined;
500
- const element = expression.args[0];
501
- if (element.kind !== "Identifier" || isLocallyResolved(element)) return undefined;
502
- return environment.variableIndex.get(element.name) === variables[0]
503
- ? { variable: variables[0], set: expression.args[1] }
504
- : undefined;
505
- };
506
-
507
- const getStateChecks = (named: NamedExpression[], environment: Environment): StateCheck[] =>
508
- named.flatMap((item) =>
509
- getConjuncts(item.expression, environment).map((expression) => {
510
- const variables = getReadVariables(expression, environment);
511
- return {
512
- name: item.name,
513
- expression,
514
- scope: item.scope,
515
- variables,
516
- membership: getMembership(expression, variables, environment),
517
- };
518
- }),
519
- );
520
-
521
- const isUnchangedFor = (stateCheck: StateCheck, state: Value[], parent: Value[] | undefined) => {
522
- const variables = stateCheck.variables;
523
- if (!parent || !variables) return false;
524
- for (let index = 0; index < variables.length; index++) {
525
- if (state[variables[index]] !== parent[variables[index]]) return false;
526
- }
527
- return true;
528
- };
529
-
530
- const WIDE_CHARACTER = /[\u0100-\uffff]/;
531
-
532
- const DESERIALIZERS = new Set(["JsonDeserialize", "ndJsonDeserialize"]);
533
-
534
- const isWideConfigValue = (value: ConfigValue): boolean =>
535
- value.kind === "String"
536
- ? WIDE_CHARACTER.test(value.value)
537
- : value.kind === "Set" && value.elements.some(isWideConfigValue);
538
-
539
- const isWideExpression = (expression: Expression): boolean =>
540
- (expression.kind === "String" && WIDE_CHARACTER.test(expression.value)) ||
541
- (expression.kind === "Apply" && DESERIALIZERS.has(expression.operator)) ||
542
- getChildren(expression).some(isWideExpression);
543
-
544
- // TLC fingerprints a string by the low byte of each character, so it merges states whose
545
- // strings differ only above U+00FF. Strings reach a state from literals, the config, or files.
546
- const hasWideString = (config: ModelConfig, environment: Environment) =>
547
- config.constants.some(
548
- (constant) =>
549
- isWideConfigValue(constant.value) || (constant.args ?? []).some(isWideConfigValue),
550
- ) ||
551
- [...environment.definitions.values()].some(
552
- (definition) =>
553
- isWideExpression(definition.body) ||
554
- (definition.kind === "Function" &&
555
- definition.bounds.some((bound) => isWideExpression(bound.set))),
556
- );
557
-
558
- interface Search {
559
- properties: Properties;
560
- spec: Specification;
561
- getFingerprintState: (state: Value[]) => Value[];
562
- getStoredFingerprints: (states: Value[][], fingerprintStates: Value[][]) => BigInt64Array;
563
- getTlcOrder: () => number[];
564
- isSymmetric: boolean;
565
- findViolatedInvariant: (state: Value[], parent?: Value[]) => StateCheck | undefined;
566
- satisfiesConstraints: (state: Value[], parent?: Value[]) => boolean;
567
- findFailedInitialPredicate: (state: Value[]) => NamedExpression | undefined;
568
- findViolatedActionProperty: (state: Value[], next: Value[]) => ActionProperty | undefined;
569
- satisfiesActionConstraints: (state: Value[], next: Value[]) => boolean;
570
- trackStatePossible: (state: Value[]) => void;
571
- trackActionPossible: (state: Value[], next: Value[]) => void;
572
- findUnwitnessedPossible: () => Postcondition | undefined;
573
- findPostconditionViolation: () => Postcondition | undefined;
574
- }
575
-
576
- const getContext = (
577
- environment: Environment,
578
- state: Value[] | undefined,
579
- next: Value[] | undefined,
580
- scope?: Scope,
581
- ) => ({ environment, scope, state, next });
582
-
583
- const holds = (expression: Expression, context: Context, description: string) =>
584
- expectBoolean(evaluate(expression, context), description);
585
-
586
- // TLC names a check that is not a boolean by the location of the predicate it evaluates.
587
- const holdsLikeTlc = (
588
- expression: Expression,
589
- context: Context,
590
- getMessage = getExpectedBoolean,
591
- ) => {
592
- const value = evaluate(expression, context);
593
- if (typeof value !== "boolean") {
594
- throw new TlaEvaluationError(getMessage(expression, context.environment));
595
- }
596
- return value;
348
+ // When TLC's replay of the initial states doesn't fail again, it exits with the code of the
349
+ // TLCRuntimeException it reported.
350
+ const getInitialExitCode = (error: TlaEvaluationError) => {
351
+ const coded = getCodedMessage(error.message);
352
+ return coded && !coded.isEvalException && CONFIG_ERROR_CODES.has(coded.code)
353
+ ? EXIT_STATUS.configParseError
354
+ : getErrorExitCode(error);
597
355
  };
598
356
 
599
- // SANY prints a number by its digits and any other expression by its location.
600
- const getExpectedBoolean = (expression: Expression, environment: Environment) => {
601
- const definition =
602
- expression.kind === "Identifier" ? getDefinition(expression.name, environment) : undefined;
603
- const body = definition?.kind === "Operator" ? definition.body : expression;
604
- const range = definition?.kind === "Operator" ? definition.bodyRange : undefined;
605
- const location =
606
- body.kind === "Number"
607
- ? (body.text ?? String(body.value))
608
- : range
609
- ? formatRange(range)
610
- : describeRange(body);
611
- return `TLC expected a boolean value, but did not find one. ${location}`;
357
+ // When TLC's replay of an error fails again, an EvalException from a standard module's Java code
358
+ // decides the exit status, and any other failure exits as a nested expression failure. An error
359
+ // that heads or wraps another exits as the other.
360
+ const getReplayExitCode = (error: TlaEvaluationError): number => {
361
+ const inner = error.cause;
362
+ if (inner instanceof TlaEvaluationError) return getReplayExitCode(inner);
363
+ return error instanceof TlaModuleError ? error.exitCode : EXIT_STATUS.specEvaluationFailure;
612
364
  };
613
365
 
614
- const ignorePossible = () => {};
615
-
616
- const trackPossible = (items: NamedExpression[], runtime: CheckerRuntime, context: Context) =>
617
- items.forEach((item) => {
618
- const count = runtime.possibleCounts.get(item.name) ?? 0;
619
- const isWitnessed = holds(item.expression, context, `_POSSIBLE ${item.name}`);
620
- runtime.possibleCounts.set(item.name, isWitnessed ? count + 1 : count);
621
- });
622
-
623
- const getConstantFailure = (
624
- expression: Expression,
625
- environment: Environment,
626
- description: string,
627
- ) => {
366
+ // TLC finishes the -dump file whether or not the search finds a violation.
367
+ export const checkSequentially = (options: CheckOptions): CheckResult => {
368
+ const stateWriter =
369
+ options.dump && createStateWriter(options.dump, options.writeFile, options.version);
628
370
  try {
629
- return holds(expression, getContext(environment, undefined, undefined), description)
630
- ? undefined
631
- : { message: undefined };
371
+ return searchStates(options, stateWriter);
632
372
  } catch (error) {
633
- if (error instanceof TlaEvaluationError) return { message: error.message };
634
- throw error;
635
- }
636
- };
637
-
638
- export const findAssumptionViolation = (
639
- assumptions: Assumption[],
640
- environment: Environment,
641
- ): Omit<Violation, "loopStart"> | undefined => {
642
- for (const assumption of assumptions.filter((candidate) => !candidate.isAxiom)) {
643
- const failure = getConstantFailure(assumption.expression, environment, "an assumption");
644
- if (failure) {
645
- return { name: describeRange(assumption.expression), trace: [], message: failure.message };
646
- }
647
- }
648
- return undefined;
649
- };
650
-
651
- export const createSearch = (
652
- config: ModelConfig,
653
- environment: Environment,
654
- getVariableOrder: () => string[],
655
- ): Search | undefined => {
656
- const configInvariants = getInvariants(config.invariants, environment);
657
- const spec = getSpecification(config, environment);
658
- const properties = getProperties(config, environment);
659
- const invariants = getStateChecks([...configInvariants, ...properties.invariants], environment);
660
- const isCheckingBehaviors =
661
- invariants.length > 0 ||
662
- properties.actionProperties.length > 0 ||
663
- properties.liveness.length > 0;
664
- if (
665
- spec.init === undefined &&
666
- (isCheckingBehaviors ||
667
- properties.initialPredicates.length > 0 ||
668
- environment.variables.length > 0)
669
- ) {
670
- throw new TlaConfigError("The configuration file did not specify the initial state predicate.");
671
- }
672
- if (spec.next === undefined && isCheckingBehaviors) {
673
- throw new TlaConfigError("The configuration file did not specify the next state predicate.");
373
+ throw isStackOverflow(error) ? createStackOverflowError() : error;
374
+ } finally {
375
+ stateWriter?.close();
674
376
  }
675
- const constraints = getStateChecks(
676
- getNamedExpressions("constraint", config.constraints, environment),
677
- environment,
678
- );
679
- const actionConstraints = getNamedExpressions(
680
- "action constraint",
681
- config.actionConstraints,
682
- environment,
683
- );
684
- if (config.rlReward !== undefined) getConfigOperator("rlreward", config.rlReward, environment);
685
- if (config.periodic !== undefined) getConfigOperator("periodic", config.periodic, environment);
686
- const possible = getPossiblePredicates(config.possible, environment);
687
- if (environment.variables.length === 0) return undefined;
688
- const symmetryGroup =
689
- config.symmetry === undefined ? [] : getSymmetryGroup(config.symmetry, environment);
690
- if (config.view !== undefined) getConfigOperator("view function", config.view, environment);
691
- const view =
692
- config.view === undefined
693
- ? undefined
694
- : { name: config.view, expression: createIdentifier(config.view), scope: undefined };
695
- const actionProperties = properties.actionProperties.map((property) => {
696
- const unchanged: Expression = {
697
- kind: "Unchanged",
698
- expression: property.subscript,
699
- location: START,
700
- };
701
- return { ...property, unchanged };
702
- });
703
- const isActionPossible = (item: NamedExpression) =>
704
- getLevel(item.expression, undefined, environment) >= ACTION_LEVEL;
705
- const statePossible = possible.filter((item) => !isActionPossible(item));
706
- const actionPossible = possible.filter(isActionPossible);
707
- const runtime = environment.runtime;
708
- const tlcOrder = { indices: undefined as number[] | undefined };
709
- const getTlcOrder = () => {
710
- if (tlcOrder.indices) return tlcOrder.indices;
711
- const variableOrder = getVariableOrder();
712
- const getTlcPosition = (index: number) => {
713
- const position = variableOrder.indexOf(environment.variables[index]);
714
- return position === -1 ? environment.variables.length : position;
715
- };
716
- tlcOrder.indices = environment.variables
717
- .map((_, index) => index)
718
- .sort((left, right) => getTlcPosition(left) - getTlcPosition(right));
719
- return tlcOrder.indices;
720
- };
721
- // A representative in TLC's variable order is the one whose fingerprint TLC reports.
722
- const order = symmetryGroup.length > 0 ? getTlcOrder() : undefined;
723
- const getViewValue = (expression: Expression, state: Value[]) =>
724
- evaluate(expression, getContext(environment, state, undefined));
725
- const getTlcStateFingerprint = (state: Value[]) => {
726
- const indices = getTlcOrder();
727
- const representative =
728
- symmetryGroup.length === 0 ? state : getRepresentative(state, symmetryGroup, indices);
729
- return getTlcFingerprint(
730
- view === undefined
731
- ? indices.map((index) => representative[index])
732
- : [getViewValue(view.expression, representative)],
733
- );
734
- };
735
- const isFingerprintedLikeTlc = hasWideString(config, environment);
736
- runtime.getFingerprint = getTlcStateFingerprint;
737
- const findUnwitnessedPossible = () => {
738
- const unwitnessed = possible.find((item) => !runtime.possibleCounts.get(item.name));
739
- if (!unwitnessed) return undefined;
740
- const range = getBodyRange(unwitnessed.name, environment);
741
- const location = range ? ` at ${formatRange(range)}` : "";
742
- return {
743
- name: unwitnessed.name,
744
- message: `The _POSSIBLE predicate ${unwitnessed.name}${location} was never witnessed.\nOthers may be unwitnessed too; only witnessed predicates appear with a\nnon-zero count in the record printed above.\nSee https://explain.tlapl.us/possible-conditions for additional details.`,
745
- counts: prettyPrint(formatValue(getPossibleCounts(runtime), true)),
746
- };
747
- };
748
- return {
749
- properties,
750
- spec,
751
- isSymmetric: symmetryGroup.length > 0,
752
- getTlcOrder,
753
- getStoredFingerprints: (states, fingerprintStates) => {
754
- if (view !== undefined || isFingerprintedLikeTlc) {
755
- return BigInt64Array.from(states, getTlcStateFingerprint);
756
- }
757
- const indices = getTlcOrder();
758
- const getFingerprint = createTlcFingerprinter();
759
- return BigInt64Array.from(fingerprintStates, (state) =>
760
- getFingerprint(indices.map((index) => state[index])),
761
- );
762
- },
763
- getFingerprintState: (state) => {
764
- if (isFingerprintedLikeTlc) return [String(getTlcStateFingerprint(state))];
765
- const representative =
766
- symmetryGroup.length === 0 ? state : getRepresentative(state, symmetryGroup, order);
767
- return view === undefined ? representative : [getViewValue(view.expression, representative)];
768
- },
769
- findViolatedInvariant: (state, parent) =>
770
- invariants.find((invariant) => {
771
- if (isUnchangedFor(invariant, state, parent)) return false;
772
- try {
773
- const context = getContext(environment, state, undefined, invariant.scope);
774
- const membership = invariant.membership;
775
- // The parent satisfies every invariant, so only the entries the step changed can fail.
776
- return parent && membership
777
- ? !isUpdatedElementOf(
778
- state[membership.variable],
779
- parent[membership.variable],
780
- evaluate(membership.set, context),
781
- )
782
- : !holdsLikeTlc(invariant.expression, context);
783
- } catch (error) {
784
- // TLC reports a failure only on a state after the initial states as an invariant failure.
785
- if (!parent) throw error;
786
- throw withHeadline(
787
- setExitCode(error, EXIT_STATUS.safetyEvaluationFailure),
788
- `Evaluating invariant ${invariant.name} failed.`,
789
- );
790
- }
791
- }),
792
- satisfiesConstraints: (state, parent) =>
793
- constraints.every(
794
- (constraint) =>
795
- isUnchangedFor(constraint, state, parent) ||
796
- holdsLikeTlc(constraint.expression, getContext(environment, state, undefined)),
797
- ),
798
- findFailedInitialPredicate: (state) =>
799
- properties.initialPredicates.find(
800
- (predicate) =>
801
- !holdsLikeTlc(
802
- predicate.expression,
803
- getContext(environment, state, undefined, predicate.scope),
804
- ),
805
- ),
806
- findViolatedActionProperty: (state, next) =>
807
- actionProperties.find((property) => {
808
- try {
809
- return (
810
- !holdsLikeTlc(
811
- property.action,
812
- getContext(environment, state, next, property.scope),
813
- () =>
814
- `Attempted to evaluate an expression of form [A]_e, but A was not a boolean.\n${describeRange(property.box)}`,
815
- ) &&
816
- !holds(
817
- property.unchanged,
818
- getContext(environment, state, next, property.scope),
819
- "a subscript",
820
- )
821
- );
822
- } catch (error) {
823
- throw withHeadline(error, `Evaluating action property ${property.name} failed.`);
824
- }
825
- }),
826
- satisfiesActionConstraints: (state, next) =>
827
- actionConstraints.every((constraint) =>
828
- holdsLikeTlc(
829
- constraint.expression,
830
- getContext(environment, state, next),
831
- (expression) =>
832
- `TLC threw an unexpected exception.\nThis was probably caused by an error in the spec or model.\nSee the User Output or TLC Console for clues to what happened.\nThe exception was a java.lang.RuntimeException\n: ${getExpectedBoolean(expression, environment)}`,
833
- ),
834
- ),
835
- trackStatePossible:
836
- statePossible.length === 0
837
- ? ignorePossible
838
- : (state) =>
839
- trackPossible(statePossible, runtime, getContext(environment, state, undefined)),
840
- trackActionPossible:
841
- actionPossible.length === 0
842
- ? ignorePossible
843
- : (state, next) =>
844
- trackPossible(actionPossible, runtime, getContext(environment, state, next)),
845
- findUnwitnessedPossible,
846
- findPostconditionViolation: () => {
847
- const unwitnessed = findUnwitnessedPossible();
848
- if (unwitnessed) return unwitnessed;
849
- for (const name of config.postconditions) {
850
- const failure = getConstantFailure(createIdentifier(name), environment, "a postcondition");
851
- if (failure) {
852
- return { name, message: failure.message ?? `Postcondition ${name} is false.` };
853
- }
854
- }
855
- return undefined;
856
- },
857
- };
858
377
  };
859
378
 
860
- const withHeadline = (error: unknown, headline: string) =>
861
- error instanceof TlaEvaluationError
862
- ? setExitCode(
863
- new TlaEvaluationError(`${headline}\n${error.message}`, error),
864
- getErrorExitCode(error),
865
- )
866
- : error;
379
+ // TLC checks liveness on the graph so far 3 seconds into the search and then every minute, once
380
+ // the graph has grown by a tenth and liveness checking has taken at most a fifth of the time.
381
+ const PERIODIC_START = 3000;
382
+ const PROGRESS_INTERVAL = 60_000;
383
+ const LIVENESS_GROWTH = 0.1;
384
+ const LIVENESS_RATIO = 0.2;
867
385
 
868
- export const checkSequentially = (options: CheckOptions): CheckResult => {
869
- setNextStatePhase(false);
870
- const config = typeof options.config === "string" ? parseConfig(options.config) : options.config;
386
+ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefined): CheckResult => {
387
+ const config =
388
+ typeof options.config === "string"
389
+ ? parseConfig(options.config, options.version)
390
+ : options.config;
871
391
  const onPrint = options.onPrint ?? console.log;
872
- // TLC prints again while it rebuilds a trace, between the states it prints. Printing those lines
873
- // before the trace would misplace them, so rebuilding a trace prints nothing.
874
- const output = { isMuted: false };
392
+ // TLC prints again while it rebuilds a trace, between the states it prints, so rebuilding a trace
393
+ // keeps what it prints for the trace.
394
+ const capturedOutput = { lines: undefined as OutputLine[] | undefined };
875
395
  const print = (text: string) => {
876
- if (!output.isMuted) onPrint(text);
396
+ if (capturedOutput.lines) capturedOutput.lines.push(text);
397
+ else onPrint(text);
877
398
  };
878
- const withoutOutput = <Result>(rebuild: () => Result) => {
879
- output.isMuted = true;
880
- const result = rebuild();
881
- output.isMuted = false;
882
- return result;
399
+ const captureOutput = <Result>(rebuild: () => Result) => {
400
+ const outer = capturedOutput.lines;
401
+ const lines: OutputLine[] = [];
402
+ capturedOutput.lines = lines;
403
+ try {
404
+ return { result: rebuild(), lines };
405
+ } finally {
406
+ capturedOutput.lines = outer;
407
+ }
883
408
  };
884
409
  setStringOrder(getTlcStringOrder(options.source, config, options.loadModule));
410
+ setValueVersion(options.version);
885
411
  const specification = createEnvironment(config, {
886
412
  source: options.source,
887
413
  loadModule: options.loadModule,
@@ -889,9 +415,16 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
889
415
  print,
890
416
  files: { readFile: options.readFile, writeFile: options.writeFile },
891
417
  seed: options.seed,
418
+ isTool: options.isTool,
419
+ isTraceRecorded: options.isTraceRecorded,
420
+ isSanyReported: options.isSanyReported,
421
+ isWarningEnabled: options.isWarningEnabled,
422
+ version: options.version,
892
423
  });
424
+ reportStartup(specification, config, options.onProgress);
893
425
  const environment = specification.environment;
894
426
  const runtime = environment.runtime;
427
+ const is174 = runtime.version === "1.7.4";
895
428
  runtime.pause = options.onPause ?? (() => {});
896
429
  runtime.getSpecification = () =>
897
430
  getSpecificationValue(
@@ -900,7 +433,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
900
433
  specification.variableLocations,
901
434
  specification.instanceActions,
902
435
  );
903
- const statistics = { depth: 0 };
436
+ const statistics = { depth: 0, initialStates: undefined as InitialStates | undefined };
904
437
  const createResult = (
905
438
  status: CheckStatus,
906
439
  violation?: Omit<Violation, "loopStart"> & { loopStart?: number },
@@ -913,15 +446,26 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
913
446
  distinctStates: runtime.distinctStates,
914
447
  queuedStates: runtime.queueSize,
915
448
  depth: runtime.generatedStates === 0 ? 0 : Math.max(statistics.depth, 1),
449
+ initialStates: statistics.initialStates,
916
450
  outDegrees: undefined,
917
451
  fingerprintDistance: undefined,
918
452
  });
919
453
  const outDegrees = Array.from({ length: OUT_DEGREE_BUCKETS }, () => 0);
920
454
  const expansion = { newStates: 0 };
921
455
  const getOutDegreeBucket = () => Math.min(expansion.newStates, OUT_DEGREE_BUCKETS - 1);
922
- // TLC counts the state it was expanding when an evaluation failed.
456
+ // TLC counts the state it was expanding when an evaluation failed, except TLC 1.7.4, whose
457
+ // worker stops before it counts the state.
923
458
  const getPartialOutDegrees = () =>
924
459
  outDegrees.map((count, degree) => (degree === getOutDegreeBucket() ? count + 1 : count));
460
+ const getFailureOutDegrees = () => (is174 ? [...outDegrees] : getPartialOutDegrees());
461
+ // TLC 1.7.4 doesn't name the properties a counterexample violates, so it evaluates none of them.
462
+ const getViolatedProperties = (checker: LivenessChecker, path: Value[][], cycleStart: number) =>
463
+ is174 ? [] : checker.getViolatedProperties(path, cycleStart);
464
+ // A violation in a successor ends the expansion of a state before TLC counts it.
465
+ const withOutDegrees = (result: CheckResult, degrees = [...outDegrees]): CheckResult => ({
466
+ ...result,
467
+ violationOutDegrees: degrees,
468
+ });
925
469
  const createSuccess = (): CheckResult => ({
926
470
  ...createResult("success"),
927
471
  outDegrees: [...outDegrees],
@@ -935,36 +479,257 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
935
479
  ),
936
480
  });
937
481
 
938
- const search = createSearch(config, environment, () =>
939
- getTlcVariableOrder(options.source, options.loadModule),
482
+ const search = createSearch(
483
+ config,
484
+ environment,
485
+ () => getTlcVariableOrder(options.source, options.loadModule),
486
+ options.onProgress,
940
487
  );
941
- const assumptionViolation = findAssumptionViolation(specification.assumptions, environment);
942
- if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
943
- if (!search) return createSuccess();
488
+ const findViolatedAssumption = () =>
489
+ findAssumptionViolation(specification.assumptions, environment);
490
+ if (!search) {
491
+ runtime.isStarted = true;
492
+ const assumptionViolation = findViolatedAssumption();
493
+ if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
494
+ // TLC computes the initial states of a spec without variables, of which there are none.
495
+ statistics.initialStates = { generated: 0, distinct: 0 };
496
+ options.onProgress?.({ kind: "initial-states-started" });
497
+ options.onProgress?.({
498
+ kind: "initial-states-computed",
499
+ initialStates: statistics.initialStates,
500
+ });
501
+ return createSuccess();
502
+ }
944
503
  const hasPostconditions = config.postconditions.length > 0 || config.possible.length > 0;
945
- const reportViolation = (
946
- status: CheckStatus,
947
- violation: Omit<Violation, "loopStart"> & { loopStart?: number },
948
- getLoopAction?: () => string | undefined,
504
+ // The state of each step of a trace without the alias, and the action TLC finds for the step,
505
+ // which CounterExample records.
506
+ const traceSteps = new WeakMap<
507
+ TraceStep,
508
+ { state: Record<string, Value>; action: SpecAction | undefined }
509
+ >();
510
+ const getStepState = (step: TraceStep) => traceSteps.get(step)?.state ?? step.state;
511
+ const getStepAction = (step: TraceStep) => {
512
+ const action = traceSteps.get(step)?.action;
513
+ return action ? toActionValue(action) : createActionRecord(step.action);
514
+ };
515
+ // Worker#printTrace checks the postconditions on the CounterExample of each trace it prints, so
516
+ // what they print follows the trace.
517
+ const checkTracePostconditions = (
518
+ trace: TraceStep[],
519
+ loop: { start: number; action: Value } | undefined,
949
520
  ) => {
950
521
  if (hasPostconditions) {
951
- const start = violation.loopStart;
952
522
  runtime.counterExample = createCounterExample(
953
- violation.trace,
954
- start === undefined || !getLoopAction ? undefined : { start, action: getLoopAction() },
523
+ trace.map(getStepState),
524
+ trace.slice(1).map(getStepAction),
525
+ loop,
955
526
  );
956
527
  }
957
528
  const unwitnessed = search.findUnwitnessedPossible();
958
- if (!unwitnessed) search.findPostconditionViolation();
959
- return createResult(status, unwitnessed ? { ...violation, unwitnessed } : violation);
529
+ const checked = unwitnessed
530
+ ? { result: undefined, lines: [] }
531
+ : captureOutput(() => search.findPostconditionViolation(true));
532
+ return { unwitnessed, postcondition: checked.result, lines: checked.lines };
533
+ };
534
+ const reportViolation = (
535
+ status: CheckStatus,
536
+ violation: Omit<Violation, "loopStart"> & { loopStart?: number },
537
+ getLoopAction?: () => Value,
538
+ ) => {
539
+ const start = violation.loopStart;
540
+ const checked = checkTracePostconditions(
541
+ violation.trace,
542
+ start === undefined || !getLoopAction ? undefined : { start, action: getLoopAction() },
543
+ );
544
+ const traceOutput = [...(violation.traceOutput ?? []), ...checked.lines];
545
+ return createResult(status, {
546
+ ...violation,
547
+ ...(traceOutput.length > 0 && { traceOutput }),
548
+ ...(checked.unwitnessed && { unwitnessed: checked.unwitnessed }),
549
+ ...(checked.postcondition && { postcondition: checked.postcondition }),
550
+ });
960
551
  };
961
552
  const spec = search.spec;
962
553
  const getFingerprintState = search.getFingerprintState;
963
- const nextActions = { value: undefined as SpecAction[] | undefined };
554
+ const specNextActions = { value: undefined as SpecAction[] | undefined };
555
+ const getSpecNextActions = () =>
556
+ (specNextActions.value ??= getNextActions(config, environment, specification.instanceActions));
557
+ const getReplayFailure = (replay: (tracing: Environment) => void): ReplayFailure | undefined => {
558
+ const tracing = createTracingEnvironment(environment);
559
+ const callStack = tracing.callStack;
560
+ try {
561
+ replay(tracing);
562
+ return undefined;
563
+ } catch (error) {
564
+ // A replay that overflows the stack again has an empty call stack.
565
+ if (isStackOverflow(error)) return { callStack: [], fingerprint: undefined };
566
+ if (!(error instanceof TlaEvaluationError) || !callStack) return undefined;
567
+ return { callStack: callStack.expressions, fingerprint: callStack.fingerprint };
568
+ }
569
+ };
570
+ // The sources of the values a fingerprint fails inside, outermost first: each value fails as it
571
+ // fingerprints a value it holds.
572
+ const findFailedSources = (value: Value, sources: CallStack["sources"]): Expression[] => {
573
+ if (typeof value !== "object") return [];
574
+ const source = sources.get(value);
575
+ const failed = getHeldValues(value).find((held) => getFingerprintError(held) !== undefined);
576
+ return [
577
+ ...(source ? [source] : []),
578
+ ...(failed === undefined ? [] : findFailedSources(failed, sources)),
579
+ ];
580
+ };
581
+ // TLC's replay fingerprints the states it finds, and a value the replay built raises a
582
+ // FingerprintException when it fails to.
583
+ const fingerprintReplayed = (state: Value[], callStack: CallStack | undefined) => {
584
+ for (const value of getFingerprintState(state)) {
585
+ const error = getFingerprintError(value);
586
+ if (!error) continue;
587
+ const sources = callStack ? findFailedSources(value, callStack.sources) : [];
588
+ // TLC fingerprints a state outside any evaluation, so its call stack is empty.
589
+ if (callStack && sources.length > 0) {
590
+ callStack.expressions.length = 0;
591
+ callStack.isFrozen = true;
592
+ callStack.fingerprint = { sources, reason: error.message };
593
+ }
594
+ throw error;
595
+ }
596
+ state.forEach(markFingerprinted);
597
+ };
598
+ // The replay adds the states it hasn't seen to TLC's set of states, which already holds the state
599
+ // that failed after TLC added it.
600
+ const createReplayedStates = () => {
601
+ const replayed = unstoredState.fingerprint ? [unstoredState.fingerprint] : [];
602
+ return (state: Value[], callStack: CallStack | undefined) => {
603
+ fingerprintReplayed(state, callStack);
604
+ const fingerprintState = getFingerprintState(state);
605
+ const isSeen =
606
+ findStateIndex(getStateHash(fingerprintState), fingerprintState) !== -1 ||
607
+ replayed.some((seen) => isSameState(seen, fingerprintState));
608
+ if (isSeen) return false;
609
+ replayed.push(fingerprintState);
610
+ runtime.distinctStates++;
611
+ return true;
612
+ };
613
+ };
614
+ // TLC's DoInitFunctor reports its progress again as it replays the initial states, and adds each
615
+ // one it hasn't seen to the behavior graph. After a FingerprintException, it only counts the
616
+ // states left, then throws the exception.
617
+ const replayInit = () => {
618
+ const replayed = { count: 0 };
619
+ const deferred: TlaEvaluationError[] = [];
620
+ const addReplayed = createReplayedStates();
621
+ return getReplayFailure((tracing) => {
622
+ replayInitialStates(
623
+ getInitActions(config, environment, specification.instanceActions),
624
+ tracing,
625
+ (state) => {
626
+ reportInitialStatesProgress(replayed.count, (progress) =>
627
+ capturedOutput.lines?.push(progress),
628
+ );
629
+ replayed.count++;
630
+ runtime.generatedStates = replayed.count;
631
+ if (deferred.length > 0) return;
632
+ try {
633
+ const addFingerprint = () => {
634
+ if (!addReplayed(state, tracing.callStack)) return;
635
+ runtime.queueSize++;
636
+ liveness?.addInitialState(states.length, state, tracing);
637
+ };
638
+ const violation = search.checkReplayedInitialState(state, tracing, addFingerprint);
639
+ if (violation) {
640
+ const traced = toTrace([{ action: undefined, state }], []).trace[0].state;
641
+ capturedOutput.lines?.push({
642
+ kind: "initial-state-violation",
643
+ ...violation,
644
+ state: traced,
645
+ });
646
+ throw STOP_REPLAY;
647
+ }
648
+ } catch (error) {
649
+ if (!(error instanceof TlaEvaluationError) || !tracing.callStack?.fingerprint) {
650
+ throw error;
651
+ }
652
+ deferred.push(error);
653
+ }
654
+ },
655
+ );
656
+ if (deferred.length > 0) throw deferred[0];
657
+ });
658
+ };
659
+ // TLC replays the expansion of a state with ModelChecker.doNext, which writes each successor in
660
+ // the model to the -dump state graph again.
661
+ const replayNext = (index: number) =>
662
+ getReplayFailure((tracing) => {
663
+ const state = states[index];
664
+ const source = stateWriter && getGraphState(state, depths[index]);
665
+ const addReplayed = createReplayedStates();
666
+ replaySuccessors(getSpecNextActions(), state, tracing, (next, action) => {
667
+ const addFingerprint = () => {
668
+ const isUnseen = addReplayed(next, tracing.callStack);
669
+ if (source) {
670
+ stateWriter?.writeSuccessor(
671
+ source,
672
+ getGraphState(next, depths[index] + 1),
673
+ !isUnseen,
674
+ isNamingEdges
675
+ ? { name: action.name, signature: getActionSignature(action) }
676
+ : undefined,
677
+ );
678
+ }
679
+ return isUnseen;
680
+ };
681
+ if (!search.checkReplayedSuccessor(state, next, tracing, addFingerprint)) {
682
+ throw STOP_REPLAY;
683
+ }
684
+ });
685
+ });
964
686
  const isReducing = config.view !== undefined || config.symmetry !== undefined;
687
+ const tlcFingerprints: number[] = [];
688
+ // TLC warns about the liveness checker before it builds it.
689
+ if (search.properties.liveness.length > 0) {
690
+ options.onProgress?.({
691
+ kind: "liveness-initializing",
692
+ isSymmetric: search.isSymmetric,
693
+ isConstrained: search.isConstrained,
694
+ });
695
+ }
965
696
  const liveness = withLivenessExitCode(() =>
966
- createLivenessChecker(search.properties.liveness, spec.temporals, environment),
697
+ withUnexpectedException(() =>
698
+ createLivenessChecker(search.properties.liveness, spec.temporals, environment, {
699
+ getFingerprint: ({ index, state }) =>
700
+ (tlcFingerprints[index] ??= Number(BigInt.asIntN(32, runtime.getFingerprint(state)))),
701
+ getSuccessors: (source, state) => {
702
+ const successors: LiveSuccessor[] = [];
703
+ if (spec.next === undefined) return successors;
704
+ // The constraints read the level of the state whose successors they check, as when TLC
705
+ // explored it.
706
+ const livenessSource = current.livenessSource;
707
+ current.livenessSource = source;
708
+ forEachSuccessor(
709
+ spec.next,
710
+ state,
711
+ environment,
712
+ (successor) => {
713
+ canonicalizeState(successor.state);
714
+ const isInModel =
715
+ search.satisfiesConstraints(successor.state, state) &&
716
+ search.satisfiesActionConstraints(state, successor.state);
717
+ if (!isInModel) return false;
718
+ const fingerprintState = getFingerprintState(successor.state);
719
+ const index = findStateIndex(getStateHash(fingerprintState), fingerprintState);
720
+ successors.push({ index, state: successor.state });
721
+ return false;
722
+ },
723
+ spec.scope,
724
+ );
725
+ current.livenessSource = livenessSource;
726
+ return successors;
727
+ },
728
+ }),
729
+ ),
967
730
  );
731
+ // TLC 1.7.4 creates its model checker, which TLCGet reads, once it has built the liveness checker.
732
+ runtime.isStarted = true;
968
733
  const isCanonicalizedFirst = search.isSymmetric || liveness !== undefined;
969
734
 
970
735
  const states: Value[][] = [];
@@ -972,7 +737,9 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
972
737
  const parents: number[] = [];
973
738
  const actions: (string | undefined)[] = [];
974
739
  const depths: number[] = [];
975
- const buckets = new Map<number, number | number[]>();
740
+ // A Map holds at most 2^24 entries, so an open-addressing table keeps each seen state's hash
741
+ // and its index plus one side by side, probed by the hash.
742
+ const seenStates = { slots: new Int32Array(1 << 17), size: 0, shift: 16 };
976
743
  const canonicalizeState = createCanonicalizer();
977
744
 
978
745
  const toRecord = (state: Value[]): Record<string, Value> =>
@@ -985,11 +752,16 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
985
752
  position: number,
986
753
  loopStart: number | undefined,
987
754
  ) => {
988
- const state = steps[position].state;
989
- const next = (steps[position + 1] ?? steps[loopStart ?? position]).state;
990
755
  // TLC evaluates TLCGet("level") and Trace in an alias at the state's position in the trace.
991
756
  runtime.getLevel = () => position + 1;
992
757
  runtime.getBehavior = () => steps.slice(0, position + 1).map((step) => step.state);
758
+ return evaluateAlias(
759
+ alias,
760
+ steps[position].state,
761
+ (steps[position + 1] ?? steps[loopStart ?? position]).state,
762
+ );
763
+ };
764
+ const evaluateAlias = (alias: string, state: Value[], next: Value[] | undefined) => {
993
765
  try {
994
766
  const body = getConfigDefinition("alias", alias, environment).body;
995
767
  const value = evaluate(createIdentifier(alias), getContext(environment, state, next));
@@ -997,58 +769,105 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
997
769
  return toAliasRecord(value, fieldOrder) ?? toRecord(state);
998
770
  } catch (error) {
999
771
  if (!(error instanceof TlaConfigError || error instanceof TlaEvaluationError)) throw error;
1000
- return { ...toRecord(state), _ALIASEvalError: error.message };
772
+ return {
773
+ ...toRecord(state),
774
+ _ALIASEvalError: formatNestedMessage(error.message, options.isTool ?? false),
775
+ };
1001
776
  }
1002
777
  };
1003
- // TLC labels a step with the first action that takes it, evaluated as when the search expanded
1004
- // the previous state.
1005
- const getLabel = (index: number, previous: Value[], state: Value[]) => {
1006
- nextActions.value ??= getNextActions(config, environment, specification.instanceActions);
778
+ // TLC finds the action of a step as the first action that takes it, evaluated as when the search
779
+ // expanded the previous state, by the values of a successor it holds and otherwise by fingerprint.
780
+ const findStepAction = (index: number, previous: Value[], state: Value[], isHeld: boolean) => {
781
+ const actions = getSpecNextActions();
1007
782
  const expanding = { ...current };
1008
783
  Object.assign(current, { index, isExpanding: true, candidate: undefined });
1009
- const fingerprintState = getFingerprintState(state);
1010
- const action = nextActions.value.find((item) =>
784
+ const getKey = isHeld ? (values: Value[]) => values : getFingerprintState;
785
+ const key = getKey(state);
786
+ const action = actions.find((item) =>
1011
787
  getSuccessors(item.expression, previous, environment, item.scope).some((successor) =>
1012
- isSameState(getFingerprintState(successor.state), fingerprintState),
788
+ isSameState(getKey(successor.state), key),
1013
789
  ),
1014
790
  );
1015
791
  Object.assign(current, expanding);
1016
- return action && getActionLabel(action);
792
+ return action;
1017
793
  };
1018
- const toTrace = (steps: Successor[], path: number[], loopStart?: number): TraceStep[] => {
794
+ // Before TLC prints a trace, it rebuilds from the initial predicate the states it does not keep,
795
+ // all but the last `known` ones. As it prints each later step, it finds the action that takes
796
+ // the step. Then it rebuilds the trace once more, unless the trace is a liveness counterexample
797
+ // or TLC is 1.7.4.
798
+ const toTrace = (
799
+ steps: Successor[],
800
+ path: number[],
801
+ traceOptions: TraceOptions = {},
802
+ ): Behavior => {
1019
803
  const alias = config.alias;
1020
- const labels = withoutOutput(() => {
1021
- // TLC rebuilds a trace from the initial predicate, which can reset what TLCSet stored.
1022
- if (steps.length > 1 && isImpure(environment)) getSpecInitialStates();
1023
- // TLC finds the action that takes each step before it evaluates the alias.
1024
- return steps.map((step, position) =>
1025
- position === 0 || step.action === "Stuttering"
1026
- ? undefined
1027
- : getLabel(path[position - 1], steps[position - 1].state, step.state),
1028
- );
1029
- });
1030
- return steps.map((step, position) => ({
1031
- action: step.action,
1032
- label: labels[position],
1033
- state:
1034
- alias === undefined
1035
- ? toRecord(step.state)
1036
- : getAliasState(alias, steps, position, loopStart),
1037
- }));
804
+ const known = traceOptions.known ?? 1;
805
+ // Rebuilding the trace from the initial predicate can reset what TLCSet stored.
806
+ const initialOutput = steps.length > 1 ? captureOutput(getSpecInitialStates).lines : [];
807
+ // TLC finds the action that takes each step before it evaluates the alias.
808
+ const stepActions = steps.map((step, position) =>
809
+ position === 0 || step.action === "Stuttering"
810
+ ? { result: undefined, lines: [] }
811
+ : captureOutput(() =>
812
+ findStepAction(
813
+ path[position - 1],
814
+ steps[position - 1].state,
815
+ step.state,
816
+ known === 2 && position === steps.length - 1,
817
+ ),
818
+ ),
819
+ );
820
+ const outputs = stepActions.map((step) => step.lines);
821
+ const loopStart = traceOptions.loopStart;
822
+ // 1.7.4's LiveWorker#printTrace rebuilds a lasso up to the start of its cycle at once, and then
823
+ // each state of the cycle as it prints it.
824
+ const rebuilt = is174 && loopStart !== undefined ? loopStart + 1 : steps.length - known;
825
+ const prefixOutput = rebuilt > 0 ? [initialOutput, ...outputs.slice(1, rebuilt)].flat() : [];
826
+ return {
827
+ trace: steps.map((step, position) => {
828
+ const action = stepActions[position].result;
829
+ const traceStep: TraceStep = {
830
+ action: step.action,
831
+ label: action && getActionLabel(action, options.version),
832
+ state:
833
+ alias === undefined
834
+ ? toRecord(step.state)
835
+ : getAliasState(alias, steps, position, loopStart),
836
+ output: position === 0 ? prefixOutput : position < rebuilt ? [] : outputs[position],
837
+ };
838
+ if (alias !== undefined || action) {
839
+ traceSteps.set(traceStep, { state: toRecord(step.state), action });
840
+ }
841
+ return traceStep;
842
+ }),
843
+ traceOutput: known > 0 && !is174 ? [initialOutput, ...outputs].flat() : [],
844
+ };
1038
845
  };
1039
846
  const getSpecInitialStates = () =>
1040
847
  spec.init === undefined ? [] : getInitialStates(spec.init, environment, spec.scope);
1041
- const getTraceSuccessors = (state: Value[]) =>
1042
- spec.next === undefined ? [] : getSuccessors(spec.next, state, environment, spec.scope);
848
+ // TLC's Tool#getState rebuilds a successor action by action, up to the first action that
849
+ // generates it. A trace keeps what the spec prints as TLC rebuilds it, so finding its states
850
+ // prints nothing.
851
+ const findTraceSuccessor = (state: Value[], isMatch: (successor: Successor) => boolean) =>
852
+ captureOutput(() => {
853
+ for (const action of getSpecNextActions()) {
854
+ const successor = getSuccessors(action.expression, state, environment, action.scope).find(
855
+ isMatch,
856
+ );
857
+ if (successor) return { ...successor, action: successor.action ?? action.name };
858
+ }
859
+ return undefined;
860
+ }).result;
1043
861
  const hasFingerprint = (state: Value[], index: number) =>
1044
862
  isSameState(getFingerprintState(state), fingerprintStates[index]);
1045
863
  const findSuccessorWithFingerprint = (state: Value[], index: number) =>
1046
- getTraceSuccessors(state).find((successor) => hasFingerprint(successor.state, index));
864
+ findTraceSuccessor(state, (successor) => hasFingerprint(successor.state, index));
1047
865
  const getPathStates = (path: number[], nextFailure: string) => {
1048
- const initial =
866
+ const initial = captureOutput(() =>
1049
867
  isReducing || isImpure(environment)
1050
868
  ? getSpecInitialStates().find((state) => hasFingerprint(state, path[0]))
1051
- : states[path[0]];
869
+ : states[path[0]],
870
+ ).result;
1052
871
  if (!initial) throw new TlaEvaluationError(INITIAL_RECOVERY_FAILURE);
1053
872
  const steps: Successor[] = [{ state: initial, action: undefined }];
1054
873
  for (let position = 1; position < path.length; position++) {
@@ -1063,7 +882,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1063
882
  }
1064
883
  return steps;
1065
884
  };
1066
- const getTrace = (index: number, last?: Successor) => {
885
+ const getTrace = (index: number, lastSuccessor?: Successor) => {
1067
886
  const path: number[] = [];
1068
887
  for (let position = index; position !== -1; position = parents[position]) {
1069
888
  path.unshift(position);
@@ -1072,48 +891,135 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1072
891
  isReducing && path.length > 1
1073
892
  ? getPathStates(path, INITIAL_RECOVERY_FAILURE)
1074
893
  : path.map((position) => ({ state: states[position], action: actions[position] }));
1075
- if (!last) return toTrace(steps, path);
894
+ if (!lastSuccessor) return toTrace(steps, path);
1076
895
  const action = isReducing
1077
- ? getTraceSuccessors(states[index]).find((successor) =>
1078
- isSameState(successor.state, last.state),
896
+ ? findTraceSuccessor(states[index], (successor) =>
897
+ isSameState(successor.state, lastSuccessor.state),
1079
898
  )?.action
1080
- : last.action;
1081
- return toTrace([...steps, { state: last.state, action }], path);
899
+ : lastSuccessor.action;
900
+ return toTrace([...steps, { state: lastSuccessor.state, action }], path, { known: 2 });
1082
901
  };
1083
- // TLC prints an initial state on its own without evaluating the alias.
1084
- const getStateTrace = (index: number) =>
902
+ // TLC prints a lone initial state without the alias. TLCTrace#getTrace still recovers it from the
903
+ // initial predicate, printing again, though TLC 1.7.4 doesn't.
904
+ const getStateTrace = (index: number): Behavior =>
1085
905
  parents[index] === -1
1086
- ? [{ action: undefined, label: undefined, state: toRecord(states[index]) }]
906
+ ? {
907
+ trace: [{ action: undefined, label: undefined, state: toRecord(states[index]) }],
908
+ traceOutput: is174 ? [] : captureOutput(getSpecInitialStates).lines,
909
+ }
1087
910
  : getTrace(index);
911
+ // TLC rebuilds the trace again for the postcondition after it prints a violation, but not after
912
+ // an evaluation fails.
913
+ const getFailedTrace = (index: number, successor: Successor): Behavior => ({
914
+ trace: getTrace(index, successor).trace,
915
+ });
1088
916
  // TLC names the initial state it was checking unless a standard module's Java code failed.
1089
- const toFailure = (
1090
- error: unknown,
1091
- trace: TraceStep[],
1092
- initialState?: Value[],
1093
- failureOutDegrees?: number[],
917
+ const getFailureExitCode = (error: TlaEvaluationError, failureOptions: FailureOptions) => {
918
+ // TLC 1.7.4 exits with the result of its replay of the initial states, which only fails again
919
+ // when the error isn't in adding a state it has already seen to the behavior graph.
920
+ if (
921
+ failureOptions.isInitial &&
922
+ !failureOptions.callStack &&
923
+ !failureOptions.fingerprint &&
924
+ is174
925
+ ) {
926
+ return EXIT_STATUS.success;
927
+ }
928
+ if (!failureOptions.callStack) {
929
+ return failureOptions.isInitial ? getInitialExitCode(error) : getErrorExitCode(error);
930
+ }
931
+ if (failureOptions.isCallStackFirst) return getErrorExitCode(error);
932
+ // Without a replay, TLC exits with the code of the error, as for any error it didn't expect.
933
+ if (failureOptions.isLiveCallStack) {
934
+ return (
935
+ getExitCode(error) ?? (error instanceof TlaModuleError ? error.exitCode : EXIT_STATUS.error)
936
+ );
937
+ }
938
+ // TLC exits with the code of a failed replay of the initial states regardless of the error, as
939
+ // it does for a replay that fails to fingerprint.
940
+ return failureOptions.isInitial || failureOptions.fingerprint
941
+ ? EXIT_STATUS.specEvaluationFailure
942
+ : getReplayExitCode(error);
943
+ };
944
+ const createFailureResult = (
945
+ failed: unknown,
946
+ behavior: Behavior,
947
+ failureOptions: FailureOptions = {},
1094
948
  ) => {
949
+ const error = isStackOverflow(failed) ? new TlaStackOverflowError() : failed;
1095
950
  if (!(error instanceof TlaEvaluationError)) throw error;
951
+ const checked =
952
+ behavior.trace.length > 0 && !failureOptions.traceFailure
953
+ ? checkTracePostconditions(behavior.trace, undefined)
954
+ : undefined;
955
+ const postcondition = checked?.unwitnessed ?? checked?.postcondition;
956
+ const traceOutput = [...(behavior.traceOutput ?? []), ...(checked?.lines ?? [])];
1096
957
  return {
1097
958
  ...createResult("error", undefined, {
1098
- message: error.message,
1099
- trace,
959
+ ...getFailureMessage(error, failureOptions.isNextState ?? false),
960
+ ...behavior,
961
+ ...(traceOutput.length > 0 && { traceOutput }),
962
+ ...(postcondition && { postcondition }),
1100
963
  initialState:
1101
- initialState && !(error instanceof TlaModuleError) ? toRecord(initialState) : undefined,
1102
- exitCode: getErrorExitCode(error),
964
+ failureOptions.initialState && !(error instanceof TlaModuleError)
965
+ ? toRecord(failureOptions.initialState)
966
+ : undefined,
967
+ exitCode: getFailureExitCode(error, failureOptions),
968
+ callStack: failureOptions.callStack,
969
+ ...(failureOptions.isCallStackFirst && { isCallStackFirst: true }),
970
+ ...(failureOptions.fingerprint && { fingerprint: failureOptions.fingerprint }),
971
+ ...(failureOptions.traceFailure && { traceFailure: failureOptions.traceFailure }),
1103
972
  }),
1104
- outDegrees: failureOutDegrees,
973
+ outDegrees: failureOptions.outDegrees,
1105
974
  };
1106
975
  };
1107
- const getPathTrace = (path: number[], loopStart?: number) => {
976
+ // TLC reports a successor state that an action leaves incomplete with the trace to it, which ends
977
+ // with the partial state. It names the action when the next-state relation has several.
978
+ const reportIncompleteSuccessor = (index: number, error: TlaIncompleteSuccessorError) => {
979
+ runtime.generatedStates++;
980
+ const actions = getSpecNextActions();
981
+ const action =
982
+ actions.length === 1 ? actions[0] : actions.find((item) => item.name === error.action);
983
+ const missing = error.variables;
984
+ const subject =
985
+ actions.length === 1
986
+ ? "the next-state action"
987
+ : `action ${error.action} of the next-state relation`;
988
+ // TLC 1.7.4 says a variable is not assigned rather than not defined.
989
+ const verb = is174 ? "assigned" : "defined";
990
+ const message = `Successor state is not completely specified by ${subject}. The following variable${missing.length > 1 ? "s are" : " is"} not ${verb}: ${missing.join(", ")}.\n`;
991
+ const undefinedValue = createModelValue("null");
992
+ const partial = error.state.map((value) => value ?? undefinedValue);
993
+ const failure = createFailureResult(error, getStateTrace(index));
994
+ return withOutDegrees({
995
+ ...failure,
996
+ failure: failure.failure && {
997
+ ...failure.failure,
998
+ code: MESSAGE_CODE.incompleteSuccessor,
999
+ message,
1000
+ toolMessage: message,
1001
+ exitCode: EXIT_STATUS.specEvaluationFailure,
1002
+ trace: [
1003
+ ...failure.failure.trace,
1004
+ {
1005
+ action: error.action,
1006
+ label: action && getActionLabel(action, options.version),
1007
+ state: toRecord(partial),
1008
+ },
1009
+ ],
1010
+ },
1011
+ });
1012
+ };
1013
+ const getPathSteps = (path: number[], loopStart?: number) => {
1108
1014
  const steps = getPathStates(path, NEXT_RECOVERY_FAILURE);
1109
- const last = steps[steps.length - 1].state;
1015
+ const lastState = steps[steps.length - 1].state;
1110
1016
  const isClosed =
1111
1017
  !isReducing ||
1112
1018
  loopStart === undefined ||
1113
1019
  loopStart === path.length - 1 ||
1114
- findSuccessorWithFingerprint(last, path[loopStart]) !== undefined;
1020
+ findSuccessorWithFingerprint(lastState, path[loopStart]) !== undefined;
1115
1021
  if (!isClosed) throw new TlaEvaluationError(NEXT_RECOVERY_FAILURE);
1116
- return toTrace(steps, path, loopStart);
1022
+ return steps;
1117
1023
  };
1118
1024
  const getStateHash = (state: Value[]) => {
1119
1025
  let hash = 0x811c9dc5;
@@ -1121,26 +1027,52 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1121
1027
  hash = combineHash(hash, getValueHash(state[index]));
1122
1028
  return hash & 0x3fffffff;
1123
1029
  };
1030
+ // TLC fingerprints a state once it finds the state in the model.
1031
+ const fingerprintModelState = (state: Value[]) => {
1032
+ for (const value of state) {
1033
+ const error = getFingerprintError(value);
1034
+ if (error) throw error;
1035
+ }
1036
+ };
1124
1037
  const isSameState = (stored: Value[], state: Value[]) => {
1125
1038
  for (let position = 0; position < state.length; position++) {
1126
1039
  if (!isSameValue(stored[position], state[position])) return false;
1127
1040
  }
1128
1041
  return true;
1129
1042
  };
1043
+ const getSlot = (hash: number) => (Math.imul(hash, 0x9e3779b1) >>> seenStates.shift) << 1;
1130
1044
  const findStateIndex = (hash: number, state: Value[]) => {
1131
- const bucket = buckets.get(hash);
1132
- if (bucket === undefined) return -1;
1133
- if (typeof bucket === "number") {
1134
- return isSameState(fingerprintStates[bucket], state) ? bucket : -1;
1045
+ const mask = seenStates.slots.length - 1;
1046
+ for (let slot = getSlot(hash); ; slot = (slot + 2) & mask) {
1047
+ const entry = seenStates.slots[slot + 1];
1048
+ if (entry === 0) return -1;
1049
+ if (seenStates.slots[slot] === hash && isSameState(fingerprintStates[entry - 1], state)) {
1050
+ return entry - 1;
1051
+ }
1135
1052
  }
1136
- return bucket.find((index) => isSameState(fingerprintStates[index], state)) ?? -1;
1053
+ };
1054
+ const insertSeen = (hash: number, entry: number) => {
1055
+ const mask = seenStates.slots.length - 1;
1056
+ let slot = getSlot(hash);
1057
+ while (seenStates.slots[slot + 1] !== 0) slot = (slot + 2) & mask;
1058
+ seenStates.slots[slot] = hash;
1059
+ seenStates.slots[slot + 1] = entry;
1137
1060
  };
1138
1061
  const markSeen = (hash: number, index: number) => {
1139
- const bucket = buckets.get(hash);
1140
- if (bucket === undefined) buckets.set(hash, index);
1141
- else if (typeof bucket === "number") buckets.set(hash, [bucket, index]);
1142
- else bucket.push(index);
1062
+ seenStates.size++;
1063
+ if (seenStates.size * 4 > seenStates.slots.length) {
1064
+ const slots = seenStates.slots;
1065
+ seenStates.slots = new Int32Array(slots.length * 2);
1066
+ seenStates.shift--;
1067
+ for (let slot = 0; slot < slots.length; slot += 2) {
1068
+ if (slots[slot + 1] !== 0) insertSeen(slots[slot], slots[slot + 1]);
1069
+ }
1070
+ }
1071
+ insertSeen(hash, index + 1);
1143
1072
  };
1073
+ // A new successor that TLC has added to its set of states before it checks the successor, which
1074
+ // the check stores after.
1075
+ const unstoredState = { fingerprint: undefined as Value[] | undefined };
1144
1076
  const countDistinctState = (depth: number) => {
1145
1077
  runtime.distinctStates = states.length + 1;
1146
1078
  statistics.depth = Math.max(statistics.depth, depth);
@@ -1179,10 +1111,15 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1179
1111
  };
1180
1112
  runtime.getCurrentState = () => (current.index === -1 ? undefined : states[current.index]);
1181
1113
  runtime.setLivenessSource = (index) => {
1182
- current.livenessSource = index;
1114
+ current.livenessSource = index ?? -1;
1183
1115
  };
1184
1116
  runtime.getLevel = (state) => {
1185
1117
  const source = current.livenessSource;
1118
+ // TLC 1.7.4 reads the level of the state its worker explores, whichever state it evaluates.
1119
+ if (is174) {
1120
+ const explored = source !== -1 ? source : current.isExpanding ? current.index : -1;
1121
+ return explored === -1 ? 0 : depths[explored];
1122
+ }
1186
1123
  if (source !== -1) return state === states[source] ? depths[source] : depths[source] + 1;
1187
1124
  if (state === current.candidate) return current.candidateLevel;
1188
1125
  if (current.index === -1) return 0;
@@ -1190,6 +1127,18 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1190
1127
  return current.isExpanding ? depths[current.index] + 1 : 0;
1191
1128
  };
1192
1129
 
1130
+ const getGraphState = (state: Value[], level: number): GraphState => ({
1131
+ fingerprint: BigInt.asIntN(64, runtime.getFingerprint(state)),
1132
+ level,
1133
+ getLabel: () =>
1134
+ formatState(
1135
+ config.alias === undefined
1136
+ ? toRecord(state)
1137
+ : evaluateAlias(config.alias, state, undefined),
1138
+ ),
1139
+ getText: () => formatState(toRecord(state)),
1140
+ });
1141
+
1193
1142
  const visitInitialState = (state: Value[]) => {
1194
1143
  canonicalizeState(state);
1195
1144
  runtime.generatedStates++;
@@ -1199,26 +1148,32 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1199
1148
  const fingerprintState = getFingerprintState(state);
1200
1149
  const hash = getStateHash(fingerprintState);
1201
1150
  const isInModel = search.satisfiesConstraints(state);
1202
- if (isInModel) search.trackStatePossible(state);
1151
+ if (isInModel) {
1152
+ search.trackStatePossible(state);
1153
+ fingerprintModelState(fingerprintState);
1154
+ state.forEach(markFingerprinted);
1155
+ }
1203
1156
  const isSeen = isInModel && findStateIndex(hash, fingerprintState) !== -1;
1204
1157
  if (isSeen) return undefined;
1158
+ unstoredState.fingerprint = isInModel ? fingerprintState : undefined;
1205
1159
  if (isInModel) {
1206
1160
  countDistinctState(1);
1207
1161
  runtime.queueSize++;
1208
1162
  liveness?.addInitialState(states.length, state);
1163
+ stateWriter?.writeInitialState(getGraphState(state, 1));
1209
1164
  }
1210
1165
  const violated = search.findViolatedInvariant(state);
1211
1166
  if (violated) {
1212
1167
  return reportViolation("invariant-violation", {
1213
1168
  name: violated.name,
1214
- trace: toTrace([{ action: undefined, state }], []),
1169
+ ...toTrace([{ action: undefined, state }], []),
1215
1170
  });
1216
1171
  }
1217
1172
  const failedPredicate = search.findFailedInitialPredicate(state);
1218
1173
  if (failedPredicate) {
1219
1174
  return reportViolation("liveness-violation", {
1220
1175
  name: failedPredicate.name,
1221
- trace: toTrace([{ action: undefined, state }], []),
1176
+ ...toTrace([{ action: undefined, state }], []),
1222
1177
  });
1223
1178
  }
1224
1179
  if (!isInModel) return undefined;
@@ -1226,7 +1181,13 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1226
1181
  addState(state, fingerprintState, -1, undefined);
1227
1182
  return undefined;
1228
1183
  };
1229
- const visitSuccessor = (index: number, successor: Successor, liveSuccessors: LiveSuccessor[]) => {
1184
+ const visitSuccessor = (
1185
+ index: number,
1186
+ successor: Successor,
1187
+ liveSuccessors: LiveSuccessor[],
1188
+ source: GraphState | undefined,
1189
+ action: SpecAction | undefined,
1190
+ ) => {
1230
1191
  const state = states[index];
1231
1192
  runtime.generatedStates++;
1232
1193
  current.candidate = successor.state;
@@ -1234,18 +1195,33 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1234
1195
  if (isCanonicalizedFirst) canonicalizeState(successor.state);
1235
1196
  const fingerprintState = getFingerprintState(successor.state);
1236
1197
  const hash = getStateHash(fingerprintState);
1237
- const found = findStateIndex(hash, fingerprintState);
1198
+ const foundIndex = findStateIndex(hash, fingerprintState);
1238
1199
  const isStateInModel = search.satisfiesConstraints(successor.state, state);
1239
1200
  if (isStateInModel) search.trackStatePossible(successor.state);
1240
1201
  const isInModel = isStateInModel && search.satisfiesActionConstraints(state, successor.state);
1241
- if (isInModel) search.trackActionPossible(state, successor.state);
1242
- const existing = isInModel ? found : -1;
1202
+ if (isInModel) {
1203
+ search.trackActionPossible(state, successor.state);
1204
+ fingerprintModelState(fingerprintState);
1205
+ successor.state.forEach(markFingerprinted);
1206
+ }
1207
+ const existing = isInModel ? foundIndex : -1;
1208
+ if (source && isInModel) {
1209
+ stateWriter?.writeSuccessor(
1210
+ source,
1211
+ getGraphState(successor.state, depths[index] + 1),
1212
+ existing !== -1,
1213
+ action && { name: action.name, signature: getActionSignature(action) },
1214
+ );
1215
+ }
1243
1216
  if (existing !== -1 && liveness) {
1244
1217
  const stored = states[existing];
1245
1218
  const isStored = stored.every((value, position) => value === successor.state[position]);
1246
1219
  liveSuccessors.push({ index: existing, state: isStored ? stored : successor.state });
1247
1220
  }
1248
1221
  const isNew = isInModel && existing === -1;
1222
+ // TLC adds a new state to the behavior graph's successors before it checks the invariants.
1223
+ if (isNew && liveness) liveSuccessors.push({ index: states.length, state: successor.state });
1224
+ unstoredState.fingerprint = isNew ? fingerprintState : undefined;
1249
1225
  if (isNew) {
1250
1226
  countDistinctState(depths[index] + 1);
1251
1227
  expansion.newStates++;
@@ -1254,53 +1230,105 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1254
1230
  try {
1255
1231
  const violated = search.findViolatedInvariant(successor.state, state);
1256
1232
  if (violated) {
1257
- return reportViolation("invariant-violation", {
1258
- name: violated.name,
1259
- trace: getTrace(index, successor),
1260
- });
1233
+ return withOutDegrees(
1234
+ reportViolation("invariant-violation", {
1235
+ name: violated.name,
1236
+ ...getTrace(index, successor),
1237
+ }),
1238
+ );
1261
1239
  }
1262
1240
  } catch (error) {
1263
- // TLC prints the outdegree when it cannot reproduce the failure, as for an invariant here.
1264
- return toFailure(error, getTrace(index, successor), undefined, getPartialOutDegrees());
1241
+ if (isStackOverflow(error)) throw error;
1242
+ // TLC replays the expansion and skips the invariants of a state it has seen, the failed one
1243
+ // included unless the constraints exclude it. When the replay fails, TLC reports where and
1244
+ // leaves out the outdegree.
1245
+ const replay = captureOutput(() => replayNext(index));
1246
+ return createFailureResult(
1247
+ error,
1248
+ appendTraceOutput(getFailedTrace(index, successor), replay.lines),
1249
+ replay.result ?? { outDegrees: getFailureOutDegrees() },
1250
+ );
1265
1251
  }
1266
1252
  }
1267
1253
  const violatedProperty = search.findViolatedActionProperty(state, successor.state);
1268
1254
  if (violatedProperty) {
1269
- return reportViolation("liveness-violation", {
1270
- name: violatedProperty.name,
1271
- trace: getTrace(index, successor),
1272
- });
1255
+ return withOutDegrees(
1256
+ reportViolation("liveness-violation", {
1257
+ name: violatedProperty.name,
1258
+ ...getTrace(index, successor),
1259
+ }),
1260
+ );
1273
1261
  }
1274
1262
  if (!isNew) return undefined;
1275
1263
  if (!isCanonicalizedFirst) canonicalizeState(successor.state);
1276
1264
  markSeen(hash, states.length);
1277
- if (liveness) liveSuccessors.push({ index: states.length, state: successor.state });
1278
1265
  addState(successor.state, fingerprintState, index, successor.action);
1279
1266
  runtime.queueSize++;
1280
1267
  return undefined;
1281
1268
  };
1282
1269
 
1283
1270
  const outcome: { result: CheckResult | undefined } = { result: undefined };
1271
+ if (liveness) {
1272
+ options.onProgress?.({ kind: "liveness-prepared", branches: liveness.branches });
1273
+ }
1274
+ // TLC checks the assumptions once it has built the liveness checker in ModelChecker's
1275
+ // constructor.
1276
+ const assumptionViolation = findViolatedAssumption();
1277
+ if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
1278
+ options.onProgress?.({ kind: "initial-states-started" });
1284
1279
  if (spec.init !== undefined) {
1285
1280
  try {
1286
1281
  forEachInitialState(
1287
1282
  spec.init,
1288
1283
  environment,
1289
1284
  (state) => {
1285
+ reportInitialStatesProgress(runtime.initialStates, options.onProgress);
1290
1286
  try {
1291
1287
  outcome.result = visitInitialState(state);
1292
1288
  } catch (error) {
1293
- outcome.result = toFailure(error, [], state);
1289
+ const replay = captureOutput(replayInit);
1290
+ outcome.result = createFailureResult(
1291
+ error,
1292
+ { trace: [], traceOutput: replay.lines },
1293
+ { initialState: state, ...replay.result, isInitial: true },
1294
+ );
1294
1295
  }
1295
1296
  return outcome.result !== undefined;
1296
1297
  },
1297
1298
  spec.scope,
1298
1299
  );
1299
1300
  } catch (error) {
1300
- return toFailure(error, []);
1301
+ // TLC prints an illegal initial state with null for each variable it leaves undefined, and
1302
+ // stops before it prints the statistics.
1303
+ if (error instanceof TlaIllegalStateError) {
1304
+ const illegal = createFailureResult(
1305
+ error,
1306
+ { trace: [] },
1307
+ { initialState: error.state.map((value) => value ?? createModelValue("null")) },
1308
+ );
1309
+ return {
1310
+ ...illegal,
1311
+ failure: illegal.failure && { ...illegal.failure, isWithoutStatistics: true },
1312
+ };
1313
+ }
1314
+ // TLC prints the error before it replays the initial predicate with its call stack.
1315
+ const replay = captureOutput(replayInit);
1316
+ return createFailureResult(
1317
+ error,
1318
+ { trace: [], traceOutput: replay.lines },
1319
+ { ...replay.result, isInitial: true },
1320
+ );
1301
1321
  }
1302
1322
  }
1303
1323
  if (outcome.result) return outcome.result;
1324
+ statistics.initialStates = {
1325
+ generated: runtime.initialStates,
1326
+ distinct: runtime.distinctStates,
1327
+ };
1328
+ options.onProgress?.({
1329
+ kind: "initial-states-computed",
1330
+ initialStates: statistics.initialStates,
1331
+ });
1304
1332
 
1305
1333
  const next = spec.next;
1306
1334
  if (next === undefined) {
@@ -1311,56 +1339,276 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1311
1339
  }
1312
1340
  return createSuccess();
1313
1341
  }
1314
- const expandState = (index: number) => {
1342
+ // TLC labels and colors an edge of the -dump state graph by the action that generated it. When
1343
+ // the graph names its edges, the search generates successors action by action, as TLC does.
1344
+ const isNamingEdges = Boolean(
1345
+ options.dump?.dot && (options.dump.actionLabels || options.dump.colorize),
1346
+ );
1347
+ const forEachActionSuccessor = (
1348
+ state: Value[],
1349
+ onSuccessor: (successor: Successor, action: SpecAction | undefined) => boolean,
1350
+ ) => {
1351
+ if (!isNamingEdges) {
1352
+ return forEachSuccessor(
1353
+ next,
1354
+ state,
1355
+ environment,
1356
+ (successor) => onSuccessor(successor, undefined),
1357
+ spec.scope,
1358
+ );
1359
+ }
1360
+ const progress = { isStopped: false };
1361
+ return getSpecNextActions().reduce((count, action) => {
1362
+ if (progress.isStopped) return count;
1363
+ return (
1364
+ count +
1365
+ forEachSuccessor(
1366
+ action.expression,
1367
+ state,
1368
+ environment,
1369
+ (successor) => {
1370
+ progress.isStopped = onSuccessor(successor, action);
1371
+ return progress.isStopped;
1372
+ },
1373
+ action.scope,
1374
+ )
1375
+ );
1376
+ }, 0);
1377
+ };
1378
+ // TLC's worker adds a state to the behavior graph even after its next states fail or violate a
1379
+ // property, and prints the call stack of an error in that, unless the error is a
1380
+ // FingerprintException, which the worker doesn't catch. TLC 1.7.4 prints none.
1381
+ const getLiveCallStack = (index: number, liveSuccessors: LiveSuccessor[]) => {
1382
+ if (!liveness || is174) return undefined;
1383
+ const replay = getReplayFailure((tracing) =>
1384
+ liveness.addState(index, states[index], liveSuccessors, tracing),
1385
+ );
1386
+ return replay?.callStack.length && !replay.fingerprint ? replay.callStack : undefined;
1387
+ };
1388
+ // TLC's worker adds the state to the behavior graph after it prints the trace. On an error in that,
1389
+ // it adds the state again to print the call stack instead of replaying the next-state relation,
1390
+ // which TLC 1.7.4 doesn't.
1391
+ const addFailedLiveState = (index: number, liveSuccessors: LiveSuccessor[]) => {
1392
+ try {
1393
+ liveness?.addState(index, states[index], liveSuccessors);
1394
+ return undefined;
1395
+ } catch (error) {
1396
+ if (!(error instanceof TlaEvaluationError)) throw error;
1397
+ return getLiveCallStack(index, liveSuccessors);
1398
+ }
1399
+ };
1400
+ const replayFailedNext = (index: number, liveSuccessors: LiveSuccessor[]) => {
1401
+ const live = captureOutput(() => addFailedLiveState(index, liveSuccessors));
1402
+ if (live.result) {
1403
+ const result = { callStack: live.result, fingerprint: undefined, isLiveCallStack: true };
1404
+ return { result, lines: live.lines };
1405
+ }
1406
+ const replay = captureOutput(() => replayNext(index));
1407
+ return { result: replay.result, lines: [...live.lines, ...replay.lines] };
1408
+ };
1409
+ // TLC reports a stack overflow while it computes next states without replaying it, with the
1410
+ // behavior up to the state it expands.
1411
+ const reportNextStateOverflow = (index: number) =>
1412
+ createFailureResult(createStackOverflowError(), getStateTrace(index));
1413
+ // After the trace, TLC replays the next-state relation with its call stack, printing again.
1414
+ const reportNextStateFailure = (
1415
+ error: unknown,
1416
+ index: number,
1417
+ liveSuccessors: LiveSuccessor[],
1418
+ ) => {
1419
+ if (isStackOverflow(error)) return reportNextStateOverflow(index);
1420
+ const replay = replayFailedNext(index, liveSuccessors);
1421
+ return createFailureResult(
1422
+ withNextStateExitCode(error),
1423
+ appendTraceOutput(getStateTrace(index), replay.lines),
1424
+ { isNextState: true, ...replay.result },
1425
+ );
1426
+ };
1427
+ const expandState = (index: number, liveSuccessors: LiveSuccessor[]) => {
1315
1428
  const state = states[index];
1316
- const liveSuccessors: LiveSuccessor[] = [];
1317
- const successorCount = forEachSuccessor(
1318
- next,
1319
- state,
1320
- environment,
1321
- (successor) => {
1322
- try {
1323
- outcome.result = visitSuccessor(index, successor, liveSuccessors);
1324
- } catch (error) {
1325
- outcome.result = toFailure(error, getTrace(index, successor));
1429
+ const source = stateWriter && getGraphState(state, depths[index]);
1430
+ const successorCount = forEachActionSuccessor(state, (successor, action) => {
1431
+ try {
1432
+ outcome.result = visitSuccessor(index, successor, liveSuccessors, source, action);
1433
+ } catch (error) {
1434
+ if (isStackOverflow(error)) {
1435
+ outcome.result = reportNextStateOverflow(index);
1436
+ return true;
1326
1437
  }
1327
- return outcome.result !== undefined;
1328
- },
1329
- spec.scope,
1330
- );
1438
+ // TLC 1.7.4 reports the wrapped error without the trace, except for a failed property,
1439
+ // which it reports with the trace before it rethrows. The error stops its worker before it
1440
+ // adds the state to the behavior graph.
1441
+ const replay = is174
1442
+ ? captureOutput(() => replayNext(index))
1443
+ : replayFailedNext(index, liveSuccessors);
1444
+ if (is174 && error instanceof TlaEvaluationError && !isHeadedError(error)) {
1445
+ outcome.result = createFailureResult(
1446
+ new TlaEvaluationError(`${getWrappedException(error)}${error.message}`, error),
1447
+ appendTraceOutput({ trace: [] }, replay.lines),
1448
+ { isNextState: true, ...replay.result },
1449
+ );
1450
+ return true;
1451
+ }
1452
+ // A successor TLC can't fingerprint fails again as TLC prints it in the trace, which TLC
1453
+ // reports as an exception it didn't expect.
1454
+ const isTraceFailed = getFingerprintState(successor.state).some(
1455
+ (value) => getFingerprintError(value) !== undefined,
1456
+ );
1457
+ const traceFailure =
1458
+ isTraceFailed && error instanceof TlaEvaluationError
1459
+ ? getFailureMessage(
1460
+ isEvalException(error)
1461
+ ? new TlaEvaluationError(`${UNEXPECTED_EVAL_EXCEPTION}${error.message}`)
1462
+ : error,
1463
+ true,
1464
+ )
1465
+ : undefined;
1466
+ outcome.result = createFailureResult(
1467
+ error,
1468
+ appendTraceOutput(
1469
+ traceFailure ? getStateTrace(index) : getFailedTrace(index, successor),
1470
+ replay.lines,
1471
+ ),
1472
+ { isNextState: true, ...replay.result, traceFailure },
1473
+ );
1474
+ }
1475
+ return outcome.result !== undefined;
1476
+ });
1331
1477
  current.isExpanding = false;
1332
- if (outcome.result) return outcome.result;
1333
- if (successorCount === 0 && config.checkDeadlock) {
1334
- return reportViolation("deadlock", { name: "deadlock", trace: getStateTrace(index) });
1478
+ const result = outcome.result;
1479
+ // TLC 1.7.4's worker stops at a violation.
1480
+ if (result?.violation && !is174) {
1481
+ const live = captureOutput(() => addFailedLiveState(index, liveSuccessors));
1482
+ return {
1483
+ ...result,
1484
+ violation: appendTraceOutput(result.violation, live.lines),
1485
+ ...(live.result && { liveCallStack: live.result }),
1486
+ };
1335
1487
  }
1336
- try {
1488
+ if (result) return result;
1489
+ const addLiveState = () => {
1490
+ if (liveness && source && is174) stateWriter?.writeStuttering(source);
1337
1491
  const accepted = liveness?.addState(index, state, liveSuccessors);
1338
- current.livenessSource = -1;
1339
- if (!accepted) return undefined;
1492
+ if (!liveness || !accepted) return undefined;
1493
+ const steps = getPathSteps(accepted);
1494
+ const properties = getViolatedProperties(
1495
+ liveness,
1496
+ steps.map((step) => step.state),
1497
+ steps.length - 1,
1498
+ );
1340
1499
  return reportViolation("property-violation", {
1341
- name: accepted.name,
1342
- trace: getPathTrace(accepted.path),
1500
+ name: properties[0],
1501
+ properties,
1502
+ ...toTrace(steps, accepted, { known: 0 }),
1503
+ });
1504
+ };
1505
+ if (successorCount === 0 && config.checkDeadlock) {
1506
+ const deadlock = reportViolation("deadlock", { name: "deadlock", ...getStateTrace(index) });
1507
+ // TLC's worker still adds the deadlocked state to the behavior graph after it reports the
1508
+ // deadlock, and reports a temporal property that this violates. Then it counts the state as
1509
+ // expanded.
1510
+ const live = captureOutput(() => {
1511
+ try {
1512
+ return { additional: addLiveState()?.violation };
1513
+ } catch (error) {
1514
+ if (!(error instanceof TlaEvaluationError)) throw error;
1515
+ return { isFailed: true, callStack: getLiveCallStack(index, liveSuccessors) };
1516
+ }
1343
1517
  });
1518
+ const reported = deadlock.violation
1519
+ ? { ...deadlock, violation: appendTraceOutput(deadlock.violation, live.lines) }
1520
+ : deadlock;
1521
+ // An error in adding the state stops TLC 1.7.4's worker before it counts the state.
1522
+ const counted = withOutDegrees(
1523
+ reported,
1524
+ live.result.isFailed ? getFailureOutDegrees() : getPartialOutDegrees(),
1525
+ );
1526
+ if (live.result.additional)
1527
+ return { ...counted, additionalViolation: live.result.additional };
1528
+ return live.result.callStack ? { ...counted, liveCallStack: live.result.callStack } : counted;
1529
+ }
1530
+ try {
1531
+ return addLiveState();
1344
1532
  } catch (error) {
1345
- return toFailure(error, getStateTrace(index), undefined, getPartialOutDegrees());
1533
+ // TLC 1.7.4's worker reports an error in adding a state to the behavior graph as an exception
1534
+ // it didn't expect, without the trace or a call stack, and exits as for any general error.
1535
+ if (is174 && error instanceof TlaEvaluationError) {
1536
+ const unexpected = new TlaEvaluationError(
1537
+ `${isEvalException(error) ? UNEXPECTED_EVAL_EXCEPTION : UNEXPECTED_EXCEPTION}${error.message}`,
1538
+ );
1539
+ return createFailureResult(
1540
+ setExitCode(unexpected, EXIT_STATUS.error),
1541
+ { trace: [] },
1542
+ { outDegrees: getFailureOutDegrees() },
1543
+ );
1544
+ }
1545
+ // TLC's Worker#doNextCheckLiveness adds the state again to find the call stack, prints it
1546
+ // before the error, and reports the error as one in computing next states.
1547
+ const replay = getReplayFailure((tracing) =>
1548
+ liveness?.addState(index, state, liveSuccessors, tracing),
1549
+ );
1550
+ return createFailureResult(error, getStateTrace(index), {
1551
+ outDegrees: getFailureOutDegrees(),
1552
+ callStack: replay?.callStack.length ? replay.callStack : undefined,
1553
+ isNextState: true,
1554
+ isCallStackFirst: true,
1555
+ });
1556
+ }
1557
+ };
1558
+ // TLC's Liveness#printStutteringCounterExampleWarning.
1559
+ const getStutteringWarning = () => {
1560
+ const name = config.specification;
1561
+ const book =
1562
+ "(compare Chapter 8, page 87ff of Specifying Systems at https://lamport.azurewebsites.net/tla/book.html).";
1563
+ if (name === undefined) {
1564
+ return {
1565
+ code: MESSAGE_CODE.noSpecificationButProperty,
1566
+ text: `The stuttering counterexample above may be caused by the absence of a behavior specification (SPECIFICATION). Only INIT and NEXT have been provided, so TLC permits infinite stuttering. To rule out such counterexamples, use SPECIFICATION Spec, with Spec asserting a suitable fairness constraint ${book}`,
1567
+ };
1346
1568
  }
1569
+ const range = getDefinition(name, environment)?.location.range;
1570
+ if (spec.temporals.length > 0 || !range) return undefined;
1571
+ return {
1572
+ code: MESSAGE_CODE.noFairnessButProperty,
1573
+ 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}`,
1574
+ };
1347
1575
  };
1348
- const reportLasso = (lasso: Lasso) => {
1576
+ // TLC names the properties and the step back into the cycle from the states it prints.
1577
+ const reportLasso = (checker: LivenessChecker, lasso: Lasso) => {
1349
1578
  const path = [...lasso.prefix, ...lasso.cycle];
1350
- const trace = getPathTrace(path, lasso.prefix.length);
1351
- const back = path[lasso.prefix.length];
1352
- const last = path[path.length - 1];
1353
- const loopLabel =
1354
- back === last ? undefined : withoutOutput(() => getLabel(last, states[last], states[back]));
1579
+ const loopStart = lasso.prefix.length;
1580
+ const steps = getPathSteps(path, loopStart);
1581
+ const trace = toTrace(steps, path, { loopStart, known: 0 }).trace;
1582
+ const properties = getViolatedProperties(
1583
+ checker,
1584
+ steps.map((step) => step.state),
1585
+ loopStart,
1586
+ );
1587
+ const cycleStart = path[loopStart];
1588
+ const cycleEnd = path[path.length - 1];
1589
+ const lastState = steps[steps.length - 1].state;
1590
+ const loop =
1591
+ cycleStart === cycleEnd
1592
+ ? { result: undefined, lines: [] }
1593
+ : captureOutput(() => findStepAction(cycleEnd, lastState, states[cycleStart], false));
1594
+ const isStutteringWarned = cycleStart === cycleEnd && lasso.isCycleConstrained;
1355
1595
  return reportViolation(
1356
1596
  "liveness-violation",
1357
- { name: lasso.name, trace, loopStart: lasso.prefix.length, loopLabel },
1597
+ {
1598
+ name: properties[0],
1599
+ properties,
1600
+ trace,
1601
+ traceOutput: loop.lines,
1602
+ loopStart,
1603
+ loopLabel: loop.result && getActionLabel(loop.result, options.version),
1604
+ warning: isStutteringWarned ? getStutteringWarning() : undefined,
1605
+ },
1358
1606
  () =>
1359
- back === last
1360
- ? trace[trace.length - 1].action
1361
- : getTraceSuccessors(states[last]).find((successor) =>
1362
- isSameState(successor.state, states[back]),
1363
- )?.action,
1607
+ cycleStart === cycleEnd
1608
+ ? getStepAction(trace[trace.length - 1])
1609
+ : loop.result
1610
+ ? toActionValue(loop.result)
1611
+ : createActionRecord(findSuccessorWithFingerprint(lastState, cycleStart)?.action),
1364
1612
  );
1365
1613
  };
1366
1614
  const isPeriodic = liveness !== undefined && options.livenessCheck !== "final";
@@ -1368,44 +1616,78 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1368
1616
  const periodic = { at: startedAt + PERIODIC_START, size: 1, time: 0 };
1369
1617
  const findPeriodicViolation = (expanded: number) => {
1370
1618
  const now = performance.now();
1371
- periodic.at = now + PROGRESS_INTERVAL;
1372
1619
  const isGrown = (expanded - periodic.size) / periodic.size > LIVENESS_GROWTH;
1373
1620
  if (!isGrown || periodic.time > (now - startedAt) * LIVENESS_RATIO) return undefined;
1374
1621
  periodic.size = expanded;
1375
- const lasso = liveness?.findViolation();
1376
- current.livenessSource = -1;
1622
+ if (!liveness) return undefined;
1623
+ options.onProgress?.({
1624
+ kind: "liveness-started",
1625
+ branches: liveness.branches,
1626
+ isComplete: false,
1627
+ states: expanded,
1628
+ statistics: createResult("success"),
1629
+ });
1630
+ const lasso = liveness.findViolation();
1631
+ if (!lasso) options.onProgress?.({ kind: "liveness-finished" });
1377
1632
  periodic.time += performance.now() - now;
1378
1633
  return lasso;
1379
1634
  };
1380
- setNextStatePhase(true);
1381
1635
  for (let index = 0; index < states.length && !runtime.isStopped; index++) {
1382
1636
  current.index = index;
1383
1637
  current.candidate = undefined;
1384
1638
  runtime.queueSize = states.length - index - 1;
1385
1639
  current.isExpanding = true;
1640
+ const liveSuccessors: LiveSuccessor[] = [];
1386
1641
  try {
1387
- outcome.result = expandState(index);
1642
+ outcome.result = expandState(index, liveSuccessors);
1388
1643
  } catch (error) {
1389
- outcome.result = toFailure(error, getStateTrace(index));
1644
+ outcome.result =
1645
+ error instanceof TlaIncompleteSuccessorError
1646
+ ? reportIncompleteSuccessor(index, error)
1647
+ : reportNextStateFailure(error, index, liveSuccessors);
1390
1648
  }
1391
1649
  if (outcome.result) return outcome.result;
1392
1650
  outDegrees[getOutDegreeBucket()]++;
1393
1651
  expansion.newStates = 0;
1394
- if (isPeriodic && performance.now() >= periodic.at) {
1395
- const lasso = findPeriodicViolation(index + 1);
1396
- if (lasso) return reportLasso(lasso);
1652
+ // TLC's AbstractChecker#runTLC checks the liveness properties on the state graph so far, then
1653
+ // reports how far the search got.
1654
+ if ((isPeriodic || options.onProgress) && performance.now() >= periodic.at) {
1655
+ periodic.at = performance.now() + PROGRESS_INTERVAL;
1656
+ const lasso = isPeriodic ? findPeriodicViolation(index + 1) : undefined;
1657
+ if (liveness && lasso) return reportLasso(liveness, lasso);
1658
+ options.onProgress?.({ kind: "progress", statistics: createResult("success") });
1397
1659
  }
1398
1660
  }
1399
1661
 
1400
1662
  current.index = -1;
1401
1663
  current.candidate = undefined;
1664
+ if (liveness) {
1665
+ options.onProgress?.({
1666
+ kind: "liveness-started",
1667
+ branches: liveness.branches,
1668
+ isComplete: true,
1669
+ states: runtime.distinctStates,
1670
+ statistics: createResult("success"),
1671
+ });
1672
+ }
1402
1673
  const lasso = liveness?.findViolation();
1403
- current.livenessSource = -1;
1404
- if (lasso) return reportLasso(lasso);
1674
+ if (liveness && lasso) return reportLasso(liveness, lasso);
1405
1675
 
1406
- const postconditionViolation = search.findPostconditionViolation();
1407
- if (postconditionViolation) {
1408
- return createResult("postcondition-violation", { ...postconditionViolation, trace: [] });
1676
+ // TLC finishes the check of the temporal properties before it checks the postconditions.
1677
+ if (liveness) options.onProgress?.({ kind: "liveness-finished" });
1678
+ try {
1679
+ const postcondition = search.findPostconditionViolation();
1680
+ if (postcondition) {
1681
+ return createResult("postcondition-violation", {
1682
+ name: postcondition.name,
1683
+ message: postcondition.message,
1684
+ counts: postcondition.counts,
1685
+ trace: [],
1686
+ postcondition,
1687
+ });
1688
+ }
1689
+ } catch (error) {
1690
+ return createFailureResult(error, { trace: [] });
1409
1691
  }
1410
1692
  return createSuccess();
1411
1693
  };