tla-ts 0.0.9 → 0.0.10-dev.b4a856304

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (390) hide show
  1. package/README.md +29 -1
  2. package/dist/compile.cjs +23 -0
  3. package/dist/compile.js +23 -0
  4. package/dist/deciders.cjs +28 -28
  5. package/dist/deciders.js +43 -43
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +72 -10
  8. package/dist/index.d.ts +72 -10
  9. package/dist/index.js +1 -1
  10. package/dist/parallel-worker.cjs +1 -1
  11. package/dist/parallel-worker.js +1 -1
  12. package/dist/prove-worker.cjs +1 -1
  13. package/dist/prove-worker.js +1 -1
  14. package/dist/prove.cjs +116 -36
  15. package/dist/prove.js +116 -36
  16. package/dist/run.cjs +143 -31
  17. package/dist/run.js +143 -31
  18. package/dist/tlapm.cjs +2 -2
  19. package/dist/tlapm.js +2 -2
  20. package/dist/transfer.cjs +128 -103
  21. package/dist/transfer.js +128 -103
  22. package/dist/worker.cjs +7 -7
  23. package/dist/worker.js +7 -7
  24. package/package.json +3 -1
  25. package/src/ast.ts +7 -21
  26. package/src/bags.ts +99 -99
  27. package/src/builtins.ts +44 -75
  28. package/src/bundled-modules.ts +1 -8
  29. package/src/check.ts +576 -300
  30. package/src/cli/options.ts +11 -6
  31. package/src/cli/run.ts +2 -2
  32. package/src/cli/runtime-invariants.ts +135 -0
  33. package/src/cli/shared.ts +20 -9
  34. package/src/cli/tlapm.ts +0 -12
  35. package/src/cli/tlc-arguments.ts +646 -0
  36. package/src/cli/tlc-usage.ts +362 -0
  37. package/src/cli/tlc.ts +538 -220
  38. package/src/cli/typescript.ts +23 -0
  39. package/src/cli/xml-exporter.ts +4 -16
  40. package/src/cli.ts +0 -1
  41. package/src/codegen.ts +191 -64
  42. package/src/config.ts +140 -109
  43. package/src/coverage.ts +837 -0
  44. package/src/dependencies.ts +6 -40
  45. package/src/dfid.ts +618 -0
  46. package/src/environment.ts +240 -118
  47. package/src/errors.ts +70 -55
  48. package/src/evaluate.ts +630 -297
  49. package/src/exit-codes.ts +37 -3
  50. package/src/fingerprints.ts +10 -10
  51. package/src/index.ts +3 -0
  52. package/src/instances.ts +79 -11
  53. package/src/java-overrides.ts +2 -12
  54. package/src/json-reader.ts +456 -0
  55. package/src/json.ts +262 -139
  56. package/src/levels.ts +2 -3
  57. package/src/lexer.ts +17 -26
  58. package/src/liveness-checker.ts +10 -18
  59. package/src/liveness.ts +121 -49
  60. package/src/obligations/action.ts +4 -28
  61. package/src/obligations/anonymize.ts +84 -80
  62. package/src/obligations/equality.ts +1 -1
  63. package/src/obligations/expression.ts +2 -19
  64. package/src/obligations/format.ts +1 -9
  65. package/src/obligations/generate.ts +1 -11
  66. package/src/obligations/index.ts +0 -11
  67. package/src/obligations/levels.ts +4 -8
  68. package/src/obligations/module.ts +1 -15
  69. package/src/obligations/normalize.ts +5 -24
  70. package/src/obligations/operators.ts +1 -2
  71. package/src/obligations/pragma.ts +1 -10
  72. package/src/obligations/printer.ts +47 -46
  73. package/src/obligations/proof.ts +1 -5
  74. package/src/obligations/regroup.ts +1 -4
  75. package/src/obligations/simplify.ts +3 -14
  76. package/src/obligations/source.ts +1 -21
  77. package/src/obligations/subexpression.ts +5 -11
  78. package/src/obligations/substitution.ts +1 -3
  79. package/src/obligations/temporal.ts +8 -14
  80. package/src/obligations/tuples.ts +3 -9
  81. package/src/parallel-worker.ts +29 -39
  82. package/src/parallel.ts +29 -13
  83. package/src/parser.ts +436 -90
  84. package/src/pcal/ast.ts +7 -28
  85. package/src/pcal/parse.ts +11 -39
  86. package/src/pcal/tokenize.ts +4 -20
  87. package/src/pcal/translate.ts +10 -42
  88. package/src/pcal/validate.ts +3 -21
  89. package/src/pretty-print.ts +1 -2
  90. package/src/prover/decide-pool.ts +5 -10
  91. package/src/prover/deciders.ts +0 -4
  92. package/src/prover/first-order.ts +0 -11
  93. package/src/prover/isabelle/decide.ts +0 -6
  94. package/src/prover/isabelle/encode.ts +11 -23
  95. package/src/prover/isabelle/isar/inner-syntax.ts +108 -114
  96. package/src/prover/isabelle/isar/method.ts +25 -38
  97. package/src/prover/isabelle/isar/proof.ts +1 -10
  98. package/src/prover/isabelle/isar/statement.ts +1 -6
  99. package/src/prover/isabelle/isar/theory.ts +15 -26
  100. package/src/prover/isabelle/isar/type-check.ts +11 -25
  101. package/src/prover/isabelle/provers/blast/blast.ts +10 -41
  102. package/src/prover/isabelle/provers/blast/branch.ts +1 -32
  103. package/src/prover/isabelle/provers/blast/prove.ts +1 -35
  104. package/src/prover/isabelle/provers/blast/rules.ts +6 -44
  105. package/src/prover/isabelle/provers/blast/state.ts +2 -28
  106. package/src/prover/isabelle/provers/blast/term.ts +9 -36
  107. package/src/prover/isabelle/provers/clasimp.ts +1 -13
  108. package/src/prover/isabelle/provers/classical.ts +14 -42
  109. package/src/prover/isabelle/provers/hypsubst.ts +11 -25
  110. package/src/prover/isabelle/pure/bicompose.ts +16 -13
  111. package/src/prover/isabelle/pure/consts.ts +1 -7
  112. package/src/prover/isabelle/pure/conv.ts +1 -9
  113. package/src/prover/isabelle/pure/drule.ts +24 -40
  114. package/src/prover/isabelle/pure/envir.ts +3 -52
  115. package/src/prover/isabelle/pure/goal.ts +1 -7
  116. package/src/prover/isabelle/pure/interrupt.ts +0 -5
  117. package/src/prover/isabelle/pure/list.ts +0 -3
  118. package/src/prover/isabelle/pure/logic.ts +1 -14
  119. package/src/prover/isabelle/pure/name.ts +2 -9
  120. package/src/prover/isabelle/pure/net.ts +3 -59
  121. package/src/prover/isabelle/pure/object-logic.ts +3 -10
  122. package/src/prover/isabelle/pure/pattern.ts +2 -19
  123. package/src/prover/isabelle/pure/raw-simplifier.ts +13 -49
  124. package/src/prover/isabelle/pure/rewriter.ts +26 -58
  125. package/src/prover/isabelle/pure/search.ts +3 -10
  126. package/src/prover/isabelle/pure/seq.ts +1 -10
  127. package/src/prover/isabelle/pure/simplifier.ts +4 -12
  128. package/src/prover/isabelle/pure/table.ts +1 -31
  129. package/src/prover/isabelle/pure/tactic.ts +12 -22
  130. package/src/prover/isabelle/pure/tactical.ts +6 -12
  131. package/src/prover/isabelle/pure/term-ord.ts +2 -6
  132. package/src/prover/isabelle/pure/term.ts +2 -43
  133. package/src/prover/isabelle/pure/thm.ts +13 -36
  134. package/src/prover/isabelle/pure/type.ts +2 -15
  135. package/src/prover/isabelle/pure/unify.ts +20 -30
  136. package/src/prover/isabelle/pure/variable.ts +3 -7
  137. package/src/prover/isabelle/tla/classical-setup.ts +9 -19
  138. package/src/prover/isabelle/tla/context.ts +8 -16
  139. package/src/prover/isabelle/tla/logic.ts +4 -11
  140. package/src/prover/isabelle/tla/simpdata.ts +46 -34
  141. package/src/prover/isabelle/tools/intuitionistic.ts +1 -10
  142. package/src/prover/ocaml.ts +0 -6
  143. package/src/prover/prep/action.ts +4 -36
  144. package/src/prover/prep/enabled-axioms.ts +12 -19
  145. package/src/prover/prep/fingerprint.ts +0 -16
  146. package/src/prover/prep/level-comparison.ts +8 -12
  147. package/src/prover/prep/md5.ts +0 -2
  148. package/src/prover/prep/methods.ts +9 -36
  149. package/src/prover/prep/normalize.ts +4 -28
  150. package/src/prover/prove-worker.ts +0 -2
  151. package/src/prover/prove.ts +0 -36
  152. package/src/prover/ptl/decide.ts +7 -12
  153. package/src/prover/ptl/encode.ts +14 -36
  154. package/src/prover/ptl/sat.ts +24 -32
  155. package/src/prover/ptl/tableau.ts +12 -26
  156. package/src/prover/smt/axioms.ts +0 -7
  157. package/src/prover/smt/context.ts +19 -26
  158. package/src/prover/smt/data.ts +51 -54
  159. package/src/prover/smt/encode.ts +14 -35
  160. package/src/prover/smt/extensionality.ts +0 -10
  161. package/src/prover/smt/flatten.ts +3 -22
  162. package/src/prover/smt/format.ts +5 -10
  163. package/src/prover/smt/instances.ts +0 -10
  164. package/src/prover/smt/rewrite.ts +66 -101
  165. package/src/prover/smt/solver/act-cache.ts +0 -15
  166. package/src/prover/smt/solver/arith-rewriter.ts +3 -48
  167. package/src/prover/smt/solver/array.ts +1 -3
  168. package/src/prover/smt/solver/asserted-formulas.ts +1 -43
  169. package/src/prover/smt/solver/ast-lt.ts +1 -11
  170. package/src/prover/smt/solver/ast-util.ts +1 -6
  171. package/src/prover/smt/solver/ast.ts +1 -143
  172. package/src/prover/smt/solver/auf-solver.ts +6 -39
  173. package/src/prover/smt/solver/case-split-queue.ts +1 -9
  174. package/src/prover/smt/solver/cg-table.ts +1 -18
  175. package/src/prover/smt/solver/clause.ts +1 -27
  176. package/src/prover/smt/solver/conflict-resolution.ts +0 -9
  177. package/src/prover/smt/solver/context.ts +4 -61
  178. package/src/prover/smt/solver/ctx-simplify.ts +14 -41
  179. package/src/prover/smt/solver/der.ts +2 -21
  180. package/src/prover/smt/solver/dyn-ack.ts +1 -11
  181. package/src/prover/smt/solver/e-matching.ts +3 -34
  182. package/src/prover/smt/solver/enode.ts +1 -21
  183. package/src/prover/smt/solver/expr-ref.ts +1 -5
  184. package/src/prover/smt/solver/expr-safe-replace.ts +0 -5
  185. package/src/prover/smt/solver/fingerprints.ts +1 -12
  186. package/src/prover/smt/solver/flat-literals.ts +1 -9
  187. package/src/prover/smt/solver/goal.ts +2 -14
  188. package/src/prover/smt/solver/hash.ts +0 -8
  189. package/src/prover/smt/solver/hashtable.ts +1 -12
  190. package/src/prover/smt/solver/internalizer.ts +6 -98
  191. package/src/prover/smt/solver/lbool.ts +1 -2
  192. package/src/prover/smt/solver/literal.ts +0 -3
  193. package/src/prover/smt/solver/lp/bound-propagator.ts +8 -26
  194. package/src/prover/smt/solver/lp/constraints.ts +2 -8
  195. package/src/prover/smt/solver/lp/containers.ts +12 -30
  196. package/src/prover/smt/solver/lp/core-solver.ts +10 -31
  197. package/src/prover/smt/solver/lp/cross-nested.ts +6 -20
  198. package/src/prover/smt/solver/lp/dep-intervals.ts +7 -22
  199. package/src/prover/smt/solver/lp/dependency.ts +1 -4
  200. package/src/prover/smt/solver/lp/dioph-eq.ts +12 -98
  201. package/src/prover/smt/solver/lp/explanation.ts +1 -6
  202. package/src/prover/smt/solver/lp/gomory.ts +9 -22
  203. package/src/prover/smt/solver/lp/hnf-cutter.ts +17 -23
  204. package/src/prover/smt/solver/lp/hnf.ts +11 -26
  205. package/src/prover/smt/solver/lp/int-cube.ts +15 -36
  206. package/src/prover/smt/solver/lp/int-solver.ts +4 -34
  207. package/src/prover/smt/solver/lp/lar-solver.ts +32 -81
  208. package/src/prover/smt/solver/lp/lar-term.ts +1 -5
  209. package/src/prover/smt/solver/lp/lp-settings.ts +1 -14
  210. package/src/prover/smt/solver/lp/maximize-term.ts +20 -45
  211. package/src/prover/smt/solver/lp/nex-creator.ts +5 -28
  212. package/src/prover/smt/solver/lp/nex.ts +1 -6
  213. package/src/prover/smt/solver/lp/nla-backoff.ts +1 -4
  214. package/src/prover/smt/solver/lp/nla-basics.ts +5 -30
  215. package/src/prover/smt/solver/lp/nla-core.ts +35 -130
  216. package/src/prover/smt/solver/lp/nla-divisions.ts +32 -42
  217. package/src/prover/smt/solver/lp/nla-emonics.ts +4 -21
  218. package/src/prover/smt/solver/lp/nla-factorization.ts +1 -4
  219. package/src/prover/smt/solver/lp/nla-grobner.ts +15 -69
  220. package/src/prover/smt/solver/lp/nla-horner.ts +3 -11
  221. package/src/prover/smt/solver/lp/nla-intervals.ts +2 -12
  222. package/src/prover/smt/solver/lp/nla-monomial-bounds.ts +16 -41
  223. package/src/prover/smt/solver/lp/nla-monotone.ts +2 -6
  224. package/src/prover/smt/solver/lp/nla-order.ts +2 -13
  225. package/src/prover/smt/solver/lp/nla-patcher.ts +4 -7
  226. package/src/prover/smt/solver/lp/nla-tangents.ts +1 -9
  227. package/src/prover/smt/solver/lp/nla-throttle.ts +1 -6
  228. package/src/prover/smt/solver/lp/nla-types.ts +1 -11
  229. package/src/prover/smt/solver/lp/nla-var-eqs.ts +4 -25
  230. package/src/prover/smt/solver/lp/nra-solver.ts +5 -52
  231. package/src/prover/smt/solver/lp/numeric-pair.ts +1 -4
  232. package/src/prover/smt/solver/lp/pdd-interval.ts +1 -3
  233. package/src/prover/smt/solver/lp/pdd-simplifier.ts +2 -14
  234. package/src/prover/smt/solver/lp/pdd-solver.ts +4 -33
  235. package/src/prover/smt/solver/lp/pdd.ts +7 -70
  236. package/src/prover/smt/solver/lp/random-updater.ts +1 -8
  237. package/src/prover/smt/solver/lp/static-matrix.ts +9 -19
  238. package/src/prover/smt/solver/lp/union-find.ts +1 -6
  239. package/src/prover/smt/solver/mam-compiler.ts +14 -56
  240. package/src/prover/smt/solver/mam-interpreter.ts +1 -21
  241. package/src/prover/smt/solver/maximize-ac-sharing.ts +2 -17
  242. package/src/prover/smt/solver/model-checker.ts +2 -36
  243. package/src/prover/smt/solver/model-evaluator.ts +3 -29
  244. package/src/prover/smt/solver/model-finder.ts +3 -15
  245. package/src/prover/smt/solver/model-generator.ts +1 -12
  246. package/src/prover/smt/solver/model-macro-solver.ts +12 -69
  247. package/src/prover/smt/solver/nlsat/algebraic.ts +55 -151
  248. package/src/prover/smt/solver/nlsat/atoms.ts +5 -19
  249. package/src/prover/smt/solver/nlsat/evaluator.ts +17 -22
  250. package/src/prover/smt/solver/nlsat/explain.ts +3 -47
  251. package/src/prover/smt/solver/nlsat/interval-set.ts +9 -50
  252. package/src/prover/smt/solver/nlsat/levelwise.ts +48 -129
  253. package/src/prover/smt/solver/nlsat/mpbq.ts +3 -14
  254. package/src/prover/smt/solver/nlsat/polynomial.ts +17 -156
  255. package/src/prover/smt/solver/nlsat/solver.ts +7 -67
  256. package/src/prover/smt/solver/nlsat/types.ts +1 -8
  257. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +1 -44
  258. package/src/prover/smt/solver/nlsat/upolynomial.ts +11 -92
  259. package/src/prover/smt/solver/nnf.ts +3 -38
  260. package/src/prover/smt/solver/pattern-inference.ts +2 -15
  261. package/src/prover/smt/solver/poly-rewriter.ts +3 -23
  262. package/src/prover/smt/solver/propagate-values.ts +1 -10
  263. package/src/prover/smt/solver/proto-model.ts +3 -48
  264. package/src/prover/smt/solver/pull-quant.ts +1 -12
  265. package/src/prover/smt/solver/qe-lite-der.ts +1 -29
  266. package/src/prover/smt/solver/qe-lite-fm.ts +2 -25
  267. package/src/prover/smt/solver/qe-lite.ts +3 -33
  268. package/src/prover/smt/solver/qi-queue.ts +1 -16
  269. package/src/prover/smt/solver/quant-tactics.ts +5 -22
  270. package/src/prover/smt/solver/quantifier-analyzer.ts +17 -37
  271. package/src/prover/smt/solver/quantifier-manager.ts +1 -8
  272. package/src/prover/smt/solver/random-gen.ts +1 -2
  273. package/src/prover/smt/solver/rational.ts +1 -8
  274. package/src/prover/smt/solver/ref-vector.ts +1 -6
  275. package/src/prover/smt/solver/relevancy.ts +2 -15
  276. package/src/prover/smt/solver/rewriter-tpl.ts +3 -147
  277. package/src/prover/smt/solver/rewriter.ts +3 -85
  278. package/src/prover/smt/solver/rlimit.ts +2 -20
  279. package/src/prover/smt/solver/smtlib-parser.ts +2 -37
  280. package/src/prover/smt/solver/solver.ts +23 -34
  281. package/src/prover/smt/solver/sort.ts +1 -5
  282. package/src/prover/smt/solver/sticky-generations.ts +0 -5
  283. package/src/prover/smt/solver/theory-lra-axioms.ts +3 -24
  284. package/src/prover/smt/solver/theory-lra-bounds.ts +0 -5
  285. package/src/prover/smt/solver/theory-lra-final-check.ts +4 -22
  286. package/src/prover/smt/solver/theory-lra-internalize.ts +1 -27
  287. package/src/prover/smt/solver/theory-lra-model.ts +4 -19
  288. package/src/prover/smt/solver/theory-lra-propagate.ts +1 -15
  289. package/src/prover/smt/solver/theory-lra-state.ts +3 -8
  290. package/src/prover/smt/solver/theory-lra.ts +1 -8
  291. package/src/prover/smt/solver/var-subst.ts +2 -26
  292. package/src/prover/smt/table.ts +0 -8
  293. package/src/prover/tlapm/cache.ts +20 -25
  294. package/src/prover/tlapm/ocaml-marshal.ts +19 -21
  295. package/src/prover/tlapm/tlapm.ts +12 -17
  296. package/src/prover/verdict.ts +0 -2
  297. package/src/prover/zenon/check/check.ts +0 -9
  298. package/src/prover/zenon/check/definitions.ts +5 -15
  299. package/src/prover/zenon/check/equality.ts +0 -8
  300. package/src/prover/zenon/check/functions.ts +0 -4
  301. package/src/prover/zenon/check/keys.ts +0 -7
  302. package/src/prover/zenon/check/propositional.ts +0 -3
  303. package/src/prover/zenon/check/records.ts +0 -5
  304. package/src/prover/zenon/check/relations.ts +0 -13
  305. package/src/prover/zenon/check/rewrites.ts +0 -6
  306. package/src/prover/zenon/check/sets.ts +0 -3
  307. package/src/prover/zenon/check/terms.ts +0 -17
  308. package/src/prover/zenon/check/tla.ts +0 -6
  309. package/src/prover/zenon/decide.ts +0 -12
  310. package/src/prover/zenon/encode.ts +1 -8
  311. package/src/prover/zenon/eqrel.ts +0 -13
  312. package/src/prover/zenon/equality-rules.ts +0 -4
  313. package/src/prover/zenon/expr.ts +1 -26
  314. package/src/prover/zenon/index-table.ts +17 -38
  315. package/src/prover/zenon/isar-case.ts +9 -19
  316. package/src/prover/zenon/isar.ts +1 -29
  317. package/src/prover/zenon/limits.ts +0 -4
  318. package/src/prover/zenon/llproof.ts +0 -9
  319. package/src/prover/zenon/mltoll.ts +54 -76
  320. package/src/prover/zenon/node.ts +1 -11
  321. package/src/prover/zenon/ocaml.ts +1 -17
  322. package/src/prover/zenon/parse.ts +2 -7
  323. package/src/prover/zenon/phrase.ts +1 -11
  324. package/src/prover/zenon/proof.ts +0 -9
  325. package/src/prover/zenon/propositional-rules.ts +0 -5
  326. package/src/prover/zenon/rules.ts +2 -6
  327. package/src/prover/zenon/search.ts +1 -17
  328. package/src/prover/zenon/tla/functions.ts +57 -29
  329. package/src/prover/zenon/tla/llproof.ts +63 -70
  330. package/src/prover/zenon/tla/records.ts +56 -27
  331. package/src/prover/zenon/tla/rewrites.ts +12 -19
  332. package/src/prover/zenon/tla/sets.ts +68 -39
  333. package/src/prover/zenon/tla/terms.ts +0 -6
  334. package/src/prover/zenon/tla/tla.ts +59 -58
  335. package/src/randomization.ts +84 -35
  336. package/src/resolve.ts +18 -60
  337. package/src/runtime.ts +11 -4
  338. package/src/sany/builtins.ts +3 -4
  339. package/src/sany/generator.ts +119 -169
  340. package/src/sany/levels.ts +6 -30
  341. package/src/sany/lexer.ts +7 -23
  342. package/src/sany/linter.ts +1 -8
  343. package/src/sany/modules.ts +1 -5
  344. package/src/sany/nodes.ts +0 -31
  345. package/src/sany/parse-error.ts +39 -117
  346. package/src/sany/report.ts +29 -63
  347. package/src/sany/selectors.ts +15 -39
  348. package/src/sany/source.ts +1 -17
  349. package/src/sany/xml.ts +13 -63
  350. package/src/search.ts +494 -154
  351. package/src/simulate.ts +694 -0
  352. package/src/spec-description.ts +166 -48
  353. package/src/standard-definitions.ts +2 -3
  354. package/src/standard-modules.ts +264 -68
  355. package/src/state-graph.ts +51 -18
  356. package/src/subexpressions.ts +31 -5
  357. package/src/substitution-levels.ts +2 -3
  358. package/src/successors.ts +267 -77
  359. package/src/symmetry.ts +31 -8
  360. package/src/tableau.ts +27 -24
  361. package/src/tlc/fingerprint.ts +183 -61
  362. package/src/tlc/jar-data.ts +113 -6
  363. package/src/tlc/messages.ts +122 -37
  364. package/src/tlc/order.ts +33 -38
  365. package/src/tlc/random.ts +16 -16
  366. package/src/tlc/replay.ts +563 -211
  367. package/src/tlc/summary.ts +2 -4
  368. package/src/tlc/tlc-operators.ts +81 -36
  369. package/src/tlc/tlcext-operators.ts +138 -117
  370. package/src/tlc/trace-spec.ts +273 -0
  371. package/src/tlc/value-stream.ts +143 -0
  372. package/src/tlc/version.ts +2 -4
  373. package/src/transfer.ts +22 -25
  374. package/src/typescript/actions.ts +481 -0
  375. package/src/typescript/collections.ts +600 -0
  376. package/src/typescript/compile.ts +65 -0
  377. package/src/typescript/context.ts +94 -0
  378. package/src/typescript/emit.ts +121 -0
  379. package/src/typescript/expressions.ts +496 -0
  380. package/src/typescript/formula.ts +152 -0
  381. package/src/typescript/functions.ts +284 -0
  382. package/src/typescript/model.ts +163 -0
  383. package/src/typescript/names.ts +114 -0
  384. package/src/typescript/program.ts +48 -0
  385. package/src/typescript/properties.ts +139 -0
  386. package/src/typescript/scope.ts +112 -0
  387. package/src/typescript/steps.ts +165 -0
  388. package/src/typescript/types.ts +171 -0
  389. package/src/values.ts +826 -276
  390. package/src/worker.ts +7 -8
package/src/cli/tlc.ts CHANGED
@@ -1,9 +1,13 @@
1
1
  import {
2
+ appendFileSync,
3
+ closeSync,
2
4
  existsSync,
3
5
  mkdirSync,
6
+ openSync,
4
7
  readFileSync,
5
8
  readSync,
6
9
  realpathSync,
10
+ statSync,
7
11
  writeFileSync,
8
12
  } from "node:fs";
9
13
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
@@ -12,11 +16,15 @@ import { pathToFileURL } from "node:url";
12
16
  import { getHeapStatistics } from "node:v8";
13
17
  import { version } from "../../package.json";
14
18
  import type { Expression } from "../ast";
19
+ import type { CoverageReport } from "../coverage";
15
20
  import { describeRange } from "../evaluate";
16
21
  import type {
22
+ CheckOptions,
17
23
  CheckProgress,
18
24
  InitialStateViolation,
25
+ ModuleOperator,
19
26
  OutputLine,
27
+ Postcondition,
20
28
  CheckResult,
21
29
  CheckStatus,
22
30
  InitialStates,
@@ -25,11 +33,14 @@ import type {
25
33
  Violation,
26
34
  } from "../check";
27
35
  import { parseConfig } from "../config";
36
+ import { checkDepthFirst, type DepthFirstOutput } from "../dfid";
28
37
  import {
29
- getErrorExitCode,
38
+ TlaAliasFormatError,
30
39
  TlaConfigError,
31
40
  TlaError,
32
41
  TlaEvaluationError,
42
+ TlaFeatureUnsupportedError,
43
+ TlaMissingCheckpointError,
33
44
  TlaSyntaxError,
34
45
  getUnexpectedException,
35
46
  UNEXPECTED_EXCEPTION,
@@ -37,7 +48,8 @@ import {
37
48
  } from "../errors";
38
49
  import { EXIT_STATUS, setExitCode } from "../exit-codes";
39
50
  import { check } from "../parallel";
40
- import { parseModule } from "../parser";
51
+ import { extractModule, parseModule } from "../parser";
52
+ import { simulate, type SimulationOutput, type SimulationStatistics } from "../simulate";
41
53
  import type { StateDump } from "../state-graph";
42
54
  import {
43
55
  formatProbability,
@@ -45,7 +57,11 @@ import {
45
57
  getOptimisticProbability,
46
58
  getOutDegreeSummary,
47
59
  } from "../tlc/summary";
48
- import { SANY_174_STANDARD_MODULES, SANY_STANDARD_MODULES } from "../sany/modules";
60
+ import {
61
+ getSanyStandardModules,
62
+ SANY_174_STANDARD_MODULES,
63
+ SANY_STANDARD_MODULES,
64
+ } from "../sany/modules";
49
65
  import { getSanyReport, type SanyModuleOrigin } from "../sany/report";
50
66
  import { getTlcFingerprint } from "../tlc/fingerprint";
51
67
  import type { TlcVersion } from "../tlc/version";
@@ -60,13 +76,16 @@ import {
60
76
  type MessagePrinter,
61
77
  } from "../tlc/messages";
62
78
  import { formatState } from "../values";
63
- import { CHECK_COMMAND, USAGE, type ParsedArgs } from "./options";
79
+ import { addRuntimeInvariants } from "./runtime-invariants";
80
+ import { parseTlcArguments, type TlcArguments } from "./tlc-arguments";
81
+ import { getTlcUsage } from "./tlc-usage";
64
82
  import {
65
83
  createModuleLoader,
66
84
  findModuleFile,
67
85
  getInputPaths,
68
86
  getToolsJar,
69
87
  getStandardModulesUrl,
88
+ getTopLevelExitCode,
70
89
  printError,
71
90
  printMissingFile,
72
91
  printMissingFile174,
@@ -75,6 +94,7 @@ import {
75
94
  toLibraryPath,
76
95
  type JavaProperties,
77
96
  } from "./shared";
97
+ import { writeTypeScriptSpec } from "./typescript";
78
98
 
79
99
  const EXIT_CODES: Record<CheckStatus, number> = {
80
100
  success: EXIT_STATUS.success,
@@ -87,19 +107,12 @@ const EXIT_CODES: Record<CheckStatus, number> = {
87
107
  error: EXIT_STATUS.error,
88
108
  };
89
109
 
90
- const isJavaLong = (text: string) =>
91
- /^[+-]?\d+$/.test(text) && BigInt.asIntN(64, BigInt(text)) === BigInt(text);
92
-
93
- const getWorkerCount = (values: string[] | undefined) => {
94
- if (!values) return 1;
95
- return values[0] === "auto"
96
- ? availableParallelism()
97
- : Math.max(1, Number.parseInt(values[0], 10) || 1);
110
+ const checkNotDirectory = (path: string) => {
111
+ if (statSync(path, { throwIfNoEntry: false })?.isDirectory()) {
112
+ throw new TlaEvaluationError(`${path} (Is a directory)`);
113
+ }
98
114
  };
99
115
 
100
- const UNSUPPORTED_DUMP_FORMATS = ["constrained", "stuttering", "strict"];
101
-
102
- // TLC names the file of a -dump by its format unless the name already ends that way.
103
116
  const getDumpPath = (path: string, extension: string) =>
104
117
  path.endsWith(extension) ? path : `${path}${extension}`;
105
118
 
@@ -112,6 +125,9 @@ const getStateDump = (values: string[]): StateDump => {
112
125
  colorize: format.includes("colorize"),
113
126
  actionLabels: format.includes("actionlabels"),
114
127
  snapshot: format.includes("snapshot"),
128
+ constrained: format.includes("constrained"),
129
+ stuttering: format.includes("stuttering"),
130
+ strict: format.includes("strict"),
115
131
  };
116
132
  };
117
133
 
@@ -136,7 +152,6 @@ const getInitialViolationHeadline = (
136
152
  text: `Property ${name} is violated by the initial state:`,
137
153
  };
138
154
 
139
- // What the spec prints as TLC rebuilds a trace, before it prints the states or after.
140
155
  const printTraceOutput = (printer: MessagePrinter, lines: OutputLine[] | undefined) =>
141
156
  lines?.forEach((line) => {
142
157
  if (typeof line === "string") return console.log(line);
@@ -151,24 +166,38 @@ const printTraceOutput = (printer: MessagePrinter, lines: OutputLine[] | undefin
151
166
  );
152
167
  });
153
168
 
169
+ interface TlcPrinter extends MessagePrinter {
170
+ isDiffTrace: boolean;
171
+ }
172
+
173
+ const BEHAVIOR = {
174
+ code: MESSAGE_CODE.behaviorUpToThisPoint,
175
+ text: "The behavior up to this point is:",
176
+ };
177
+
154
178
  const printTrace = (
155
- printer: MessagePrinter,
179
+ printer: TlcPrinter,
156
180
  trace: TraceStep[],
157
- heading: { code: number; text: string } = {
158
- code: MESSAGE_CODE.behaviorUpToThisPoint,
159
- text: "The behavior up to this point is:",
160
- },
181
+ heading: { code: number; text: string } = BEHAVIOR,
161
182
  isRebuiltAfterHeading = false,
183
+ isLastDiffed = heading !== BEHAVIOR,
162
184
  ) => {
163
185
  if (trace.length > 0) printer.print(heading.code, MESSAGE_LEVEL.error, heading.text);
164
- trace.forEach((step, index) => {
165
- if (index > 0 || isRebuiltAfterHeading) printTraceOutput(printer, step.output);
166
- printer.print(
167
- MESSAGE_CODE.statePrint2,
168
- MESSAGE_LEVEL.state,
169
- `${index + 1}: <${step.label ?? step.action ?? "Initial predicate"}>\n${formatState(step.state)}`,
170
- );
171
- });
186
+ try {
187
+ trace.forEach((step, index) => {
188
+ if (index > 0 || isRebuiltAfterHeading) printTraceOutput(printer, step.output);
189
+ const isDiffed =
190
+ printer.isDiffTrace && index > 0 && (isLastDiffed || index < trace.length - 1);
191
+ printer.print(
192
+ MESSAGE_CODE.statePrint2,
193
+ MESSAGE_LEVEL.state,
194
+ `${index + 1}: <${step.label ?? step.action ?? "Initial predicate"}>\n${formatState(step.state, isDiffed ? trace[index - 1].state : undefined)}`,
195
+ );
196
+ });
197
+ } catch (error) {
198
+ if (!(error instanceof TlaAliasFormatError)) throw error;
199
+ printer.print(MESSAGE_CODE.general, MESSAGE_LEVEL.error, error.message);
200
+ }
172
201
  };
173
202
 
174
203
  const COUNTER_EXAMPLE = {
@@ -176,7 +205,6 @@ const COUNTER_EXAMPLE = {
176
205
  text: "The following behavior constitutes a counter-example:\n",
177
206
  };
178
207
 
179
- // TLC 1.7.4 doesn't name the properties, and later versions name none when they can't tell which.
180
208
  const getTemporalHeadline = (names: string[], version: TlcVersion) =>
181
209
  version === "1.7.4" || names.length === 0
182
210
  ? "Temporal properties were violated.\n"
@@ -184,8 +212,6 @@ const getTemporalHeadline = (names: string[], version: TlcVersion) =>
184
212
  ? `Temporal property ${names[0]} was violated.\n`
185
213
  : `Temporal properties ${names.slice(0, -1).join(", ")}${names.length > 2 ? "," : ""} and ${names[names.length - 1]} were violated.\n`;
186
214
 
187
- // TLC's FingerprintException#getTrace: the range of each source, innermost first, skipping a
188
- // source the same as the one inside it.
189
215
  const formatFingerprintTrace = (sources: Expression[]) =>
190
216
  sources
191
217
  .filter((source, index) => source !== sources[index - 1])
@@ -193,8 +219,6 @@ const formatFingerprintTrace = (sources: Expression[]) =>
193
219
  .toReversed()
194
220
  .join("");
195
221
 
196
- // TLC's CallStack.toString: the range of each expression, skipping an expression that it evaluates
197
- // again right inside itself.
198
222
  const formatCallStack = (expressions: Expression[]) => {
199
223
  if (expressions.length === 0) return " The error call stack is empty.\n";
200
224
  const lines: string[] = [];
@@ -229,13 +253,10 @@ const printInitialStates = (printer: MessagePrinter, initialStates: InitialState
229
253
 
230
254
  interface Timing {
231
255
  startTime: number;
232
- // Whether TLC has printed that SANY finished.
233
256
  isParsed: boolean;
234
257
  livenessStartTime: number | undefined;
235
258
  }
236
259
 
237
- // TLC reports a depth of at least 1, even before it finds a state, and rates a minute only once the
238
- // search has started.
239
260
  const printProgress = (
240
261
  printer: MessagePrinter,
241
262
  statistics: SearchStatistics,
@@ -252,10 +273,55 @@ const printProgress = (
252
273
  );
253
274
  };
254
275
 
276
+ const COVERAGE_CODES = {
277
+ init: MESSAGE_CODE.coverageInit,
278
+ next: MESSAGE_CODE.coverageNext,
279
+ invariant: MESSAGE_CODE.coverageProperty,
280
+ implied: MESSAGE_CODE.coverageProperty,
281
+ constraint: MESSAGE_CODE.coverageConstraint,
282
+ };
283
+
284
+ const COVERAGE_OVERHEAD = 5 * 60_000;
285
+
286
+ const printCoverage = (printer: MessagePrinter, coverage: CoverageReport, startTime: number) => {
287
+ const print = (code: number, text: string) => printer.print(code, MESSAGE_LEVEL.none, text);
288
+ print(
289
+ MESSAGE_CODE.coverageStart,
290
+ `The coverage statistics at ${formatTlcDate(new Date())} (see https://explain.tlapl.us/module-coverage-statistics for how to interpret the following statistics).`,
291
+ );
292
+ coverage.variables.forEach((variable) =>
293
+ print(MESSAGE_CODE.coverageVariable, `<${variable.label}>: ${variable.distinct}`),
294
+ );
295
+ coverage.relations.forEach((relation) => {
296
+ const code = COVERAGE_CODES[relation.kind];
297
+ print(
298
+ code,
299
+ code === MESSAGE_CODE.coverageProperty
300
+ ? `<${relation.label}>`
301
+ : `<${relation.label}>: ${relation.distinct}:${relation.generated}`,
302
+ );
303
+ relation.expressions.forEach((expression) => {
304
+ const location = ` ${"|".repeat(expression.depth)}${expression.location}`;
305
+ if (expression.cost > 0) {
306
+ print(
307
+ MESSAGE_CODE.coverageValueCost,
308
+ `${location}: ${expression.count}:${expression.cost}`,
309
+ );
310
+ } else print(MESSAGE_CODE.coverageValue, `${location}: ${expression.count}`);
311
+ });
312
+ });
313
+ if (Date.now() - startTime > COVERAGE_OVERHEAD) {
314
+ print(
315
+ MESSAGE_CODE.coverageEndOverhead,
316
+ "End of statistics (please note that for performance reasons large models\nare best checked with coverage and cost statistics disabled).",
317
+ );
318
+ } else print(MESSAGE_CODE.coverageEnd, "End of statistics.");
319
+ };
320
+
255
321
  const getClassPath = (directory: string, module: string) => join(directory, `${module}.class`);
256
322
 
257
323
  const printCheckProgress = (
258
- printer: MessagePrinter,
324
+ printer: TlcPrinter,
259
325
  progress: CheckProgress,
260
326
  timing: Timing,
261
327
  directory: string,
@@ -271,7 +337,6 @@ const printCheckProgress = (
271
337
  `Starting... (${formatTlcDate(new Date())})`,
272
338
  );
273
339
  return;
274
- // TLC 1.7.4 warns about neither a constant-level invariant nor a state-level property.
275
340
  case "constant-level-invariant":
276
341
  if (printer.version === "1.7.4") return;
277
342
  print(
@@ -296,7 +361,6 @@ const printCheckProgress = (
296
361
  "Declaring symmetry during liveness checking is dangerous. It might cause TLC to miss violations of the stated liveness properties. Please check liveness without symmetry defined.",
297
362
  );
298
363
  }
299
- // Only TLC 1.7.4 warns about constraints.
300
364
  if (progress.isConstrained && printer.version === "1.7.4") {
301
365
  print(
302
366
  MESSAGE_CODE.livenessConstraints,
@@ -313,7 +377,6 @@ const printCheckProgress = (
313
377
  );
314
378
  return;
315
379
  case "java-override": {
316
- // Class#getResource, which names the class file TLC loads the override from.
317
380
  const location = pathToFileURL(resolve(getClassPath(directory, progress.module))).href;
318
381
  print(
319
382
  progress.isMatched ? MESSAGE_CODE.javaOverrideLoaded : MESSAGE_CODE.javaOverrideMismatch,
@@ -333,13 +396,14 @@ const printCheckProgress = (
333
396
  return;
334
397
  case "progress":
335
398
  printProgress(printer, progress.statistics, timing.startTime);
399
+ if (progress.statistics.coverage) {
400
+ printCoverage(printer, progress.statistics.coverage, timing.startTime);
401
+ }
336
402
  return;
337
403
  case "liveness-started": {
338
404
  timing.livenessStartTime = Date.now();
339
- // TLC reports how far the search got before it checks the complete state graph.
340
405
  if (progress.isComplete) printProgress(printer, progress.statistics);
341
406
  const branches = progress.branches > 1 ? `${progress.branches} branches of ` : "";
342
- // TLC counts the states of the behavior graph of each branch, without its tableau nodes.
343
407
  const states = progress.branches * progress.states;
344
408
  print(
345
409
  MESSAGE_CODE.checkingTemporal,
@@ -353,7 +417,7 @@ const printCheckProgress = (
353
417
  return;
354
418
  case "sequential-fallback":
355
419
  process.stderr.write(
356
- `Warning: the search created the string ${JSON.stringify(progress.string)}, so tla-ts checks the model again with one worker. Workers agree on the order of strings only when the strings exist before the search.\n`,
420
+ `Warning: the search ordered the string ${JSON.stringify(progress.string)} against another string it created, so tla-ts checks the model again with one worker. Workers don't agree on the order of strings the search creates.\n`,
357
421
  );
358
422
  return;
359
423
  case "warning":
@@ -374,12 +438,20 @@ const printLivenessEnd = (printer: MessagePrinter, timing: Timing) => {
374
438
  timing.livenessStartTime = undefined;
375
439
  };
376
440
 
377
- // Prints a violation, and returns whether TLC goes on to print the statistics of the search.
378
- const printViolation = (status: CheckStatus, violation: Violation, printer: MessagePrinter) => {
441
+ const printPostcondition = (printer: MessagePrinter, postcondition: Postcondition | undefined) => {
442
+ if (!postcondition) return;
443
+ if (postcondition.counts) console.log(postcondition.counts);
444
+ printer.print(
445
+ postcondition.code,
446
+ MESSAGE_LEVEL.error,
447
+ formatInnerMessage(postcondition.code, postcondition.message, printer.isTool),
448
+ );
449
+ };
450
+
451
+ const printViolation = (status: CheckStatus, violation: Violation, printer: TlcPrinter) => {
379
452
  const print = printer.print;
380
453
  const name = violation.name;
381
454
  const loopStart = violation.loopStart;
382
- // TLC prints a violation by an initial state without the behavior or the statistics.
383
455
  const isInitial =
384
456
  loopStart === undefined &&
385
457
  violation.trace.length === 1 &&
@@ -417,20 +489,20 @@ const printViolation = (status: CheckStatus, violation: Violation, printer: Mess
417
489
  },
418
490
  "postcondition-violation": {
419
491
  code: violation.postcondition?.code ?? MESSAGE_CODE.general,
420
- text: violation.message ?? `Postcondition ${name} is false.`,
492
+ text: formatInnerMessage(
493
+ violation.postcondition?.code ?? MESSAGE_CODE.general,
494
+ violation.message ?? `Postcondition ${name} is false.`,
495
+ printer.isTool,
496
+ ),
421
497
  },
422
498
  }[status];
423
- // A safety property's counterexample ends where it breaks, and a liveness one loops back.
424
499
  const isProperty = status === "property-violation";
425
500
  const isLasso = loopStart !== undefined && !isProperty;
426
501
  const isCounterExample = isProperty || isLasso;
427
- // TLC rebuilds a liveness counterexample before it reports the violation, and 1.7.4's
428
- // LiveWorker#printTrace after it prints the heading of the counterexample.
429
502
  const isRebuiltFirst = isCounterExample && printer.version !== "1.7.4";
430
503
  if (isRebuiltFirst) printTraceOutput(printer, violation.trace[0]?.output);
431
504
  if (violation.counts) console.log(violation.counts);
432
505
  if (headline) {
433
- // TLC prints the initial state that violates a property in the same message.
434
506
  const text = isInitial
435
507
  ? `${headline.text}\n${formatState(violation.trace[0].state)}`
436
508
  : headline.text;
@@ -444,8 +516,8 @@ const printViolation = (status: CheckStatus, violation: Violation, printer: Mess
444
516
  isCounterExample ? COUNTER_EXAMPLE : undefined,
445
517
  isCounterExample && !isRebuiltFirst,
446
518
  );
447
- printTraceOutput(printer, violation.traceOutput);
448
519
  }
520
+ printTraceOutput(printer, violation.traceOutput);
449
521
  if (isLasso) {
450
522
  const label = violation.loopLabel;
451
523
  if (loopStart === violation.trace.length - 1)
@@ -458,16 +530,13 @@ const printViolation = (status: CheckStatus, violation: Violation, printer: Mess
458
530
  );
459
531
  else console.log(`Back to state ${loopStart + 1}${label ? `: <${label}>\n` : ""}`);
460
532
  }
461
- // TLC 1.7.4 doesn't explain a stuttering counterexample.
462
533
  if (violation.warning && printer.version !== "1.7.4")
463
534
  print(violation.warning.code, MESSAGE_LEVEL.warning, violation.warning.text);
464
- // TLC checks the postconditions after it prints a counterexample.
465
535
  const postcondition =
466
536
  violation.unwitnessed ??
467
537
  (status === "postcondition-violation" ? undefined : violation.postcondition);
468
- if (postcondition?.counts) console.log(postcondition.counts);
469
- if (postcondition) print(postcondition.code, MESSAGE_LEVEL.error, postcondition.message);
470
- // TLC checks assumptions before it starts the search, so it has no statistics to print.
538
+ printTraceOutput(printer, violation.postconditionOutput);
539
+ printPostcondition(printer, postcondition);
471
540
  return !isInitial && status !== "assumption-violation";
472
541
  };
473
542
 
@@ -478,7 +547,54 @@ const printNestedExpressions = (printer: MessagePrinter, callStack: Expression[]
478
547
  `The error occurred when TLC was evaluating the nested\nexpressions at the following positions:\n${formatCallStack(callStack)}`,
479
548
  );
480
549
 
481
- const printResult = (result: CheckResult, printer: MessagePrinter, timing: Timing) => {
550
+ const printSuccess = (printer: MessagePrinter, optimistic: number, actual: number | undefined) =>
551
+ printer.print(
552
+ MESSAGE_CODE.success,
553
+ MESSAGE_LEVEL.none,
554
+ [
555
+ "Model checking completed. No error has been found.",
556
+ " Estimates of the probability that TLC did not check all reachable states",
557
+ " because two distinct states had the same fingerprint:",
558
+ ` calculated (optimistic): val = ${formatProbability(optimistic)}`,
559
+ ...(actual === undefined
560
+ ? []
561
+ : [` based on the actual fingerprints: val = ${formatProbability(actual)}`]),
562
+ ].join("\n"),
563
+ );
564
+
565
+ const printDepthFirst = (printer: TlcPrinter, output: DepthFirstOutput) => {
566
+ switch (output.kind) {
567
+ case "message":
568
+ printer.print(
569
+ output.code,
570
+ output.isError ? MESSAGE_LEVEL.error : MESSAGE_LEVEL.none,
571
+ printer.isTool ? output.toolMessage : output.message,
572
+ );
573
+ return;
574
+ case "behavior":
575
+ output.states.forEach((state, index) =>
576
+ output.isInvariant
577
+ ? printer.print(
578
+ MESSAGE_CODE.statePrint2,
579
+ MESSAGE_LEVEL.state,
580
+ `${index + 1}: \n${formatState(state, printer.isDiffTrace ? output.states[index - 1] : undefined)}`,
581
+ )
582
+ : printer.print(
583
+ MESSAGE_CODE.statePrint1,
584
+ MESSAGE_LEVEL.state,
585
+ `${index + 1}:\n${formatState(state)}`,
586
+ ),
587
+ );
588
+ return;
589
+ case "nested-expressions":
590
+ printNestedExpressions(printer, output.callStack);
591
+ return;
592
+ case "success":
593
+ printSuccess(printer, output.optimistic, output.actual);
594
+ }
595
+ };
596
+
597
+ const printResult = (result: CheckResult, printer: TlcPrinter, timing: Timing) => {
482
598
  const print = printer.print;
483
599
  if (result.failure) {
484
600
  const failure = result.failure;
@@ -486,8 +602,6 @@ const printResult = (result: CheckResult, printer: MessagePrinter, timing: Timin
486
602
  const printCallStack = () => {
487
603
  const fingerprint = failure.fingerprint;
488
604
  if (fingerprint) {
489
- // TLC prints the call stack when the replay has one, and otherwise the sources of the
490
- // values it failed to fingerprint, innermost first. TLC 1.7.4 always prints the sources.
491
605
  const trace =
492
606
  failure.callStack?.length && printer.version !== "1.7.4"
493
607
  ? formatCallStack(failure.callStack)
@@ -502,8 +616,6 @@ const printResult = (result: CheckResult, printer: MessagePrinter, timing: Timin
502
616
  if (failure.callStack) printNestedExpressions(printer, failure.callStack);
503
617
  };
504
618
  if (failure.isCallStackFirst) printCallStack();
505
- // TLC prints the state as it reports the error, so a state it can't print fails outside the
506
- // checker, which TLC reports as an exception it did not expect.
507
619
  const initialState =
508
620
  failure.initialState &&
509
621
  (() => {
@@ -517,7 +629,6 @@ const printResult = (result: CheckResult, printer: MessagePrinter, timing: Timin
517
629
  );
518
630
  }
519
631
  })();
520
- // TLC prints an error on an initial state and the state as one message.
521
632
  print(
522
633
  initialState ? MESSAGE_CODE.initialState : failure.code,
523
634
  MESSAGE_LEVEL.error,
@@ -534,48 +645,32 @@ const printResult = (result: CheckResult, printer: MessagePrinter, timing: Timin
534
645
  );
535
646
  }
536
647
  printTraceOutput(printer, failure.traceOutput);
537
- const postcondition = failure.postcondition;
538
- if (postcondition?.counts) console.log(postcondition.counts);
539
- if (postcondition) print(postcondition.code, MESSAGE_LEVEL.error, postcondition.message);
648
+ printPostcondition(printer, failure.postcondition);
540
649
  if (!failure.isCallStackFirst) printCallStack();
541
650
  } else if (result.violation) {
542
651
  if (!printViolation(result.status, result.violation, printer)) return;
543
- // TLC adds a deadlocked state to the behavior graph after it reports the deadlock, which can
544
- // violate a temporal property too.
545
652
  const additionalViolation = result.additionalViolation;
546
653
  if (additionalViolation) printViolation("property-violation", additionalViolation, printer);
547
654
  if (result.liveCallStack) printNestedExpressions(printer, result.liveCallStack);
548
- } else {
655
+ } else if (result.status === "success") {
549
656
  printLivenessEnd(printer, timing);
550
- const optimistic = getOptimisticProbability(result.distinctStates, result.generatedStates);
551
- const actual =
657
+ printSuccess(
658
+ printer,
659
+ getOptimisticProbability(result.distinctStates, result.generatedStates),
552
660
  result.fingerprintDistance === undefined
553
- ? []
554
- : [
555
- ` based on the actual fingerprints: val = ${formatProbability(getActualProbability(result.fingerprintDistance))}`,
556
- ];
557
- print(
558
- MESSAGE_CODE.success,
559
- MESSAGE_LEVEL.none,
560
- [
561
- "Model checking completed. No error has been found.",
562
- " Estimates of the probability that TLC did not check all reachable states",
563
- " because two distinct states had the same fingerprint:",
564
- ` calculated (optimistic): val = ${formatProbability(optimistic)}`,
565
- ...actual,
566
- ].join("\n"),
661
+ ? undefined
662
+ : getActualProbability(result.fingerprintDistance),
567
663
  );
568
664
  }
569
665
  if (result.failure?.isWithoutStatistics) return;
570
666
  if (result.status !== "success") printLivenessEnd(printer, timing);
667
+ if (result.coverage) printCoverage(printer, result.coverage, timing.startTime);
571
668
  if (printer.isTool) printProgress(printer, result, timing.startTime);
572
669
  print(
573
670
  MESSAGE_CODE.stats,
574
671
  MESSAGE_LEVEL.none,
575
672
  `${result.generatedStates} states generated, ${result.distinctStates} distinct states found, ${result.queuedStates} states left on queue.`,
576
673
  );
577
- // ModelChecker#printSummary prints the depth, which TLC 1.7.4 prints only after a search it
578
- // reports as successful, and as at least 1, and then the outdegree of a successful search.
579
674
  const is174 = printer.version === "1.7.4";
580
675
  const outDegrees = is174 ? (result.outDegrees ?? result.violationOutDegrees) : result.outDegrees;
581
676
  if (!is174 || outDegrees) {
@@ -589,14 +684,9 @@ const printResult = (result: CheckResult, printer: MessagePrinter, timing: Timin
589
684
  if (outDegree) print(MESSAGE_CODE.stateGraphOutdegree, MESSAGE_LEVEL.none, outDegree);
590
685
  };
591
686
 
592
- // Java's Files.createTempDirectory names a directory by a random unsigned long. tla-ts derives it
593
- // from TLC's fingerprint of what the directory holds, so that each run of a spec prints the same
594
- // files.
687
+ // Deviation from TLC: Java names the directory by a random unsigned long, and tla-ts by what the directory holds, so that each run of a spec prints the same files.
595
688
  const getTemporaryName = (contents: string) => getTlcFingerprint([contents]).toString();
596
689
 
597
- // The file TLC's SANY says it parses each module from: the real path of a module's own file, or a
598
- // copy in a temporary directory of a module from the root module's file or from the jar on the
599
- // class path, followed by where TLC copied it from.
600
690
  const createFileDescriber = (
601
691
  specPath: string,
602
692
  directories: string[],
@@ -611,9 +701,7 @@ const createFileDescriber = (
611
701
  return (name: string, origin: SanyModuleOrigin) => {
612
702
  const fileName = `${name}.tla`;
613
703
  if (origin === "file") return realpathSync(findModuleFile(directories, name) ?? specPath);
614
- // TLC 1.7.4 copies a standard module into the temporary directory itself.
615
704
  if (version === "1.7.4") return join(temporaryDirectory, fileName);
616
- // FileUtil.createTempFile copies a module from the root module's file into the -metadir.
617
705
  if (origin === "root file") {
618
706
  const directory = metadir === undefined ? temporaryDirectory : resolve(metadir);
619
707
  const root = realpathSync(specPath);
@@ -627,8 +715,21 @@ const createFileDescriber = (
627
715
  const printWelcome = (printer: MessagePrinter) =>
628
716
  printer.print(MESSAGE_CODE.version, MESSAGE_LEVEL.none, `TLC2 Version ${version} (rev: tla-ts)`);
629
717
 
630
- // TLC.printErrorMsg: TLC says which version it is, then why it can't read its options.
631
- const printCommandLineError = (printer: MessagePrinter, message: string) => {
718
+ const getEmbeddedConfig = (contents: string, name: string) => {
719
+ const lines = contents.split(/\r?\n/);
720
+ const start = lines.findIndex(
721
+ (line) => line.match(/^-----*\s*CONFIG\s+(\S+?)\s*-----*$/)?.[1] === name,
722
+ );
723
+ if (start === -1) return "\n";
724
+ const end = lines.findIndex((line, index) => index > start && line.startsWith("===="));
725
+ return `${lines
726
+ .slice(start + 1, end === -1 ? undefined : end)
727
+ .join("\n")
728
+ .trim()}\n`;
729
+ };
730
+
731
+ const printCommandLineError = (isTool: boolean, version: TlcVersion, message: string) => {
732
+ const printer = createMessagePrinter(isTool, true, version);
632
733
  printWelcome(printer);
633
734
  printer.print(
634
735
  MESSAGE_CODE.commandLineError,
@@ -638,86 +739,188 @@ const printCommandLineError = (printer: MessagePrinter, message: string) => {
638
739
  return 1;
639
740
  };
640
741
 
641
- // TLC.printStartupBanner, with what runs tla-ts in place of the JVM. tla-ts keeps its fingerprints
642
- // and its queue of states in memory.
643
- const printStartupBanner = (printer: MessagePrinter, seed: string, workers: number) =>
742
+ // Deviation from TLC: tla-ts keeps its fingerprints and its queue of states in memory.
743
+ const printStartupBanner = (printer: MessagePrinter, args: TlcArguments) => {
744
+ const workers = `${args.workers} worker${args.workers === 1 ? "" : "s"} on ${availableParallelism()} cores with ${Math.floor(getHeapStatistics().heap_size_limit / 1024 / 1024)}MB heap and 0MB offheap memory [pid: ${process.pid}] (${type()} ${release()} ${arch()}, Node.js ${process.versions.node} ${process.arch.endsWith("64") ? 64 : 32}bit`;
745
+ if (args.mode === "model-check" && args.dfidDepth !== undefined) {
746
+ printer.print(
747
+ MESSAGE_CODE.depthFirstModelChecking,
748
+ MESSAGE_LEVEL.none,
749
+ `Running depth-first search Model-Checking with fp ${args.fingerprintIndex} and seed ${args.seed} with ${workers}).`,
750
+ );
751
+ return;
752
+ }
753
+ if (args.mode === "model-check") {
754
+ printer.print(
755
+ MESSAGE_CODE.modelChecking,
756
+ MESSAGE_LEVEL.none,
757
+ `Running breadth-first search Model-Checking with fp ${args.fingerprintIndex} and seed ${args.seed} with ${workers}, MemFPSet, MemStateQueue).`,
758
+ );
759
+ return;
760
+ }
644
761
  printer.print(
645
- MESSAGE_CODE.modelChecking,
762
+ MESSAGE_CODE.simulating,
646
763
  MESSAGE_LEVEL.none,
647
- `Running breadth-first search Model-Checking with fp 0 and seed ${BigInt(seed)} with ${workers} worker${workers === 1 ? "" : "s"} on ${availableParallelism()} cores with ${Math.floor(getHeapStatistics().heap_size_limit / 1024 / 1024)}MB heap and 0MB offheap memory [pid: ${process.pid}] (${type()} ${release()} ${arch()}, Node.js ${process.versions.node} ${process.arch.endsWith("64") ? 64 : 32}bit, MemFPSet, MemStateQueue).`,
764
+ `Running ${args.scheduler === "rl" ? "RL" : "Random"} Simulation with seed ${args.seed} with ${workers}).`,
648
765
  );
766
+ };
649
767
 
650
- // TLC loads Integers for the binary trace that its trace exploration spec records. -generateSpecTE
651
- // turns the spec on, and -tool, -continue, -noGenerateSpecTE and -noTE turn it off, as
652
- // -noGenerateSpecTEBin and -noTEBin turn off the binary trace. TLC 1.7.4 records no such trace.
653
- const isTraceRecorded = (args: ParsedArgs, version: TlcVersion) => {
654
- const flags = [...args.unknown, ...args.options.map((option) => option.name)];
655
- const hasFlag = (name: string, alias = name) =>
656
- flags.some((flag) => flag === name || flag.toLowerCase() === alias.toLowerCase());
657
- const isSpecGenerated =
658
- hasFlag("-generateSpecTE") ||
659
- (!hasFlag("-noGenerateSpecTE", "-noTE") && !hasFlag("-tool") && !hasFlag("-continue"));
660
- return version !== "1.7.4" && isSpecGenerated && !hasFlag("-noGenerateSpecTEBin", "-noTEBin");
768
+ const printSimulation = (printer: TlcPrinter, output: SimulationOutput) => {
769
+ const print = printer.print;
770
+ switch (output.kind) {
771
+ case "message":
772
+ print(
773
+ output.code,
774
+ output.isError ? MESSAGE_LEVEL.error : MESSAGE_LEVEL.none,
775
+ printer.isTool ? output.toolMessage : output.message,
776
+ );
777
+ return;
778
+ case "behavior": {
779
+ const last = output.trace[output.trace.length - 1];
780
+ if (!output.isLastStateOnly) {
781
+ printTrace(printer, output.trace, BEHAVIOR, false, true);
782
+ return;
783
+ }
784
+ print(MESSAGE_CODE.errorState, MESSAGE_LEVEL.none, "The error state is:\n");
785
+ print(MESSAGE_CODE.statePrint1, MESSAGE_LEVEL.state, `:\n${formatState(last.state)}`);
786
+ return;
787
+ }
788
+ case "progress": {
789
+ const statistics = output.statistics;
790
+ if (printer.isTool) {
791
+ printSimulationProgress(printer, statistics);
792
+ return;
793
+ }
794
+ const variance = statistics.levelM2 / (statistics.traces + 1);
795
+ print(
796
+ MESSAGE_CODE.simulationProgress,
797
+ MESSAGE_LEVEL.none,
798
+ `Progress: ${statistics.generatedStates} states checked, ${statistics.traces} traces generated (trace length: mean=${statistics.levelMean}, var(x)=${Math.round(variance)}, sd=${Math.round(Math.sqrt(variance))})`,
799
+ );
800
+ return;
801
+ }
802
+ case "summary":
803
+ if (printer.isTool) printSimulationProgress(printer, output.statistics);
804
+ print(
805
+ MESSAGE_CODE.simulationStats,
806
+ MESSAGE_LEVEL.none,
807
+ `The number of states generated: ${output.statistics.generatedStates}\nSimulation using seed ${output.statistics.seed} and aril ${output.statistics.aril}`,
808
+ );
809
+ }
810
+ };
811
+
812
+ const printSimulationProgress = (printer: MessagePrinter, statistics: SimulationStatistics) =>
813
+ printer.print(
814
+ MESSAGE_CODE.simulationProgress,
815
+ MESSAGE_LEVEL.none,
816
+ `Progress(${statistics.traces}) at ${formatTlcDate(new Date())}: ${statistics.generatedStates} states generated, -1 distinct states found, -1 states left on queue.`,
817
+ );
818
+
819
+ const getJavaPath = (path: string) => path.replace(/\/+/g, "/").replace(/(.)\/$/, "$1");
820
+
821
+ const getJavaParent = (path: string) => {
822
+ const normalized = getJavaPath(path);
823
+ const separator = normalized.lastIndexOf("/");
824
+ return separator === -1 ? "." : normalized.slice(0, Math.max(separator, 1));
825
+ };
826
+
827
+ const resolveJavaPath = (directory: string, name: string) =>
828
+ directory.endsWith("/") ? `${directory}${name}` : `${directory}/${name}`;
829
+
830
+ const getTraceSpecLocation = (
831
+ args: TlcArguments,
832
+ version: TlcVersion,
833
+ mainFile: string,
834
+ startTime: number,
835
+ ) => {
836
+ const isGenerated =
837
+ version !== "1.7.4" &&
838
+ (args.isTraceSpecForced ||
839
+ (!args.isTraceSpecDisabled &&
840
+ !args.isTool &&
841
+ !args.isContinued &&
842
+ !basename(mainFile).includes("_TTrace")));
843
+ if (!isGenerated) return undefined;
844
+ const output = args.traceSpecPath;
845
+ const module = `${basename(mainFile)}_TTrace_${Math.floor(startTime / 1000)}`;
846
+ const location =
847
+ output === undefined
848
+ ? { directory: getJavaParent(mainFile), module }
849
+ : output.toLowerCase().endsWith(".tla")
850
+ ? { directory: getJavaParent(output), module: basename(output).replace(/\.tla$/, "") }
851
+ : { directory: getJavaPath(output), module };
852
+ return {
853
+ ...location,
854
+ traceFile: args.isTraceBinaryDisabled
855
+ ? undefined
856
+ : resolveJavaPath(location.directory, `${location.module}.bin`),
857
+ };
858
+ };
859
+
860
+ const JAVA_FILE_ERRORS: Record<string, string> = {
861
+ ENOENT: "No such file or directory",
862
+ ENOTDIR: "Not a directory",
863
+ EISDIR: "Is a directory",
864
+ EACCES: "Permission denied",
865
+ };
866
+
867
+ const writeJavaFile = (path: string, content: string | Uint8Array) => {
868
+ try {
869
+ writeFileSync(path, content);
870
+ } catch (error) {
871
+ const reason =
872
+ error instanceof Error && "code" in error ? JAVA_FILE_ERRORS[String(error.code)] : undefined;
873
+ if (reason === undefined) throw error;
874
+ throw new TlaEvaluationError(`${path} (${reason})`);
875
+ }
876
+ };
877
+
878
+ // Java's File#mkdirs reports a failure only through its result, which TLC ignores.
879
+ const makeJavaDirectory = (path: string) => {
880
+ try {
881
+ mkdirSync(path, { recursive: true });
882
+ } catch {}
883
+ };
884
+
885
+ const createMetadir = (args: TlcArguments) => {
886
+ const now = new Date();
887
+ const pad = (value: number, length = 2) => String(value).padStart(length, "0");
888
+ const name = `${pad(now.getFullYear() % 100)}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}-${pad(now.getHours())}-${pad(now.getMinutes())}-${pad(now.getSeconds())}.${pad(now.getMilliseconds(), 3)}`;
889
+ const directory = join(args.metadir ?? "states", name);
890
+ mkdirSync(directory, { recursive: true });
891
+ return directory;
661
892
  };
662
893
 
663
894
  const checkSpec = async (
664
895
  specPath: string,
665
- args: ParsedArgs,
896
+ args: TlcArguments,
897
+ dump: StateDump | undefined,
666
898
  java: JavaProperties,
667
- printer: MessagePrinter,
899
+ printer: TlcPrinter,
668
900
  ) => {
669
- // TLC.handleParameters: TLC reads its options before it says which version it is.
670
- const seed = args.has("-seed") ? args.get("-seed")?.[0] : "0";
671
- if (seed === undefined) return printCommandLineError(printer, "Error: seed required.");
672
- if (!isJavaLong(seed)) {
673
- return printCommandLineError(
674
- printer,
675
- `Error: An integer for seed required. But encountered ${seed}`,
676
- );
677
- }
678
- const livenessCheck = args.has("-lncheck") ? args.get("-lncheck")?.[0]?.toLowerCase() : "default";
679
- if (livenessCheck === undefined) {
680
- return printCommandLineError(
681
- printer,
682
- "Error: expect a strategy such as final for -lncheck option.",
683
- );
684
- }
685
- const dumpValues = args.get("-dump");
686
- if (dumpValues?.length === 0) {
687
- return printCommandLineError(printer, "Error: A file name for dumping states required.");
688
- }
689
- const unsupportedFormat =
690
- dumpValues?.length === 2 &&
691
- UNSUPPORTED_DUMP_FORMATS.find((format) => dumpValues[0].toLowerCase().includes(format));
692
- if (unsupportedFormat) {
693
- console.error(`Error: tla-ts does not support the -dump format ${unsupportedFormat}.`);
694
- return 1;
695
- }
696
- const fingerprintIndex = args.get("-fp")?.[0];
697
- if (fingerprintIndex !== undefined && Number(fingerprintIndex) !== 0) {
698
- console.error(
699
- `Error: tla-ts fingerprints states as TLC does with -fp 0, not -fp ${fingerprintIndex}.`,
700
- );
701
- return 1;
702
- }
703
- const workers = getWorkerCount(args.get("-workers"));
901
+ const livenessCheck = args.livenessCheck;
704
902
  const version = printer.version;
705
903
  printWelcome(printer);
706
- printStartupBanner(printer, seed, workers);
707
- const configPath =
708
- args.get("-config")?.[0] ??
709
- (args.has("-config") ? undefined : specPath.replace(/\.tla$/, ".cfg"));
710
- if (!configPath || !existsSync(configPath)) {
904
+ const recoverDirectory = args.recoverDirectory;
905
+ if (recoverDirectory !== undefined) {
906
+ throw existsSync(join(recoverDirectory, "vars.chkpt"))
907
+ ? new TlaFeatureUnsupportedError(
908
+ `tla-ts can't recover a model check from the checkpoint in ${recoverDirectory}.`,
909
+ )
910
+ : new TlaMissingCheckpointError(recoverDirectory);
911
+ }
912
+ printStartupBanner(printer, args);
913
+ const configPath = args.configPath ?? specPath.replace(/\.tla$/, ".cfg");
914
+ if (!existsSync(configPath)) {
711
915
  printer.print(
712
916
  MESSAGE_CODE.configFileError,
713
917
  MESSAGE_LEVEL.error,
714
- `TLC encountered the following error when trying to read the configuration file ${configPath ?? ""}:\nFile not found.`,
918
+ `TLC encountered the following error when trying to read the configuration file ${configPath}:\nFile not found.`,
715
919
  );
716
920
  return EXIT_STATUS.configParseError;
717
921
  }
718
922
  const fileName = basename(specPath, ".tla");
719
923
  const timing: Timing = { startTime: Date.now(), livenessStartTime: undefined, isParsed: false };
720
- // Without -tool, TLC prints how long it ran for a person to read.
721
924
  const printFinished = () => {
722
925
  const runtime = Date.now() - timing.startTime;
723
926
  printer.print(
@@ -732,7 +935,6 @@ const checkSpec = async (
732
935
  MESSAGE_LEVEL.error,
733
936
  "Parsing or semantic analysis failed.",
734
937
  );
735
- // TLC prints how long it ran even when it stops at an error.
736
938
  const printFailure = (error: TlaError) => {
737
939
  if (error instanceof TlaSyntaxError) {
738
940
  printParsingFailed();
@@ -740,19 +942,22 @@ const checkSpec = async (
740
942
  printError(error, printer);
741
943
  }
742
944
  printFinished();
743
- return getErrorExitCode(error);
945
+ return getTopLevelExitCode(error);
744
946
  };
745
- // TLC reads the configuration file before it parses the spec, and prints how long it ran even
746
- // when it can't read it.
747
947
  const config = (() => {
748
948
  try {
749
- return parseConfig(readFileSync(configPath, "utf8"), version);
949
+ const contents = readFileSync(configPath, "utf8");
950
+ return parseConfig(
951
+ configPath.endsWith(".tla")
952
+ ? getEmbeddedConfig(contents, configPath.replaceAll(".tla", ""))
953
+ : contents,
954
+ version,
955
+ );
750
956
  } catch (error) {
751
957
  if (!(error instanceof TlaConfigError)) throw error;
752
958
  return error;
753
959
  }
754
960
  })();
755
- // TLC 1.7.4 reports a configuration file it can't parse as an exception it didn't expect.
756
961
  if (config instanceof TlaConfigError && version === "1.7.4") {
757
962
  printer.print(
758
963
  MESSAGE_CODE.general,
@@ -763,17 +968,23 @@ const checkSpec = async (
763
968
  return EXIT_STATUS.error;
764
969
  }
765
970
  if (config instanceof TlaConfigError) return printFailure(config);
766
- if (args.has("-deadlock")) config.checkDeadlock = false;
971
+ if (!args.isDeadlockChecked) config.checkDeadlock = false;
767
972
  const directory = dirname(specPath);
768
973
  const directories = [directory, ...java.libraries];
769
974
  const loadModule = createModuleLoader(directories);
770
- const isRecorded = isTraceRecorded(args, version);
975
+ const traceSpec = getTraceSpecLocation(
976
+ args,
977
+ version,
978
+ specPath.replace(/\.tla$/, ""),
979
+ timing.startTime,
980
+ );
981
+ const getOperatorModules = (kind: ModuleOperator["kind"]) =>
982
+ args.moduleOperators
983
+ .filter((operator) => operator.kind === kind)
984
+ .map((operator) => operator.module);
771
985
  if (printer.isTool) {
772
986
  printer.print(MESSAGE_CODE.startingSany, MESSAGE_LEVEL.none, "Starting SANY...");
773
987
  }
774
- // TLC.handleParameters: SANY names the spec as TLC's arguments do, except that TLC runs from the
775
- // directory of a spec given by an absolute path, and names it by its file name. SANY looks for
776
- // the spec's modules in the spec's directory and the TLA-Library directories.
777
988
  const isAbsoluteSpec = isAbsolute(specPath);
778
989
  const specName = isAbsoluteSpec ? fileName : specPath.replace(/\.tla$/, "");
779
990
  const jar = getToolsJar(java);
@@ -790,27 +1001,28 @@ const checkSpec = async (
790
1001
  [...(isAbsoluteSpec || directory === "." ? [] : [directory]), ...java.libraries],
791
1002
  );
792
1003
  }
793
- // TLC prints what SANY prints as it parses the spec, and the errors it rejects the spec for.
794
1004
  const sany = getSanyReport(
795
1005
  specPath,
796
1006
  reportMissingFile ? reportMissingModules174(loadModule, reportMissingFile) : loadModule,
797
1007
  {
798
1008
  fileName: specName,
799
- describeFile: createFileDescriber(
800
- specPath,
801
- directories,
802
- java,
803
- args.get("-metadir")?.[0],
804
- version,
805
- ),
1009
+ describeFile: createFileDescriber(specPath, directories, java, args.metadir, version),
806
1010
  version,
807
- // TLC's trace exploration spec records the trace with the post condition of _TLCTrace.
808
- rootExtendees: isRecorded ? ["_TLCTrace"] : undefined,
1011
+ rootExtendees: [
1012
+ ...getOperatorModules("postcondition"),
1013
+ ...(traceSpec?.traceFile === undefined ? [] : ["_TLCTrace"]),
1014
+ ...args.invariants.flatMap((invariant) => invariant.modules),
1015
+ ...getOperatorModules("constraint"),
1016
+ ...getOperatorModules("view").slice(0, 1),
1017
+ ],
1018
+ suppressedCodes: args.suppressedCodes,
1019
+ errorCodes: args.errorCodes,
809
1020
  onPrint: (text) => process.stdout.write(text),
810
1021
  onPrintError: (text) => process.stderr.write(text),
811
1022
  },
812
1023
  );
813
- if (sany.isFailed) {
1024
+ const specification = sany.specification;
1025
+ if (sany.isFailed || specification === undefined) {
814
1026
  printCheckProgress(printer, { kind: "parsed" }, timing, directory);
815
1027
  printParsingFailed();
816
1028
  printFinished();
@@ -825,19 +1037,41 @@ const checkSpec = async (
825
1037
  undefined,
826
1038
  );
827
1039
  }
828
- const result = await check({
829
- workers,
830
- livenessCheck: ["final", "seqfinal", "off"].includes(livenessCheck) ? "final" : "default",
831
- seed: BigInt(seed),
832
- dump: dumpValues && getStateDump(dumpValues),
1040
+ const userFile = args.userFile;
1041
+ const standardModules = getSanyStandardModules(version);
1042
+ const invariants = addRuntimeInvariants(
1043
+ source,
1044
+ specification.root,
1045
+ args.invariants,
1046
+ (name) => loadModule(name) ?? standardModules.get(name) ?? extractModule(source, name),
1047
+ version,
1048
+ );
1049
+ config.invariants.push(...invariants.names);
1050
+ const options: CheckOptions = {
1051
+ workers: args.workers,
1052
+ livenessCheck:
1053
+ livenessCheck === "off"
1054
+ ? "off"
1055
+ : ["final", "seqfinal"].includes(livenessCheck)
1056
+ ? "final"
1057
+ : "default",
1058
+ seed: args.seed,
1059
+ fingerprintPolynomial: args.fingerprintIndex,
1060
+ maxSetSize: args.maxSetSize,
1061
+ isLazyValueExpanded: args.isLazyValueExpanded,
1062
+ isViewPrinted: args.isViewPrinted,
1063
+ dump,
833
1064
  isTool: printer.isTool,
834
- isContinued: args.has("-continue"),
835
- isTraceRecorded: isRecorded,
1065
+ isContinued: args.isContinued,
1066
+ moduleOperators: args.moduleOperators,
1067
+ traceSpec,
1068
+ coverage: args.coverage,
836
1069
  isSanyReported: true,
837
- isWarningEnabled: !args.has("-nowarning"),
1070
+ isWarningEnabled: args.isWarningEnabled,
838
1071
  version,
839
1072
  onProgress: (progress) => printCheckProgress(printer, progress, timing, directory),
840
- source,
1073
+ onPrint: userFile === undefined ? undefined : (text) => appendFileSync(userFile, `${text}\n`),
1074
+ source: invariants.source,
841
1075
  config,
842
1076
  onPause: () => readSync(0, Buffer.alloc(1)),
843
1077
  loadModule,
@@ -845,14 +1079,58 @@ const checkSpec = async (
845
1079
  const classPath = getClassPath(directory, name);
846
1080
  return existsSync(classPath) ? readFileSync(classPath) : undefined;
847
1081
  },
848
- readFile: (path) => (existsSync(path) ? readFileSync(path, "utf8") : undefined),
849
- writeFile: (path, content) => {
850
- mkdirSync(dirname(resolve(path)), { recursive: true });
851
- writeFileSync(path, content);
1082
+ readFile: (path) => {
1083
+ checkNotDirectory(path);
1084
+ return existsSync(path) ? readFileSync(path, "utf8") : undefined;
852
1085
  },
853
- });
1086
+ writeFile: writeJavaFile,
1087
+ makeDirectory: makeJavaDirectory,
1088
+ };
1089
+ if (args.mode !== "model-check") {
1090
+ const status = simulate({
1091
+ ...options,
1092
+ traceDepth: args.traceDepth,
1093
+ traceCount: args.traceCount,
1094
+ aril: args.aril,
1095
+ isGenerating: args.mode === "generate",
1096
+ scheduler: args.scheduler,
1097
+ onSimulation: (output) => printSimulation(printer, output),
1098
+ });
1099
+ printFinished();
1100
+ return status;
1101
+ }
1102
+ if (args.dfidDepth !== undefined) {
1103
+ const status = checkDepthFirst({
1104
+ ...options,
1105
+ maxDepth: args.dfidDepth,
1106
+ onOutput: (output) => printDepthFirst(printer, output),
1107
+ });
1108
+ printFinished();
1109
+ return status;
1110
+ }
1111
+ const result = await check(options);
854
1112
  printResult(result, printer, timing);
855
1113
  printFinished();
1114
+ if (traceSpec && result.traceSpec !== undefined) {
1115
+ const path = resolveJavaPath(traceSpec.directory, `${traceSpec.module}.tla`);
1116
+ makeJavaDirectory(traceSpec.directory);
1117
+ const failure = (() => {
1118
+ try {
1119
+ writeJavaFile(path, result.traceSpec);
1120
+ return undefined;
1121
+ } catch (error) {
1122
+ if (!(error instanceof TlaEvaluationError)) throw error;
1123
+ return error;
1124
+ }
1125
+ })();
1126
+ printer.print(
1127
+ failure ? MESSAGE_CODE.traceSpecFailed : MESSAGE_CODE.traceSpecWritten,
1128
+ MESSAGE_LEVEL.none,
1129
+ failure
1130
+ ? `Failed to generate trace exploration spec; error message: ${failure.message}`
1131
+ : `Trace exploration spec path: ${path}`,
1132
+ );
1133
+ }
856
1134
  return result.failure?.exitCode ?? EXIT_CODES[result.status];
857
1135
  } catch (error) {
858
1136
  if (!(error instanceof TlaError)) throw error;
@@ -862,8 +1140,6 @@ const checkSpec = async (
862
1140
  }
863
1141
  };
864
1142
 
865
- // What SANY prints about a spec it rejects: a module it can't find or parse is a fatal error, and
866
- // it reports the other errors as semantic errors.
867
1143
  const formatSanyErrors = (error: TlaSyntaxError, specName: string) => {
868
1144
  const isFatal = error instanceof TlaSanyFatalError;
869
1145
  if (!isFatal && !error.failure)
@@ -878,60 +1154,102 @@ const formatSanyErrors = (error: TlaSyntaxError, specName: string) => {
878
1154
  };
879
1155
 
880
1156
  export const checkSpecs = async (args: string[], java: JavaProperties) => {
881
- const parsed = CHECK_COMMAND.parse(args);
882
- const inputs = getInputPaths(parsed.positionals);
883
- const isConfigured = parsed.has("-config");
884
- // Like TLC, a spec named without an extension is the .tla file of that name. A glob also matches
885
- // modules that only other specs import, which have no configuration.
1157
+ const version = java.tlcVersion ?? "master";
1158
+ const parsed = parseTlcArguments(args);
1159
+ if ("error" in parsed) {
1160
+ if (parsed.isUncaught) {
1161
+ console.error(`Exception in thread "main" ${parsed.error}`);
1162
+ return 1;
1163
+ }
1164
+ return printCommandLineError(parsed.isTool, version, parsed.error);
1165
+ }
1166
+ if (parsed.isUsage) {
1167
+ console.log(getTlcUsage());
1168
+ return 1;
1169
+ }
1170
+ const dump =
1171
+ parsed.dump &&
1172
+ getStateDump(
1173
+ parsed.dump.map((value) =>
1174
+ value.includes("${metadir}") ? value.replace("${metadir}", createMetadir(parsed)) : value,
1175
+ ),
1176
+ );
1177
+ const dumpPath = dump?.path;
1178
+ if (dumpPath !== undefined) {
1179
+ try {
1180
+ closeSync(openSync(dumpPath, "w"));
1181
+ } catch {
1182
+ console.log(`Error: Unable to write to file ${dumpPath}`);
1183
+ return printCommandLineError(
1184
+ parsed.isTool,
1185
+ version,
1186
+ `Error: Given file name ${dumpPath} for dumping states invalid.`,
1187
+ );
1188
+ }
1189
+ }
1190
+ const isConfigured = parsed.configPath !== undefined;
1191
+ if (isConfigured && parsed.specs.length > 1) {
1192
+ return printCommandLineError(
1193
+ parsed.isTool,
1194
+ version,
1195
+ `Error: more than one input files: ${parsed.specs[0].replace(/\.tla$/, "")} and ${parsed.specs[1]}`,
1196
+ );
1197
+ }
1198
+ const inputs = getInputPaths(parsed.specs);
886
1199
  const specPaths = inputs
887
1200
  .map((input) => ({
888
1201
  ...input,
889
1202
  path:
890
- input.isGlobbed || /\.(tla|cfg)$/.test(input.path)
1203
+ input.isGlobbed || /\.(tla|cfg|ts)$/.test(input.path)
891
1204
  ? input.path.replace(/\.cfg$/, ".tla")
892
1205
  : `${input.path}.tla`,
893
1206
  }))
894
1207
  .filter(
895
1208
  (input) =>
896
- input.path.endsWith(".tla") &&
897
- (!input.isGlobbed || isConfigured || existsSync(input.path.replace(/\.tla$/, ".cfg"))),
1209
+ input.path.endsWith(".ts") ||
1210
+ (input.path.endsWith(".tla") &&
1211
+ (!input.isGlobbed || isConfigured || existsSync(input.path.replace(/\.tla$/, ".cfg")))),
898
1212
  )
899
1213
  .map((input) => input.path);
900
1214
  if (specPaths.length === 0) {
901
- console.error(USAGE);
902
- return 1;
1215
+ return printCommandLineError(parsed.isTool, version, "Error: Missing input TLA+ module.");
903
1216
  }
904
1217
  if (isConfigured && specPaths.length > 1) {
905
1218
  console.error("Error: -config applies to one specification, but several were given.");
906
1219
  return 1;
907
1220
  }
908
- // TLC also looks for the spec itself in the library directories.
909
1221
  const findSpec = (path: string) =>
910
1222
  existsSync(path) || isAbsolute(path)
911
1223
  ? path
912
1224
  : (java.libraries.map((directory) => join(directory, path)).find(existsSync) ?? path);
913
1225
  const paths = [...new Set(specPaths.map(findSpec))];
914
- // Each spec is checked as TLC would in a process of its own, so an error in one leaves the others
915
- // to report. The exit code is the first that is not success.
916
1226
  const exitCodes: number[] = [];
917
1227
  for (const [index, path] of paths.entries()) {
918
1228
  if (index > 0) console.log("");
919
- // TLC checks one spec, so tla-ts names each of several it checks.
920
- if (paths.length > 1)
921
- console.log(`Checking ${basename(path)} with ${basename(path, ".tla")}.cfg`);
922
- const printer = createMessagePrinter(
923
- parsed.has("-tool"),
924
- !parsed.has("-nowarning"),
925
- java.tlcVersion ?? "master",
1229
+ const printer = {
1230
+ ...createMessagePrinter(
1231
+ parsed.isTool,
1232
+ parsed.isWarningEnabled,
1233
+ version,
1234
+ parsed.suppressedCodes,
1235
+ parsed.errorCodes,
1236
+ ),
1237
+ isDiffTrace: parsed.isDiffTrace,
1238
+ };
1239
+ exitCodes.push(
1240
+ await reportErrors(async () => {
1241
+ const specPath = path.endsWith(".ts") ? await writeTypeScriptSpec(path) : path;
1242
+ // Deviation from TLC: TLC checks one spec, so tla-ts names each of several it checks.
1243
+ if (paths.length > 1) {
1244
+ console.log(`Checking ${basename(specPath)} with ${basename(specPath, ".tla")}.cfg`);
1245
+ }
1246
+ return checkSpec(specPath, parsed, dump, java, printer);
1247
+ }, printer),
926
1248
  );
927
- exitCodes.push(await reportErrors(() => checkSpec(path, parsed, java, printer), printer));
928
1249
  }
929
1250
  return exitCodes.find((exitCode) => exitCode !== EXIT_STATUS.success) ?? EXIT_STATUS.success;
930
1251
  };
931
1252
 
932
- // TLC 1.7.4's SimpleFilenameToStream looks for a module in the directory of a spec that TLC is
933
- // given by an absolute path, then in the directory that a relative path names, or else in the
934
- // TLA-Library directories.
935
1253
  const createMissingFilePrinter174 = (
936
1254
  specPath: string,
937
1255
  java: JavaProperties,