tla-ts 0.0.9 → 0.0.10-dev.63a6693bd

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 (400) 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 +29 -29
  5. package/dist/deciders.js +42 -42
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +106 -10
  8. package/dist/index.d.ts +106 -10
  9. package/dist/index.js +1 -1
  10. package/dist/parallel-worker.cjs +1 -1
  11. package/dist/parallel-worker.js +1 -1
  12. package/dist/prove-worker.cjs +1 -1
  13. package/dist/prove-worker.js +1 -1
  14. package/dist/prove.cjs +117 -37
  15. package/dist/prove.js +116 -36
  16. package/dist/run.cjs +143 -31
  17. package/dist/run.js +143 -31
  18. package/dist/tlapm.cjs +2 -2
  19. package/dist/tlapm.js +2 -2
  20. package/dist/transfer.cjs +129 -104
  21. package/dist/transfer.js +129 -104
  22. package/dist/worker.cjs +7 -7
  23. package/dist/worker.js +7 -7
  24. package/package.json +3 -1
  25. package/src/ast.ts +48 -62
  26. package/src/bags.ts +99 -102
  27. package/src/builtins.ts +28 -75
  28. package/src/bundled-modules.ts +1 -8
  29. package/src/check-failure.ts +116 -0
  30. package/src/check-trace.ts +282 -0
  31. package/src/check.ts +599 -754
  32. package/src/cli/options.ts +12 -32
  33. package/src/cli/run.ts +0 -2
  34. package/src/cli/runtime-invariants.ts +136 -0
  35. package/src/cli/shared.ts +19 -12
  36. package/src/cli/tlapm.ts +14 -25
  37. package/src/cli/tlc-arguments.ts +652 -0
  38. package/src/cli/tlc-output.ts +687 -0
  39. package/src/cli/tlc-usage.ts +361 -0
  40. package/src/cli/tlc.ts +309 -658
  41. package/src/cli/typescript.ts +23 -0
  42. package/src/cli/xml-exporter.ts +27 -49
  43. package/src/cli.ts +0 -1
  44. package/src/codegen.ts +196 -74
  45. package/src/config.ts +140 -109
  46. package/src/coverage.ts +830 -0
  47. package/src/dependencies.ts +14 -53
  48. package/src/dfid.ts +618 -0
  49. package/src/environment-config.ts +315 -0
  50. package/src/environment.ts +169 -335
  51. package/src/errors.ts +71 -55
  52. package/src/evaluate.ts +598 -340
  53. package/src/exit-codes.ts +37 -3
  54. package/src/fingerprints.ts +75 -11
  55. package/src/index.ts +3 -0
  56. package/src/instances.ts +126 -21
  57. package/src/java-hash.ts +7 -0
  58. package/src/java-overrides.ts +4 -19
  59. package/src/json-reader.ts +455 -0
  60. package/src/json.ts +252 -139
  61. package/src/levels.ts +46 -58
  62. package/src/lexer.ts +80 -100
  63. package/src/liveness-checker.ts +103 -153
  64. package/src/liveness.ts +150 -109
  65. package/src/obligations/action.ts +8 -39
  66. package/src/obligations/anonymize.ts +88 -82
  67. package/src/obligations/equality.ts +1 -1
  68. package/src/obligations/expression.ts +20 -21
  69. package/src/obligations/format.ts +1 -9
  70. package/src/obligations/generate.ts +46 -49
  71. package/src/obligations/index.ts +2 -13
  72. package/src/obligations/levels.ts +4 -8
  73. package/src/obligations/module.ts +28 -53
  74. package/src/obligations/normalize.ts +7 -25
  75. package/src/obligations/operators.ts +1 -2
  76. package/src/obligations/pragma.ts +1 -10
  77. package/src/obligations/printer.ts +47 -46
  78. package/src/obligations/proof.ts +1 -5
  79. package/src/obligations/regroup.ts +1 -4
  80. package/src/obligations/simplify.ts +42 -58
  81. package/src/obligations/source.ts +48 -78
  82. package/src/obligations/subexpression.ts +5 -11
  83. package/src/obligations/substitution.ts +1 -3
  84. package/src/obligations/temporal.ts +13 -19
  85. package/src/obligations/tuples.ts +3 -9
  86. package/src/parallel-worker.ts +30 -60
  87. package/src/parallel.ts +57 -71
  88. package/src/parser.ts +584 -316
  89. package/src/pcal/ast.ts +53 -86
  90. package/src/pcal/parse.ts +144 -219
  91. package/src/pcal/tokenize.ts +91 -131
  92. package/src/pcal/translate.ts +83 -130
  93. package/src/pcal/validate.ts +48 -68
  94. package/src/pretty-print.ts +7 -8
  95. package/src/prover/decide-pool.ts +8 -13
  96. package/src/prover/deciders.ts +3 -7
  97. package/src/prover/first-order.ts +0 -11
  98. package/src/prover/isabelle/decide.ts +0 -6
  99. package/src/prover/isabelle/encode.ts +11 -23
  100. package/src/prover/isabelle/isar/inner-syntax.ts +114 -115
  101. package/src/prover/isabelle/isar/method.ts +29 -53
  102. package/src/prover/isabelle/isar/proof.ts +1 -10
  103. package/src/prover/isabelle/isar/statement.ts +1 -6
  104. package/src/prover/isabelle/isar/theory.ts +26 -36
  105. package/src/prover/isabelle/isar/type-check.ts +17 -31
  106. package/src/prover/isabelle/provers/blast/blast.ts +17 -104
  107. package/src/prover/isabelle/provers/blast/branch.ts +1 -32
  108. package/src/prover/isabelle/provers/blast/prove.ts +1 -35
  109. package/src/prover/isabelle/provers/blast/rules.ts +6 -44
  110. package/src/prover/isabelle/provers/blast/state.ts +2 -28
  111. package/src/prover/isabelle/provers/blast/term.ts +9 -36
  112. package/src/prover/isabelle/provers/clasimp.ts +1 -13
  113. package/src/prover/isabelle/provers/classical.ts +14 -42
  114. package/src/prover/isabelle/provers/hypsubst.ts +28 -51
  115. package/src/prover/isabelle/pure/bicompose.ts +25 -38
  116. package/src/prover/isabelle/pure/consts.ts +1 -7
  117. package/src/prover/isabelle/pure/conv.ts +3 -17
  118. package/src/prover/isabelle/pure/drule.ts +33 -42
  119. package/src/prover/isabelle/pure/envir.ts +3 -52
  120. package/src/prover/isabelle/pure/goal.ts +1 -7
  121. package/src/prover/isabelle/pure/interrupt.ts +0 -5
  122. package/src/prover/isabelle/pure/list.ts +0 -3
  123. package/src/prover/isabelle/pure/logic.ts +2 -15
  124. package/src/prover/isabelle/pure/name.ts +2 -9
  125. package/src/prover/isabelle/pure/net.ts +3 -59
  126. package/src/prover/isabelle/pure/object-logic.ts +3 -10
  127. package/src/prover/isabelle/pure/pattern.ts +2 -19
  128. package/src/prover/isabelle/pure/raw-simplifier.ts +17 -62
  129. package/src/prover/isabelle/pure/rewriter.ts +31 -67
  130. package/src/prover/isabelle/pure/search.ts +3 -10
  131. package/src/prover/isabelle/pure/seq.ts +1 -10
  132. package/src/prover/isabelle/pure/simplifier.ts +4 -12
  133. package/src/prover/isabelle/pure/table.ts +3 -32
  134. package/src/prover/isabelle/pure/tactic.ts +12 -22
  135. package/src/prover/isabelle/pure/tactical.ts +48 -47
  136. package/src/prover/isabelle/pure/term-ord.ts +2 -6
  137. package/src/prover/isabelle/pure/term.ts +2 -43
  138. package/src/prover/isabelle/pure/thm.ts +27 -47
  139. package/src/prover/isabelle/pure/type.ts +2 -15
  140. package/src/prover/isabelle/pure/unify.ts +20 -30
  141. package/src/prover/isabelle/pure/variable.ts +3 -7
  142. package/src/prover/isabelle/tla/classical-setup.ts +17 -24
  143. package/src/prover/isabelle/tla/context.ts +15 -18
  144. package/src/prover/isabelle/tla/logic.ts +14 -32
  145. package/src/prover/isabelle/tla/simpdata.ts +46 -43
  146. package/src/prover/isabelle/tools/intuitionistic.ts +1 -10
  147. package/src/prover/ocaml.ts +0 -6
  148. package/src/prover/prep/action.ts +14 -54
  149. package/src/prover/prep/enabled-axioms.ts +12 -19
  150. package/src/prover/prep/fingerprint.ts +2 -21
  151. package/src/prover/prep/level-comparison.ts +8 -12
  152. package/src/prover/prep/md5.ts +0 -2
  153. package/src/prover/prep/methods.ts +33 -39
  154. package/src/prover/prep/normalize.ts +4 -28
  155. package/src/prover/prove-worker.ts +0 -2
  156. package/src/prover/prove.ts +87 -100
  157. package/src/prover/ptl/decide.ts +7 -12
  158. package/src/prover/ptl/encode.ts +14 -36
  159. package/src/prover/ptl/sat.ts +24 -32
  160. package/src/prover/ptl/tableau.ts +12 -26
  161. package/src/prover/smt/axioms.ts +0 -7
  162. package/src/prover/smt/context.ts +20 -28
  163. package/src/prover/smt/data.ts +433 -424
  164. package/src/prover/smt/encode.ts +43 -52
  165. package/src/prover/smt/extensionality.ts +0 -10
  166. package/src/prover/smt/flatten.ts +3 -22
  167. package/src/prover/smt/format.ts +5 -10
  168. package/src/prover/smt/instances.ts +0 -10
  169. package/src/prover/smt/rewrite.ts +663 -667
  170. package/src/prover/smt/solver/act-cache.ts +0 -15
  171. package/src/prover/smt/solver/arith-rewriter.ts +3 -48
  172. package/src/prover/smt/solver/array.ts +1 -3
  173. package/src/prover/smt/solver/asserted-formulas.ts +1 -43
  174. package/src/prover/smt/solver/ast-lt.ts +1 -11
  175. package/src/prover/smt/solver/ast-util.ts +1 -6
  176. package/src/prover/smt/solver/ast.ts +1 -165
  177. package/src/prover/smt/solver/auf-solver.ts +8 -44
  178. package/src/prover/smt/solver/case-split-queue.ts +1 -9
  179. package/src/prover/smt/solver/cg-table.ts +1 -18
  180. package/src/prover/smt/solver/clause.ts +1 -27
  181. package/src/prover/smt/solver/conflict-resolution.ts +0 -9
  182. package/src/prover/smt/solver/context.ts +7 -64
  183. package/src/prover/smt/solver/ctx-simplify.ts +14 -41
  184. package/src/prover/smt/solver/der.ts +2 -21
  185. package/src/prover/smt/solver/dyn-ack.ts +1 -11
  186. package/src/prover/smt/solver/e-matching.ts +4 -35
  187. package/src/prover/smt/solver/enode.ts +1 -21
  188. package/src/prover/smt/solver/expr-ref.ts +1 -5
  189. package/src/prover/smt/solver/expr-safe-replace.ts +1 -6
  190. package/src/prover/smt/solver/fingerprints.ts +1 -12
  191. package/src/prover/smt/solver/flat-literals.ts +1 -9
  192. package/src/prover/smt/solver/goal.ts +2 -14
  193. package/src/prover/smt/solver/hash.ts +0 -8
  194. package/src/prover/smt/solver/hashtable.ts +1 -12
  195. package/src/prover/smt/solver/internalizer.ts +7 -100
  196. package/src/prover/smt/solver/lbool.ts +1 -2
  197. package/src/prover/smt/solver/literal.ts +0 -3
  198. package/src/prover/smt/solver/lp/bound-propagator.ts +8 -26
  199. package/src/prover/smt/solver/lp/constraints.ts +2 -8
  200. package/src/prover/smt/solver/lp/containers.ts +12 -30
  201. package/src/prover/smt/solver/lp/core-solver.ts +10 -31
  202. package/src/prover/smt/solver/lp/cross-nested.ts +6 -20
  203. package/src/prover/smt/solver/lp/dep-intervals.ts +7 -22
  204. package/src/prover/smt/solver/lp/dependency.ts +1 -4
  205. package/src/prover/smt/solver/lp/dioph-eq.ts +9 -102
  206. package/src/prover/smt/solver/lp/explanation.ts +1 -6
  207. package/src/prover/smt/solver/lp/gomory.ts +9 -22
  208. package/src/prover/smt/solver/lp/hnf-cutter.ts +17 -23
  209. package/src/prover/smt/solver/lp/hnf.ts +11 -26
  210. package/src/prover/smt/solver/lp/int-cube.ts +15 -36
  211. package/src/prover/smt/solver/lp/int-solver.ts +4 -34
  212. package/src/prover/smt/solver/lp/lar-solver.ts +32 -81
  213. package/src/prover/smt/solver/lp/lar-term.ts +1 -5
  214. package/src/prover/smt/solver/lp/lp-settings.ts +1 -14
  215. package/src/prover/smt/solver/lp/maximize-term.ts +20 -45
  216. package/src/prover/smt/solver/lp/nex-creator.ts +5 -28
  217. package/src/prover/smt/solver/lp/nex.ts +1 -6
  218. package/src/prover/smt/solver/lp/nla-backoff.ts +1 -4
  219. package/src/prover/smt/solver/lp/nla-basics.ts +5 -30
  220. package/src/prover/smt/solver/lp/nla-core.ts +36 -135
  221. package/src/prover/smt/solver/lp/nla-divisions.ts +32 -42
  222. package/src/prover/smt/solver/lp/nla-emonics.ts +4 -21
  223. package/src/prover/smt/solver/lp/nla-factorization.ts +1 -4
  224. package/src/prover/smt/solver/lp/nla-grobner.ts +15 -69
  225. package/src/prover/smt/solver/lp/nla-horner.ts +3 -11
  226. package/src/prover/smt/solver/lp/nla-intervals.ts +2 -12
  227. package/src/prover/smt/solver/lp/nla-monomial-bounds.ts +16 -41
  228. package/src/prover/smt/solver/lp/nla-monotone.ts +2 -6
  229. package/src/prover/smt/solver/lp/nla-order.ts +2 -13
  230. package/src/prover/smt/solver/lp/nla-patcher.ts +4 -7
  231. package/src/prover/smt/solver/lp/nla-tangents.ts +1 -9
  232. package/src/prover/smt/solver/lp/nla-throttle.ts +1 -6
  233. package/src/prover/smt/solver/lp/nla-types.ts +1 -11
  234. package/src/prover/smt/solver/lp/nla-var-eqs.ts +4 -25
  235. package/src/prover/smt/solver/lp/nra-solver.ts +5 -52
  236. package/src/prover/smt/solver/lp/numeric-pair.ts +1 -4
  237. package/src/prover/smt/solver/lp/pdd-interval.ts +1 -3
  238. package/src/prover/smt/solver/lp/pdd-simplifier.ts +2 -14
  239. package/src/prover/smt/solver/lp/pdd-solver.ts +4 -33
  240. package/src/prover/smt/solver/lp/pdd.ts +7 -70
  241. package/src/prover/smt/solver/lp/random-updater.ts +1 -8
  242. package/src/prover/smt/solver/lp/static-matrix.ts +9 -19
  243. package/src/prover/smt/solver/lp/union-find.ts +1 -6
  244. package/src/prover/smt/solver/mam-compiler.ts +18 -58
  245. package/src/prover/smt/solver/mam-interpreter.ts +1 -21
  246. package/src/prover/smt/solver/maximize-ac-sharing.ts +2 -17
  247. package/src/prover/smt/solver/model-checker.ts +3 -37
  248. package/src/prover/smt/solver/model-evaluator.ts +3 -29
  249. package/src/prover/smt/solver/model-finder.ts +15 -32
  250. package/src/prover/smt/solver/model-generator.ts +1 -12
  251. package/src/prover/smt/solver/model-macro-solver.ts +23 -88
  252. package/src/prover/smt/solver/nlsat/algebraic.ts +63 -159
  253. package/src/prover/smt/solver/nlsat/atoms.ts +25 -23
  254. package/src/prover/smt/solver/nlsat/evaluator.ts +17 -22
  255. package/src/prover/smt/solver/nlsat/explain.ts +10 -69
  256. package/src/prover/smt/solver/nlsat/interval-set.ts +9 -50
  257. package/src/prover/smt/solver/nlsat/levelwise.ts +49 -135
  258. package/src/prover/smt/solver/nlsat/mpbq.ts +3 -14
  259. package/src/prover/smt/solver/nlsat/polynomial.ts +29 -159
  260. package/src/prover/smt/solver/nlsat/solver.ts +18 -90
  261. package/src/prover/smt/solver/nlsat/types.ts +1 -8
  262. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +2 -45
  263. package/src/prover/smt/solver/nlsat/upolynomial.ts +11 -92
  264. package/src/prover/smt/solver/nnf.ts +3 -38
  265. package/src/prover/smt/solver/pattern-inference.ts +2 -15
  266. package/src/prover/smt/solver/poly-rewriter.ts +3 -23
  267. package/src/prover/smt/solver/propagate-values.ts +1 -10
  268. package/src/prover/smt/solver/proto-model.ts +3 -52
  269. package/src/prover/smt/solver/pull-quant.ts +1 -12
  270. package/src/prover/smt/solver/qe-lite-der.ts +1 -29
  271. package/src/prover/smt/solver/qe-lite-fm.ts +2 -25
  272. package/src/prover/smt/solver/qe-lite.ts +3 -33
  273. package/src/prover/smt/solver/qi-queue.ts +1 -16
  274. package/src/prover/smt/solver/quant-tactics.ts +5 -22
  275. package/src/prover/smt/solver/quantifier-analyzer.ts +27 -47
  276. package/src/prover/smt/solver/quantifier-manager.ts +2 -13
  277. package/src/prover/smt/solver/random-gen.ts +1 -2
  278. package/src/prover/smt/solver/rational.ts +1 -8
  279. package/src/prover/smt/solver/ref-vector.ts +1 -6
  280. package/src/prover/smt/solver/relevancy.ts +2 -15
  281. package/src/prover/smt/solver/rewriter-tpl.ts +3 -147
  282. package/src/prover/smt/solver/rewriter.ts +3 -85
  283. package/src/prover/smt/solver/rlimit.ts +2 -20
  284. package/src/prover/smt/solver/smtlib-parser.ts +80 -131
  285. package/src/prover/smt/solver/solver.ts +23 -34
  286. package/src/prover/smt/solver/sort.ts +1 -5
  287. package/src/prover/smt/solver/sticky-generations.ts +0 -5
  288. package/src/prover/smt/solver/theory-lra-axioms.ts +3 -24
  289. package/src/prover/smt/solver/theory-lra-bounds.ts +1 -7
  290. package/src/prover/smt/solver/theory-lra-final-check.ts +4 -22
  291. package/src/prover/smt/solver/theory-lra-internalize.ts +6 -43
  292. package/src/prover/smt/solver/theory-lra-model.ts +4 -19
  293. package/src/prover/smt/solver/theory-lra-propagate.ts +1 -15
  294. package/src/prover/smt/solver/theory-lra-state.ts +3 -8
  295. package/src/prover/smt/solver/theory-lra.ts +1 -8
  296. package/src/prover/smt/solver/var-subst.ts +2 -26
  297. package/src/prover/smt/table.ts +0 -8
  298. package/src/prover/tlapm/cache.ts +45 -40
  299. package/src/prover/tlapm/ocaml-marshal.ts +19 -21
  300. package/src/prover/tlapm/tlapm.ts +21 -20
  301. package/src/prover/verdict.ts +7 -2
  302. package/src/prover/zenon/check/check.ts +1 -11
  303. package/src/prover/zenon/check/definitions.ts +5 -15
  304. package/src/prover/zenon/check/equality.ts +0 -8
  305. package/src/prover/zenon/check/functions.ts +0 -4
  306. package/src/prover/zenon/check/keys.ts +0 -7
  307. package/src/prover/zenon/check/propositional.ts +0 -3
  308. package/src/prover/zenon/check/records.ts +1 -6
  309. package/src/prover/zenon/check/relations.ts +2 -14
  310. package/src/prover/zenon/check/rewrites.ts +2 -21
  311. package/src/prover/zenon/check/sets.ts +40 -61
  312. package/src/prover/zenon/check/terms.ts +1 -19
  313. package/src/prover/zenon/check/tla.ts +0 -6
  314. package/src/prover/zenon/decide.ts +0 -12
  315. package/src/prover/zenon/encode.ts +1 -8
  316. package/src/prover/zenon/eqrel.ts +2 -13
  317. package/src/prover/zenon/equality-rules.ts +0 -4
  318. package/src/prover/zenon/expr.ts +8 -26
  319. package/src/prover/zenon/index-table.ts +26 -57
  320. package/src/prover/zenon/isar-case.ts +9 -19
  321. package/src/prover/zenon/isar.ts +36 -64
  322. package/src/prover/zenon/limits.ts +0 -4
  323. package/src/prover/zenon/llproof.ts +2 -20
  324. package/src/prover/zenon/mltoll.ts +66 -104
  325. package/src/prover/zenon/node.ts +1 -11
  326. package/src/prover/zenon/ocaml.ts +1 -17
  327. package/src/prover/zenon/parse.ts +4 -12
  328. package/src/prover/zenon/phrase.ts +1 -11
  329. package/src/prover/zenon/proof.ts +0 -9
  330. package/src/prover/zenon/propositional-rules.ts +0 -5
  331. package/src/prover/zenon/rules.ts +2 -6
  332. package/src/prover/zenon/search.ts +5 -31
  333. package/src/prover/zenon/tla/functions.ts +59 -31
  334. package/src/prover/zenon/tla/llproof.ts +67 -76
  335. package/src/prover/zenon/tla/records.ts +57 -33
  336. package/src/prover/zenon/tla/rewrites.ts +12 -19
  337. package/src/prover/zenon/tla/sets.ts +83 -53
  338. package/src/prover/zenon/tla/terms.ts +0 -6
  339. package/src/prover/zenon/tla/tla.ts +66 -64
  340. package/src/randomization.ts +81 -35
  341. package/src/resolve.ts +67 -184
  342. package/src/runtime.ts +22 -22
  343. package/src/sany/builtins.ts +2 -5
  344. package/src/sany/generation.ts +394 -0
  345. package/src/sany/generator-def-entries.ts +210 -0
  346. package/src/sany/generator-definitions.ts +686 -0
  347. package/src/sany/generator-expressions.ts +1100 -0
  348. package/src/sany/generator-proofs.ts +662 -0
  349. package/src/sany/generator.ts +191 -2764
  350. package/src/sany/levels.ts +6 -34
  351. package/src/sany/lexer.ts +58 -77
  352. package/src/sany/linter.ts +1 -9
  353. package/src/sany/modules.ts +1 -5
  354. package/src/sany/nodes.ts +5 -43
  355. package/src/sany/parse-error.ts +39 -117
  356. package/src/sany/report.ts +32 -69
  357. package/src/sany/selectors.ts +49 -76
  358. package/src/sany/source.ts +1 -17
  359. package/src/sany/xml.ts +35 -117
  360. package/src/search.ts +541 -163
  361. package/src/simulate.ts +709 -0
  362. package/src/spec-description.ts +192 -100
  363. package/src/standard-definitions.ts +0 -4
  364. package/src/standard-modules.ts +264 -95
  365. package/src/state-graph.ts +52 -31
  366. package/src/subexpressions.ts +69 -52
  367. package/src/substitution-levels.ts +7 -7
  368. package/src/successors.ts +266 -99
  369. package/src/symmetry.ts +33 -25
  370. package/src/tableau.ts +27 -24
  371. package/src/tlc/fingerprint.ts +183 -67
  372. package/src/tlc/jar-data.ts +112 -6
  373. package/src/tlc/messages.ts +125 -54
  374. package/src/tlc/order.ts +39 -69
  375. package/src/tlc/random.ts +37 -49
  376. package/src/tlc/replay.ts +553 -228
  377. package/src/tlc/summary.ts +36 -47
  378. package/src/tlc/tlc-operators.ts +78 -44
  379. package/src/tlc/tlcext-operators.ts +139 -122
  380. package/src/tlc/trace-spec.ts +249 -0
  381. package/src/tlc/value-stream.ts +139 -0
  382. package/src/tlc/version.ts +1 -4
  383. package/src/transfer.ts +22 -25
  384. package/src/typescript/actions.ts +479 -0
  385. package/src/typescript/collections.ts +614 -0
  386. package/src/typescript/compile.ts +63 -0
  387. package/src/typescript/context.ts +94 -0
  388. package/src/typescript/emit.ts +121 -0
  389. package/src/typescript/expressions.ts +496 -0
  390. package/src/typescript/formula.ts +154 -0
  391. package/src/typescript/functions.ts +284 -0
  392. package/src/typescript/model.ts +162 -0
  393. package/src/typescript/names.ts +114 -0
  394. package/src/typescript/program.ts +48 -0
  395. package/src/typescript/properties.ts +139 -0
  396. package/src/typescript/scope.ts +112 -0
  397. package/src/typescript/steps.ts +167 -0
  398. package/src/typescript/types.ts +171 -0
  399. package/src/values.ts +832 -484
  400. package/src/worker.ts +7 -8
package/src/cli/tlc.ts CHANGED
@@ -1,72 +1,74 @@
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";
10
- import { arch, availableParallelism, release, tmpdir, type } from "node:os";
11
- import { pathToFileURL } from "node:url";
12
- import { getHeapStatistics } from "node:v8";
13
- import { version } from "../../package.json";
14
- import type { Expression } from "../ast";
15
- import { describeRange } from "../evaluate";
16
- import type {
17
- CheckProgress,
18
- InitialStateViolation,
19
- OutputLine,
20
- CheckResult,
21
- CheckStatus,
22
- InitialStates,
23
- SearchStatistics,
24
- TraceStep,
25
- Violation,
26
- } from "../check";
14
+ import { tmpdir } from "node:os";
15
+ import type { CheckOptions, ModuleOperator, CheckStatus } from "../check";
27
16
  import { parseConfig } from "../config";
17
+ import { checkDepthFirst } from "../dfid";
28
18
  import {
29
- getErrorExitCode,
30
19
  TlaConfigError,
31
20
  TlaError,
32
21
  TlaEvaluationError,
22
+ TlaFeatureUnsupportedError,
23
+ TlaMissingCheckpointError,
33
24
  TlaSyntaxError,
34
25
  getUnexpectedException,
35
- UNEXPECTED_EXCEPTION,
36
26
  TlaSanyFatalError,
37
27
  } from "../errors";
38
- import { EXIT_STATUS, setExitCode } from "../exit-codes";
28
+ import { EXIT_STATUS } from "../exit-codes";
39
29
  import { check } from "../parallel";
40
- import { parseModule } from "../parser";
30
+ import { extractModule, parseModule } from "../parser";
31
+ import { simulate } from "../simulate";
41
32
  import type { StateDump } from "../state-graph";
42
33
  import {
43
- formatProbability,
44
- getActualProbability,
45
- getOptimisticProbability,
46
- getOutDegreeSummary,
47
- } from "../tlc/summary";
48
- import { SANY_174_STANDARD_MODULES, SANY_STANDARD_MODULES } from "../sany/modules";
34
+ getSanyStandardModules,
35
+ SANY_174_STANDARD_MODULES,
36
+ SANY_STANDARD_MODULES,
37
+ } from "../sany/modules";
49
38
  import { getSanyReport, type SanyModuleOrigin } from "../sany/report";
50
39
  import { getTlcFingerprint } from "../tlc/fingerprint";
51
40
  import type { TlcVersion } from "../tlc/version";
52
41
  import {
53
42
  createMessagePrinter,
54
43
  formatTlcDate,
55
- formatInnerMessage,
56
44
  formatNestedMessage,
57
45
  formatTlcDuration,
58
46
  MESSAGE_CODE,
59
47
  MESSAGE_LEVEL,
60
48
  type MessagePrinter,
49
+ zeroPad,
61
50
  } from "../tlc/messages";
62
- import { formatState } from "../values";
63
- import { CHECK_COMMAND, USAGE, type ParsedArgs } from "./options";
51
+ import { addRuntimeInvariants } from "./runtime-invariants";
52
+ import { parseTlcArguments, type TlcArguments } from "./tlc-arguments";
53
+ import {
54
+ getClassPath,
55
+ printCheckProgress,
56
+ printCommandLineError,
57
+ printDepthFirst,
58
+ printResult,
59
+ printSimulation,
60
+ printStartupBanner,
61
+ printWelcome,
62
+ type Timing,
63
+ } from "./tlc-output";
64
+ import { getTlcUsage } from "./tlc-usage";
64
65
  import {
65
66
  createModuleLoader,
66
67
  findModuleFile,
67
68
  getInputPaths,
68
69
  getToolsJar,
69
70
  getStandardModulesUrl,
71
+ getTopLevelExitCode,
70
72
  printError,
71
73
  printMissingFile,
72
74
  printMissingFile174,
@@ -75,6 +77,7 @@ import {
75
77
  toLibraryPath,
76
78
  type JavaProperties,
77
79
  } from "./shared";
80
+ import { writeTypeScriptSpec } from "./typescript";
78
81
 
79
82
  const EXIT_CODES: Record<CheckStatus, number> = {
80
83
  success: EXIT_STATUS.success,
@@ -87,19 +90,12 @@ const EXIT_CODES: Record<CheckStatus, number> = {
87
90
  error: EXIT_STATUS.error,
88
91
  };
89
92
 
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);
93
+ const checkNotDirectory = (path: string) => {
94
+ if (statSync(path, { throwIfNoEntry: false })?.isDirectory()) {
95
+ throw new TlaEvaluationError(`${path} (Is a directory)`);
96
+ }
98
97
  };
99
98
 
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
99
  const getDumpPath = (path: string, extension: string) =>
104
100
  path.endsWith(extension) ? path : `${path}${extension}`;
105
101
 
@@ -112,491 +108,15 @@ const getStateDump = (values: string[]): StateDump => {
112
108
  colorize: format.includes("colorize"),
113
109
  actionLabels: format.includes("actionlabels"),
114
110
  snapshot: format.includes("snapshot"),
111
+ constrained: format.includes("constrained"),
112
+ stuttering: format.includes("stuttering"),
113
+ strict: format.includes("strict"),
115
114
  };
116
115
  };
117
116
 
118
- const printInitialStatesProgress = (printer: MessagePrinter, count: number) =>
119
- printer.print(
120
- MESSAGE_CODE.computingInitProgress,
121
- MESSAGE_LEVEL.none,
122
- `Computed ${count} initial states...`,
123
- );
124
-
125
- const getInitialViolationHeadline = (
126
- status: InitialStateViolation["status"],
127
- name: string | undefined,
128
- ) =>
129
- status === "invariant-violation"
130
- ? {
131
- code: MESSAGE_CODE.invariantViolatedInitial,
132
- text: `Invariant ${name} is violated by the initial state:`,
133
- }
134
- : {
135
- code: MESSAGE_CODE.propertyViolatedInitial,
136
- text: `Property ${name} is violated by the initial state:`,
137
- };
138
-
139
- // What the spec prints as TLC rebuilds a trace, before it prints the states or after.
140
- const printTraceOutput = (printer: MessagePrinter, lines: OutputLine[] | undefined) =>
141
- lines?.forEach((line) => {
142
- if (typeof line === "string") return console.log(line);
143
- if (line.kind === "initial-states-progress") {
144
- return printInitialStatesProgress(printer, line.count);
145
- }
146
- const headline = getInitialViolationHeadline(line.status, line.name);
147
- printer.print(
148
- headline.code,
149
- MESSAGE_LEVEL.error,
150
- `${headline.text}\n${formatState(line.state)}`,
151
- );
152
- });
153
-
154
- const printTrace = (
155
- printer: MessagePrinter,
156
- trace: TraceStep[],
157
- heading: { code: number; text: string } = {
158
- code: MESSAGE_CODE.behaviorUpToThisPoint,
159
- text: "The behavior up to this point is:",
160
- },
161
- isRebuiltAfterHeading = false,
162
- ) => {
163
- 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
- });
172
- };
173
-
174
- const COUNTER_EXAMPLE = {
175
- code: MESSAGE_CODE.counterExample,
176
- text: "The following behavior constitutes a counter-example:\n",
177
- };
178
-
179
- // TLC 1.7.4 doesn't name the properties, and later versions name none when they can't tell which.
180
- const getTemporalHeadline = (names: string[], version: TlcVersion) =>
181
- version === "1.7.4" || names.length === 0
182
- ? "Temporal properties were violated.\n"
183
- : names.length === 1
184
- ? `Temporal property ${names[0]} was violated.\n`
185
- : `Temporal properties ${names.slice(0, -1).join(", ")}${names.length > 2 ? "," : ""} and ${names[names.length - 1]} were violated.\n`;
186
-
187
- // TLC's FingerprintException#getTrace: the range of each source, innermost first, skipping a
188
- // source the same as the one inside it.
189
- const formatFingerprintTrace = (sources: Expression[]) =>
190
- sources
191
- .filter((source, index) => source !== sources[index - 1])
192
- .map((source, index) => `${index}) ${describeRange(source)}\n`)
193
- .toReversed()
194
- .join("");
195
-
196
- // TLC's CallStack.toString: the range of each expression, skipping an expression that it evaluates
197
- // again right inside itself.
198
- const formatCallStack = (expressions: Expression[]) => {
199
- if (expressions.length === 0) return " The error call stack is empty.\n";
200
- const lines: string[] = [];
201
- expressions.forEach((expression, index) => {
202
- const range = expression.location.range;
203
- if (expression === expressions[index - 1] || !range) return;
204
- lines.push(
205
- `${lines.length}. Line ${range.start.line}, column ${range.start.column} to line ${range.end.line}, column ${range.end.column} in ${range.module}\n`,
206
- );
207
- });
208
- return `${lines.join("")}\n`;
209
- };
210
-
211
- const printInitialStates = (printer: MessagePrinter, initialStates: InitialStates) => {
212
- const generated = initialStates.generated;
213
- const distinct = initialStates.distinct;
214
- const date = formatTlcDate(new Date());
215
- if (generated === distinct) {
216
- printer.print(
217
- MESSAGE_CODE.initGenerated1,
218
- MESSAGE_LEVEL.none,
219
- `Finished computing initial states: ${distinct} distinct state${distinct === 1 ? "" : "s"} generated at ${date}.`,
220
- );
221
- return;
222
- }
223
- printer.print(
224
- MESSAGE_CODE.initGenerated2,
225
- MESSAGE_LEVEL.none,
226
- `Finished computing initial states: ${generated} state${generated === 1 ? "" : "s"} generated, with ${distinct} of them distinct at ${date}.`,
227
- );
228
- };
229
-
230
- interface Timing {
231
- startTime: number;
232
- // Whether TLC has printed that SANY finished.
233
- isParsed: boolean;
234
- livenessStartTime: number | undefined;
235
- }
236
-
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
- const printProgress = (
240
- printer: MessagePrinter,
241
- statistics: SearchStatistics,
242
- startTime?: number,
243
- ) => {
244
- const minutes = Math.max(Date.now() - (startTime ?? 0), 1) / 60_000;
245
- const formatCount = (count: number) => count.toLocaleString("en-US");
246
- const getRate = (count: number, unit: string) =>
247
- startTime === undefined ? "" : ` (${formatCount(Math.floor(count / minutes))} ${unit}/min)`;
248
- printer.print(
249
- MESSAGE_CODE.progress,
250
- MESSAGE_LEVEL.none,
251
- `Progress(${Math.max(statistics.depth, 1)}) at ${formatTlcDate(new Date())}: ${formatCount(statistics.generatedStates)} states generated${getRate(statistics.generatedStates, "s")}, ${formatCount(statistics.distinctStates)} distinct states found${getRate(statistics.distinctStates, "ds")}, ${formatCount(statistics.queuedStates)} states left on queue.`,
252
- );
253
- };
254
-
255
- const getClassPath = (directory: string, module: string) => join(directory, `${module}.class`);
256
-
257
- const printCheckProgress = (
258
- printer: MessagePrinter,
259
- progress: CheckProgress,
260
- timing: Timing,
261
- directory: string,
262
- ) => {
263
- const print = printer.print;
264
- switch (progress.kind) {
265
- case "parsed":
266
- timing.isParsed = true;
267
- if (printer.isTool) print(MESSAGE_CODE.sanyFinished, MESSAGE_LEVEL.none, "SANY finished.");
268
- print(
269
- MESSAGE_CODE.starting,
270
- MESSAGE_LEVEL.none,
271
- `Starting... (${formatTlcDate(new Date())})`,
272
- );
273
- return;
274
- // TLC 1.7.4 warns about neither a constant-level invariant nor a state-level property.
275
- case "constant-level-invariant":
276
- if (printer.version === "1.7.4") return;
277
- print(
278
- MESSAGE_CODE.constantLevelInvariant,
279
- MESSAGE_LEVEL.warning,
280
- `The invariant ${progress.name} is a constant-level formula (i.e., it contains no variables, primes, or temporal operators) and evaluates to TRUE. To assert constant-level formulas in your spec, use ASSUME ConstInv. If you optionally want to give the assumption a name, write ASSUME YourAssumption == ConstInv instead. See https://explain.tlapl.us/assumptions-and-invariants for additional details.`,
281
- );
282
- return;
283
- case "state-level-property":
284
- if (printer.version === "1.7.4") return;
285
- print(
286
- MESSAGE_CODE.stateLevelProperty,
287
- MESSAGE_LEVEL.warning,
288
- `The formula ${progress.name} is a state-level formula, but it was used as a PROPERTY (or PROPERTIES), where a temporal formula is typically expected. State-level formulas used as PROPERTY or PROPERTIES are only checked in the initial state. To verify that the formula ${progress.name} holds in all states of every behavior, use INVARIANT ${progress.name} instead. Alternatively, applying the "always" temporal operator ([]) to the state-level formula ${progress.name} changes it into a temporal formula, asserting that ${progress.name} holds in all states of every behavior. See https://explain.tlapl.us/invariants-and-properties for additional details.`,
289
- );
290
- return;
291
- case "liveness-initializing":
292
- if (progress.isSymmetric) {
293
- print(
294
- MESSAGE_CODE.livenessSymmetry,
295
- MESSAGE_LEVEL.warning,
296
- "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
- );
298
- }
299
- // Only TLC 1.7.4 warns about constraints.
300
- if (progress.isConstrained && printer.version === "1.7.4") {
301
- print(
302
- MESSAGE_CODE.livenessConstraints,
303
- MESSAGE_LEVEL.warning,
304
- "Declaring state or action constraints during liveness checking is dangerous: Please read section 14.3.5 on page 247 of Specifying Systems (https://lamport.azurewebsites.net/tla/book.html) and optionally the discussion at https://discuss.tlapl.us/msg00994.html for more details.",
305
- );
306
- }
307
- return;
308
- case "liveness-prepared":
309
- print(
310
- MESSAGE_CODE.temporalBranches,
311
- MESSAGE_LEVEL.none,
312
- `Implied-temporal checking--satisfiability problem has ${progress.branches} branches.`,
313
- );
314
- return;
315
- case "java-override": {
316
- // Class#getResource, which names the class file TLC loads the override from.
317
- const location = pathToFileURL(resolve(getClassPath(directory, progress.module))).href;
318
- print(
319
- progress.isMatched ? MESSAGE_CODE.javaOverrideLoaded : MESSAGE_CODE.javaOverrideMismatch,
320
- progress.isMatched ? MESSAGE_LEVEL.none : MESSAGE_LEVEL.warning,
321
- `${progress.isMatched ? "Loading" : "Failed to match"} ${progress.operator} operator override from ${location.replace("file:///", "file:/")} with signature: <Java Method: ${progress.signature}>.`,
322
- );
323
- return;
324
- }
325
- case "initial-states-started":
326
- print(MESSAGE_CODE.computingInit, MESSAGE_LEVEL.none, "Computing initial states...");
327
- return;
328
- case "initial-states-progress":
329
- printInitialStatesProgress(printer, progress.count);
330
- return;
331
- case "initial-states-computed":
332
- printInitialStates(printer, progress.initialStates);
333
- return;
334
- case "progress":
335
- printProgress(printer, progress.statistics, timing.startTime);
336
- return;
337
- case "liveness-started": {
338
- timing.livenessStartTime = Date.now();
339
- // TLC reports how far the search got before it checks the complete state graph.
340
- if (progress.isComplete) printProgress(printer, progress.statistics);
341
- 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
- const states = progress.branches * progress.states;
344
- print(
345
- MESSAGE_CODE.checkingTemporal,
346
- MESSAGE_LEVEL.none,
347
- `Checking ${branches}temporal properties for the ${progress.isComplete ? "complete" : "current"} state space with ${states} total distinct states at (${formatTlcDate(new Date())})`,
348
- );
349
- return;
350
- }
351
- case "liveness-finished":
352
- printLivenessEnd(printer, timing);
353
- return;
354
- case "sequential-fallback":
355
- 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`,
357
- );
358
- return;
359
- case "warning":
360
- print(progress.code, MESSAGE_LEVEL.warning, progress.text);
361
- return;
362
- case "violation":
363
- printViolation(progress.status, progress.violation, printer);
364
- }
365
- };
366
-
367
- const printLivenessEnd = (printer: MessagePrinter, timing: Timing) => {
368
- if (timing.livenessStartTime === undefined) return;
369
- printer.print(
370
- MESSAGE_CODE.checkingTemporalEnd,
371
- MESSAGE_LEVEL.none,
372
- `Finished checking temporal properties in ${formatTlcDuration(Date.now() - timing.livenessStartTime)} at ${formatTlcDate(new Date())}`,
373
- );
374
- timing.livenessStartTime = undefined;
375
- };
376
-
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) => {
379
- const print = printer.print;
380
- const name = violation.name;
381
- const loopStart = violation.loopStart;
382
- // TLC prints a violation by an initial state without the behavior or the statistics.
383
- const isInitial =
384
- loopStart === undefined &&
385
- violation.trace.length === 1 &&
386
- (status === "invariant-violation" || status === "liveness-violation");
387
- const temporal = {
388
- code: MESSAGE_CODE.temporalPropertyViolated,
389
- text: getTemporalHeadline(violation.properties ?? [name], printer.version),
390
- };
391
- const headline = {
392
- success: undefined,
393
- error: undefined,
394
- "assumption-violation": violation.message
395
- ? {
396
- code: MESSAGE_CODE.assumptionEvaluationError,
397
- text: formatInnerMessage(
398
- MESSAGE_CODE.assumptionEvaluationError,
399
- `Evaluating assumption ${name} failed.\n${violation.message}`,
400
- printer.isTool,
401
- ),
402
- }
403
- : { code: MESSAGE_CODE.assumptionFalse, text: `Assumption ${name} is false.` },
404
- deadlock: { code: MESSAGE_CODE.deadlockReached, text: "Deadlock reached." },
405
- "invariant-violation": isInitial
406
- ? getInitialViolationHeadline("invariant-violation", name)
407
- : { code: MESSAGE_CODE.invariantViolatedBehavior, text: `Invariant ${name} is violated.` },
408
- "property-violation": temporal,
409
- "liveness-violation":
410
- loopStart !== undefined
411
- ? temporal
412
- : isInitial
413
- ? getInitialViolationHeadline("liveness-violation", name)
414
- : {
415
- code: MESSAGE_CODE.actionPropertyViolatedBehavior,
416
- text: `Action property ${name} is violated.`,
417
- },
418
- "postcondition-violation": {
419
- code: violation.postcondition?.code ?? MESSAGE_CODE.general,
420
- text: violation.message ?? `Postcondition ${name} is false.`,
421
- },
422
- }[status];
423
- // A safety property's counterexample ends where it breaks, and a liveness one loops back.
424
- const isProperty = status === "property-violation";
425
- const isLasso = loopStart !== undefined && !isProperty;
426
- 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
- const isRebuiltFirst = isCounterExample && printer.version !== "1.7.4";
430
- if (isRebuiltFirst) printTraceOutput(printer, violation.trace[0]?.output);
431
- if (violation.counts) console.log(violation.counts);
432
- if (headline) {
433
- // TLC prints the initial state that violates a property in the same message.
434
- const text = isInitial
435
- ? `${headline.text}\n${formatState(violation.trace[0].state)}`
436
- : headline.text;
437
- print(headline.code, MESSAGE_LEVEL.error, text);
438
- }
439
- if (!isInitial) {
440
- if (!isCounterExample) printTraceOutput(printer, violation.trace[0]?.output);
441
- printTrace(
442
- printer,
443
- violation.trace,
444
- isCounterExample ? COUNTER_EXAMPLE : undefined,
445
- isCounterExample && !isRebuiltFirst,
446
- );
447
- printTraceOutput(printer, violation.traceOutput);
448
- }
449
- if (isLasso) {
450
- const label = violation.loopLabel;
451
- if (loopStart === violation.trace.length - 1)
452
- print(MESSAGE_CODE.statePrint3, MESSAGE_LEVEL.state, `${loopStart + 2}: Stuttering`);
453
- else if (printer.isTool)
454
- print(
455
- MESSAGE_CODE.backToState,
456
- MESSAGE_LEVEL.state,
457
- `${loopStart + 1}: Back to state${label ? `: <${label}>\n` : ""}`,
458
- );
459
- else console.log(`Back to state ${loopStart + 1}${label ? `: <${label}>\n` : ""}`);
460
- }
461
- // TLC 1.7.4 doesn't explain a stuttering counterexample.
462
- if (violation.warning && printer.version !== "1.7.4")
463
- print(violation.warning.code, MESSAGE_LEVEL.warning, violation.warning.text);
464
- // TLC checks the postconditions after it prints a counterexample.
465
- const postcondition =
466
- violation.unwitnessed ??
467
- (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.
471
- return !isInitial && status !== "assumption-violation";
472
- };
473
-
474
- const printNestedExpressions = (printer: MessagePrinter, callStack: Expression[]) =>
475
- printer.print(
476
- MESSAGE_CODE.nestedExpression,
477
- MESSAGE_LEVEL.error,
478
- `The error occurred when TLC was evaluating the nested\nexpressions at the following positions:\n${formatCallStack(callStack)}`,
479
- );
480
-
481
- const printResult = (result: CheckResult, printer: MessagePrinter, timing: Timing) => {
482
- const print = printer.print;
483
- if (result.failure) {
484
- const failure = result.failure;
485
- const message = printer.isTool ? failure.toolMessage : failure.message;
486
- const printCallStack = () => {
487
- const fingerprint = failure.fingerprint;
488
- 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
- const trace =
492
- failure.callStack?.length && printer.version !== "1.7.4"
493
- ? formatCallStack(failure.callStack)
494
- : formatFingerprintTrace(fingerprint.sources);
495
- print(
496
- MESSAGE_CODE.fingerprintFailed,
497
- MESSAGE_LEVEL.error,
498
- `TLC was unable to fingerprint.\n\nFingerprint Stack Trace:\n${trace}\nReason:\n${formatNestedMessage(fingerprint.reason, printer.isTool)}`,
499
- );
500
- return;
501
- }
502
- if (failure.callStack) printNestedExpressions(printer, failure.callStack);
503
- };
504
- 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
- const initialState =
508
- failure.initialState &&
509
- (() => {
510
- try {
511
- return `While working on the initial state:\n${formatState(failure.initialState)}`;
512
- } catch (error) {
513
- if (!(error instanceof TlaEvaluationError)) throw error;
514
- throw setExitCode(
515
- new TlaEvaluationError(`${UNEXPECTED_EXCEPTION}${error.message}`),
516
- EXIT_STATUS.error,
517
- );
518
- }
519
- })();
520
- // TLC prints an error on an initial state and the state as one message.
521
- print(
522
- initialState ? MESSAGE_CODE.initialState : failure.code,
523
- MESSAGE_LEVEL.error,
524
- initialState ? `${message}\n${initialState}` : message,
525
- );
526
- printTraceOutput(printer, failure.trace[0]?.output);
527
- printTrace(printer, failure.trace);
528
- const traceFailure = failure.traceFailure;
529
- if (traceFailure) {
530
- print(
531
- traceFailure.code,
532
- MESSAGE_LEVEL.error,
533
- printer.isTool ? traceFailure.toolMessage : traceFailure.message,
534
- );
535
- }
536
- 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);
540
- if (!failure.isCallStackFirst) printCallStack();
541
- } else if (result.violation) {
542
- 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
- const additionalViolation = result.additionalViolation;
546
- if (additionalViolation) printViolation("property-violation", additionalViolation, printer);
547
- if (result.liveCallStack) printNestedExpressions(printer, result.liveCallStack);
548
- } else {
549
- printLivenessEnd(printer, timing);
550
- const optimistic = getOptimisticProbability(result.distinctStates, result.generatedStates);
551
- const actual =
552
- 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"),
567
- );
568
- }
569
- if (result.failure?.isWithoutStatistics) return;
570
- if (result.status !== "success") printLivenessEnd(printer, timing);
571
- if (printer.isTool) printProgress(printer, result, timing.startTime);
572
- print(
573
- MESSAGE_CODE.stats,
574
- MESSAGE_LEVEL.none,
575
- `${result.generatedStates} states generated, ${result.distinctStates} distinct states found, ${result.queuedStates} states left on queue.`,
576
- );
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
- const is174 = printer.version === "1.7.4";
580
- const outDegrees = is174 ? (result.outDegrees ?? result.violationOutDegrees) : result.outDegrees;
581
- if (!is174 || outDegrees) {
582
- print(
583
- MESSAGE_CODE.searchDepth,
584
- MESSAGE_LEVEL.none,
585
- `The depth of the complete state graph search is ${is174 ? Math.max(result.depth, 1) : result.depth}.`,
586
- );
587
- }
588
- const outDegree = outDegrees && getOutDegreeSummary(outDegrees);
589
- if (outDegree) print(MESSAGE_CODE.stateGraphOutdegree, MESSAGE_LEVEL.none, outDegree);
590
- };
591
-
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.
117
+ // 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
118
  const getTemporaryName = (contents: string) => getTlcFingerprint([contents]).toString();
596
119
 
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
120
  const createFileDescriber = (
601
121
  specPath: string,
602
122
  directories: string[],
@@ -611,9 +131,7 @@ const createFileDescriber = (
611
131
  return (name: string, origin: SanyModuleOrigin) => {
612
132
  const fileName = `${name}.tla`;
613
133
  if (origin === "file") return realpathSync(findModuleFile(directories, name) ?? specPath);
614
- // TLC 1.7.4 copies a standard module into the temporary directory itself.
615
134
  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
135
  if (origin === "root file") {
618
136
  const directory = metadir === undefined ? temporaryDirectory : resolve(metadir);
619
137
  const root = realpathSync(specPath);
@@ -624,100 +142,123 @@ const createFileDescriber = (
624
142
  };
625
143
  };
626
144
 
627
- const printWelcome = (printer: MessagePrinter) =>
628
- printer.print(MESSAGE_CODE.version, MESSAGE_LEVEL.none, `TLC2 Version ${version} (rev: tla-ts)`);
629
-
630
- // TLC.printErrorMsg: TLC says which version it is, then why it can't read its options.
631
- const printCommandLineError = (printer: MessagePrinter, message: string) => {
632
- printWelcome(printer);
633
- printer.print(
634
- MESSAGE_CODE.commandLineError,
635
- MESSAGE_LEVEL.error,
636
- `${message}\nUsage: java tlc2.TLC [-help] [-option] inputfile`,
145
+ const getEmbeddedConfig = (contents: string, name: string) => {
146
+ const lines = contents.split(/\r?\n/);
147
+ const start = lines.findIndex(
148
+ (line) => line.match(/^-----*\s*CONFIG\s+(\S+?)\s*-----*$/)?.[1] === name,
637
149
  );
638
- return 1;
150
+ if (start === -1) return "\n";
151
+ const end = lines.findIndex((line, index) => index > start && line.startsWith("===="));
152
+ return `${lines
153
+ .slice(start + 1, end === -1 ? undefined : end)
154
+ .join("\n")
155
+ .trim()}\n`;
639
156
  };
640
157
 
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) =>
644
- printer.print(
645
- MESSAGE_CODE.modelChecking,
646
- 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).`,
648
- );
158
+ const getJavaPath = (path: string) => path.replace(/\/+/g, "/").replace(/(.)\/$/, "$1");
649
159
 
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");
160
+ const getJavaParent = (path: string) => {
161
+ const normalized = getJavaPath(path);
162
+ const separator = normalized.lastIndexOf("/");
163
+ return separator === -1 ? "." : normalized.slice(0, Math.max(separator, 1));
164
+ };
165
+
166
+ const resolveJavaPath = (directory: string, name: string) =>
167
+ directory.endsWith("/") ? `${directory}${name}` : `${directory}/${name}`;
168
+
169
+ const getTraceSpecLocation = (
170
+ args: TlcArguments,
171
+ version: TlcVersion,
172
+ mainFile: string,
173
+ startTime: number,
174
+ ) => {
175
+ const isGenerated =
176
+ version !== "1.7.4" &&
177
+ (args.isTraceSpecForced ||
178
+ (!args.isTraceSpecDisabled &&
179
+ !args.isTool &&
180
+ !args.isContinued &&
181
+ !basename(mainFile).includes("_TTrace")));
182
+ if (!isGenerated) return undefined;
183
+ const output = args.traceSpecPath;
184
+ const module = `${basename(mainFile)}_TTrace_${Math.floor(startTime / 1000)}`;
185
+ const location =
186
+ output === undefined
187
+ ? { directory: getJavaParent(mainFile), module }
188
+ : output.toLowerCase().endsWith(".tla")
189
+ ? { directory: getJavaParent(output), module: basename(output).replace(/\.tla$/, "") }
190
+ : { directory: getJavaPath(output), module };
191
+ return {
192
+ ...location,
193
+ traceFile: args.isTraceBinaryDisabled
194
+ ? undefined
195
+ : resolveJavaPath(location.directory, `${location.module}.bin`),
196
+ };
197
+ };
198
+
199
+ const JAVA_FILE_ERRORS: Record<string, string> = {
200
+ ENOENT: "No such file or directory",
201
+ ENOTDIR: "Not a directory",
202
+ EISDIR: "Is a directory",
203
+ EACCES: "Permission denied",
204
+ };
205
+
206
+ const writeJavaFile = (path: string, content: string | Uint8Array) => {
207
+ try {
208
+ writeFileSync(path, content);
209
+ } catch (error) {
210
+ const reason =
211
+ error instanceof Error && "code" in error ? JAVA_FILE_ERRORS[String(error.code)] : undefined;
212
+ if (reason === undefined) throw error;
213
+ throw new TlaEvaluationError(`${path} (${reason})`);
214
+ }
215
+ };
216
+
217
+ // Java's File#mkdirs reports a failure only through its result, which TLC ignores.
218
+ const makeJavaDirectory = (path: string) => {
219
+ try {
220
+ mkdirSync(path, { recursive: true });
221
+ } catch {}
222
+ };
223
+
224
+ const createMetadir = (args: TlcArguments) => {
225
+ const now = new Date();
226
+ const name = `${zeroPad(now.getFullYear() % 100)}-${zeroPad(now.getMonth() + 1)}-${zeroPad(now.getDate())}-${zeroPad(now.getHours())}-${zeroPad(now.getMinutes())}-${zeroPad(now.getSeconds())}.${zeroPad(now.getMilliseconds(), 3)}`;
227
+ const directory = join(args.metadir ?? "states", name);
228
+ mkdirSync(directory, { recursive: true });
229
+ return directory;
661
230
  };
662
231
 
663
232
  const checkSpec = async (
664
233
  specPath: string,
665
- args: ParsedArgs,
234
+ args: TlcArguments,
235
+ dump: StateDump | undefined,
666
236
  java: JavaProperties,
667
237
  printer: MessagePrinter,
668
238
  ) => {
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"));
239
+ const livenessCheck = args.livenessCheck;
704
240
  const version = printer.version;
705
241
  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)) {
242
+ const recoverDirectory = args.recoverDirectory;
243
+ if (recoverDirectory !== undefined) {
244
+ throw existsSync(join(recoverDirectory, "vars.chkpt"))
245
+ ? new TlaFeatureUnsupportedError(
246
+ `tla-ts can't recover a model check from the checkpoint in ${recoverDirectory}.`,
247
+ )
248
+ : new TlaMissingCheckpointError(recoverDirectory);
249
+ }
250
+ printStartupBanner(printer, args);
251
+ const configPath = args.configPath ?? specPath.replace(/\.tla$/, ".cfg");
252
+ if (!existsSync(configPath)) {
711
253
  printer.print(
712
254
  MESSAGE_CODE.configFileError,
713
255
  MESSAGE_LEVEL.error,
714
- `TLC encountered the following error when trying to read the configuration file ${configPath ?? ""}:\nFile not found.`,
256
+ `TLC encountered the following error when trying to read the configuration file ${configPath}:\nFile not found.`,
715
257
  );
716
258
  return EXIT_STATUS.configParseError;
717
259
  }
718
260
  const fileName = basename(specPath, ".tla");
719
261
  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
262
  const printFinished = () => {
722
263
  const runtime = Date.now() - timing.startTime;
723
264
  printer.print(
@@ -732,7 +273,6 @@ const checkSpec = async (
732
273
  MESSAGE_LEVEL.error,
733
274
  "Parsing or semantic analysis failed.",
734
275
  );
735
- // TLC prints how long it ran even when it stops at an error.
736
276
  const printFailure = (error: TlaError) => {
737
277
  if (error instanceof TlaSyntaxError) {
738
278
  printParsingFailed();
@@ -740,19 +280,22 @@ const checkSpec = async (
740
280
  printError(error, printer);
741
281
  }
742
282
  printFinished();
743
- return getErrorExitCode(error);
283
+ return getTopLevelExitCode(error);
744
284
  };
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
285
  const config = (() => {
748
286
  try {
749
- return parseConfig(readFileSync(configPath, "utf8"), version);
287
+ const contents = readFileSync(configPath, "utf8");
288
+ return parseConfig(
289
+ configPath.endsWith(".tla")
290
+ ? getEmbeddedConfig(contents, configPath.replaceAll(".tla", ""))
291
+ : contents,
292
+ version,
293
+ );
750
294
  } catch (error) {
751
295
  if (!(error instanceof TlaConfigError)) throw error;
752
296
  return error;
753
297
  }
754
298
  })();
755
- // TLC 1.7.4 reports a configuration file it can't parse as an exception it didn't expect.
756
299
  if (config instanceof TlaConfigError && version === "1.7.4") {
757
300
  printer.print(
758
301
  MESSAGE_CODE.general,
@@ -763,17 +306,23 @@ const checkSpec = async (
763
306
  return EXIT_STATUS.error;
764
307
  }
765
308
  if (config instanceof TlaConfigError) return printFailure(config);
766
- if (args.has("-deadlock")) config.checkDeadlock = false;
309
+ if (!args.isDeadlockChecked) config.checkDeadlock = false;
767
310
  const directory = dirname(specPath);
768
311
  const directories = [directory, ...java.libraries];
769
312
  const loadModule = createModuleLoader(directories);
770
- const isRecorded = isTraceRecorded(args, version);
313
+ const traceSpec = getTraceSpecLocation(
314
+ args,
315
+ version,
316
+ specPath.replace(/\.tla$/, ""),
317
+ timing.startTime,
318
+ );
319
+ const getOperatorModules = (kind: ModuleOperator["kind"]) =>
320
+ args.moduleOperators
321
+ .filter((operator) => operator.kind === kind)
322
+ .map((operator) => operator.module);
771
323
  if (printer.isTool) {
772
324
  printer.print(MESSAGE_CODE.startingSany, MESSAGE_LEVEL.none, "Starting SANY...");
773
325
  }
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
326
  const isAbsoluteSpec = isAbsolute(specPath);
778
327
  const specName = isAbsoluteSpec ? fileName : specPath.replace(/\.tla$/, "");
779
328
  const jar = getToolsJar(java);
@@ -790,27 +339,28 @@ const checkSpec = async (
790
339
  [...(isAbsoluteSpec || directory === "." ? [] : [directory]), ...java.libraries],
791
340
  );
792
341
  }
793
- // TLC prints what SANY prints as it parses the spec, and the errors it rejects the spec for.
794
342
  const sany = getSanyReport(
795
343
  specPath,
796
344
  reportMissingFile ? reportMissingModules174(loadModule, reportMissingFile) : loadModule,
797
345
  {
798
346
  fileName: specName,
799
- describeFile: createFileDescriber(
800
- specPath,
801
- directories,
802
- java,
803
- args.get("-metadir")?.[0],
804
- version,
805
- ),
347
+ describeFile: createFileDescriber(specPath, directories, java, args.metadir, version),
806
348
  version,
807
- // TLC's trace exploration spec records the trace with the post condition of _TLCTrace.
808
- rootExtendees: isRecorded ? ["_TLCTrace"] : undefined,
349
+ rootExtendees: [
350
+ ...getOperatorModules("postcondition"),
351
+ ...(traceSpec?.traceFile === undefined ? [] : ["_TLCTrace"]),
352
+ ...args.invariants.flatMap((invariant) => invariant.modules),
353
+ ...getOperatorModules("constraint"),
354
+ ...getOperatorModules("view").slice(0, 1),
355
+ ],
356
+ suppressedCodes: args.suppressedCodes,
357
+ errorCodes: args.errorCodes,
809
358
  onPrint: (text) => process.stdout.write(text),
810
359
  onPrintError: (text) => process.stderr.write(text),
811
360
  },
812
361
  );
813
- if (sany.isFailed) {
362
+ const specification = sany.specification;
363
+ if (sany.isFailed || specification === undefined) {
814
364
  printCheckProgress(printer, { kind: "parsed" }, timing, directory);
815
365
  printParsingFailed();
816
366
  printFinished();
@@ -825,19 +375,41 @@ const checkSpec = async (
825
375
  undefined,
826
376
  );
827
377
  }
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),
378
+ const userFile = args.userFile;
379
+ const standardModules = getSanyStandardModules(version);
380
+ const invariants = addRuntimeInvariants(
381
+ source,
382
+ specification.root,
383
+ args.invariants,
384
+ (name) => loadModule(name) ?? standardModules.get(name) ?? extractModule(source, name),
385
+ version,
386
+ );
387
+ config.invariants.push(...invariants.names);
388
+ const options: CheckOptions = {
389
+ workers: args.workers,
390
+ livenessCheck:
391
+ livenessCheck === "off"
392
+ ? "off"
393
+ : ["final", "seqfinal"].includes(livenessCheck)
394
+ ? "final"
395
+ : "default",
396
+ seed: args.seed,
397
+ fingerprintPolynomial: args.fingerprintIndex,
398
+ maxSetSize: args.maxSetSize,
399
+ isLazyValueExpanded: args.isLazyValueExpanded,
400
+ isViewPrinted: args.isViewPrinted,
401
+ dump,
833
402
  isTool: printer.isTool,
834
- isContinued: args.has("-continue"),
835
- isTraceRecorded: isRecorded,
403
+ isContinued: args.isContinued,
404
+ moduleOperators: args.moduleOperators,
405
+ traceSpec,
406
+ coverage: args.coverage,
836
407
  isSanyReported: true,
837
- isWarningEnabled: !args.has("-nowarning"),
408
+ isWarningEnabled: args.isWarningEnabled,
838
409
  version,
839
410
  onProgress: (progress) => printCheckProgress(printer, progress, timing, directory),
840
- source,
411
+ onPrint: userFile === undefined ? undefined : (text) => appendFileSync(userFile, `${text}\n`),
412
+ source: invariants.source,
841
413
  config,
842
414
  onPause: () => readSync(0, Buffer.alloc(1)),
843
415
  loadModule,
@@ -845,14 +417,58 @@ const checkSpec = async (
845
417
  const classPath = getClassPath(directory, name);
846
418
  return existsSync(classPath) ? readFileSync(classPath) : undefined;
847
419
  },
848
- readFile: (path) => (existsSync(path) ? readFileSync(path, "utf8") : undefined),
849
- writeFile: (path, content) => {
850
- mkdirSync(dirname(resolve(path)), { recursive: true });
851
- writeFileSync(path, content);
420
+ readFile: (path) => {
421
+ checkNotDirectory(path);
422
+ return existsSync(path) ? readFileSync(path, "utf8") : undefined;
852
423
  },
853
- });
424
+ writeFile: writeJavaFile,
425
+ makeDirectory: makeJavaDirectory,
426
+ };
427
+ if (args.mode !== "model-check") {
428
+ const status = simulate({
429
+ ...options,
430
+ traceDepth: args.traceDepth,
431
+ traceCount: args.traceCount,
432
+ aril: args.aril,
433
+ isGenerating: args.mode === "generate",
434
+ scheduler: args.scheduler,
435
+ onSimulation: (output) => printSimulation(printer, output),
436
+ });
437
+ printFinished();
438
+ return status;
439
+ }
440
+ if (args.dfidDepth !== undefined) {
441
+ const status = checkDepthFirst({
442
+ ...options,
443
+ maxDepth: args.dfidDepth,
444
+ onOutput: (output) => printDepthFirst(printer, output),
445
+ });
446
+ printFinished();
447
+ return status;
448
+ }
449
+ const result = await check(options);
854
450
  printResult(result, printer, timing);
855
451
  printFinished();
452
+ if (traceSpec && result.traceSpec !== undefined) {
453
+ const path = resolveJavaPath(traceSpec.directory, `${traceSpec.module}.tla`);
454
+ makeJavaDirectory(traceSpec.directory);
455
+ const failure = (() => {
456
+ try {
457
+ writeJavaFile(path, result.traceSpec);
458
+ return undefined;
459
+ } catch (error) {
460
+ if (!(error instanceof TlaEvaluationError)) throw error;
461
+ return error;
462
+ }
463
+ })();
464
+ printer.print(
465
+ failure ? MESSAGE_CODE.traceSpecFailed : MESSAGE_CODE.traceSpecWritten,
466
+ MESSAGE_LEVEL.none,
467
+ failure
468
+ ? `Failed to generate trace exploration spec; error message: ${failure.message}`
469
+ : `Trace exploration spec path: ${path}`,
470
+ );
471
+ }
856
472
  return result.failure?.exitCode ?? EXIT_CODES[result.status];
857
473
  } catch (error) {
858
474
  if (!(error instanceof TlaError)) throw error;
@@ -862,8 +478,6 @@ const checkSpec = async (
862
478
  }
863
479
  };
864
480
 
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
481
  const formatSanyErrors = (error: TlaSyntaxError, specName: string) => {
868
482
  const isFatal = error instanceof TlaSanyFatalError;
869
483
  if (!isFatal && !error.failure)
@@ -878,60 +492,97 @@ const formatSanyErrors = (error: TlaSyntaxError, specName: string) => {
878
492
  };
879
493
 
880
494
  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.
495
+ const version = java.tlcVersion ?? "master";
496
+ const parsed = parseTlcArguments(args);
497
+ if (parsed === "usage") {
498
+ console.log(getTlcUsage());
499
+ return 1;
500
+ }
501
+ if ("error" in parsed) {
502
+ if (parsed.kind === "uncaught") {
503
+ console.error(`Exception in thread "main" ${parsed.error}`);
504
+ return 1;
505
+ }
506
+ return printCommandLineError(parsed.isTool, version, parsed.error);
507
+ }
508
+ const dump = parsed.dump && getStateDump(parsed.dump);
509
+ if (dump?.path.startsWith("${metadir}")) {
510
+ dump.path = dump.path.replaceAll("${metadir}", createMetadir(parsed));
511
+ }
512
+ const dumpPath = dump?.path;
513
+ if (dumpPath !== undefined) {
514
+ try {
515
+ closeSync(openSync(dumpPath, "w"));
516
+ } catch {
517
+ console.log(`Error: Unable to write to file ${dumpPath}`);
518
+ return printCommandLineError(
519
+ parsed.isTool,
520
+ version,
521
+ `Error: Given file name ${dumpPath} for dumping states invalid.`,
522
+ );
523
+ }
524
+ }
525
+ const isConfigured = parsed.configPath !== undefined;
526
+ if (isConfigured && parsed.specs.length > 1) {
527
+ return printCommandLineError(
528
+ parsed.isTool,
529
+ version,
530
+ `Error: more than one input files: ${parsed.specs[0].replace(/\.tla$/, "")} and ${parsed.specs[1]}`,
531
+ );
532
+ }
533
+ const inputs = getInputPaths(parsed.specs);
886
534
  const specPaths = inputs
887
535
  .map((input) => ({
888
536
  ...input,
889
537
  path:
890
- input.isGlobbed || /\.(tla|cfg)$/.test(input.path)
538
+ input.isGlobbed || /\.(tla|cfg|ts)$/.test(input.path)
891
539
  ? input.path.replace(/\.cfg$/, ".tla")
892
540
  : `${input.path}.tla`,
893
541
  }))
894
542
  .filter(
895
543
  (input) =>
896
- input.path.endsWith(".tla") &&
897
- (!input.isGlobbed || isConfigured || existsSync(input.path.replace(/\.tla$/, ".cfg"))),
544
+ input.path.endsWith(".ts") ||
545
+ (input.path.endsWith(".tla") &&
546
+ (!input.isGlobbed || isConfigured || existsSync(input.path.replace(/\.tla$/, ".cfg")))),
898
547
  )
899
548
  .map((input) => input.path);
900
549
  if (specPaths.length === 0) {
901
- console.error(USAGE);
902
- return 1;
550
+ return printCommandLineError(parsed.isTool, version, "Error: Missing input TLA+ module.");
903
551
  }
904
552
  if (isConfigured && specPaths.length > 1) {
905
553
  console.error("Error: -config applies to one specification, but several were given.");
906
554
  return 1;
907
555
  }
908
- // TLC also looks for the spec itself in the library directories.
909
556
  const findSpec = (path: string) =>
910
557
  existsSync(path) || isAbsolute(path)
911
558
  ? path
912
559
  : (java.libraries.map((directory) => join(directory, path)).find(existsSync) ?? path);
913
560
  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
561
  const exitCodes: number[] = [];
917
562
  for (const [index, path] of paths.entries()) {
918
563
  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",
564
+ const printer = createMessagePrinter({
565
+ isTool: parsed.isTool,
566
+ isWarningEnabled: parsed.isWarningEnabled,
567
+ isDiffTrace: parsed.isDiffTrace,
568
+ version,
569
+ suppressedCodes: parsed.suppressedCodes,
570
+ errorCodes: parsed.errorCodes,
571
+ });
572
+ exitCodes.push(
573
+ await reportErrors(async () => {
574
+ const specPath = path.endsWith(".ts") ? await writeTypeScriptSpec(path) : path;
575
+ // Deviation from TLC: TLC checks one spec, so tla-ts names each of several it checks.
576
+ if (paths.length > 1) {
577
+ console.log(`Checking ${basename(specPath)} with ${basename(specPath, ".tla")}.cfg`);
578
+ }
579
+ return checkSpec(specPath, parsed, dump, java, printer);
580
+ }, printer),
926
581
  );
927
- exitCodes.push(await reportErrors(() => checkSpec(path, parsed, java, printer), printer));
928
582
  }
929
583
  return exitCodes.find((exitCode) => exitCode !== EXIT_STATUS.success) ?? EXIT_STATUS.success;
930
584
  };
931
585
 
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
586
  const createMissingFilePrinter174 = (
936
587
  specPath: string,
937
588
  java: JavaProperties,