tla-ts 0.0.3 → 0.0.4-dev.2a873ee

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 (370) 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 +996 -0
  17. package/dist/prove.js +996 -0
  18. package/dist/run-cli.cjs +37 -20
  19. package/dist/run-cli.js +37 -20
  20. package/dist/tlapm.cjs +10 -0
  21. package/dist/tlapm.js +10 -0
  22. package/dist/transfer.cjs +1387 -18
  23. package/dist/transfer.js +1387 -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 +4 -7
  29. package/src/builtins.ts +29 -11
  30. package/src/bundled-modules.ts +3 -3
  31. package/src/canonical.ts +4 -3
  32. package/src/check.ts +1540 -235
  33. package/src/cli-options.ts +12 -6
  34. package/src/cli.ts +8 -1
  35. package/src/codegen.ts +98 -39
  36. package/src/config.ts +254 -181
  37. package/src/dependencies.ts +2 -2
  38. package/src/environment.ts +540 -140
  39. package/src/errors.ts +284 -4
  40. package/src/evaluate.ts +1043 -293
  41. package/src/exit-codes.ts +22 -43
  42. package/src/fingerprints.ts +46 -11
  43. package/src/index.ts +11 -0
  44. package/src/instances.ts +19 -16
  45. package/src/java-overrides.ts +104 -25
  46. package/src/levels.ts +191 -45
  47. package/src/lexer.ts +127 -30
  48. package/src/live-check.ts +867 -0
  49. package/src/liveness.ts +218 -572
  50. package/src/{obligation-action.ts → obligations/action.ts} +247 -69
  51. package/src/{obligation-anon.ts → obligations/anon.ts} +49 -47
  52. package/src/obligations/ctx.ts +64 -0
  53. package/src/{obligation-deref.ts → obligations/deref.ts} +51 -92
  54. package/src/{obligation-expression.ts → obligations/expression.ts} +117 -57
  55. package/src/{obligation-format.ts → obligations/format.ts} +7 -8
  56. package/src/{obligation-generate.ts → obligations/generate.ts} +170 -192
  57. package/src/{obligations.ts → obligations/index.ts} +32 -16
  58. package/src/{obligation-levels.ts → obligations/levels.ts} +26 -28
  59. package/src/{obligation-module.ts → obligations/module.ts} +113 -121
  60. package/src/obligations/pickle.ts +98 -0
  61. package/src/obligations/pragma.ts +189 -0
  62. package/src/{obligation-printer.ts → obligations/printer.ts} +22 -80
  63. package/src/{obligation-proof.ts → obligations/proof.ts} +7 -2
  64. package/src/{obligation-source.ts → obligations/source.ts} +156 -99
  65. package/src/obligations/temporal.ts +321 -0
  66. package/src/{obligation-tuples.ts → obligations/tuples.ts} +38 -54
  67. package/src/ocaml-marshal.ts +166 -0
  68. package/src/parallel-worker.ts +169 -224
  69. package/src/parallel.ts +140 -81
  70. package/src/parser.ts +456 -147
  71. package/src/pcal-ast.ts +770 -0
  72. package/src/pcal-parse.ts +1523 -0
  73. package/src/pcal-tokenize.ts +516 -0
  74. package/src/pcal-translate.ts +1230 -0
  75. package/src/pcal-validate.ts +454 -0
  76. package/src/prove/decide-pool.ts +95 -0
  77. package/src/prove/deciders.ts +33 -0
  78. package/src/prove/first-order.ts +78 -0
  79. package/src/prove/isabelle/LICENSE +36 -0
  80. package/src/prove/isabelle/LICENSE-tlapm +26 -0
  81. package/src/prove/isabelle/decide.ts +47 -0
  82. package/src/prove/isabelle/encode.ts +446 -0
  83. package/src/prove/isabelle/isar/inner-syntax.ts +579 -0
  84. package/src/prove/isabelle/isar/method.ts +367 -0
  85. package/src/prove/isabelle/isar/proof.ts +28 -0
  86. package/src/prove/isabelle/isar/statement.ts +57 -0
  87. package/src/prove/isabelle/isar/theory.ts +192 -0
  88. package/src/prove/isabelle/isar/type-check.ts +278 -0
  89. package/src/prove/isabelle/provers/blast/blast.ts +258 -0
  90. package/src/prove/isabelle/provers/blast/branch.ts +322 -0
  91. package/src/prove/isabelle/provers/blast/prove.ts +347 -0
  92. package/src/prove/isabelle/provers/blast/rules.ts +330 -0
  93. package/src/prove/isabelle/provers/blast/state.ts +180 -0
  94. package/src/prove/isabelle/provers/blast/term.ts +546 -0
  95. package/src/prove/isabelle/provers/clasimp.ts +150 -0
  96. package/src/prove/isabelle/provers/classical.ts +389 -0
  97. package/src/prove/isabelle/provers/hypsubst.ts +433 -0
  98. package/src/prove/isabelle/pure/bicompose.ts +174 -0
  99. package/src/prove/isabelle/pure/consts.ts +32 -0
  100. package/src/prove/isabelle/pure/conv.ts +79 -0
  101. package/src/prove/isabelle/pure/drule.ts +264 -0
  102. package/src/prove/isabelle/pure/envir.ts +331 -0
  103. package/src/prove/isabelle/pure/goal.ts +53 -0
  104. package/src/prove/isabelle/pure/interrupt.ts +16 -0
  105. package/src/prove/isabelle/pure/list.ts +12 -0
  106. package/src/prove/isabelle/pure/logic.ts +330 -0
  107. package/src/prove/isabelle/pure/name.ts +98 -0
  108. package/src/prove/isabelle/pure/net.ts +215 -0
  109. package/src/prove/isabelle/pure/object-logic.ts +41 -0
  110. package/src/prove/isabelle/pure/pattern.ts +631 -0
  111. package/src/prove/isabelle/pure/raw-simplifier.ts +338 -0
  112. package/src/prove/isabelle/pure/rewriter.ts +602 -0
  113. package/src/prove/isabelle/pure/search.ts +68 -0
  114. package/src/prove/isabelle/pure/seq.ts +133 -0
  115. package/src/prove/isabelle/pure/simplifier.ts +106 -0
  116. package/src/prove/isabelle/pure/table.ts +201 -0
  117. package/src/prove/isabelle/pure/tactic.ts +168 -0
  118. package/src/prove/isabelle/pure/tactical.ts +264 -0
  119. package/src/prove/isabelle/pure/term-ord.ts +105 -0
  120. package/src/prove/isabelle/pure/term.ts +688 -0
  121. package/src/prove/isabelle/pure/thm.ts +783 -0
  122. package/src/prove/isabelle/pure/type.ts +121 -0
  123. package/src/prove/isabelle/pure/unify.ts +753 -0
  124. package/src/prove/isabelle/pure/variable.ts +25 -0
  125. package/src/prove/isabelle/tla/classical-setup.ts +101 -0
  126. package/src/prove/isabelle/tla/context.ts +74 -0
  127. package/src/prove/isabelle/tla/logic-data.ts +5 -0
  128. package/src/prove/isabelle/tla/logic.ts +215 -0
  129. package/src/prove/isabelle/tla/simpdata.ts +241 -0
  130. package/src/prove/isabelle/tools/intuitionistic.ts +132 -0
  131. package/src/prove/ocaml.ts +22 -0
  132. package/src/prove/prep/action.ts +508 -0
  133. package/src/prove/prep/defs.ts +33 -0
  134. package/src/prove/prep/elab.ts +156 -0
  135. package/src/prove/prep/enabled-axioms.ts +189 -0
  136. package/src/prove/prep/enabled.ts +43 -0
  137. package/src/prove/prep/fingerprint.ts +388 -0
  138. package/src/prove/prep/flatten.ts +70 -0
  139. package/src/prove/prep/level-comparison.ts +529 -0
  140. package/src/prove/prep/md5.ts +67 -0
  141. package/src/prove/prep/pragma.ts +221 -0
  142. package/src/prove/prep/trivial.ts +22 -0
  143. package/src/prove/prove-worker.ts +22 -0
  144. package/src/prove/prove.ts +498 -0
  145. package/src/prove/ptl/decide.ts +68 -0
  146. package/src/prove/ptl/encode.ts +255 -0
  147. package/src/prove/ptl/sat.ts +151 -0
  148. package/src/prove/ptl/tableau.ts +276 -0
  149. package/src/prove/smt/axiomatize.ts +69 -0
  150. package/src/prove/smt/axioms.ts +209 -0
  151. package/src/prove/smt/context.ts +108 -0
  152. package/src/prove/smt/data.ts +636 -0
  153. package/src/prove/smt/encode.ts +164 -0
  154. package/src/prove/smt/extensionality.ts +65 -0
  155. package/src/prove/smt/flatten.ts +112 -0
  156. package/src/prove/smt/format.ts +154 -0
  157. package/src/prove/smt/instances.ts +181 -0
  158. package/src/prove/smt/rewrite.ts +772 -0
  159. package/src/prove/smt/simplify.ts +57 -0
  160. package/src/prove/smt/solver/act-cache.ts +265 -0
  161. package/src/prove/smt/solver/arith-rewriter.ts +962 -0
  162. package/src/prove/smt/solver/array.ts +22 -0
  163. package/src/prove/smt/solver/asserted-formulas.ts +469 -0
  164. package/src/prove/smt/solver/ast-lt.ts +157 -0
  165. package/src/prove/smt/solver/ast-util.ts +91 -0
  166. package/src/prove/smt/solver/ast.ts +1315 -0
  167. package/src/prove/smt/solver/auf-solver.ts +572 -0
  168. package/src/prove/smt/solver/case-split-queue.ts +178 -0
  169. package/src/prove/smt/solver/cg-table.ts +175 -0
  170. package/src/prove/smt/solver/clause.ts +276 -0
  171. package/src/prove/smt/solver/conflict-resolution.ts +343 -0
  172. package/src/prove/smt/solver/context.ts +1292 -0
  173. package/src/prove/smt/solver/ctx-simplify.ts +334 -0
  174. package/src/prove/smt/solver/der.ts +224 -0
  175. package/src/prove/smt/solver/dyn-ack.ts +141 -0
  176. package/src/prove/smt/solver/e-matching.ts +659 -0
  177. package/src/prove/smt/solver/enode.ts +259 -0
  178. package/src/prove/smt/solver/expr-ref.ts +21 -0
  179. package/src/prove/smt/solver/expr-safe-replace.ts +172 -0
  180. package/src/prove/smt/solver/fingerprints.ts +92 -0
  181. package/src/prove/smt/solver/flat-literals.ts +51 -0
  182. package/src/prove/smt/solver/goal.ts +138 -0
  183. package/src/prove/smt/solver/hash.ts +173 -0
  184. package/src/prove/smt/solver/hashtable.ts +166 -0
  185. package/src/prove/smt/solver/internalizer.ts +1381 -0
  186. package/src/prove/smt/solver/lbool.ts +5 -0
  187. package/src/prove/smt/solver/literal.ts +24 -0
  188. package/src/prove/smt/solver/lp/bound-propagator.ts +391 -0
  189. package/src/prove/smt/solver/lp/constraints.ts +78 -0
  190. package/src/prove/smt/solver/lp/containers.ts +296 -0
  191. package/src/prove/smt/solver/lp/core-solver.ts +504 -0
  192. package/src/prove/smt/solver/lp/cross-nested.ts +224 -0
  193. package/src/prove/smt/solver/lp/dep-intervals.ts +642 -0
  194. package/src/prove/smt/solver/lp/dependency.ts +51 -0
  195. package/src/prove/smt/solver/lp/dioph-eq.ts +1181 -0
  196. package/src/prove/smt/solver/lp/explanation.ts +46 -0
  197. package/src/prove/smt/solver/lp/gomory.ts +255 -0
  198. package/src/prove/smt/solver/lp/hnf-cutter.ts +125 -0
  199. package/src/prove/smt/solver/lp/hnf.ts +281 -0
  200. package/src/prove/smt/solver/lp/int-cube.ts +295 -0
  201. package/src/prove/smt/solver/lp/int-solver.ts +514 -0
  202. package/src/prove/smt/solver/lp/lar-solver.ts +816 -0
  203. package/src/prove/smt/solver/lp/lar-term.ts +62 -0
  204. package/src/prove/smt/solver/lp/lp-settings.ts +91 -0
  205. package/src/prove/smt/solver/lp/maximize-term.ts +347 -0
  206. package/src/prove/smt/solver/lp/nex-creator.ts +381 -0
  207. package/src/prove/smt/solver/lp/nex.ts +120 -0
  208. package/src/prove/smt/solver/lp/nla-backoff.ts +43 -0
  209. package/src/prove/smt/solver/lp/nla-basics.ts +398 -0
  210. package/src/prove/smt/solver/lp/nla-core.ts +968 -0
  211. package/src/prove/smt/solver/lp/nla-divisions.ts +332 -0
  212. package/src/prove/smt/solver/lp/nla-emonics.ts +373 -0
  213. package/src/prove/smt/solver/lp/nla-factorization.ts +30 -0
  214. package/src/prove/smt/solver/lp/nla-grobner.ts +904 -0
  215. package/src/prove/smt/solver/lp/nla-horner.ts +126 -0
  216. package/src/prove/smt/solver/lp/nla-intervals.ts +265 -0
  217. package/src/prove/smt/solver/lp/nla-monomial-bounds.ts +715 -0
  218. package/src/prove/smt/solver/lp/nla-monotone.ts +59 -0
  219. package/src/prove/smt/solver/lp/nla-order.ts +307 -0
  220. package/src/prove/smt/solver/lp/nla-patcher.ts +112 -0
  221. package/src/prove/smt/solver/lp/nla-tangents.ts +251 -0
  222. package/src/prove/smt/solver/lp/nla-throttle.ts +85 -0
  223. package/src/prove/smt/solver/lp/nla-types.ts +124 -0
  224. package/src/prove/smt/solver/lp/nla-var-eqs.ts +141 -0
  225. package/src/prove/smt/solver/lp/nra-solver.ts +440 -0
  226. package/src/prove/smt/solver/lp/numeric-pair.ts +65 -0
  227. package/src/prove/smt/solver/lp/pdd-interval.ts +31 -0
  228. package/src/prove/smt/solver/lp/pdd-simplifier.ts +184 -0
  229. package/src/prove/smt/solver/lp/pdd-solver.ts +408 -0
  230. package/src/prove/smt/solver/lp/pdd.ts +971 -0
  231. package/src/prove/smt/solver/lp/random-updater.ts +138 -0
  232. package/src/prove/smt/solver/lp/static-matrix.ts +246 -0
  233. package/src/prove/smt/solver/lp/union-find.ts +96 -0
  234. package/src/prove/smt/solver/mam-compiler.ts +847 -0
  235. package/src/prove/smt/solver/mam-interpreter.ts +400 -0
  236. package/src/prove/smt/solver/maximize-ac-sharing.ts +118 -0
  237. package/src/prove/smt/solver/model-checker.ts +347 -0
  238. package/src/prove/smt/solver/model-evaluator.ts +262 -0
  239. package/src/prove/smt/solver/model-finder.ts +155 -0
  240. package/src/prove/smt/solver/model-generator.ts +97 -0
  241. package/src/prove/smt/solver/model-macro-solver.ts +728 -0
  242. package/src/prove/smt/solver/nlsat/algebraic.ts +1161 -0
  243. package/src/prove/smt/solver/nlsat/atoms.ts +238 -0
  244. package/src/prove/smt/solver/nlsat/evaluator.ts +303 -0
  245. package/src/prove/smt/solver/nlsat/explain.ts +607 -0
  246. package/src/prove/smt/solver/nlsat/interval-set.ts +351 -0
  247. package/src/prove/smt/solver/nlsat/levelwise.ts +737 -0
  248. package/src/prove/smt/solver/nlsat/mpbq.ts +161 -0
  249. package/src/prove/smt/solver/nlsat/polynomial.ts +1722 -0
  250. package/src/prove/smt/solver/nlsat/solver.ts +911 -0
  251. package/src/prove/smt/solver/nlsat/types.ts +43 -0
  252. package/src/prove/smt/solver/nlsat/upolynomial-factorization.ts +648 -0
  253. package/src/prove/smt/solver/nlsat/upolynomial.ts +996 -0
  254. package/src/prove/smt/solver/nnf.ts +469 -0
  255. package/src/prove/smt/solver/pattern-inference.ts +351 -0
  256. package/src/prove/smt/solver/poly-rewriter.ts +477 -0
  257. package/src/prove/smt/solver/propagate-values.ts +83 -0
  258. package/src/prove/smt/solver/proto-model.ts +551 -0
  259. package/src/prove/smt/solver/pull-quant.ts +139 -0
  260. package/src/prove/smt/solver/qe-lite-der.ts +526 -0
  261. package/src/prove/smt/solver/qe-lite-fm.ts +576 -0
  262. package/src/prove/smt/solver/qe-lite.ts +381 -0
  263. package/src/prove/smt/solver/qi-queue.ts +362 -0
  264. package/src/prove/smt/solver/quant-tactics.ts +117 -0
  265. package/src/prove/smt/solver/quantifier-analyzer.ts +562 -0
  266. package/src/prove/smt/solver/quantifier-manager.ts +186 -0
  267. package/src/prove/smt/solver/random-gen.ts +10 -0
  268. package/src/prove/smt/solver/rational.ts +165 -0
  269. package/src/prove/smt/solver/ref-vector.ts +62 -0
  270. package/src/prove/smt/solver/relevancy.ts +247 -0
  271. package/src/prove/smt/solver/rewriter-tpl.ts +1159 -0
  272. package/src/prove/smt/solver/rewriter.ts +843 -0
  273. package/src/prove/smt/solver/rlimit.ts +79 -0
  274. package/src/prove/smt/solver/smtlib-parser.ts +526 -0
  275. package/src/prove/smt/solver/solver.ts +71 -0
  276. package/src/prove/smt/solver/sort.ts +35 -0
  277. package/src/prove/smt/solver/sticky-generations.ts +69 -0
  278. package/src/prove/smt/solver/theory-lra-axioms.ts +340 -0
  279. package/src/prove/smt/solver/theory-lra-bounds.ts +226 -0
  280. package/src/prove/smt/solver/theory-lra-final-check.ts +252 -0
  281. package/src/prove/smt/solver/theory-lra-internalize.ts +476 -0
  282. package/src/prove/smt/solver/theory-lra-model.ts +243 -0
  283. package/src/prove/smt/solver/theory-lra-propagate.ts +405 -0
  284. package/src/prove/smt/solver/theory-lra-state.ts +43 -0
  285. package/src/prove/smt/solver/theory-lra.ts +56 -0
  286. package/src/prove/smt/solver/var-subst.ts +258 -0
  287. package/src/prove/smt/solver/z3-license.txt +10 -0
  288. package/src/prove/smt/table.ts +170 -0
  289. package/src/prove/tlapm/tlapm.ts +96 -0
  290. package/src/prove/tlaps-module.ts +510 -0
  291. package/src/prove/verdict.ts +18 -0
  292. package/src/prove/zenon/LICENSE +32 -0
  293. package/src/prove/zenon/check/check.ts +105 -0
  294. package/src/prove/zenon/check/definitions.ts +144 -0
  295. package/src/prove/zenon/check/equality.ts +182 -0
  296. package/src/prove/zenon/check/functions.ts +62 -0
  297. package/src/prove/zenon/check/keys.ts +125 -0
  298. package/src/prove/zenon/check/propositional.ts +104 -0
  299. package/src/prove/zenon/check/records.ts +188 -0
  300. package/src/prove/zenon/check/relations.ts +121 -0
  301. package/src/prove/zenon/check/rewrites.ts +224 -0
  302. package/src/prove/zenon/check/sets.ts +302 -0
  303. package/src/prove/zenon/check/terms.ts +127 -0
  304. package/src/prove/zenon/check/tla.ts +126 -0
  305. package/src/prove/zenon/decide.ts +113 -0
  306. package/src/prove/zenon/encode.ts +379 -0
  307. package/src/prove/zenon/eqrel.ts +300 -0
  308. package/src/prove/zenon/equality-rules.ts +435 -0
  309. package/src/prove/zenon/expr.ts +551 -0
  310. package/src/prove/zenon/index-table.ts +350 -0
  311. package/src/prove/zenon/isar-case.ts +513 -0
  312. package/src/prove/zenon/isar.ts +1249 -0
  313. package/src/prove/zenon/limits.ts +15 -0
  314. package/src/prove/zenon/llproof.ts +173 -0
  315. package/src/prove/zenon/mltoll.ts +1566 -0
  316. package/src/prove/zenon/node.ts +297 -0
  317. package/src/prove/zenon/ocaml.ts +169 -0
  318. package/src/prove/zenon/parse.ts +247 -0
  319. package/src/prove/zenon/phrase.ts +191 -0
  320. package/src/prove/zenon/proof.ts +198 -0
  321. package/src/prove/zenon/propositional-rules.ts +387 -0
  322. package/src/prove/zenon/rules.ts +94 -0
  323. package/src/prove/zenon/search.ts +288 -0
  324. package/src/prove/zenon/tla/functions.ts +151 -0
  325. package/src/prove/zenon/tla/llproof.ts +480 -0
  326. package/src/prove/zenon/tla/records.ts +225 -0
  327. package/src/prove/zenon/tla/rewrites.ts +447 -0
  328. package/src/prove/zenon/tla/sets.ts +304 -0
  329. package/src/prove/zenon/tla/terms.ts +162 -0
  330. package/src/prove/zenon/tla/tla.ts +506 -0
  331. package/src/randomization.ts +24 -7
  332. package/src/resolve.ts +1481 -426
  333. package/src/run-cli.ts +1483 -212
  334. package/src/runtime.ts +19 -1
  335. package/src/sany-builtins.ts +147 -0
  336. package/src/sany-generator.ts +3128 -0
  337. package/src/sany-levels.ts +1208 -0
  338. package/src/sany-lexer.ts +545 -0
  339. package/src/sany-linter.ts +122 -0
  340. package/src/sany-modules.ts +1398 -0
  341. package/src/sany-nodes.ts +463 -0
  342. package/src/sany-parse-error.ts +2161 -0
  343. package/src/sany-report.ts +356 -0
  344. package/src/sany-selectors.ts +738 -0
  345. package/src/sany-source.ts +248 -0
  346. package/src/sany-xml.ts +1017 -0
  347. package/src/spec-description.ts +42 -11
  348. package/src/standard-modules.ts +203 -148
  349. package/src/standard-ranges.ts +116 -0
  350. package/src/state-graph.ts +180 -0
  351. package/src/subexpressions.ts +231 -171
  352. package/src/substitution-levels.ts +38 -17
  353. package/src/successors.ts +241 -110
  354. package/src/symmetry.ts +194 -54
  355. package/src/tableau.ts +54 -25
  356. package/src/tlapm-cache.ts +236 -0
  357. package/src/tlc-ext.ts +42 -29
  358. package/src/tlc-messages.ts +329 -0
  359. package/src/tlc-module.ts +52 -43
  360. package/src/tlc-modules.ts +4 -0
  361. package/src/tlc-order.ts +78 -10
  362. package/src/tlc-random.ts +84 -33
  363. package/src/tlc-replay.ts +655 -0
  364. package/src/tlc-summary.ts +20 -5
  365. package/src/tlc-version.ts +19 -0
  366. package/src/transfer.ts +15 -3
  367. package/src/values.ts +787 -190
  368. package/src/worker.ts +65 -0
  369. package/dist/parallel.cjs +0 -12
  370. package/dist/parallel.js +0 -12
package/src/check.ts CHANGED
@@ -1,32 +1,52 @@
1
- import type { Assumption, Definition, Expression, SourceLocation } from "./ast";
1
+ import {
2
+ getChildren,
3
+ isLocallyResolved,
4
+ type Assumption,
5
+ type Definition,
6
+ type Expression,
7
+ type SourceLocation,
8
+ } from "./ast";
2
9
  import { parseConfig, type ConfigValue, type ModelConfig } from "./config";
3
10
  import { getReadVariables } from "./dependencies";
4
11
  import { createEnvironment } from "./environment";
5
- import { getErrorExitCode, TlaConfigError, TlaEvaluationError, TlaModuleError } from "./errors";
6
- import { EXIT_STATUS, setExitCode, setNextStatePhase, withLivenessExitCode } from "./exit-codes";
7
12
  import {
13
+ getErrorExitCode,
14
+ isStackOverflow,
15
+ TlaConfigError,
16
+ TlaEvaluationError,
17
+ TlaIllegalStateError,
18
+ TlaIncompleteSuccessorError,
19
+ TlaModuleError,
20
+ TlaStackOverflowError,
21
+ getUnexpectedException,
22
+ UNEXPECTED_EXCEPTION,
23
+ } from "./errors";
24
+ import type { JavaOverride } from "./java-overrides";
25
+ import { EXIT_STATUS, getExitCode, setExitCode, withLivenessExitCode } from "./exit-codes";
26
+ import {
27
+ describeNode,
8
28
  describeRange,
29
+ createTracingEnvironment,
9
30
  evaluate,
31
+ evaluateStartupDefinitions,
10
32
  expectBoolean,
11
33
  formatRange,
12
- getChildren,
13
34
  getDefinition,
14
35
  isConstantLevel,
15
36
  isImpure,
16
- isLocallyResolved,
37
+ type CallStack,
17
38
  type Context,
18
39
  type Environment,
40
+ type FingerprintFailure,
19
41
  type Scope,
20
42
  } from "./evaluate";
21
43
  import {
22
44
  createLivenessChecker,
23
- expandTemporal,
24
- getLevel,
25
45
  type Lasso,
46
+ type LivenessChecker,
26
47
  type LiveSuccessor,
27
- type ScopedExpression,
28
- type TemporalProperty,
29
- } from "./liveness";
48
+ } from "./live-check";
49
+ import { expandTemporal, getLevel, type ScopedExpression, type TemporalProperty } from "./liveness";
30
50
  import { ACTION_LEVEL, createLevelAnalyzer, TEMPORAL_LEVEL } from "./levels";
31
51
  import { prettyPrint } from "./pretty-print";
32
52
  import {
@@ -38,25 +58,49 @@ import {
38
58
  } from "./successors";
39
59
  import {
40
60
  getActionLabel,
61
+ getActionSignature,
62
+ getInitActions,
41
63
  getNextActions,
42
64
  getSpecificationValue,
65
+ toActionValue,
43
66
  type SpecAction,
44
67
  } from "./spec-description";
68
+ import {
69
+ createStateWriter,
70
+ type GraphState,
71
+ type StateDump,
72
+ type StateWriter,
73
+ } from "./state-graph";
45
74
  import { getRepresentative, getSymmetryGroup } from "./symmetry";
46
75
  import { getTlcStringOrder, getTlcVariableOrder } from "./tlc-order";
76
+ import {
77
+ formatNestedMessage,
78
+ getCodedMessage,
79
+ isEvalException,
80
+ MESSAGE_CODE,
81
+ MISSING_INIT_174,
82
+ } from "./tlc-messages";
83
+ import { replayInitialStates, replaySuccessors } from "./tlc-replay";
47
84
  import { createTlcFingerprinter, getTlcFingerprint } from "./tlc-random";
48
85
  import { createCanonicalizer } from "./canonical";
49
86
  import { getPossibleCounts, type CheckerRuntime } from "./runtime";
50
- import { createCounterExample } from "./tlc-ext";
87
+ import { createActionRecord, createCounterExample } from "./tlc-ext";
51
88
  import { getFingerprintDistance, OUT_DEGREE_BUCKETS } from "./tlc-summary";
89
+ import type { TlcVersion } from "./tlc-version";
52
90
  import {
53
91
  combineHash,
92
+ createModelValue,
93
+ formatState,
54
94
  formatValue,
95
+ getHeldValues,
96
+ getFingerprintError,
97
+ markFingerprinted,
55
98
  getValueHash,
56
99
  isFunctionValue,
57
100
  isSameValue,
58
101
  isUpdatedElementOf,
59
102
  setStringOrder,
103
+ setValueVersion,
60
104
  toFiniteFunction,
61
105
  type Value,
62
106
  } from "./values";
@@ -74,8 +118,73 @@ export interface CheckOptions {
74
118
  workers?: number;
75
119
  // TLC's -lncheck: "final" checks liveness only on the complete state graph.
76
120
  livenessCheck?: "default" | "final";
121
+ // TLC's -dump: writes the reachable states, or with `dot` the state graph, through writeFile.
122
+ dump?: StateDump;
123
+ // TLC's -tool, which changes the messages of TLC's errors.
124
+ isTool?: boolean;
125
+ // Whether TLC records a binary trace for its trace exploration spec, for which it loads Integers.
126
+ isTraceRecorded?: boolean;
127
+ // Whether the caller printed SANY's report, its warnings included, before the check.
128
+ isSanyReported?: boolean;
129
+ // False for TLC's -nowarning, which changes how TLC computes the successors of some actions.
130
+ isWarningEnabled?: boolean;
131
+ // The TLC whose output tla-ts reproduces, which changes how TLC labels an action.
132
+ version?: TlcVersion;
133
+ // Reports the points of the search at which TLC prints a message.
134
+ onProgress?: (progress: CheckProgress) => void;
77
135
  }
78
136
 
137
+ export interface InitialStatesProgress {
138
+ kind: "initial-states-progress";
139
+ count: number;
140
+ }
141
+
142
+ // A check that TLC's DoInitFunctor reports as violated before it stops its replay of the initial
143
+ // states.
144
+ export interface InitialStateViolation {
145
+ kind: "initial-state-violation";
146
+ status: "invariant-violation" | "liveness-violation";
147
+ name: string;
148
+ state: Record<string, Value>;
149
+ }
150
+
151
+ // A line the spec prints, or what TLC reports as it replays the initial states.
152
+ export type OutputLine = string | InitialStatesProgress | InitialStateViolation;
153
+
154
+ // The spec is parsed, TLC warns about each invariant that is a true constant formula and each
155
+ // property that is a state formula, finds the branches of the temporal properties, computes the
156
+ // initial states, reporting each time their count reaches a power of two, reports how far the
157
+ // search got 3 seconds after it starts and every minute after, and checks the temporal properties
158
+ // on the state graph so far at those times and on the complete state graph at the end.
159
+ export type CheckProgress =
160
+ | { kind: "parsed" }
161
+ | { kind: "constant-level-invariant"; name: string }
162
+ | { kind: "state-level-property"; name: string }
163
+ | { kind: "liveness-initializing"; isSymmetric: boolean; isConstrained: boolean }
164
+ | { kind: "liveness-prepared"; branches: number }
165
+ | { kind: "initial-states-started" }
166
+ | InitialStatesProgress
167
+ | { kind: "initial-states-computed"; initialStates: InitialStates }
168
+ | { kind: "progress"; statistics: SearchStatistics }
169
+ | {
170
+ kind: "liveness-started";
171
+ branches: number;
172
+ // Whether TLC checks the complete state graph, and how many states of it each branch has.
173
+ isComplete: boolean;
174
+ states: number;
175
+ statistics: SearchStatistics;
176
+ }
177
+ | { kind: "liveness-finished" }
178
+ // A warning TLC prints as it evaluates the spec, with its message code.
179
+ | { kind: "warning"; code: number; text: string }
180
+ // A method of the class named after a module, which TLC reports as it loads the class.
181
+ | ({ kind: "java-override" } & JavaOverride);
182
+
183
+ export interface SearchStatistics extends Pick<
184
+ CheckResult,
185
+ "generatedStates" | "distinctStates" | "queuedStates" | "depth"
186
+ > {}
187
+
79
188
  export type CheckStatus =
80
189
  | "success"
81
190
  | "assumption-violation"
@@ -91,30 +200,74 @@ export interface TraceStep {
91
200
  // TLC's name, parameters and location for the action that took this step.
92
201
  label: string | undefined;
93
202
  state: Record<string, Value>;
203
+ // What the spec prints, before TLC prints this step, as TLC evaluates it again to rebuild the
204
+ // trace. The first step has what TLC prints before the trace.
205
+ output?: OutputLine[];
94
206
  }
95
207
 
96
208
  export interface Violation {
97
209
  name: string;
210
+ // Every temporal property that a liveness counterexample violates, in the configuration's order.
211
+ properties?: string[];
98
212
  trace: TraceStep[];
213
+ // What the spec prints after TLC prints the states of the trace, as TLC finds the step back into
214
+ // the cycle of a lasso or rebuilds the trace once more.
215
+ traceOutput?: OutputLine[];
99
216
  loopStart: number | undefined;
100
217
  loopLabel?: string;
101
218
  message?: string;
102
219
  counts?: string;
103
220
  unwitnessed?: Postcondition;
221
+ // A POSTCONDITION that is false or fails after the counterexample, which TLC checks as it
222
+ // prints one.
223
+ postcondition?: Postcondition;
224
+ // What TLC warns about after a counterexample, with its code.
225
+ warning?: { code: number; text: string };
104
226
  }
105
227
 
106
228
  interface Postcondition {
107
229
  name: string;
230
+ // TLC's message code.
231
+ code: number;
108
232
  message: string;
109
233
  counts?: string;
110
234
  }
111
235
 
112
236
  // An evaluation that failed during the search, with the behavior up to the state TLC was working on.
113
237
  export interface EvaluationFailure {
238
+ // TLC's code for the message, and its text with and without -tool.
239
+ code: number;
114
240
  message: string;
241
+ toolMessage: string;
115
242
  trace: TraceStep[];
243
+ traceOutput?: OutputLine[];
116
244
  initialState: Record<string, Value> | undefined;
117
245
  exitCode: number;
246
+ // The expressions TLC was evaluating when the failure occurred, outermost first, when TLC finds
247
+ // them by replaying the failure.
248
+ callStack: Expression[] | undefined;
249
+ // Whether TLC prints the call stack before the error, as it does for a failed liveness check.
250
+ isCallStackFirst?: boolean;
251
+ // The FingerprintException the replay raises, which TLC reports in place of the call stack.
252
+ fingerprint?: FingerprintFailure;
253
+ // How TLC reports failing again as it prints the trace, since it can't fingerprint the state the
254
+ // failure occurred in.
255
+ traceFailure?: FailureMessage;
256
+ // A POSTCONDITION that is false or fails after the trace, which TLC checks as it prints one.
257
+ postcondition?: Postcondition;
258
+ // Whether TLC stops before it prints the statistics, as it does for an illegal initial state.
259
+ isWithoutStatistics?: boolean;
260
+ }
261
+
262
+ // Where TLC's replay of a failure fails.
263
+ interface ReplayFailure {
264
+ callStack: Expression[];
265
+ fingerprint: FingerprintFailure | undefined;
266
+ }
267
+
268
+ export interface InitialStates {
269
+ generated: number;
270
+ distinct: number;
118
271
  }
119
272
 
120
273
  export interface CheckResult {
@@ -125,14 +278,55 @@ export interface CheckResult {
125
278
  distinctStates: number;
126
279
  queuedStates: number;
127
280
  depth: number;
281
+ // How many initial states TLC generated and how many of them were distinct, once it computed
282
+ // them all without a violation or an error.
283
+ initialStates: InitialStates | undefined;
128
284
  // How many states that TLC counts as expanded found each number of new states, when TLC prints
129
285
  // the outdegree of the state graph.
130
286
  outDegrees: number[] | undefined;
131
287
  // The smallest distance between the fingerprints of two distinct states, when TLC estimates a
132
288
  // collision from the actual fingerprints.
133
289
  fingerprintDistance: bigint | undefined;
290
+ // A temporal property TLC finds violated as it adds a deadlocked state to the behavior graph,
291
+ // which it reports after the deadlock.
292
+ additionalViolation?: Violation;
293
+ // Where TLC's worker fails to add the state to the behavior graph after it reports a violation.
294
+ liveCallStack?: Expression[];
295
+ // How many states that TLC counts as expanded found each number of new states, when its workers
296
+ // stop on a violation without an error code, which TLC 1.7.4 reports as a successful search.
297
+ violationOutDegrees?: number[];
298
+ }
299
+
300
+ interface Behavior {
301
+ trace: TraceStep[];
302
+ traceOutput?: OutputLine[];
303
+ }
304
+
305
+ interface TraceOptions {
306
+ loopStart?: number;
307
+ known?: number;
134
308
  }
135
309
 
310
+ interface FailureOptions {
311
+ initialState?: Value[];
312
+ isInitial?: boolean;
313
+ outDegrees?: number[];
314
+ callStack?: Expression[];
315
+ fingerprint?: FingerprintFailure;
316
+ isNextState?: boolean;
317
+ isCallStackFirst?: boolean;
318
+ traceFailure?: FailureMessage;
319
+ // Whether the call stack is of adding the state to the behavior graph, which TLC prints instead
320
+ // of replaying the error.
321
+ isLiveCallStack?: boolean;
322
+ }
323
+
324
+ // TLC prints what the spec prints as it replays a failure after the trace.
325
+ const appendTraceOutput = <Traced extends Behavior>(behavior: Traced, lines: OutputLine[]) => ({
326
+ ...behavior,
327
+ traceOutput: [...(behavior.traceOutput ?? []), ...lines],
328
+ });
329
+
136
330
  interface NamedExpression {
137
331
  name: string;
138
332
  expression: Expression;
@@ -142,6 +336,8 @@ interface NamedExpression {
142
336
  interface StateCheck extends NamedExpression {
143
337
  variables: number[] | undefined;
144
338
  membership: Membership | undefined;
339
+ // The whole predicate that TLC evaluates for the check, of which the expression is a conjunct.
340
+ predicate: Expression;
145
341
  }
146
342
 
147
343
  // A conjunct `x \in S` whose S reads no variables.
@@ -210,14 +406,6 @@ const getConfigOperator = (kind: string, name: string, environment: Environment)
210
406
  return definition;
211
407
  };
212
408
 
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
409
  // TLC evaluates every constant definition before it reads the configuration. It keeps a literal
222
410
  // number or string, and a definition that fails to evaluate, as an operator.
223
411
  const getConstantValue = (name: string, definition: Definition, environment: Environment) => {
@@ -226,20 +414,77 @@ const getConstantValue = (name: string, definition: Definition, environment: Env
226
414
  try {
227
415
  return evaluate(createIdentifier(name), getContext(environment, undefined, undefined));
228
416
  } catch (error) {
229
- if (error instanceof TlaEvaluationError) return undefined;
417
+ // TLC swallows whatever the definition throws, a stack overflow included.
418
+ if (error instanceof TlaEvaluationError || isStackOverflow(error)) return undefined;
230
419
  throw error;
231
420
  }
232
421
  };
233
422
 
234
- const getConfigPredicate = (kind: string, name: string, environment: Environment) => {
423
+ // TLC takes for an operator only a definition it hasn't replaced with its value.
424
+ const getConfigDefinition = (kind: string, name: string, environment: Environment) => {
235
425
  const definition = getConfigOperator(kind, name, environment);
236
- const value = getConstantValue(name, definition, environment);
426
+ if (getConstantValue(name, definition, environment) !== undefined) {
427
+ throw new TlaConfigError(`The ${kind} ${name} cannot be a constant.`);
428
+ }
429
+ return definition;
430
+ };
431
+
432
+ // TLC also takes a constant that the configuration assigns a value, which must be TRUE.
433
+ const getConfigPredicate = (kind: string, name: string, environment: Environment) => {
434
+ const definition = environment.constants.has(name)
435
+ ? undefined
436
+ : getConfigOperator(kind, name, environment);
437
+ const value = definition
438
+ ? getConstantValue(name, definition, environment)
439
+ : environment.constants.get(name);
237
440
  if (value !== undefined && value !== true) {
238
441
  throw new TlaConfigError(`The ${kind} of ${name} is equal to ${formatValue(value)}`);
239
442
  }
240
443
  return value === undefined ? definition : undefined;
241
444
  };
242
445
 
446
+ // TLC reports how many initial states it has computed each time the count is a power of two.
447
+ export const reportInitialStatesProgress = (
448
+ count: number,
449
+ onProgress: ((progress: InitialStatesProgress) => void) | undefined,
450
+ ) => {
451
+ if (count > 1 && (count & (count - 1)) === 0) {
452
+ onProgress?.({ kind: "initial-states-progress", count });
453
+ }
454
+ };
455
+
456
+ // What TLC does once SANY is done: it computes the constant definitions, then warns about each
457
+ // invariant that is a true constant formula, which it doesn't check. TLC prints each distinct
458
+ // warning once.
459
+ export const reportStartup = (
460
+ specification: {
461
+ environment: Environment;
462
+ startupDefinitions: Definition[];
463
+ javaOverrides: JavaOverride[];
464
+ },
465
+ config: ModelConfig,
466
+ onProgress: CheckOptions["onProgress"],
467
+ ) => {
468
+ const environment = specification.environment;
469
+ const warned = new Set<string>();
470
+ environment.runtime.warn = (code, text) => {
471
+ if (warned.has(text)) return;
472
+ warned.add(text);
473
+ onProgress?.({ kind: "warning", code, text });
474
+ };
475
+ onProgress?.({ kind: "parsed" });
476
+ // TLC loads the classes of the modules before it computes the constant definitions.
477
+ specification.javaOverrides.forEach((override) =>
478
+ onProgress?.({ kind: "java-override", ...override }),
479
+ );
480
+ evaluateStartupDefinitions(specification.startupDefinitions, environment);
481
+ config.invariants.forEach((name) => {
482
+ if (!getConfigPredicate("invariant", name, environment)) {
483
+ onProgress?.({ kind: "constant-level-invariant", name });
484
+ }
485
+ });
486
+ };
487
+
243
488
  const getInvariants = (names: string[], environment: Environment) => {
244
489
  const analyzer = createLevelAnalyzer({
245
490
  constants: new Set(environment.constants.keys()),
@@ -255,8 +500,11 @@ const getInvariants = (names: string[], environment: Environment) => {
255
500
  levels.params.size === 0
256
501
  ? ""
257
502
  : "\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}`,
503
+ throw setExitCode(
504
+ new TlaConfigError(
505
+ `The invariant ${name} is not a state predicate (one with no primes or temporal operators).${note}`,
506
+ ),
507
+ EXIT_STATUS.safetyEvaluationFailure,
260
508
  );
261
509
  }
262
510
  return [{ name, expression: createIdentifier(name), scope: undefined }];
@@ -309,14 +557,8 @@ const getSpecification = (config: ModelConfig, environment: Environment): Specif
309
557
  if (config.specification === undefined) {
310
558
  const getOperator = (name: string | undefined, description: string) => {
311
559
  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;
560
+ getConfigDefinition(description, name, environment);
561
+ return createIdentifier(name);
320
562
  };
321
563
  return {
322
564
  init: getOperator(config.init, "initial predicate"),
@@ -325,6 +567,11 @@ const getSpecification = (config: ModelConfig, environment: Environment): Specif
325
567
  temporals: [],
326
568
  };
327
569
  }
570
+ if (config.init !== undefined || config.next !== undefined) {
571
+ throw new TlaConfigError(
572
+ "The configuration file cannot specify both INIT/NEXT and SPECIFICATION fields.",
573
+ );
574
+ }
328
575
  const initConjuncts: ScopedExpression[] = [];
329
576
  const nextActions: ScopedExpression[] = [];
330
577
  const temporals: ScopedExpression[] = [];
@@ -354,8 +601,12 @@ const getSpecification = (config: ModelConfig, environment: Environment): Specif
354
601
  conjunct.kind === "Always" &&
355
602
  getLevel(conjunct.expression, item.scope, environment) < ACTION_LEVEL
356
603
  ) {
357
- throw new TlaConfigError(
358
- `TLC cannot handle []P in the specification ${config.specification} when P is a state predicate`,
604
+ // TLC accepts the spec and fails when it builds the tableau of the temporal formulas.
605
+ throw setExitCode(
606
+ new TlaEvaluationError(
607
+ `TLC cannot handle the temporal formula ${describeRange(conjunct.expression)}`,
608
+ ),
609
+ EXIT_STATUS.error,
359
610
  );
360
611
  }
361
612
  const level = getLevel(conjunct, item.scope, environment);
@@ -390,6 +641,7 @@ const getSpecification = (config: ModelConfig, environment: Environment): Specif
390
641
  state: undefined,
391
642
  next: undefined,
392
643
  cache: undefined,
644
+ isStreamed: false,
393
645
  },
394
646
  parent,
395
647
  },
@@ -415,7 +667,11 @@ const getSpecification = (config: ModelConfig, environment: Environment): Specif
415
667
  };
416
668
  };
417
669
 
418
- const getProperties = (config: ModelConfig, environment: Environment): Properties => {
670
+ const getProperties = (
671
+ config: ModelConfig,
672
+ environment: Environment,
673
+ onProgress: CheckOptions["onProgress"],
674
+ ): Properties => {
419
675
  const properties: Properties = {
420
676
  initialPredicates: [],
421
677
  invariants: [],
@@ -425,12 +681,21 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
425
681
  config.properties.forEach((name) => {
426
682
  const definition = getConfigPredicate("property", name, environment);
427
683
  if (!definition) return;
428
- expandTemporal(definition.body, undefined, environment, true).forEach((item) => {
684
+ // TLC checks a property that is a state formula only on the initial states, so it warns about
685
+ // one as it processes the property, before the constraints.
686
+ if (getLevel(definition.body, undefined, environment) === 1) {
687
+ onProgress?.({ kind: "state-level-property", name });
688
+ }
689
+ // TLC 1.7.4 expands a property as it does a specification, so it doesn't unroll one that
690
+ // quantifies over a constant set.
691
+ const isProperty = environment.runtime.version !== "1.7.4";
692
+ expandTemporal(definition.body, undefined, environment, isProperty).forEach((item) => {
429
693
  const conjunct = item.expression;
430
694
  if (isConstantTrue(item, environment, "property")) return;
695
+ const partName = item.name ?? name;
431
696
  if (conjunct.kind === "Always" && conjunct.expression.kind === "BoxAction") {
432
697
  properties.actionProperties.push({
433
- name,
698
+ name: partName,
434
699
  box: conjunct.expression,
435
700
  action: conjunct.expression.action,
436
701
  subscript: conjunct.expression.subscript,
@@ -442,12 +707,28 @@ const getProperties = (config: ModelConfig, environment: Environment): Propertie
442
707
  conjunct.kind === "Always" &&
443
708
  getLevel(conjunct.expression, item.scope, environment) <= 1
444
709
  ) {
445
- properties.invariants.push({ name, expression: conjunct.expression, scope: item.scope });
710
+ // TLC names the invariant by the operator the property asserts always holds, when it
711
+ // applies the operator to no arguments. The name of an operator another module defines
712
+ // resolves to its key, so the name comes from its definition.
713
+ const body = conjunct.expression;
714
+ const operator =
715
+ body.kind === "Identifier" && !isLocallyResolved(body)
716
+ ? getDefinition(body.name, environment)
717
+ : undefined;
718
+ properties.invariants.push({
719
+ name: operator?.name ?? (body.kind === "Identifier" ? body.name : partName),
720
+ expression: body,
721
+ scope: item.scope,
722
+ });
446
723
  return;
447
724
  }
448
725
  const level = getLevel(conjunct, item.scope, environment);
449
726
  if (level < ACTION_LEVEL) {
450
- properties.initialPredicates.push({ name, expression: conjunct, scope: item.scope });
727
+ properties.initialPredicates.push({
728
+ name: partName,
729
+ expression: conjunct,
730
+ scope: item.scope,
731
+ });
451
732
  return;
452
733
  }
453
734
  if (level === ACTION_LEVEL) {
@@ -504,16 +785,30 @@ const getMembership = (
504
785
  : undefined;
505
786
  };
506
787
 
788
+ // TLC evaluates the body of an invariant that the configuration names.
789
+ const getPredicate = (expression: Expression, environment: Environment) => {
790
+ if (expression.kind !== "Identifier" || environment.constants.has(expression.name)) {
791
+ return expression;
792
+ }
793
+ const definition = getDefinition(expression.name, environment);
794
+ return definition?.kind === "Operator" && definition.params.length === 0
795
+ ? definition.body
796
+ : expression;
797
+ };
798
+
507
799
  const getStateChecks = (named: NamedExpression[], environment: Environment): StateCheck[] =>
508
800
  named.flatMap((item) =>
509
801
  getConjuncts(item.expression, environment).map((expression) => {
510
- const variables = getReadVariables(expression, environment);
802
+ // A LET or an argument in the scope can read variables the expression doesn't name.
803
+ const variables =
804
+ item.scope === undefined ? getReadVariables(expression, environment) : undefined;
511
805
  return {
512
806
  name: item.name,
513
807
  expression,
514
808
  scope: item.scope,
515
809
  variables,
516
810
  membership: getMembership(expression, variables, environment),
811
+ predicate: getPredicate(item.expression, environment),
517
812
  };
518
813
  }),
519
814
  );
@@ -562,7 +857,25 @@ interface Search {
562
857
  getStoredFingerprints: (states: Value[][], fingerprintStates: Value[][]) => BigInt64Array;
563
858
  getTlcOrder: () => number[];
564
859
  isSymmetric: boolean;
860
+ // TLC drops a constraint that is a true constant formula.
861
+ isConstrained: boolean;
565
862
  findViolatedInvariant: (state: Value[], parent?: Value[]) => StateCheck | undefined;
863
+ // The checks of a state that TLC evaluates when it replays the computation of the initial states
864
+ // or of the successors of a state, with an environment that records the call stack. The first
865
+ // returns the check that stops the replay, and the second false where TLC stops it.
866
+ // TLC fingerprints a replayed state that satisfies the constraints before it checks the rest.
867
+ checkReplayedInitialState: (
868
+ state: Value[],
869
+ tracing: Environment,
870
+ addFingerprint: () => void,
871
+ ) => Pick<InitialStateViolation, "status" | "name"> | undefined;
872
+ // Adding the fingerprint of a successor tells whether TLC had not seen it yet.
873
+ checkReplayedSuccessor: (
874
+ state: Value[],
875
+ next: Value[],
876
+ tracing: Environment,
877
+ addFingerprint: () => boolean,
878
+ ) => boolean;
566
879
  satisfiesConstraints: (state: Value[], parent?: Value[]) => boolean;
567
880
  findFailedInitialPredicate: (state: Value[]) => NamedExpression | undefined;
568
881
  findViolatedActionProperty: (state: Value[], next: Value[]) => ActionProperty | undefined;
@@ -570,7 +883,8 @@ interface Search {
570
883
  trackStatePossible: (state: Value[]) => void;
571
884
  trackActionPossible: (state: Value[], next: Value[]) => void;
572
885
  findUnwitnessedPossible: () => Postcondition | undefined;
573
- findPostconditionViolation: () => Postcondition | undefined;
886
+ // After a counterexample, TLC skips the postconditions when one of them is constant.
887
+ findPostconditionViolation: (isAfterViolation?: boolean) => Postcondition | undefined;
574
888
  }
575
889
 
576
890
  const getContext = (
@@ -596,21 +910,23 @@ const holdsLikeTlc = (
596
910
  return value;
597
911
  };
598
912
 
599
- // SANY prints a number by its digits and any other expression by its location.
600
913
  const getExpectedBoolean = (expression: Expression, environment: Environment) => {
601
914
  const definition =
602
915
  expression.kind === "Identifier" ? getDefinition(expression.name, environment) : undefined;
603
916
  const body = definition?.kind === "Operator" ? definition.body : expression;
604
917
  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);
918
+ const location = range && body.kind !== "Number" ? formatRange(range) : describeNode(body);
611
919
  return `TLC expected a boolean value, but did not find one. ${location}`;
612
920
  };
613
921
 
922
+ // TLC evaluates the whole predicate of a check, which fails at a conjunct that isn't a boolean as
923
+ // the conjunction does.
924
+ const holdsAsConjunct = (check: StateCheck, context: Context) =>
925
+ holdsLikeTlc(check.expression, context, (expression, environment) => {
926
+ holdsLikeTlc(check.predicate, context);
927
+ return getExpectedBoolean(expression, environment);
928
+ });
929
+
614
930
  const ignorePossible = () => {};
615
931
 
616
932
  const trackPossible = (items: NamedExpression[], runtime: CheckerRuntime, context: Context) =>
@@ -652,11 +968,16 @@ export const createSearch = (
652
968
  config: ModelConfig,
653
969
  environment: Environment,
654
970
  getVariableOrder: () => string[],
971
+ onProgress?: CheckOptions["onProgress"],
655
972
  ): Search | undefined => {
656
973
  const configInvariants = getInvariants(config.invariants, environment);
657
974
  const spec = getSpecification(config, environment);
658
- const properties = getProperties(config, environment);
975
+ const properties = getProperties(config, environment, onProgress);
659
976
  const invariants = getStateChecks([...configInvariants, ...properties.invariants], environment);
977
+ // The invariants TLC evaluates, each of which may have several conjuncts among the checks.
978
+ const invariantPredicates = [
979
+ ...new Map(invariants.map((invariant) => [invariant.predicate, invariant])).values(),
980
+ ];
660
981
  const isCheckingBehaviors =
661
982
  invariants.length > 0 ||
662
983
  properties.actionProperties.length > 0 ||
@@ -667,7 +988,11 @@ export const createSearch = (
667
988
  properties.initialPredicates.length > 0 ||
668
989
  environment.variables.length > 0)
669
990
  ) {
670
- throw new TlaConfigError("The configuration file did not specify the initial state predicate.");
991
+ throw new TlaConfigError(
992
+ environment.runtime.version === "1.7.4"
993
+ ? MISSING_INIT_174
994
+ : "The configuration file did not specify the initial state predicate.",
995
+ );
671
996
  }
672
997
  if (spec.next === undefined && isCheckingBehaviors) {
673
998
  throw new TlaConfigError("The configuration file did not specify the next state predicate.");
@@ -686,7 +1011,9 @@ export const createSearch = (
686
1011
  const possible = getPossiblePredicates(config.possible, environment);
687
1012
  if (environment.variables.length === 0) return undefined;
688
1013
  const symmetryGroup =
689
- config.symmetry === undefined ? [] : getSymmetryGroup(config.symmetry, environment);
1014
+ config.symmetry === undefined
1015
+ ? undefined
1016
+ : getSymmetryGroup(config.symmetry, environment, config.substitutions);
690
1017
  if (config.view !== undefined) getConfigOperator("view function", config.view, environment);
691
1018
  const view =
692
1019
  config.view === undefined
@@ -718,14 +1045,12 @@ export const createSearch = (
718
1045
  .sort((left, right) => getTlcPosition(left) - getTlcPosition(right));
719
1046
  return tlcOrder.indices;
720
1047
  };
721
- // A representative in TLC's variable order is the one whose fingerprint TLC reports.
722
- const order = symmetryGroup.length > 0 ? getTlcOrder() : undefined;
723
1048
  const getViewValue = (expression: Expression, state: Value[]) =>
724
1049
  evaluate(expression, getContext(environment, state, undefined));
725
1050
  const getTlcStateFingerprint = (state: Value[]) => {
726
1051
  const indices = getTlcOrder();
727
1052
  const representative =
728
- symmetryGroup.length === 0 ? state : getRepresentative(state, symmetryGroup, indices);
1053
+ symmetryGroup === undefined ? state : getRepresentative(state, symmetryGroup, indices);
729
1054
  return getTlcFingerprint(
730
1055
  view === undefined
731
1056
  ? indices.map((index) => representative[index])
@@ -741,6 +1066,7 @@ export const createSearch = (
741
1066
  const location = range ? ` at ${formatRange(range)}` : "";
742
1067
  return {
743
1068
  name: unwitnessed.name,
1069
+ code: MESSAGE_CODE.possibleUnwitnessed,
744
1070
  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
1071
  counts: prettyPrint(formatValue(getPossibleCounts(runtime), true)),
746
1072
  };
@@ -748,22 +1074,28 @@ export const createSearch = (
748
1074
  return {
749
1075
  properties,
750
1076
  spec,
751
- isSymmetric: symmetryGroup.length > 0,
1077
+ isSymmetric: symmetryGroup !== undefined,
1078
+ isConstrained: constraints.length > 0 || actionConstraints.length > 0,
752
1079
  getTlcOrder,
753
1080
  getStoredFingerprints: (states, fingerprintStates) => {
754
1081
  if (view !== undefined || isFingerprintedLikeTlc) {
755
1082
  return BigInt64Array.from(states, getTlcStateFingerprint);
756
1083
  }
757
- const indices = getTlcOrder();
758
- const getFingerprint = createTlcFingerprinter();
759
- return BigInt64Array.from(fingerprintStates, (state) =>
760
- getFingerprint(indices.map((index) => state[index])),
1084
+ const fingerprints = new BigInt64Array(fingerprintStates.length);
1085
+ const fingerprint = createTlcFingerprinter(
1086
+ getTlcOrder(),
1087
+ new Int32Array(fingerprints.buffer),
761
1088
  );
1089
+ fingerprintStates.forEach(fingerprint);
1090
+ return fingerprints;
762
1091
  },
763
1092
  getFingerprintState: (state) => {
764
1093
  if (isFingerprintedLikeTlc) return [String(getTlcStateFingerprint(state))];
1094
+ // A representative in TLC's variable order is the one whose fingerprint TLC reports.
765
1095
  const representative =
766
- symmetryGroup.length === 0 ? state : getRepresentative(state, symmetryGroup, order);
1096
+ symmetryGroup === undefined
1097
+ ? state
1098
+ : getRepresentative(state, symmetryGroup, getTlcOrder());
767
1099
  return view === undefined ? representative : [getViewValue(view.expression, representative)];
768
1100
  },
769
1101
  findViolatedInvariant: (state, parent) =>
@@ -779,21 +1111,63 @@ export const createSearch = (
779
1111
  parent[membership.variable],
780
1112
  evaluate(membership.set, context),
781
1113
  )
782
- : !holdsLikeTlc(invariant.expression, context);
1114
+ : !holdsAsConjunct(invariant, context);
783
1115
  } catch (error) {
784
1116
  // TLC reports a failure only on a state after the initial states as an invariant failure.
785
1117
  if (!parent) throw error;
786
1118
  throw withHeadline(
787
1119
  setExitCode(error, EXIT_STATUS.safetyEvaluationFailure),
1120
+ MESSAGE_CODE.invariantEvaluationFailed,
788
1121
  `Evaluating invariant ${invariant.name} failed.`,
789
1122
  );
790
1123
  }
791
1124
  }),
1125
+ checkReplayedInitialState: (state, tracing, addFingerprint) => {
1126
+ const holdsIn = (expression: Expression, scope: Scope | undefined) =>
1127
+ holdsLikeTlc(expression, getContext(tracing, state, undefined, scope));
1128
+ if (constraints.every((constraint) => holdsIn(constraint.predicate, constraint.scope))) {
1129
+ addFingerprint();
1130
+ }
1131
+ const invariant = invariantPredicates.find((check) => !holdsIn(check.predicate, check.scope));
1132
+ if (invariant) return { status: "invariant-violation", name: invariant.name };
1133
+ const predicate = properties.initialPredicates.find(
1134
+ (check) => !holdsIn(check.expression, check.scope),
1135
+ );
1136
+ return predicate && { status: "liveness-violation", name: predicate.name };
1137
+ },
1138
+ checkReplayedSuccessor: (state, next, tracing, addFingerprint) => {
1139
+ // TLC evaluates the action constraints only on a state that satisfies the constraints.
1140
+ const isInModel =
1141
+ constraints.every((constraint) =>
1142
+ holdsLikeTlc(
1143
+ constraint.predicate,
1144
+ getContext(tracing, next, undefined, constraint.scope),
1145
+ ),
1146
+ ) &&
1147
+ actionConstraints.every((constraint) =>
1148
+ holdsLikeTlc(constraint.expression, getContext(tracing, state, next, constraint.scope)),
1149
+ );
1150
+ // ModelChecker.doNext checks the invariants of a successor it has not seen, which includes
1151
+ // one outside the model.
1152
+ const isUnseen = isInModel ? addFingerprint() : true;
1153
+ return (
1154
+ (!isUnseen ||
1155
+ invariantPredicates.every((invariant) =>
1156
+ holdsLikeTlc(
1157
+ invariant.predicate,
1158
+ getContext(tracing, next, undefined, invariant.scope),
1159
+ ),
1160
+ )) &&
1161
+ actionProperties.every((property) =>
1162
+ holdsLikeTlc(property.box, getContext(tracing, state, next, property.scope)),
1163
+ )
1164
+ );
1165
+ },
792
1166
  satisfiesConstraints: (state, parent) =>
793
1167
  constraints.every(
794
1168
  (constraint) =>
795
1169
  isUnchangedFor(constraint, state, parent) ||
796
- holdsLikeTlc(constraint.expression, getContext(environment, state, undefined)),
1170
+ holdsAsConjunct(constraint, getContext(environment, state, undefined)),
797
1171
  ),
798
1172
  findFailedInitialPredicate: (state) =>
799
1173
  properties.initialPredicates.find(
@@ -820,7 +1194,11 @@ export const createSearch = (
820
1194
  )
821
1195
  );
822
1196
  } catch (error) {
823
- throw withHeadline(error, `Evaluating action property ${property.name} failed.`);
1197
+ throw withHeadline(
1198
+ withNextStateExitCode(error),
1199
+ MESSAGE_CODE.actionPropertyEvaluationFailed,
1200
+ `Evaluating action property ${property.name} failed.`,
1201
+ );
824
1202
  }
825
1203
  }),
826
1204
  satisfiesActionConstraints: (state, next) =>
@@ -828,8 +1206,7 @@ export const createSearch = (
828
1206
  holdsLikeTlc(
829
1207
  constraint.expression,
830
1208
  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)}`,
1209
+ (expression) => `${UNEXPECTED_EXCEPTION}${getExpectedBoolean(expression, environment)}`,
833
1210
  ),
834
1211
  ),
835
1212
  trackStatePossible:
@@ -843,45 +1220,224 @@ export const createSearch = (
843
1220
  : (state, next) =>
844
1221
  trackPossible(actionPossible, runtime, getContext(environment, state, next)),
845
1222
  findUnwitnessedPossible,
846
- findPostconditionViolation: () => {
1223
+ findPostconditionViolation: (isAfterViolation = false) => {
1224
+ // TLC replaces a definition it computes when it starts by its value, and then rejects it as
1225
+ // a postcondition before it checks any of them.
1226
+ const constant = config.postconditions.find((name) => {
1227
+ const definition = getDefinition(name, environment);
1228
+ return definition !== undefined && environment.definitionValues.has(definition);
1229
+ });
1230
+ if (constant !== undefined) {
1231
+ if (isAfterViolation) return undefined;
1232
+ throw setExitCode(
1233
+ new TlaEvaluationError(
1234
+ `${UNEXPECTED_EXCEPTION}The post condition ${constant} cannot be a constant.`,
1235
+ ),
1236
+ EXIT_STATUS.error,
1237
+ );
1238
+ }
847
1239
  const unwitnessed = findUnwitnessedPossible();
848
1240
  if (unwitnessed) return unwitnessed;
849
1241
  for (const name of config.postconditions) {
850
1242
  const failure = getConstantFailure(createIdentifier(name), environment, "a postcondition");
851
- if (failure) {
852
- return { name, message: failure.message ?? `Postcondition ${name} is false.` };
853
- }
1243
+ if (!failure) continue;
1244
+ const range = getBodyRange(name, environment);
1245
+ const location = range ? ` at ${formatRange(range)}` : "";
1246
+ return failure.message === undefined
1247
+ ? {
1248
+ name,
1249
+ code: MESSAGE_CODE.postconditionFalse,
1250
+ message: `Postcondition ${name}${location} is false.`,
1251
+ }
1252
+ : {
1253
+ name,
1254
+ code: MESSAGE_CODE.postconditionFailed,
1255
+ message: `Evaluating postcondition ${name}${location} failed.\n${failure.message}`,
1256
+ };
854
1257
  }
855
1258
  return undefined;
856
1259
  },
857
1260
  };
858
1261
  };
859
1262
 
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;
1263
+ // TLC exits with the code of a standard module's failure only when the failure escapes the
1264
+ // computation of next states. In every other phase, the phase decides the code.
1265
+ const withNextStateExitCode = (error: unknown) =>
1266
+ error instanceof TlaModuleError ? setExitCode(error, error.exitCode) : error;
1267
+
1268
+ // Stops a replay where TLC stops it without a failure, as at a violated invariant.
1269
+ const STOP_REPLAY = new Error("The replay stopped");
1270
+
1271
+ // The codes of the errors in the configuration and the spec that TLC's EC.ExitStatus maps to a
1272
+ // configuration error.
1273
+ const CONFIG_ERROR_CODES = new Set([
1274
+ ...Array.from({ length: 24 }, (_, index) => 2222 + index),
1275
+ 2272,
1276
+ 2273,
1277
+ 2274,
1278
+ 2280,
1279
+ 2281,
1280
+ ]);
1281
+
1282
+ // When TLC's replay of the initial states doesn't fail again, it exits with the code of the
1283
+ // TLCRuntimeException it reported.
1284
+ const getInitialExitCode = (error: TlaEvaluationError) => {
1285
+ const coded = getCodedMessage(error.message);
1286
+ return coded && !coded.isEvalException && CONFIG_ERROR_CODES.has(coded.code)
1287
+ ? EXIT_STATUS.configParseError
1288
+ : getErrorExitCode(error);
1289
+ };
1290
+
1291
+ // When TLC's replay of an error fails again, an EvalException from a standard module's Java code
1292
+ // decides the exit status, and any other failure exits as a nested expression failure. An error
1293
+ // that heads or wraps another exits as the other.
1294
+ const getReplayExitCode = (error: TlaEvaluationError): number => {
1295
+ const inner = error.cause;
1296
+ if (inner instanceof TlaEvaluationError) return getReplayExitCode(inner);
1297
+ return error instanceof TlaModuleError ? error.exitCode : EXIT_STATUS.specEvaluationFailure;
1298
+ };
1299
+
1300
+ // An error that TLC reports with a message of its own, by that message's code and first line, and
1301
+ // the error whose message follows.
1302
+ interface HeadedError {
1303
+ code: number;
1304
+ headline: string;
1305
+ inner: TlaEvaluationError;
1306
+ }
1307
+
1308
+ const headedErrors = new WeakMap<Error, HeadedError>();
1309
+
1310
+ const withHeadline = (error: unknown, code: number, headline: string) => {
1311
+ if (!(error instanceof TlaEvaluationError)) return error;
1312
+ const headed = setExitCode(
1313
+ new TlaEvaluationError(`${headline}\n${error.message}`, error),
1314
+ getErrorExitCode(error),
1315
+ );
1316
+ headedErrors.set(headed, { code, headline, inner: error });
1317
+ return headed;
1318
+ };
1319
+
1320
+ const UNEXPECTED_HEADLINE = UNEXPECTED_EXCEPTION.slice(0, UNEXPECTED_EXCEPTION.indexOf("\n"));
1321
+
1322
+ // TLC 1.7.4's Worker wraps an error in adding a successor in a RuntimeException, whose message
1323
+ // names the class of the error.
1324
+ const WRAPPED_EVAL_EXCEPTION = `${UNEXPECTED_EXCEPTION}tlc2.tool.EvalException: `;
1325
+ const WRAPPED_RUNTIME_EXCEPTION = `${UNEXPECTED_EXCEPTION}util.Assert$TLCRuntimeException: `;
1326
+
1327
+ const UNEXPECTED_EVAL_EXCEPTION = getUnexpectedException("tlc2.tool.EvalException");
867
1328
 
1329
+ const getWrappedException = (error: TlaEvaluationError) =>
1330
+ isEvalException(error) ? WRAPPED_EVAL_EXCEPTION : WRAPPED_RUNTIME_EXCEPTION;
1331
+
1332
+ // TLC reports an EvalException, or a TLCRuntimeException without a message of its own, as an
1333
+ // exception it didn't expect.
1334
+ const withUnexpectedException = <Result>(compute: () => Result) => {
1335
+ try {
1336
+ return compute();
1337
+ } catch (error) {
1338
+ if (!(error instanceof TlaEvaluationError)) throw error;
1339
+ if (isEvalException(error)) {
1340
+ throw new TlaEvaluationError(`${UNEXPECTED_EVAL_EXCEPTION}${error.message}`);
1341
+ }
1342
+ if (getCodedMessage(error.message)) throw error;
1343
+ throw new TlaEvaluationError(`${UNEXPECTED_EXCEPTION}${error.message}`);
1344
+ }
1345
+ };
1346
+
1347
+ // The starts of TLC's messages for the exceptions it didn't expect.
1348
+ const UNEXPECTED_EXCEPTIONS = [
1349
+ WRAPPED_EVAL_EXCEPTION,
1350
+ WRAPPED_RUNTIME_EXCEPTION,
1351
+ UNEXPECTED_EXCEPTION,
1352
+ UNEXPECTED_EVAL_EXCEPTION,
1353
+ ];
1354
+
1355
+ // The text of an error's message, with the message of a coded error inside it marked in -tool
1356
+ // output as TLC marks it.
1357
+ const formatErrorMessage = (error: TlaEvaluationError, isTool: boolean): string => {
1358
+ const headed = headedErrors.get(error);
1359
+ if (headed) return `${headed.headline}\n${formatErrorMessage(headed.inner, isTool)}`;
1360
+ const message = error.message;
1361
+ const prefix = UNEXPECTED_EXCEPTIONS.find((start) => message.startsWith(start)) ?? "";
1362
+ return `${prefix}${formatNestedMessage(message.slice(prefix.length), isTool)}`;
1363
+ };
1364
+
1365
+ // How TLC reports an error: with the code of its own message for an error that it reports with a
1366
+ // headline; and, when the error escapes the computation of next states, with the code of an
1367
+ // EvalException, or as an unexpected exception for any other error.
1368
+ interface FailureMessage {
1369
+ code: number;
1370
+ message: string;
1371
+ toolMessage: string;
1372
+ }
1373
+
1374
+ const getFailureMessage = (error: TlaEvaluationError, isNextState: boolean): FailureMessage => {
1375
+ const headed = headedErrors.get(error);
1376
+ const message = error.message;
1377
+ if (headed) {
1378
+ return {
1379
+ code: headed.code,
1380
+ message,
1381
+ toolMessage: formatErrorMessage(error, true),
1382
+ };
1383
+ }
1384
+ if (isNextState && isEvalException(error)) {
1385
+ return {
1386
+ code: getCodedMessage(message)?.code ?? MESSAGE_CODE.general,
1387
+ message,
1388
+ toolMessage: message,
1389
+ };
1390
+ }
1391
+ const isUnexpected = isNextState && !message.startsWith(UNEXPECTED_HEADLINE);
1392
+ const prefix = isUnexpected ? UNEXPECTED_EXCEPTION : "";
1393
+ return {
1394
+ code: MESSAGE_CODE.general,
1395
+ message: `${prefix}${message}`,
1396
+ toolMessage: `${prefix}${formatErrorMessage(error, true)}`,
1397
+ };
1398
+ };
1399
+
1400
+ // TLC finishes the -dump file whether or not the search finds a violation.
868
1401
  export const checkSequentially = (options: CheckOptions): CheckResult => {
869
- setNextStatePhase(false);
870
- const config = typeof options.config === "string" ? parseConfig(options.config) : options.config;
1402
+ const stateWriter =
1403
+ options.dump && createStateWriter(options.dump, options.writeFile, options.version);
1404
+ try {
1405
+ return searchStates(options, stateWriter);
1406
+ } catch (error) {
1407
+ // TLC reports a stack overflow outside the search on its own, and exits with 255.
1408
+ throw isStackOverflow(error) ? createStackOverflowError() : error;
1409
+ } finally {
1410
+ stateWriter?.close();
1411
+ }
1412
+ };
1413
+
1414
+ const createStackOverflowError = () => setExitCode(new TlaStackOverflowError(), EXIT_STATUS.error);
1415
+
1416
+ const searchStates = (options: CheckOptions, stateWriter: StateWriter | undefined): CheckResult => {
1417
+ const config =
1418
+ typeof options.config === "string"
1419
+ ? parseConfig(options.config, options.version)
1420
+ : options.config;
871
1421
  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 };
1422
+ // TLC prints again while it rebuilds a trace, between the states it prints, so rebuilding a trace
1423
+ // keeps what it prints for the trace.
1424
+ const output = { lines: undefined as OutputLine[] | undefined };
875
1425
  const print = (text: string) => {
876
- if (!output.isMuted) onPrint(text);
1426
+ if (output.lines) output.lines.push(text);
1427
+ else onPrint(text);
877
1428
  };
878
- const withoutOutput = <Result>(rebuild: () => Result) => {
879
- output.isMuted = true;
880
- const result = rebuild();
881
- output.isMuted = false;
882
- return result;
1429
+ const getOutput = <Result>(rebuild: () => Result) => {
1430
+ const outer = output.lines;
1431
+ const lines: OutputLine[] = [];
1432
+ output.lines = lines;
1433
+ try {
1434
+ return { result: rebuild(), lines };
1435
+ } finally {
1436
+ output.lines = outer;
1437
+ }
883
1438
  };
884
1439
  setStringOrder(getTlcStringOrder(options.source, config, options.loadModule));
1440
+ setValueVersion(options.version);
885
1441
  const specification = createEnvironment(config, {
886
1442
  source: options.source,
887
1443
  loadModule: options.loadModule,
@@ -889,9 +1445,16 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
889
1445
  print,
890
1446
  files: { readFile: options.readFile, writeFile: options.writeFile },
891
1447
  seed: options.seed,
1448
+ isTool: options.isTool,
1449
+ isTraceRecorded: options.isTraceRecorded,
1450
+ isSanyReported: options.isSanyReported,
1451
+ isWarningEnabled: options.isWarningEnabled,
1452
+ version: options.version,
892
1453
  });
1454
+ reportStartup(specification, config, options.onProgress);
893
1455
  const environment = specification.environment;
894
1456
  const runtime = environment.runtime;
1457
+ const is174 = runtime.version === "1.7.4";
895
1458
  runtime.pause = options.onPause ?? (() => {});
896
1459
  runtime.getSpecification = () =>
897
1460
  getSpecificationValue(
@@ -900,7 +1463,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
900
1463
  specification.variableLocations,
901
1464
  specification.instanceActions,
902
1465
  );
903
- const statistics = { depth: 0 };
1466
+ const statistics = { depth: 0, initialStates: undefined as InitialStates | undefined };
904
1467
  const createResult = (
905
1468
  status: CheckStatus,
906
1469
  violation?: Omit<Violation, "loopStart"> & { loopStart?: number },
@@ -913,15 +1476,26 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
913
1476
  distinctStates: runtime.distinctStates,
914
1477
  queuedStates: runtime.queueSize,
915
1478
  depth: runtime.generatedStates === 0 ? 0 : Math.max(statistics.depth, 1),
1479
+ initialStates: statistics.initialStates,
916
1480
  outDegrees: undefined,
917
1481
  fingerprintDistance: undefined,
918
1482
  });
919
1483
  const outDegrees = Array.from({ length: OUT_DEGREE_BUCKETS }, () => 0);
920
1484
  const expansion = { newStates: 0 };
921
1485
  const getOutDegreeBucket = () => Math.min(expansion.newStates, OUT_DEGREE_BUCKETS - 1);
922
- // TLC counts the state it was expanding when an evaluation failed.
1486
+ // TLC counts the state it was expanding when an evaluation failed, except TLC 1.7.4, whose
1487
+ // worker stops before it counts the state.
923
1488
  const getPartialOutDegrees = () =>
924
1489
  outDegrees.map((count, degree) => (degree === getOutDegreeBucket() ? count + 1 : count));
1490
+ const getFailureOutDegrees = () => (is174 ? [...outDegrees] : getPartialOutDegrees());
1491
+ // TLC 1.7.4 doesn't name the properties a counterexample violates, so it evaluates none of them.
1492
+ const getViolatedProperties = (checker: LivenessChecker, path: Value[][], cycleStart: number) =>
1493
+ is174 ? [] : checker.getViolatedProperties(path, cycleStart);
1494
+ // A violation in a successor ends the expansion of a state before TLC counts it.
1495
+ const withOutDegrees = (result: CheckResult, degrees = [...outDegrees]): CheckResult => ({
1496
+ ...result,
1497
+ violationOutDegrees: degrees,
1498
+ });
925
1499
  const createSuccess = (): CheckResult => ({
926
1500
  ...createResult("success"),
927
1501
  outDegrees: [...outDegrees],
@@ -935,36 +1509,252 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
935
1509
  ),
936
1510
  });
937
1511
 
938
- const search = createSearch(config, environment, () =>
939
- getTlcVariableOrder(options.source, options.loadModule),
1512
+ const search = createSearch(
1513
+ config,
1514
+ environment,
1515
+ () => getTlcVariableOrder(options.source, options.loadModule),
1516
+ options.onProgress,
940
1517
  );
941
- const assumptionViolation = findAssumptionViolation(specification.assumptions, environment);
942
- if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
943
- if (!search) return createSuccess();
1518
+ const findViolatedAssumption = () =>
1519
+ findAssumptionViolation(specification.assumptions, environment);
1520
+ if (!search) {
1521
+ runtime.isStarted = true;
1522
+ const assumptionViolation = findViolatedAssumption();
1523
+ if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
1524
+ // TLC computes the initial states of a spec without variables, of which there are none.
1525
+ statistics.initialStates = { generated: 0, distinct: 0 };
1526
+ options.onProgress?.({ kind: "initial-states-started" });
1527
+ options.onProgress?.({
1528
+ kind: "initial-states-computed",
1529
+ initialStates: statistics.initialStates,
1530
+ });
1531
+ return createSuccess();
1532
+ }
944
1533
  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,
1534
+ // The state of each step of a trace without the alias, and the action TLC finds for the step,
1535
+ // which CounterExample records.
1536
+ const traceSteps = new WeakMap<
1537
+ TraceStep,
1538
+ { state: Record<string, Value>; action: SpecAction | undefined }
1539
+ >();
1540
+ const getStepState = (step: TraceStep) => traceSteps.get(step)?.state ?? step.state;
1541
+ const getStepAction = (step: TraceStep) => {
1542
+ const action = traceSteps.get(step)?.action;
1543
+ return action ? toActionValue(action) : createActionRecord(step.action);
1544
+ };
1545
+ // Worker#printTrace checks the postconditions on the CounterExample of each trace it prints, so
1546
+ // what they print follows the trace.
1547
+ const checkTracePostconditions = (
1548
+ trace: TraceStep[],
1549
+ loop: { start: number; action: Value } | undefined,
949
1550
  ) => {
950
1551
  if (hasPostconditions) {
951
- const start = violation.loopStart;
952
1552
  runtime.counterExample = createCounterExample(
953
- violation.trace,
954
- start === undefined || !getLoopAction ? undefined : { start, action: getLoopAction() },
1553
+ trace.map(getStepState),
1554
+ trace.slice(1).map(getStepAction),
1555
+ loop,
955
1556
  );
956
1557
  }
957
1558
  const unwitnessed = search.findUnwitnessedPossible();
958
- if (!unwitnessed) search.findPostconditionViolation();
959
- return createResult(status, unwitnessed ? { ...violation, unwitnessed } : violation);
1559
+ const checked = unwitnessed
1560
+ ? { result: undefined, lines: [] }
1561
+ : getOutput(() => search.findPostconditionViolation(true));
1562
+ return { unwitnessed, postcondition: checked.result, lines: checked.lines };
1563
+ };
1564
+ const reportViolation = (
1565
+ status: CheckStatus,
1566
+ violation: Omit<Violation, "loopStart"> & { loopStart?: number },
1567
+ getLoopAction?: () => Value,
1568
+ ) => {
1569
+ const start = violation.loopStart;
1570
+ const checked = checkTracePostconditions(
1571
+ violation.trace,
1572
+ start === undefined || !getLoopAction ? undefined : { start, action: getLoopAction() },
1573
+ );
1574
+ const traceOutput = [...(violation.traceOutput ?? []), ...checked.lines];
1575
+ return createResult(status, {
1576
+ ...violation,
1577
+ ...(traceOutput.length > 0 && { traceOutput }),
1578
+ ...(checked.unwitnessed && { unwitnessed: checked.unwitnessed }),
1579
+ ...(checked.postcondition && { postcondition: checked.postcondition }),
1580
+ });
960
1581
  };
961
1582
  const spec = search.spec;
962
1583
  const getFingerprintState = search.getFingerprintState;
963
1584
  const nextActions = { value: undefined as SpecAction[] | undefined };
1585
+ const getSpecNextActions = () =>
1586
+ (nextActions.value ??= getNextActions(config, environment, specification.instanceActions));
1587
+ // Where TLC's replay of a failed computation fails, or undefined when the replay completes.
1588
+ const getReplayFailure = (replay: (tracing: Environment) => void): ReplayFailure | undefined => {
1589
+ const tracing = createTracingEnvironment(environment);
1590
+ const callStack = tracing.callStack;
1591
+ try {
1592
+ replay(tracing);
1593
+ return undefined;
1594
+ } catch (error) {
1595
+ // A replay that overflows the stack again has an empty call stack.
1596
+ if (isStackOverflow(error)) return { callStack: [], fingerprint: undefined };
1597
+ if (!(error instanceof TlaEvaluationError) || !callStack) return undefined;
1598
+ return { callStack: callStack.expressions, fingerprint: callStack.fingerprint };
1599
+ }
1600
+ };
1601
+ // The sources of the values a fingerprint fails inside, outermost first: each value fails as it
1602
+ // fingerprints a value it holds.
1603
+ const findFailedSources = (value: Value, sources: CallStack["sources"]): Expression[] => {
1604
+ if (typeof value !== "object") return [];
1605
+ const source = sources.get(value);
1606
+ const failed = getHeldValues(value).find((held) => getFingerprintError(held) !== undefined);
1607
+ return [
1608
+ ...(source ? [source] : []),
1609
+ ...(failed === undefined ? [] : findFailedSources(failed, sources)),
1610
+ ];
1611
+ };
1612
+ // TLC's replay fingerprints the states it finds, and a value the replay built raises a
1613
+ // FingerprintException when it fails to.
1614
+ const fingerprintReplayed = (state: Value[], callStack: CallStack | undefined) => {
1615
+ for (const value of getFingerprintState(state)) {
1616
+ const error = getFingerprintError(value);
1617
+ if (!error) continue;
1618
+ const sources = callStack ? findFailedSources(value, callStack.sources) : [];
1619
+ // TLC fingerprints a state outside any evaluation, so its call stack is empty.
1620
+ if (callStack && sources.length > 0) {
1621
+ callStack.expressions.length = 0;
1622
+ callStack.isFrozen = true;
1623
+ callStack.fingerprint = { sources, reason: error.message };
1624
+ }
1625
+ throw error;
1626
+ }
1627
+ state.forEach(markFingerprinted);
1628
+ };
1629
+ // The replay adds the states it hasn't seen to TLC's set of states, which already holds the state
1630
+ // that failed after TLC added it.
1631
+ const createReplayedStates = () => {
1632
+ const replayed = unstoredState.fingerprint ? [unstoredState.fingerprint] : [];
1633
+ return (state: Value[], callStack: CallStack | undefined) => {
1634
+ fingerprintReplayed(state, callStack);
1635
+ const fingerprintState = getFingerprintState(state);
1636
+ const isSeen =
1637
+ findStateIndex(getStateHash(fingerprintState), fingerprintState) !== -1 ||
1638
+ replayed.some((seen) => isSameState(seen, fingerprintState));
1639
+ if (isSeen) return false;
1640
+ replayed.push(fingerprintState);
1641
+ runtime.distinctStates++;
1642
+ return true;
1643
+ };
1644
+ };
1645
+ // TLC's DoInitFunctor reports its progress again as it replays the initial states, and adds each
1646
+ // one it hasn't seen to the behavior graph. After a FingerprintException, it only counts the
1647
+ // states left, then throws the exception.
1648
+ const replayInit = () => {
1649
+ const replayed = { count: 0 };
1650
+ const deferred: TlaEvaluationError[] = [];
1651
+ const addReplayed = createReplayedStates();
1652
+ return getReplayFailure((tracing) => {
1653
+ replayInitialStates(
1654
+ getInitActions(config, environment, specification.instanceActions),
1655
+ tracing,
1656
+ (state) => {
1657
+ reportInitialStatesProgress(replayed.count, (progress) => output.lines?.push(progress));
1658
+ replayed.count++;
1659
+ runtime.generatedStates = replayed.count;
1660
+ if (deferred.length > 0) return;
1661
+ try {
1662
+ const addFingerprint = () => {
1663
+ if (!addReplayed(state, tracing.callStack)) return;
1664
+ runtime.queueSize++;
1665
+ liveness?.addInitialState(states.length, state, tracing);
1666
+ };
1667
+ const violation = search.checkReplayedInitialState(state, tracing, addFingerprint);
1668
+ if (violation) {
1669
+ const traced = toTrace([{ action: undefined, state }], []).trace[0].state;
1670
+ output.lines?.push({ kind: "initial-state-violation", ...violation, state: traced });
1671
+ throw STOP_REPLAY;
1672
+ }
1673
+ } catch (error) {
1674
+ if (!(error instanceof TlaEvaluationError) || !tracing.callStack?.fingerprint) {
1675
+ throw error;
1676
+ }
1677
+ deferred.push(error);
1678
+ }
1679
+ },
1680
+ );
1681
+ if (deferred.length > 0) throw deferred[0];
1682
+ });
1683
+ };
1684
+ // TLC replays the expansion of a state with ModelChecker.doNext, which writes each successor in
1685
+ // the model to the -dump state graph again.
1686
+ const replayNext = (index: number) =>
1687
+ getReplayFailure((tracing) => {
1688
+ const state = states[index];
1689
+ const source = stateWriter && getGraphState(state, depths[index]);
1690
+ const addReplayed = createReplayedStates();
1691
+ replaySuccessors(getSpecNextActions(), state, tracing, (next, action) => {
1692
+ const addFingerprint = () => {
1693
+ const isUnseen = addReplayed(next, tracing.callStack);
1694
+ if (source) {
1695
+ stateWriter?.writeSuccessor(
1696
+ source,
1697
+ getGraphState(next, depths[index] + 1),
1698
+ !isUnseen,
1699
+ isNamingEdges
1700
+ ? { name: action.name, signature: getActionSignature(action) }
1701
+ : undefined,
1702
+ );
1703
+ }
1704
+ return isUnseen;
1705
+ };
1706
+ if (!search.checkReplayedSuccessor(state, next, tracing, addFingerprint)) {
1707
+ throw STOP_REPLAY;
1708
+ }
1709
+ });
1710
+ });
964
1711
  const isReducing = config.view !== undefined || config.symmetry !== undefined;
1712
+ const tlcFingerprints: number[] = [];
1713
+ // TLC warns about the liveness checker before it builds it.
1714
+ if (search.properties.liveness.length > 0) {
1715
+ options.onProgress?.({
1716
+ kind: "liveness-initializing",
1717
+ isSymmetric: search.isSymmetric,
1718
+ isConstrained: search.isConstrained,
1719
+ });
1720
+ }
965
1721
  const liveness = withLivenessExitCode(() =>
966
- createLivenessChecker(search.properties.liveness, spec.temporals, environment),
1722
+ withUnexpectedException(() =>
1723
+ createLivenessChecker(search.properties.liveness, spec.temporals, environment, {
1724
+ getFingerprint: ({ index, state }) =>
1725
+ (tlcFingerprints[index] ??= Number(BigInt.asIntN(32, runtime.getFingerprint(state)))),
1726
+ getSuccessors: (source, state) => {
1727
+ const successors: LiveSuccessor[] = [];
1728
+ if (spec.next === undefined) return successors;
1729
+ // The constraints read the level of the state whose successors they check, as when TLC
1730
+ // explored it.
1731
+ const livenessSource = current.livenessSource;
1732
+ current.livenessSource = source;
1733
+ forEachSuccessor(
1734
+ spec.next,
1735
+ state,
1736
+ environment,
1737
+ (successor) => {
1738
+ canonicalizeState(successor.state);
1739
+ const isInModel =
1740
+ search.satisfiesConstraints(successor.state, state) &&
1741
+ search.satisfiesActionConstraints(state, successor.state);
1742
+ if (!isInModel) return false;
1743
+ const fingerprintState = getFingerprintState(successor.state);
1744
+ const index = findStateIndex(getStateHash(fingerprintState), fingerprintState);
1745
+ successors.push({ index, state: successor.state });
1746
+ return false;
1747
+ },
1748
+ spec.scope,
1749
+ );
1750
+ current.livenessSource = livenessSource;
1751
+ return successors;
1752
+ },
1753
+ }),
1754
+ ),
967
1755
  );
1756
+ // TLC 1.7.4 creates its model checker, which TLCGet reads, once it has built the liveness checker.
1757
+ runtime.isStarted = true;
968
1758
  const isCanonicalizedFirst = search.isSymmetric || liveness !== undefined;
969
1759
 
970
1760
  const states: Value[][] = [];
@@ -972,7 +1762,9 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
972
1762
  const parents: number[] = [];
973
1763
  const actions: (string | undefined)[] = [];
974
1764
  const depths: number[] = [];
975
- const buckets = new Map<number, number | number[]>();
1765
+ // A Map holds at most 2^24 entries, so an open-addressing table keeps each seen state's hash
1766
+ // and its index plus one side by side, probed by the hash.
1767
+ const seen = { slots: new Int32Array(1 << 17), size: 0, shift: 16 };
976
1768
  const canonicalizeState = createCanonicalizer();
977
1769
 
978
1770
  const toRecord = (state: Value[]): Record<string, Value> =>
@@ -985,11 +1777,16 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
985
1777
  position: number,
986
1778
  loopStart: number | undefined,
987
1779
  ) => {
988
- const state = steps[position].state;
989
- const next = (steps[position + 1] ?? steps[loopStart ?? position]).state;
990
1780
  // TLC evaluates TLCGet("level") and Trace in an alias at the state's position in the trace.
991
1781
  runtime.getLevel = () => position + 1;
992
1782
  runtime.getBehavior = () => steps.slice(0, position + 1).map((step) => step.state);
1783
+ return evaluateAlias(
1784
+ alias,
1785
+ steps[position].state,
1786
+ (steps[position + 1] ?? steps[loopStart ?? position]).state,
1787
+ );
1788
+ };
1789
+ const evaluateAlias = (alias: string, state: Value[], next: Value[] | undefined) => {
993
1790
  try {
994
1791
  const body = getConfigDefinition("alias", alias, environment).body;
995
1792
  const value = evaluate(createIdentifier(alias), getContext(environment, state, next));
@@ -997,58 +1794,107 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
997
1794
  return toAliasRecord(value, fieldOrder) ?? toRecord(state);
998
1795
  } catch (error) {
999
1796
  if (!(error instanceof TlaConfigError || error instanceof TlaEvaluationError)) throw error;
1000
- return { ...toRecord(state), _ALIASEvalError: error.message };
1797
+ return {
1798
+ ...toRecord(state),
1799
+ _ALIASEvalError: formatNestedMessage(error.message, options.isTool ?? false),
1800
+ };
1001
1801
  }
1002
1802
  };
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);
1803
+ // TLC finds the action of a step as the first action that takes it, evaluated as when the search
1804
+ // expanded the previous state.
1805
+ // TLC finds the action of a successor it holds by the successor's values, and of any other state
1806
+ // by its fingerprint.
1807
+ const findStepAction = (index: number, previous: Value[], state: Value[], isHeld: boolean) => {
1808
+ const actions = getSpecNextActions();
1007
1809
  const expanding = { ...current };
1008
1810
  Object.assign(current, { index, isExpanding: true, candidate: undefined });
1009
- const fingerprintState = getFingerprintState(state);
1010
- const action = nextActions.value.find((item) =>
1811
+ const getKey = isHeld ? (values: Value[]) => values : getFingerprintState;
1812
+ const key = getKey(state);
1813
+ const action = actions.find((item) =>
1011
1814
  getSuccessors(item.expression, previous, environment, item.scope).some((successor) =>
1012
- isSameState(getFingerprintState(successor.state), fingerprintState),
1815
+ isSameState(getKey(successor.state), key),
1013
1816
  ),
1014
1817
  );
1015
1818
  Object.assign(current, expanding);
1016
- return action && getActionLabel(action);
1819
+ return action;
1017
1820
  };
1018
- const toTrace = (steps: Successor[], path: number[], loopStart?: number): TraceStep[] => {
1821
+ // Before TLC prints a trace, it rebuilds from the initial predicate the states it does not keep,
1822
+ // all but the last `known` ones. As it prints each later step, it finds the action that takes
1823
+ // the step. Then it rebuilds the trace once more, unless the trace is a liveness counterexample
1824
+ // or TLC is 1.7.4.
1825
+ const toTrace = (
1826
+ steps: Successor[],
1827
+ path: number[],
1828
+ traceOptions: TraceOptions = {},
1829
+ ): Behavior => {
1019
1830
  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
- }));
1831
+ const known = traceOptions.known ?? 1;
1832
+ // Rebuilding the trace from the initial predicate can reset what TLCSet stored.
1833
+ const initialOutput = steps.length > 1 ? getOutput(getSpecInitialStates).lines : [];
1834
+ // TLC finds the action that takes each step before it evaluates the alias.
1835
+ const found = steps.map((step, position) =>
1836
+ position === 0 || step.action === "Stuttering"
1837
+ ? { result: undefined, lines: [] }
1838
+ : getOutput(() =>
1839
+ findStepAction(
1840
+ path[position - 1],
1841
+ steps[position - 1].state,
1842
+ step.state,
1843
+ known === 2 && position === steps.length - 1,
1844
+ ),
1845
+ ),
1846
+ );
1847
+ const outputs = found.map((step) => step.lines);
1848
+ const loopStart = traceOptions.loopStart;
1849
+ // 1.7.4's LiveWorker#printTrace rebuilds a lasso up to the start of its cycle at once, and then
1850
+ // each state of the cycle as it prints it.
1851
+ const rebuilt = is174 && loopStart !== undefined ? loopStart + 1 : steps.length - known;
1852
+ const prefixOutput = rebuilt > 0 ? [initialOutput, ...outputs.slice(1, rebuilt)].flat() : [];
1853
+ return {
1854
+ trace: steps.map((step, position) => {
1855
+ const action = found[position].result;
1856
+ const traceStep: TraceStep = {
1857
+ action: step.action,
1858
+ label: action && getActionLabel(action, options.version),
1859
+ state:
1860
+ alias === undefined
1861
+ ? toRecord(step.state)
1862
+ : getAliasState(alias, steps, position, loopStart),
1863
+ output: position === 0 ? prefixOutput : position < rebuilt ? [] : outputs[position],
1864
+ };
1865
+ if (alias !== undefined || action) {
1866
+ traceSteps.set(traceStep, { state: toRecord(step.state), action });
1867
+ }
1868
+ return traceStep;
1869
+ }),
1870
+ traceOutput: known > 0 && !is174 ? [initialOutput, ...outputs].flat() : [],
1871
+ };
1038
1872
  };
1039
1873
  const getSpecInitialStates = () =>
1040
1874
  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);
1875
+ // TLC's Tool#getState rebuilds a successor action by action, up to the first action that
1876
+ // generates it. A trace keeps what the spec prints as TLC rebuilds it, so finding its states
1877
+ // prints nothing.
1878
+ const findTraceSuccessor = (state: Value[], isMatch: (successor: Successor) => boolean) =>
1879
+ getOutput(() => {
1880
+ for (const action of getSpecNextActions()) {
1881
+ const successor = getSuccessors(action.expression, state, environment, action.scope).find(
1882
+ isMatch,
1883
+ );
1884
+ if (successor) return { ...successor, action: successor.action ?? action.name };
1885
+ }
1886
+ return undefined;
1887
+ }).result;
1043
1888
  const hasFingerprint = (state: Value[], index: number) =>
1044
1889
  isSameState(getFingerprintState(state), fingerprintStates[index]);
1045
1890
  const findSuccessorWithFingerprint = (state: Value[], index: number) =>
1046
- getTraceSuccessors(state).find((successor) => hasFingerprint(successor.state, index));
1891
+ findTraceSuccessor(state, (successor) => hasFingerprint(successor.state, index));
1047
1892
  const getPathStates = (path: number[], nextFailure: string) => {
1048
- const initial =
1893
+ const initial = getOutput(() =>
1049
1894
  isReducing || isImpure(environment)
1050
1895
  ? getSpecInitialStates().find((state) => hasFingerprint(state, path[0]))
1051
- : states[path[0]];
1896
+ : states[path[0]],
1897
+ ).result;
1052
1898
  if (!initial) throw new TlaEvaluationError(INITIAL_RECOVERY_FAILURE);
1053
1899
  const steps: Successor[] = [{ state: initial, action: undefined }];
1054
1900
  for (let position = 1; position < path.length; position++) {
@@ -1074,37 +1920,120 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1074
1920
  : path.map((position) => ({ state: states[position], action: actions[position] }));
1075
1921
  if (!last) return toTrace(steps, path);
1076
1922
  const action = isReducing
1077
- ? getTraceSuccessors(states[index]).find((successor) =>
1078
- isSameState(successor.state, last.state),
1079
- )?.action
1923
+ ? findTraceSuccessor(states[index], (successor) => isSameState(successor.state, last.state))
1924
+ ?.action
1080
1925
  : last.action;
1081
- return toTrace([...steps, { state: last.state, action }], path);
1926
+ return toTrace([...steps, { state: last.state, action }], path, { known: 2 });
1082
1927
  };
1083
1928
  // TLC prints an initial state on its own without evaluating the alias.
1084
- const getStateTrace = (index: number) =>
1929
+ // TLCTrace#getTrace recovers even a lone initial state from the initial predicate, printing
1930
+ // again, though TLC 1.7.4 doesn't.
1931
+ const getStateTrace = (index: number): Behavior =>
1085
1932
  parents[index] === -1
1086
- ? [{ action: undefined, label: undefined, state: toRecord(states[index]) }]
1933
+ ? {
1934
+ trace: [{ action: undefined, label: undefined, state: toRecord(states[index]) }],
1935
+ traceOutput: is174 ? [] : getOutput(getSpecInitialStates).lines,
1936
+ }
1087
1937
  : getTrace(index);
1938
+ // TLC rebuilds the trace again for the postcondition after it prints a violation, but not after
1939
+ // an evaluation fails.
1940
+ const getFailedTrace = (index: number, successor: Successor): Behavior => ({
1941
+ trace: getTrace(index, successor).trace,
1942
+ });
1088
1943
  // 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[],
1094
- ) => {
1944
+ const getFailureExitCode = (error: TlaEvaluationError, failureOptions: FailureOptions) => {
1945
+ // TLC 1.7.4 exits with the result of its replay of the initial states, which only fails again
1946
+ // when the error isn't in adding a state it has already seen to the behavior graph.
1947
+ if (
1948
+ failureOptions.isInitial &&
1949
+ !failureOptions.callStack &&
1950
+ !failureOptions.fingerprint &&
1951
+ is174
1952
+ ) {
1953
+ return EXIT_STATUS.success;
1954
+ }
1955
+ if (!failureOptions.callStack) {
1956
+ return failureOptions.isInitial ? getInitialExitCode(error) : getErrorExitCode(error);
1957
+ }
1958
+ if (failureOptions.isCallStackFirst) return getErrorExitCode(error);
1959
+ // Without a replay, TLC exits with the code of the error, as for any error it didn't expect.
1960
+ if (failureOptions.isLiveCallStack) {
1961
+ return (
1962
+ getExitCode(error) ?? (error instanceof TlaModuleError ? error.exitCode : EXIT_STATUS.error)
1963
+ );
1964
+ }
1965
+ // TLC exits with the code of a failed replay of the initial states regardless of the error, as
1966
+ // it does for a replay that fails to fingerprint.
1967
+ return failureOptions.isInitial || failureOptions.fingerprint
1968
+ ? EXIT_STATUS.specEvaluationFailure
1969
+ : getReplayExitCode(error);
1970
+ };
1971
+ const toFailure = (failed: unknown, behavior: Behavior, failureOptions: FailureOptions = {}) => {
1972
+ const error = isStackOverflow(failed) ? new TlaStackOverflowError() : failed;
1095
1973
  if (!(error instanceof TlaEvaluationError)) throw error;
1974
+ const checked =
1975
+ behavior.trace.length > 0 && !failureOptions.traceFailure
1976
+ ? checkTracePostconditions(behavior.trace, undefined)
1977
+ : undefined;
1978
+ const postcondition = checked?.unwitnessed ?? checked?.postcondition;
1979
+ const traceOutput = [...(behavior.traceOutput ?? []), ...(checked?.lines ?? [])];
1096
1980
  return {
1097
1981
  ...createResult("error", undefined, {
1098
- message: error.message,
1099
- trace,
1982
+ ...getFailureMessage(error, failureOptions.isNextState ?? false),
1983
+ ...behavior,
1984
+ ...(traceOutput.length > 0 && { traceOutput }),
1985
+ ...(postcondition && { postcondition }),
1100
1986
  initialState:
1101
- initialState && !(error instanceof TlaModuleError) ? toRecord(initialState) : undefined,
1102
- exitCode: getErrorExitCode(error),
1987
+ failureOptions.initialState && !(error instanceof TlaModuleError)
1988
+ ? toRecord(failureOptions.initialState)
1989
+ : undefined,
1990
+ exitCode: getFailureExitCode(error, failureOptions),
1991
+ callStack: failureOptions.callStack,
1992
+ ...(failureOptions.isCallStackFirst && { isCallStackFirst: true }),
1993
+ ...(failureOptions.fingerprint && { fingerprint: failureOptions.fingerprint }),
1994
+ ...(failureOptions.traceFailure && { traceFailure: failureOptions.traceFailure }),
1103
1995
  }),
1104
- outDegrees: failureOutDegrees,
1996
+ outDegrees: failureOptions.outDegrees,
1105
1997
  };
1106
1998
  };
1107
- const getPathTrace = (path: number[], loopStart?: number) => {
1999
+ // TLC reports a successor state that an action leaves incomplete with the trace to it, which ends
2000
+ // with the partial state. It names the action when the next-state relation has several.
2001
+ const reportIncompleteSuccessor = (index: number, error: TlaIncompleteSuccessorError) => {
2002
+ runtime.generatedStates++;
2003
+ const actions = getSpecNextActions();
2004
+ const action =
2005
+ actions.length === 1 ? actions[0] : actions.find((item) => item.name === error.action);
2006
+ const missing = error.variables;
2007
+ const subject =
2008
+ actions.length === 1
2009
+ ? "the next-state action"
2010
+ : `action ${error.action} of the next-state relation`;
2011
+ // TLC 1.7.4 says a variable is not assigned rather than not defined.
2012
+ const verb = is174 ? "assigned" : "defined";
2013
+ const message = `Successor state is not completely specified by ${subject}. The following variable${missing.length > 1 ? "s are" : " is"} not ${verb}: ${missing.join(", ")}.\n`;
2014
+ const undefinedValue = createModelValue("null");
2015
+ const partial = error.state.map((value) => value ?? undefinedValue);
2016
+ const failure = toFailure(error, getStateTrace(index));
2017
+ return withOutDegrees({
2018
+ ...failure,
2019
+ failure: failure.failure && {
2020
+ ...failure.failure,
2021
+ code: MESSAGE_CODE.incompleteSuccessor,
2022
+ message,
2023
+ toolMessage: message,
2024
+ exitCode: EXIT_STATUS.specEvaluationFailure,
2025
+ trace: [
2026
+ ...failure.failure.trace,
2027
+ {
2028
+ action: error.action,
2029
+ label: action && getActionLabel(action, options.version),
2030
+ state: toRecord(partial),
2031
+ },
2032
+ ],
2033
+ },
2034
+ });
2035
+ };
2036
+ const getPathSteps = (path: number[], loopStart?: number) => {
1108
2037
  const steps = getPathStates(path, NEXT_RECOVERY_FAILURE);
1109
2038
  const last = steps[steps.length - 1].state;
1110
2039
  const isClosed =
@@ -1113,7 +2042,7 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1113
2042
  loopStart === path.length - 1 ||
1114
2043
  findSuccessorWithFingerprint(last, path[loopStart]) !== undefined;
1115
2044
  if (!isClosed) throw new TlaEvaluationError(NEXT_RECOVERY_FAILURE);
1116
- return toTrace(steps, path, loopStart);
2045
+ return steps;
1117
2046
  };
1118
2047
  const getStateHash = (state: Value[]) => {
1119
2048
  let hash = 0x811c9dc5;
@@ -1121,26 +2050,52 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1121
2050
  hash = combineHash(hash, getValueHash(state[index]));
1122
2051
  return hash & 0x3fffffff;
1123
2052
  };
2053
+ // TLC fingerprints a state once it finds the state in the model.
2054
+ const fingerprintModelState = (state: Value[]) => {
2055
+ for (const value of state) {
2056
+ const error = getFingerprintError(value);
2057
+ if (error) throw error;
2058
+ }
2059
+ };
1124
2060
  const isSameState = (stored: Value[], state: Value[]) => {
1125
2061
  for (let position = 0; position < state.length; position++) {
1126
2062
  if (!isSameValue(stored[position], state[position])) return false;
1127
2063
  }
1128
2064
  return true;
1129
2065
  };
2066
+ const getSlot = (hash: number) => (Math.imul(hash, 0x9e3779b1) >>> seen.shift) << 1;
1130
2067
  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;
2068
+ const mask = seen.slots.length - 1;
2069
+ for (let slot = getSlot(hash); ; slot = (slot + 2) & mask) {
2070
+ const entry = seen.slots[slot + 1];
2071
+ if (entry === 0) return -1;
2072
+ if (seen.slots[slot] === hash && isSameState(fingerprintStates[entry - 1], state)) {
2073
+ return entry - 1;
2074
+ }
1135
2075
  }
1136
- return bucket.find((index) => isSameState(fingerprintStates[index], state)) ?? -1;
2076
+ };
2077
+ const insertSeen = (hash: number, entry: number) => {
2078
+ const mask = seen.slots.length - 1;
2079
+ let slot = getSlot(hash);
2080
+ while (seen.slots[slot + 1] !== 0) slot = (slot + 2) & mask;
2081
+ seen.slots[slot] = hash;
2082
+ seen.slots[slot + 1] = entry;
1137
2083
  };
1138
2084
  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);
2085
+ seen.size++;
2086
+ if (seen.size * 4 > seen.slots.length) {
2087
+ const slots = seen.slots;
2088
+ seen.slots = new Int32Array(slots.length * 2);
2089
+ seen.shift--;
2090
+ for (let slot = 0; slot < slots.length; slot += 2) {
2091
+ if (slots[slot + 1] !== 0) insertSeen(slots[slot], slots[slot + 1]);
2092
+ }
2093
+ }
2094
+ insertSeen(hash, index + 1);
1143
2095
  };
2096
+ // A new successor that TLC has added to its set of states before it checks the successor, which
2097
+ // the check stores after.
2098
+ const unstoredState = { fingerprint: undefined as Value[] | undefined };
1144
2099
  const countDistinctState = (depth: number) => {
1145
2100
  runtime.distinctStates = states.length + 1;
1146
2101
  statistics.depth = Math.max(statistics.depth, depth);
@@ -1179,10 +2134,15 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1179
2134
  };
1180
2135
  runtime.getCurrentState = () => (current.index === -1 ? undefined : states[current.index]);
1181
2136
  runtime.setLivenessSource = (index) => {
1182
- current.livenessSource = index;
2137
+ current.livenessSource = index ?? -1;
1183
2138
  };
1184
2139
  runtime.getLevel = (state) => {
1185
2140
  const source = current.livenessSource;
2141
+ // TLC 1.7.4 reads the level of the state its worker explores, whichever state it evaluates.
2142
+ if (is174) {
2143
+ const explored = source !== -1 ? source : current.isExpanding ? current.index : -1;
2144
+ return explored === -1 ? 0 : depths[explored];
2145
+ }
1186
2146
  if (source !== -1) return state === states[source] ? depths[source] : depths[source] + 1;
1187
2147
  if (state === current.candidate) return current.candidateLevel;
1188
2148
  if (current.index === -1) return 0;
@@ -1190,6 +2150,18 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1190
2150
  return current.isExpanding ? depths[current.index] + 1 : 0;
1191
2151
  };
1192
2152
 
2153
+ const getGraphState = (state: Value[], level: number): GraphState => ({
2154
+ fingerprint: BigInt.asIntN(64, runtime.getFingerprint(state)),
2155
+ level,
2156
+ getLabel: () =>
2157
+ formatState(
2158
+ config.alias === undefined
2159
+ ? toRecord(state)
2160
+ : evaluateAlias(config.alias, state, undefined),
2161
+ ),
2162
+ getText: () => formatState(toRecord(state)),
2163
+ });
2164
+
1193
2165
  const visitInitialState = (state: Value[]) => {
1194
2166
  canonicalizeState(state);
1195
2167
  runtime.generatedStates++;
@@ -1199,26 +2171,32 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1199
2171
  const fingerprintState = getFingerprintState(state);
1200
2172
  const hash = getStateHash(fingerprintState);
1201
2173
  const isInModel = search.satisfiesConstraints(state);
1202
- if (isInModel) search.trackStatePossible(state);
2174
+ if (isInModel) {
2175
+ search.trackStatePossible(state);
2176
+ fingerprintModelState(fingerprintState);
2177
+ state.forEach(markFingerprinted);
2178
+ }
1203
2179
  const isSeen = isInModel && findStateIndex(hash, fingerprintState) !== -1;
1204
2180
  if (isSeen) return undefined;
2181
+ unstoredState.fingerprint = isInModel ? fingerprintState : undefined;
1205
2182
  if (isInModel) {
1206
2183
  countDistinctState(1);
1207
2184
  runtime.queueSize++;
1208
2185
  liveness?.addInitialState(states.length, state);
2186
+ stateWriter?.writeInitialState(getGraphState(state, 1));
1209
2187
  }
1210
2188
  const violated = search.findViolatedInvariant(state);
1211
2189
  if (violated) {
1212
2190
  return reportViolation("invariant-violation", {
1213
2191
  name: violated.name,
1214
- trace: toTrace([{ action: undefined, state }], []),
2192
+ ...toTrace([{ action: undefined, state }], []),
1215
2193
  });
1216
2194
  }
1217
2195
  const failedPredicate = search.findFailedInitialPredicate(state);
1218
2196
  if (failedPredicate) {
1219
2197
  return reportViolation("liveness-violation", {
1220
2198
  name: failedPredicate.name,
1221
- trace: toTrace([{ action: undefined, state }], []),
2199
+ ...toTrace([{ action: undefined, state }], []),
1222
2200
  });
1223
2201
  }
1224
2202
  if (!isInModel) return undefined;
@@ -1226,7 +2204,13 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1226
2204
  addState(state, fingerprintState, -1, undefined);
1227
2205
  return undefined;
1228
2206
  };
1229
- const visitSuccessor = (index: number, successor: Successor, liveSuccessors: LiveSuccessor[]) => {
2207
+ const visitSuccessor = (
2208
+ index: number,
2209
+ successor: Successor,
2210
+ liveSuccessors: LiveSuccessor[],
2211
+ source: GraphState | undefined,
2212
+ action: SpecAction | undefined,
2213
+ ) => {
1230
2214
  const state = states[index];
1231
2215
  runtime.generatedStates++;
1232
2216
  current.candidate = successor.state;
@@ -1238,14 +2222,29 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1238
2222
  const isStateInModel = search.satisfiesConstraints(successor.state, state);
1239
2223
  if (isStateInModel) search.trackStatePossible(successor.state);
1240
2224
  const isInModel = isStateInModel && search.satisfiesActionConstraints(state, successor.state);
1241
- if (isInModel) search.trackActionPossible(state, successor.state);
2225
+ if (isInModel) {
2226
+ search.trackActionPossible(state, successor.state);
2227
+ fingerprintModelState(fingerprintState);
2228
+ successor.state.forEach(markFingerprinted);
2229
+ }
1242
2230
  const existing = isInModel ? found : -1;
2231
+ if (source && isInModel) {
2232
+ stateWriter?.writeSuccessor(
2233
+ source,
2234
+ getGraphState(successor.state, depths[index] + 1),
2235
+ existing !== -1,
2236
+ action && { name: action.name, signature: getActionSignature(action) },
2237
+ );
2238
+ }
1243
2239
  if (existing !== -1 && liveness) {
1244
2240
  const stored = states[existing];
1245
2241
  const isStored = stored.every((value, position) => value === successor.state[position]);
1246
2242
  liveSuccessors.push({ index: existing, state: isStored ? stored : successor.state });
1247
2243
  }
1248
2244
  const isNew = isInModel && existing === -1;
2245
+ // TLC adds a new state to the behavior graph's successors before it checks the invariants.
2246
+ if (isNew && liveness) liveSuccessors.push({ index: states.length, state: successor.state });
2247
+ unstoredState.fingerprint = isNew ? fingerprintState : undefined;
1249
2248
  if (isNew) {
1250
2249
  countDistinctState(depths[index] + 1);
1251
2250
  expansion.newStates++;
@@ -1254,53 +2253,105 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1254
2253
  try {
1255
2254
  const violated = search.findViolatedInvariant(successor.state, state);
1256
2255
  if (violated) {
1257
- return reportViolation("invariant-violation", {
1258
- name: violated.name,
1259
- trace: getTrace(index, successor),
1260
- });
2256
+ return withOutDegrees(
2257
+ reportViolation("invariant-violation", {
2258
+ name: violated.name,
2259
+ ...getTrace(index, successor),
2260
+ }),
2261
+ );
1261
2262
  }
1262
2263
  } 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());
2264
+ if (isStackOverflow(error)) throw error;
2265
+ // TLC replays the expansion and skips the invariants of a state it has seen, the failed one
2266
+ // included unless the constraints exclude it. When the replay fails, TLC reports where and
2267
+ // leaves out the outdegree.
2268
+ const replay = getOutput(() => replayNext(index));
2269
+ return toFailure(
2270
+ error,
2271
+ appendTraceOutput(getFailedTrace(index, successor), replay.lines),
2272
+ replay.result ?? { outDegrees: getFailureOutDegrees() },
2273
+ );
1265
2274
  }
1266
2275
  }
1267
2276
  const violatedProperty = search.findViolatedActionProperty(state, successor.state);
1268
2277
  if (violatedProperty) {
1269
- return reportViolation("liveness-violation", {
1270
- name: violatedProperty.name,
1271
- trace: getTrace(index, successor),
1272
- });
2278
+ return withOutDegrees(
2279
+ reportViolation("liveness-violation", {
2280
+ name: violatedProperty.name,
2281
+ ...getTrace(index, successor),
2282
+ }),
2283
+ );
1273
2284
  }
1274
2285
  if (!isNew) return undefined;
1275
2286
  if (!isCanonicalizedFirst) canonicalizeState(successor.state);
1276
2287
  markSeen(hash, states.length);
1277
- if (liveness) liveSuccessors.push({ index: states.length, state: successor.state });
1278
2288
  addState(successor.state, fingerprintState, index, successor.action);
1279
2289
  runtime.queueSize++;
1280
2290
  return undefined;
1281
2291
  };
1282
2292
 
1283
2293
  const outcome: { result: CheckResult | undefined } = { result: undefined };
2294
+ if (liveness) {
2295
+ options.onProgress?.({ kind: "liveness-prepared", branches: liveness.branches });
2296
+ }
2297
+ // TLC checks the assumptions once it has built the liveness checker in ModelChecker's
2298
+ // constructor.
2299
+ const assumptionViolation = findViolatedAssumption();
2300
+ if (assumptionViolation) return createResult("assumption-violation", assumptionViolation);
2301
+ options.onProgress?.({ kind: "initial-states-started" });
1284
2302
  if (spec.init !== undefined) {
1285
2303
  try {
1286
2304
  forEachInitialState(
1287
2305
  spec.init,
1288
2306
  environment,
1289
2307
  (state) => {
2308
+ reportInitialStatesProgress(runtime.initialStates, options.onProgress);
1290
2309
  try {
1291
2310
  outcome.result = visitInitialState(state);
1292
2311
  } catch (error) {
1293
- outcome.result = toFailure(error, [], state);
2312
+ const replay = getOutput(replayInit);
2313
+ outcome.result = toFailure(
2314
+ error,
2315
+ { trace: [], traceOutput: replay.lines },
2316
+ { initialState: state, ...replay.result, isInitial: true },
2317
+ );
1294
2318
  }
1295
2319
  return outcome.result !== undefined;
1296
2320
  },
1297
2321
  spec.scope,
1298
2322
  );
1299
2323
  } catch (error) {
1300
- return toFailure(error, []);
2324
+ // TLC prints an illegal initial state with null for each variable it leaves undefined, and
2325
+ // stops before it prints the statistics.
2326
+ if (error instanceof TlaIllegalStateError) {
2327
+ const illegal = toFailure(
2328
+ error,
2329
+ { trace: [] },
2330
+ { initialState: error.state.map((value) => value ?? createModelValue("null")) },
2331
+ );
2332
+ return {
2333
+ ...illegal,
2334
+ failure: illegal.failure && { ...illegal.failure, isWithoutStatistics: true },
2335
+ };
2336
+ }
2337
+ // TLC prints the error before it replays the initial predicate with its call stack.
2338
+ const replay = getOutput(replayInit);
2339
+ return toFailure(
2340
+ error,
2341
+ { trace: [], traceOutput: replay.lines },
2342
+ { ...replay.result, isInitial: true },
2343
+ );
1301
2344
  }
1302
2345
  }
1303
2346
  if (outcome.result) return outcome.result;
2347
+ statistics.initialStates = {
2348
+ generated: runtime.initialStates,
2349
+ distinct: runtime.distinctStates,
2350
+ };
2351
+ options.onProgress?.({
2352
+ kind: "initial-states-computed",
2353
+ initialStates: statistics.initialStates,
2354
+ });
1304
2355
 
1305
2356
  const next = spec.next;
1306
2357
  if (next === undefined) {
@@ -1311,56 +2362,276 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1311
2362
  }
1312
2363
  return createSuccess();
1313
2364
  }
1314
- const expandState = (index: number) => {
2365
+ // TLC labels and colors an edge of the -dump state graph by the action that generated it. When
2366
+ // the graph names its edges, the search generates successors action by action, as TLC does.
2367
+ const isNamingEdges = Boolean(
2368
+ options.dump?.dot && (options.dump.actionLabels || options.dump.colorize),
2369
+ );
2370
+ const forEachActionSuccessor = (
2371
+ state: Value[],
2372
+ onSuccessor: (successor: Successor, action: SpecAction | undefined) => boolean,
2373
+ ) => {
2374
+ if (!isNamingEdges) {
2375
+ return forEachSuccessor(
2376
+ next,
2377
+ state,
2378
+ environment,
2379
+ (successor) => onSuccessor(successor, undefined),
2380
+ spec.scope,
2381
+ );
2382
+ }
2383
+ const progress = { isStopped: false };
2384
+ return getSpecNextActions().reduce((count, action) => {
2385
+ if (progress.isStopped) return count;
2386
+ return (
2387
+ count +
2388
+ forEachSuccessor(
2389
+ action.expression,
2390
+ state,
2391
+ environment,
2392
+ (successor) => {
2393
+ progress.isStopped = onSuccessor(successor, action);
2394
+ return progress.isStopped;
2395
+ },
2396
+ action.scope,
2397
+ )
2398
+ );
2399
+ }, 0);
2400
+ };
2401
+ // TLC's worker adds a state to the behavior graph even after its next states fail or violate a
2402
+ // property, and prints the call stack of an error in that, unless the error is a
2403
+ // FingerprintException, which the worker doesn't catch. TLC 1.7.4 prints none.
2404
+ const getLiveCallStack = (index: number, liveSuccessors: LiveSuccessor[]) => {
2405
+ if (!liveness || is174) return undefined;
2406
+ const replay = getReplayFailure((tracing) =>
2407
+ liveness.addState(index, states[index], liveSuccessors, tracing),
2408
+ );
2409
+ return replay?.callStack.length && !replay.fingerprint ? replay.callStack : undefined;
2410
+ };
2411
+ // TLC's worker adds the state to the behavior graph after it prints the trace. On an error in that,
2412
+ // it adds the state again to print the call stack instead of replaying the next-state relation,
2413
+ // which TLC 1.7.4 doesn't.
2414
+ const addFailedLiveState = (index: number, liveSuccessors: LiveSuccessor[]) => {
2415
+ try {
2416
+ liveness?.addState(index, states[index], liveSuccessors);
2417
+ return undefined;
2418
+ } catch (error) {
2419
+ if (!(error instanceof TlaEvaluationError)) throw error;
2420
+ return getLiveCallStack(index, liveSuccessors);
2421
+ }
2422
+ };
2423
+ const replayFailedNext = (index: number, liveSuccessors: LiveSuccessor[]) => {
2424
+ const live = getOutput(() => addFailedLiveState(index, liveSuccessors));
2425
+ if (live.result) {
2426
+ const result = { callStack: live.result, fingerprint: undefined, isLiveCallStack: true };
2427
+ return { result, lines: live.lines };
2428
+ }
2429
+ const replay = getOutput(() => replayNext(index));
2430
+ return { result: replay.result, lines: [...live.lines, ...replay.lines] };
2431
+ };
2432
+ // TLC reports a stack overflow while it computes next states without replaying it, with the
2433
+ // behavior up to the state it expands.
2434
+ const reportNextStateOverflow = (index: number) =>
2435
+ toFailure(createStackOverflowError(), getStateTrace(index));
2436
+ // After the trace, TLC replays the next-state relation with its call stack, printing again.
2437
+ const reportNextStateFailure = (
2438
+ error: unknown,
2439
+ index: number,
2440
+ liveSuccessors: LiveSuccessor[],
2441
+ ) => {
2442
+ if (isStackOverflow(error)) return reportNextStateOverflow(index);
2443
+ const replay = replayFailedNext(index, liveSuccessors);
2444
+ return toFailure(
2445
+ withNextStateExitCode(error),
2446
+ appendTraceOutput(getStateTrace(index), replay.lines),
2447
+ { isNextState: true, ...replay.result },
2448
+ );
2449
+ };
2450
+ const expandState = (index: number, liveSuccessors: LiveSuccessor[]) => {
1315
2451
  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));
2452
+ const source = stateWriter && getGraphState(state, depths[index]);
2453
+ const successorCount = forEachActionSuccessor(state, (successor, action) => {
2454
+ try {
2455
+ outcome.result = visitSuccessor(index, successor, liveSuccessors, source, action);
2456
+ } catch (error) {
2457
+ if (isStackOverflow(error)) {
2458
+ outcome.result = reportNextStateOverflow(index);
2459
+ return true;
1326
2460
  }
1327
- return outcome.result !== undefined;
1328
- },
1329
- spec.scope,
1330
- );
2461
+ // TLC 1.7.4 reports the wrapped error without the trace, except for a failed property,
2462
+ // which it reports with the trace before it rethrows. The error stops its worker before it
2463
+ // adds the state to the behavior graph.
2464
+ const replay = is174
2465
+ ? getOutput(() => replayNext(index))
2466
+ : replayFailedNext(index, liveSuccessors);
2467
+ if (is174 && error instanceof TlaEvaluationError && !headedErrors.has(error)) {
2468
+ outcome.result = toFailure(
2469
+ new TlaEvaluationError(`${getWrappedException(error)}${error.message}`, error),
2470
+ appendTraceOutput({ trace: [] }, replay.lines),
2471
+ { isNextState: true, ...replay.result },
2472
+ );
2473
+ return true;
2474
+ }
2475
+ // A successor TLC can't fingerprint fails again as TLC prints it in the trace, which TLC
2476
+ // reports as an exception it didn't expect.
2477
+ const isTraceFailed = getFingerprintState(successor.state).some(
2478
+ (value) => getFingerprintError(value) !== undefined,
2479
+ );
2480
+ const traceFailure =
2481
+ isTraceFailed && error instanceof TlaEvaluationError
2482
+ ? getFailureMessage(
2483
+ isEvalException(error)
2484
+ ? new TlaEvaluationError(`${UNEXPECTED_EVAL_EXCEPTION}${error.message}`)
2485
+ : error,
2486
+ true,
2487
+ )
2488
+ : undefined;
2489
+ outcome.result = toFailure(
2490
+ error,
2491
+ appendTraceOutput(
2492
+ traceFailure ? getStateTrace(index) : getFailedTrace(index, successor),
2493
+ replay.lines,
2494
+ ),
2495
+ { isNextState: true, ...replay.result, traceFailure },
2496
+ );
2497
+ }
2498
+ return outcome.result !== undefined;
2499
+ });
1331
2500
  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) });
2501
+ const result = outcome.result;
2502
+ // TLC 1.7.4's worker stops at a violation.
2503
+ if (result?.violation && !is174) {
2504
+ const live = getOutput(() => addFailedLiveState(index, liveSuccessors));
2505
+ return {
2506
+ ...result,
2507
+ violation: appendTraceOutput(result.violation, live.lines),
2508
+ ...(live.result && { liveCallStack: live.result }),
2509
+ };
1335
2510
  }
1336
- try {
2511
+ if (result) return result;
2512
+ const addLiveState = () => {
2513
+ if (liveness && source && is174) stateWriter?.writeStuttering(source);
1337
2514
  const accepted = liveness?.addState(index, state, liveSuccessors);
1338
- current.livenessSource = -1;
1339
- if (!accepted) return undefined;
2515
+ if (!liveness || !accepted) return undefined;
2516
+ const steps = getPathSteps(accepted);
2517
+ const properties = getViolatedProperties(
2518
+ liveness,
2519
+ steps.map((step) => step.state),
2520
+ steps.length - 1,
2521
+ );
1340
2522
  return reportViolation("property-violation", {
1341
- name: accepted.name,
1342
- trace: getPathTrace(accepted.path),
2523
+ name: properties[0],
2524
+ properties,
2525
+ ...toTrace(steps, accepted, { known: 0 }),
2526
+ });
2527
+ };
2528
+ if (successorCount === 0 && config.checkDeadlock) {
2529
+ const deadlock = reportViolation("deadlock", { name: "deadlock", ...getStateTrace(index) });
2530
+ // TLC's worker still adds the deadlocked state to the behavior graph after it reports the
2531
+ // deadlock, and reports a temporal property that this violates. Then it counts the state as
2532
+ // expanded.
2533
+ const live = getOutput(() => {
2534
+ try {
2535
+ return { additional: addLiveState()?.violation };
2536
+ } catch (error) {
2537
+ if (!(error instanceof TlaEvaluationError)) throw error;
2538
+ return { isFailed: true, callStack: getLiveCallStack(index, liveSuccessors) };
2539
+ }
1343
2540
  });
2541
+ const reported = deadlock.violation
2542
+ ? { ...deadlock, violation: appendTraceOutput(deadlock.violation, live.lines) }
2543
+ : deadlock;
2544
+ // An error in adding the state stops TLC 1.7.4's worker before it counts the state.
2545
+ const counted = withOutDegrees(
2546
+ reported,
2547
+ live.result.isFailed ? getFailureOutDegrees() : getPartialOutDegrees(),
2548
+ );
2549
+ if (live.result.additional)
2550
+ return { ...counted, additionalViolation: live.result.additional };
2551
+ return live.result.callStack ? { ...counted, liveCallStack: live.result.callStack } : counted;
2552
+ }
2553
+ try {
2554
+ return addLiveState();
1344
2555
  } catch (error) {
1345
- return toFailure(error, getStateTrace(index), undefined, getPartialOutDegrees());
2556
+ // TLC 1.7.4's worker reports an error in adding a state to the behavior graph as an exception
2557
+ // it didn't expect, without the trace or a call stack, and exits as for any general error.
2558
+ if (is174 && error instanceof TlaEvaluationError) {
2559
+ const unexpected = new TlaEvaluationError(
2560
+ `${isEvalException(error) ? UNEXPECTED_EVAL_EXCEPTION : UNEXPECTED_EXCEPTION}${error.message}`,
2561
+ );
2562
+ return toFailure(
2563
+ setExitCode(unexpected, EXIT_STATUS.error),
2564
+ { trace: [] },
2565
+ { outDegrees: getFailureOutDegrees() },
2566
+ );
2567
+ }
2568
+ // TLC's Worker#doNextCheckLiveness adds the state again to find the call stack, prints it
2569
+ // before the error, and reports the error as one in computing next states.
2570
+ const replay = getReplayFailure((tracing) =>
2571
+ liveness?.addState(index, state, liveSuccessors, tracing),
2572
+ );
2573
+ return toFailure(error, getStateTrace(index), {
2574
+ outDegrees: getFailureOutDegrees(),
2575
+ callStack: replay?.callStack.length ? replay.callStack : undefined,
2576
+ isNextState: true,
2577
+ isCallStackFirst: true,
2578
+ });
2579
+ }
2580
+ };
2581
+ // TLC's Liveness#printStutteringCounterExampleWarning.
2582
+ const getStutteringWarning = () => {
2583
+ const name = config.specification;
2584
+ const book =
2585
+ "(compare Chapter 8, page 87ff of Specifying Systems at https://lamport.azurewebsites.net/tla/book.html).";
2586
+ if (name === undefined) {
2587
+ return {
2588
+ code: MESSAGE_CODE.noSpecificationButProperty,
2589
+ 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}`,
2590
+ };
1346
2591
  }
2592
+ const range = getDefinition(name, environment)?.location.range;
2593
+ if (spec.temporals.length > 0 || !range) return undefined;
2594
+ return {
2595
+ code: MESSAGE_CODE.noFairnessButProperty,
2596
+ 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}`,
2597
+ };
1347
2598
  };
1348
- const reportLasso = (lasso: Lasso) => {
2599
+ // TLC names the properties and the step back into the cycle from the states it prints.
2600
+ const reportLasso = (checker: LivenessChecker, lasso: Lasso) => {
1349
2601
  const path = [...lasso.prefix, ...lasso.cycle];
1350
- const trace = getPathTrace(path, lasso.prefix.length);
1351
- const back = path[lasso.prefix.length];
2602
+ const loopStart = lasso.prefix.length;
2603
+ const steps = getPathSteps(path, loopStart);
2604
+ const trace = toTrace(steps, path, { loopStart, known: 0 }).trace;
2605
+ const properties = getViolatedProperties(
2606
+ checker,
2607
+ steps.map((step) => step.state),
2608
+ loopStart,
2609
+ );
2610
+ const back = path[loopStart];
1352
2611
  const last = path[path.length - 1];
1353
- const loopLabel =
1354
- back === last ? undefined : withoutOutput(() => getLabel(last, states[last], states[back]));
2612
+ const lastState = steps[steps.length - 1].state;
2613
+ const loop =
2614
+ back === last
2615
+ ? { result: undefined, lines: [] }
2616
+ : getOutput(() => findStepAction(last, lastState, states[back], false));
2617
+ const isStutteringWarned = back === last && lasso.isCycleConstrained;
1355
2618
  return reportViolation(
1356
2619
  "liveness-violation",
1357
- { name: lasso.name, trace, loopStart: lasso.prefix.length, loopLabel },
2620
+ {
2621
+ name: properties[0],
2622
+ properties,
2623
+ trace,
2624
+ traceOutput: loop.lines,
2625
+ loopStart,
2626
+ loopLabel: loop.result && getActionLabel(loop.result, options.version),
2627
+ warning: isStutteringWarned ? getStutteringWarning() : undefined,
2628
+ },
1358
2629
  () =>
1359
2630
  back === last
1360
- ? trace[trace.length - 1].action
1361
- : getTraceSuccessors(states[last]).find((successor) =>
1362
- isSameState(successor.state, states[back]),
1363
- )?.action,
2631
+ ? getStepAction(trace[trace.length - 1])
2632
+ : loop.result
2633
+ ? toActionValue(loop.result)
2634
+ : createActionRecord(findSuccessorWithFingerprint(lastState, back)?.action),
1364
2635
  );
1365
2636
  };
1366
2637
  const isPeriodic = liveness !== undefined && options.livenessCheck !== "final";
@@ -1368,44 +2639,78 @@ export const checkSequentially = (options: CheckOptions): CheckResult => {
1368
2639
  const periodic = { at: startedAt + PERIODIC_START, size: 1, time: 0 };
1369
2640
  const findPeriodicViolation = (expanded: number) => {
1370
2641
  const now = performance.now();
1371
- periodic.at = now + PROGRESS_INTERVAL;
1372
2642
  const isGrown = (expanded - periodic.size) / periodic.size > LIVENESS_GROWTH;
1373
2643
  if (!isGrown || periodic.time > (now - startedAt) * LIVENESS_RATIO) return undefined;
1374
2644
  periodic.size = expanded;
1375
- const lasso = liveness?.findViolation();
1376
- current.livenessSource = -1;
2645
+ if (!liveness) return undefined;
2646
+ options.onProgress?.({
2647
+ kind: "liveness-started",
2648
+ branches: liveness.branches,
2649
+ isComplete: false,
2650
+ states: expanded,
2651
+ statistics: createResult("success"),
2652
+ });
2653
+ const lasso = liveness.findViolation();
2654
+ if (!lasso) options.onProgress?.({ kind: "liveness-finished" });
1377
2655
  periodic.time += performance.now() - now;
1378
2656
  return lasso;
1379
2657
  };
1380
- setNextStatePhase(true);
1381
2658
  for (let index = 0; index < states.length && !runtime.isStopped; index++) {
1382
2659
  current.index = index;
1383
2660
  current.candidate = undefined;
1384
2661
  runtime.queueSize = states.length - index - 1;
1385
2662
  current.isExpanding = true;
2663
+ const liveSuccessors: LiveSuccessor[] = [];
1386
2664
  try {
1387
- outcome.result = expandState(index);
2665
+ outcome.result = expandState(index, liveSuccessors);
1388
2666
  } catch (error) {
1389
- outcome.result = toFailure(error, getStateTrace(index));
2667
+ outcome.result =
2668
+ error instanceof TlaIncompleteSuccessorError
2669
+ ? reportIncompleteSuccessor(index, error)
2670
+ : reportNextStateFailure(error, index, liveSuccessors);
1390
2671
  }
1391
2672
  if (outcome.result) return outcome.result;
1392
2673
  outDegrees[getOutDegreeBucket()]++;
1393
2674
  expansion.newStates = 0;
1394
- if (isPeriodic && performance.now() >= periodic.at) {
1395
- const lasso = findPeriodicViolation(index + 1);
1396
- if (lasso) return reportLasso(lasso);
2675
+ // TLC's AbstractChecker#runTLC checks the liveness properties on the state graph so far, then
2676
+ // reports how far the search got.
2677
+ if ((isPeriodic || options.onProgress) && performance.now() >= periodic.at) {
2678
+ periodic.at = performance.now() + PROGRESS_INTERVAL;
2679
+ const lasso = isPeriodic ? findPeriodicViolation(index + 1) : undefined;
2680
+ if (liveness && lasso) return reportLasso(liveness, lasso);
2681
+ options.onProgress?.({ kind: "progress", statistics: createResult("success") });
1397
2682
  }
1398
2683
  }
1399
2684
 
1400
2685
  current.index = -1;
1401
2686
  current.candidate = undefined;
2687
+ if (liveness) {
2688
+ options.onProgress?.({
2689
+ kind: "liveness-started",
2690
+ branches: liveness.branches,
2691
+ isComplete: true,
2692
+ states: runtime.distinctStates,
2693
+ statistics: createResult("success"),
2694
+ });
2695
+ }
1402
2696
  const lasso = liveness?.findViolation();
1403
- current.livenessSource = -1;
1404
- if (lasso) return reportLasso(lasso);
2697
+ if (liveness && lasso) return reportLasso(liveness, lasso);
1405
2698
 
1406
- const postconditionViolation = search.findPostconditionViolation();
1407
- if (postconditionViolation) {
1408
- return createResult("postcondition-violation", { ...postconditionViolation, trace: [] });
2699
+ // TLC finishes the check of the temporal properties before it checks the postconditions.
2700
+ if (liveness) options.onProgress?.({ kind: "liveness-finished" });
2701
+ try {
2702
+ const postcondition = search.findPostconditionViolation();
2703
+ if (postcondition) {
2704
+ return createResult("postcondition-violation", {
2705
+ name: postcondition.name,
2706
+ message: postcondition.message,
2707
+ counts: postcondition.counts,
2708
+ trace: [],
2709
+ postcondition,
2710
+ });
2711
+ }
2712
+ } catch (error) {
2713
+ return toFailure(error, { trace: [] });
1409
2714
  }
1410
2715
  return createSuccess();
1411
2716
  };