tla-ts 0.0.4 → 0.0.5-dev.5b2dea1

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 (378) hide show
  1. package/README.md +38 -127
  2. package/dist/cli.cjs +1 -1
  3. package/dist/cli.js +1 -1
  4. package/dist/deciders.cjs +366 -0
  5. package/dist/deciders.js +366 -0
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +46 -12
  8. package/dist/index.d.ts +46 -12
  9. package/dist/index.js +1 -1
  10. package/dist/parallel-worker.cjs +1 -4
  11. package/dist/parallel-worker.js +1 -4
  12. package/dist/prove-worker.cjs +9 -0
  13. package/dist/prove-worker.d.cts +9 -0
  14. package/dist/prove-worker.d.ts +9 -0
  15. package/dist/prove-worker.js +9 -0
  16. package/dist/prove.cjs +1006 -0
  17. package/dist/prove.js +1006 -0
  18. package/dist/run.cjs +45 -0
  19. package/dist/run.js +45 -0
  20. package/dist/tlapm.cjs +10 -0
  21. package/dist/tlapm.js +10 -0
  22. package/dist/transfer.cjs +76 -92
  23. package/dist/transfer.js +76 -92
  24. package/dist/worker.cjs +21 -0
  25. package/dist/worker.js +21 -0
  26. package/package.json +21 -12
  27. package/src/ast.ts +2 -2
  28. package/src/bags.ts +22 -23
  29. package/src/builtins.ts +16 -8
  30. package/src/check.ts +131 -1153
  31. package/src/{cli-options.ts → cli/options.ts} +54 -9
  32. package/src/cli/run.ts +63 -0
  33. package/src/cli/shared.ts +106 -0
  34. package/src/cli/tlapm.ts +374 -0
  35. package/src/{run-cli.ts → cli/tlc.ts} +115 -721
  36. package/src/cli/xml-exporter.ts +221 -0
  37. package/src/cli.ts +1 -1
  38. package/src/codegen.ts +43 -22
  39. package/src/config.ts +5 -5
  40. package/src/dependencies.ts +4 -6
  41. package/src/environment.ts +55 -60
  42. package/src/errors.ts +97 -35
  43. package/src/evaluate.ts +361 -181
  44. package/src/exit-codes.ts +1 -1
  45. package/src/fingerprints.ts +3 -3
  46. package/src/index.ts +10 -0
  47. package/src/instances.ts +56 -46
  48. package/src/java-overrides.ts +79 -41
  49. package/src/json.ts +31 -36
  50. package/src/levels.ts +10 -13
  51. package/src/{live-check.ts → liveness-checker.ts} +207 -141
  52. package/src/liveness.ts +38 -34
  53. package/src/{obligation-action.ts → obligations/action.ts} +248 -74
  54. package/src/{obligation-anon.ts → obligations/anonymize.ts} +55 -57
  55. package/src/obligations/equality.ts +260 -0
  56. package/src/obligations/expression.ts +618 -0
  57. package/src/{obligation-format.ts → obligations/format.ts} +7 -8
  58. package/src/obligations/generate.ts +457 -0
  59. package/src/{obligations.ts → obligations/index.ts} +46 -32
  60. package/src/{obligation-levels.ts → obligations/levels.ts} +44 -40
  61. package/src/obligations/module.ts +445 -0
  62. package/src/obligations/normalize.ts +554 -0
  63. package/src/obligations/operators.ts +176 -0
  64. package/src/obligations/pragma.ts +195 -0
  65. package/src/{obligation-printer.ts → obligations/printer.ts} +65 -230
  66. package/src/{obligation-proof.ts → obligations/proof.ts} +7 -2
  67. package/src/obligations/regroup.ts +100 -0
  68. package/src/{obligation-generate.ts → obligations/simplify.ts} +130 -536
  69. package/src/{obligation-source.ts → obligations/source.ts} +172 -216
  70. package/src/{obligation-deref.ts → obligations/subexpression.ts} +84 -115
  71. package/src/obligations/substitution.ts +261 -0
  72. package/src/obligations/temporal.ts +321 -0
  73. package/src/{obligation-tuples.ts → obligations/tuples.ts} +38 -54
  74. package/src/parallel-worker.ts +39 -51
  75. package/src/parallel.ts +39 -66
  76. package/src/parser.ts +67 -74
  77. package/src/{pcal-ast.ts → pcal/ast.ts} +2 -17
  78. package/src/{pcal-parse.ts → pcal/parse.ts} +28 -64
  79. package/src/{pcal-tokenize.ts → pcal/tokenize.ts} +10 -39
  80. package/src/{pcal-translate.ts → pcal/translate.ts} +30 -109
  81. package/src/{pcal-validate.ts → pcal/validate.ts} +10 -20
  82. package/src/prover/decide-pool.ts +95 -0
  83. package/src/prover/deciders.ts +33 -0
  84. package/src/prover/first-order.ts +175 -0
  85. package/src/prover/isabelle/LICENSE +36 -0
  86. package/src/prover/isabelle/LICENSE-tlapm +26 -0
  87. package/src/prover/isabelle/decide.ts +44 -0
  88. package/src/prover/isabelle/encode.ts +445 -0
  89. package/src/prover/isabelle/isar/inner-syntax.ts +579 -0
  90. package/src/prover/isabelle/isar/method.ts +367 -0
  91. package/src/prover/isabelle/isar/proof.ts +28 -0
  92. package/src/prover/isabelle/isar/statement.ts +57 -0
  93. package/src/prover/isabelle/isar/theory.ts +192 -0
  94. package/src/prover/isabelle/isar/type-check.ts +278 -0
  95. package/src/prover/isabelle/provers/blast/blast.ts +258 -0
  96. package/src/prover/isabelle/provers/blast/branch.ts +322 -0
  97. package/src/prover/isabelle/provers/blast/prove.ts +347 -0
  98. package/src/prover/isabelle/provers/blast/rules.ts +330 -0
  99. package/src/prover/isabelle/provers/blast/state.ts +180 -0
  100. package/src/prover/isabelle/provers/blast/term.ts +546 -0
  101. package/src/prover/isabelle/provers/clasimp.ts +150 -0
  102. package/src/prover/isabelle/provers/classical.ts +389 -0
  103. package/src/prover/isabelle/provers/hypsubst.ts +433 -0
  104. package/src/prover/isabelle/pure/bicompose.ts +174 -0
  105. package/src/prover/isabelle/pure/consts.ts +32 -0
  106. package/src/prover/isabelle/pure/conv.ts +79 -0
  107. package/src/prover/isabelle/pure/drule.ts +264 -0
  108. package/src/prover/isabelle/pure/envir.ts +331 -0
  109. package/src/prover/isabelle/pure/goal.ts +53 -0
  110. package/src/prover/isabelle/pure/interrupt.ts +16 -0
  111. package/src/prover/isabelle/pure/list.ts +12 -0
  112. package/src/prover/isabelle/pure/logic.ts +330 -0
  113. package/src/prover/isabelle/pure/name.ts +98 -0
  114. package/src/prover/isabelle/pure/net.ts +215 -0
  115. package/src/prover/isabelle/pure/object-logic.ts +41 -0
  116. package/src/prover/isabelle/pure/pattern.ts +631 -0
  117. package/src/prover/isabelle/pure/raw-simplifier.ts +338 -0
  118. package/src/prover/isabelle/pure/rewriter.ts +602 -0
  119. package/src/prover/isabelle/pure/search.ts +68 -0
  120. package/src/prover/isabelle/pure/seq.ts +133 -0
  121. package/src/prover/isabelle/pure/simplifier.ts +106 -0
  122. package/src/prover/isabelle/pure/table.ts +201 -0
  123. package/src/prover/isabelle/pure/tactic.ts +168 -0
  124. package/src/prover/isabelle/pure/tactical.ts +264 -0
  125. package/src/prover/isabelle/pure/term-ord.ts +105 -0
  126. package/src/prover/isabelle/pure/term.ts +688 -0
  127. package/src/prover/isabelle/pure/thm.ts +783 -0
  128. package/src/prover/isabelle/pure/type.ts +121 -0
  129. package/src/prover/isabelle/pure/unify.ts +753 -0
  130. package/src/prover/isabelle/pure/variable.ts +25 -0
  131. package/src/prover/isabelle/tla/classical-setup.ts +101 -0
  132. package/src/prover/isabelle/tla/context.ts +74 -0
  133. package/src/prover/isabelle/tla/logic-data.ts +5 -0
  134. package/src/prover/isabelle/tla/logic.ts +215 -0
  135. package/src/prover/isabelle/tla/simpdata.ts +241 -0
  136. package/src/prover/isabelle/tools/intuitionistic.ts +132 -0
  137. package/src/prover/ocaml.ts +22 -0
  138. package/src/prover/prep/action.ts +508 -0
  139. package/src/prover/prep/enabled-axioms.ts +189 -0
  140. package/src/prover/prep/fingerprint.ts +388 -0
  141. package/src/prover/prep/level-comparison.ts +529 -0
  142. package/src/prover/prep/md5.ts +60 -0
  143. package/src/prover/prep/methods.ts +221 -0
  144. package/src/prover/prep/normalize.ts +309 -0
  145. package/src/prover/prove-worker.ts +22 -0
  146. package/src/prover/prove.ts +492 -0
  147. package/src/prover/ptl/decide.ts +68 -0
  148. package/src/prover/ptl/encode.ts +244 -0
  149. package/src/prover/ptl/sat.ts +151 -0
  150. package/src/prover/ptl/tableau.ts +276 -0
  151. package/src/prover/smt/axioms.ts +209 -0
  152. package/src/prover/smt/context.ts +108 -0
  153. package/src/prover/smt/data.ts +636 -0
  154. package/src/prover/smt/encode.ts +275 -0
  155. package/src/prover/smt/extensionality.ts +65 -0
  156. package/src/prover/smt/flatten.ts +112 -0
  157. package/src/prover/smt/format.ts +154 -0
  158. package/src/prover/smt/instances.ts +181 -0
  159. package/src/prover/smt/rewrite.ts +766 -0
  160. package/src/prover/smt/solver/act-cache.ts +265 -0
  161. package/src/prover/smt/solver/arith-rewriter.ts +962 -0
  162. package/src/prover/smt/solver/array.ts +22 -0
  163. package/src/prover/smt/solver/asserted-formulas.ts +469 -0
  164. package/src/prover/smt/solver/ast-lt.ts +157 -0
  165. package/src/prover/smt/solver/ast-util.ts +91 -0
  166. package/src/prover/smt/solver/ast.ts +1315 -0
  167. package/src/prover/smt/solver/auf-solver.ts +572 -0
  168. package/src/prover/smt/solver/case-split-queue.ts +178 -0
  169. package/src/prover/smt/solver/cg-table.ts +175 -0
  170. package/src/prover/smt/solver/clause.ts +276 -0
  171. package/src/prover/smt/solver/conflict-resolution.ts +343 -0
  172. package/src/prover/smt/solver/context.ts +1292 -0
  173. package/src/prover/smt/solver/ctx-simplify.ts +334 -0
  174. package/src/prover/smt/solver/der.ts +224 -0
  175. package/src/prover/smt/solver/dyn-ack.ts +141 -0
  176. package/src/prover/smt/solver/e-matching.ts +659 -0
  177. package/src/prover/smt/solver/enode.ts +259 -0
  178. package/src/prover/smt/solver/expr-ref.ts +21 -0
  179. package/src/prover/smt/solver/expr-safe-replace.ts +172 -0
  180. package/src/prover/smt/solver/fingerprints.ts +92 -0
  181. package/src/prover/smt/solver/flat-literals.ts +51 -0
  182. package/src/prover/smt/solver/goal.ts +138 -0
  183. package/src/prover/smt/solver/hash.ts +173 -0
  184. package/src/prover/smt/solver/hashtable.ts +166 -0
  185. package/src/prover/smt/solver/internalizer.ts +1381 -0
  186. package/src/prover/smt/solver/lbool.ts +5 -0
  187. package/src/prover/smt/solver/literal.ts +24 -0
  188. package/src/prover/smt/solver/lp/bound-propagator.ts +391 -0
  189. package/src/prover/smt/solver/lp/constraints.ts +78 -0
  190. package/src/prover/smt/solver/lp/containers.ts +296 -0
  191. package/src/prover/smt/solver/lp/core-solver.ts +504 -0
  192. package/src/prover/smt/solver/lp/cross-nested.ts +224 -0
  193. package/src/prover/smt/solver/lp/dep-intervals.ts +642 -0
  194. package/src/prover/smt/solver/lp/dependency.ts +51 -0
  195. package/src/prover/smt/solver/lp/dioph-eq.ts +1181 -0
  196. package/src/prover/smt/solver/lp/explanation.ts +46 -0
  197. package/src/prover/smt/solver/lp/gomory.ts +255 -0
  198. package/src/prover/smt/solver/lp/hnf-cutter.ts +125 -0
  199. package/src/prover/smt/solver/lp/hnf.ts +281 -0
  200. package/src/prover/smt/solver/lp/int-cube.ts +295 -0
  201. package/src/prover/smt/solver/lp/int-solver.ts +514 -0
  202. package/src/prover/smt/solver/lp/lar-solver.ts +816 -0
  203. package/src/prover/smt/solver/lp/lar-term.ts +62 -0
  204. package/src/prover/smt/solver/lp/lp-settings.ts +91 -0
  205. package/src/prover/smt/solver/lp/maximize-term.ts +347 -0
  206. package/src/prover/smt/solver/lp/nex-creator.ts +381 -0
  207. package/src/prover/smt/solver/lp/nex.ts +120 -0
  208. package/src/prover/smt/solver/lp/nla-backoff.ts +43 -0
  209. package/src/prover/smt/solver/lp/nla-basics.ts +398 -0
  210. package/src/prover/smt/solver/lp/nla-core.ts +968 -0
  211. package/src/prover/smt/solver/lp/nla-divisions.ts +332 -0
  212. package/src/prover/smt/solver/lp/nla-emonics.ts +373 -0
  213. package/src/prover/smt/solver/lp/nla-factorization.ts +30 -0
  214. package/src/prover/smt/solver/lp/nla-grobner.ts +904 -0
  215. package/src/prover/smt/solver/lp/nla-horner.ts +126 -0
  216. package/src/prover/smt/solver/lp/nla-intervals.ts +265 -0
  217. package/src/prover/smt/solver/lp/nla-monomial-bounds.ts +715 -0
  218. package/src/prover/smt/solver/lp/nla-monotone.ts +59 -0
  219. package/src/prover/smt/solver/lp/nla-order.ts +307 -0
  220. package/src/prover/smt/solver/lp/nla-patcher.ts +112 -0
  221. package/src/prover/smt/solver/lp/nla-tangents.ts +251 -0
  222. package/src/prover/smt/solver/lp/nla-throttle.ts +85 -0
  223. package/src/prover/smt/solver/lp/nla-types.ts +124 -0
  224. package/src/prover/smt/solver/lp/nla-var-eqs.ts +141 -0
  225. package/src/prover/smt/solver/lp/nra-solver.ts +440 -0
  226. package/src/prover/smt/solver/lp/numeric-pair.ts +65 -0
  227. package/src/prover/smt/solver/lp/pdd-interval.ts +31 -0
  228. package/src/prover/smt/solver/lp/pdd-simplifier.ts +184 -0
  229. package/src/prover/smt/solver/lp/pdd-solver.ts +408 -0
  230. package/src/prover/smt/solver/lp/pdd.ts +971 -0
  231. package/src/prover/smt/solver/lp/random-updater.ts +138 -0
  232. package/src/prover/smt/solver/lp/static-matrix.ts +246 -0
  233. package/src/prover/smt/solver/lp/union-find.ts +96 -0
  234. package/src/prover/smt/solver/mam-compiler.ts +847 -0
  235. package/src/prover/smt/solver/mam-interpreter.ts +400 -0
  236. package/src/prover/smt/solver/maximize-ac-sharing.ts +118 -0
  237. package/src/prover/smt/solver/model-checker.ts +347 -0
  238. package/src/prover/smt/solver/model-evaluator.ts +262 -0
  239. package/src/prover/smt/solver/model-finder.ts +155 -0
  240. package/src/prover/smt/solver/model-generator.ts +97 -0
  241. package/src/prover/smt/solver/model-macro-solver.ts +728 -0
  242. package/src/prover/smt/solver/nlsat/algebraic.ts +1161 -0
  243. package/src/prover/smt/solver/nlsat/atoms.ts +238 -0
  244. package/src/prover/smt/solver/nlsat/evaluator.ts +303 -0
  245. package/src/prover/smt/solver/nlsat/explain.ts +607 -0
  246. package/src/prover/smt/solver/nlsat/interval-set.ts +351 -0
  247. package/src/prover/smt/solver/nlsat/levelwise.ts +737 -0
  248. package/src/prover/smt/solver/nlsat/mpbq.ts +161 -0
  249. package/src/prover/smt/solver/nlsat/polynomial.ts +1722 -0
  250. package/src/prover/smt/solver/nlsat/solver.ts +911 -0
  251. package/src/prover/smt/solver/nlsat/types.ts +43 -0
  252. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +645 -0
  253. package/src/prover/smt/solver/nlsat/upolynomial.ts +996 -0
  254. package/src/prover/smt/solver/nnf.ts +469 -0
  255. package/src/prover/smt/solver/pattern-inference.ts +351 -0
  256. package/src/prover/smt/solver/poly-rewriter.ts +477 -0
  257. package/src/prover/smt/solver/propagate-values.ts +83 -0
  258. package/src/prover/smt/solver/proto-model.ts +551 -0
  259. package/src/prover/smt/solver/pull-quant.ts +139 -0
  260. package/src/prover/smt/solver/qe-lite-der.ts +526 -0
  261. package/src/prover/smt/solver/qe-lite-fm.ts +576 -0
  262. package/src/prover/smt/solver/qe-lite.ts +381 -0
  263. package/src/prover/smt/solver/qi-queue.ts +362 -0
  264. package/src/prover/smt/solver/quant-tactics.ts +117 -0
  265. package/src/prover/smt/solver/quantifier-analyzer.ts +562 -0
  266. package/src/prover/smt/solver/quantifier-manager.ts +186 -0
  267. package/src/prover/smt/solver/random-gen.ts +10 -0
  268. package/src/prover/smt/solver/rational.ts +165 -0
  269. package/src/prover/smt/solver/ref-vector.ts +62 -0
  270. package/src/prover/smt/solver/relevancy.ts +247 -0
  271. package/src/prover/smt/solver/rewriter-tpl.ts +1159 -0
  272. package/src/prover/smt/solver/rewriter.ts +843 -0
  273. package/src/prover/smt/solver/rlimit.ts +84 -0
  274. package/src/prover/smt/solver/smtlib-parser.ts +526 -0
  275. package/src/prover/smt/solver/solver.ts +71 -0
  276. package/src/prover/smt/solver/sort.ts +35 -0
  277. package/src/prover/smt/solver/sticky-generations.ts +69 -0
  278. package/src/prover/smt/solver/theory-lra-axioms.ts +340 -0
  279. package/src/prover/smt/solver/theory-lra-bounds.ts +226 -0
  280. package/src/prover/smt/solver/theory-lra-final-check.ts +252 -0
  281. package/src/prover/smt/solver/theory-lra-internalize.ts +476 -0
  282. package/src/prover/smt/solver/theory-lra-model.ts +243 -0
  283. package/src/prover/smt/solver/theory-lra-propagate.ts +405 -0
  284. package/src/prover/smt/solver/theory-lra-state.ts +43 -0
  285. package/src/prover/smt/solver/theory-lra.ts +56 -0
  286. package/src/prover/smt/solver/var-subst.ts +258 -0
  287. package/src/prover/smt/solver/z3-license.txt +10 -0
  288. package/src/prover/smt/table.ts +170 -0
  289. package/src/prover/tlapm/cache.ts +236 -0
  290. package/src/prover/tlapm/ocaml-marshal.ts +166 -0
  291. package/src/prover/tlapm/tlapm.ts +96 -0
  292. package/src/prover/tlaps-module.ts +510 -0
  293. package/src/prover/verdict.ts +13 -0
  294. package/src/prover/zenon/LICENSE +32 -0
  295. package/src/prover/zenon/check/check.ts +105 -0
  296. package/src/prover/zenon/check/definitions.ts +144 -0
  297. package/src/prover/zenon/check/equality.ts +182 -0
  298. package/src/prover/zenon/check/functions.ts +62 -0
  299. package/src/prover/zenon/check/keys.ts +125 -0
  300. package/src/prover/zenon/check/propositional.ts +104 -0
  301. package/src/prover/zenon/check/records.ts +188 -0
  302. package/src/prover/zenon/check/relations.ts +121 -0
  303. package/src/prover/zenon/check/rewrites.ts +224 -0
  304. package/src/prover/zenon/check/sets.ts +302 -0
  305. package/src/prover/zenon/check/terms.ts +127 -0
  306. package/src/prover/zenon/check/tla.ts +126 -0
  307. package/src/prover/zenon/decide.ts +107 -0
  308. package/src/prover/zenon/encode.ts +378 -0
  309. package/src/prover/zenon/eqrel.ts +300 -0
  310. package/src/prover/zenon/equality-rules.ts +435 -0
  311. package/src/prover/zenon/expr.ts +551 -0
  312. package/src/prover/zenon/index-table.ts +350 -0
  313. package/src/prover/zenon/isar-case.ts +513 -0
  314. package/src/prover/zenon/isar.ts +1249 -0
  315. package/src/prover/zenon/limits.ts +15 -0
  316. package/src/prover/zenon/llproof.ts +173 -0
  317. package/src/prover/zenon/mltoll.ts +1566 -0
  318. package/src/prover/zenon/node.ts +297 -0
  319. package/src/prover/zenon/ocaml.ts +169 -0
  320. package/src/prover/zenon/parse.ts +247 -0
  321. package/src/prover/zenon/phrase.ts +191 -0
  322. package/src/prover/zenon/proof.ts +198 -0
  323. package/src/prover/zenon/propositional-rules.ts +387 -0
  324. package/src/prover/zenon/rules.ts +94 -0
  325. package/src/prover/zenon/search.ts +288 -0
  326. package/src/prover/zenon/tla/functions.ts +151 -0
  327. package/src/prover/zenon/tla/llproof.ts +480 -0
  328. package/src/prover/zenon/tla/records.ts +225 -0
  329. package/src/prover/zenon/tla/rewrites.ts +447 -0
  330. package/src/prover/zenon/tla/sets.ts +304 -0
  331. package/src/prover/zenon/tla/terms.ts +162 -0
  332. package/src/prover/zenon/tla/tla.ts +506 -0
  333. package/src/randomization.ts +19 -24
  334. package/src/resolve.ts +15 -22
  335. package/src/runtime.ts +8 -8
  336. package/src/{sany-builtins.ts → sany/builtins.ts} +1 -1
  337. package/src/{sany-generator.ts → sany/generator.ts} +38 -55
  338. package/src/{sany-levels.ts → sany/levels.ts} +45 -48
  339. package/src/{sany-lexer.ts → sany/lexer.ts} +2 -3
  340. package/src/{sany-linter.ts → sany/linter.ts} +1 -1
  341. package/src/{sany-modules.ts → sany/modules.ts} +2 -2
  342. package/src/{sany-nodes.ts → sany/nodes.ts} +2 -2
  343. package/src/{sany-parse-error.ts → sany/parse-error.ts} +2 -2
  344. package/src/{sany-report.ts → sany/report.ts} +16 -17
  345. package/src/{sany-selectors.ts → sany/selectors.ts} +3 -5
  346. package/src/{sany-source.ts → sany/source.ts} +6 -7
  347. package/src/{sany-xml.ts → sany/xml.ts} +5 -6
  348. package/src/search.ts +969 -0
  349. package/src/spec-description.ts +26 -20
  350. package/src/{standard-levels.ts → standard-definitions.ts} +118 -2
  351. package/src/standard-modules.ts +21 -22
  352. package/src/state-graph.ts +9 -8
  353. package/src/substitution-levels.ts +2 -2
  354. package/src/successors.ts +39 -23
  355. package/src/symmetry.ts +1 -1
  356. package/src/tableau.ts +6 -7
  357. package/src/tlc/fingerprint.ts +214 -0
  358. package/src/{tlc-messages.ts → tlc/messages.ts} +119 -7
  359. package/src/{tlc-order.ts → tlc/order.ts} +7 -7
  360. package/src/{tlc-random.ts → tlc/random.ts} +3 -190
  361. package/src/{tlc-replay.ts → tlc/replay.ts} +40 -36
  362. package/src/{tlc-module.ts → tlc/tlc-operators.ts} +9 -9
  363. package/src/{tlc-ext.ts → tlc/tlcext-operators.ts} +30 -25
  364. package/src/{tlc-version.ts → tlc/version.ts} +8 -7
  365. package/src/transfer.ts +32 -32
  366. package/src/values.ts +166 -111
  367. package/src/worker.ts +62 -0
  368. package/dist/parallel.cjs +0 -12
  369. package/dist/parallel.js +0 -12
  370. package/dist/run-cli.cjs +0 -55
  371. package/dist/run-cli.js +0 -55
  372. package/src/canonical.ts +0 -40
  373. package/src/obligation-expression.ts +0 -1060
  374. package/src/obligation-module.ts +0 -1042
  375. package/src/standard-ranges.ts +0 -116
  376. package/src/value-sources.ts +0 -29
  377. /package/src/{tlc-modules.ts → tlc/jar-data.ts} +0 -0
  378. /package/src/{tlc-summary.ts → tlc/summary.ts} +0 -0
@@ -1,21 +1,18 @@
1
1
  import {
2
2
  existsSync,
3
- globSync,
4
3
  mkdirSync,
5
4
  readFileSync,
6
5
  readSync,
7
6
  realpathSync,
8
7
  writeFileSync,
9
8
  } from "node:fs";
10
- import { spawnSync } from "node:child_process";
11
- import { createHash } from "node:crypto";
12
- import { basename, delimiter, dirname, isAbsolute, join, resolve } from "node:path";
9
+ import { basename, dirname, isAbsolute, join, resolve } from "node:path";
13
10
  import { arch, availableParallelism, release, tmpdir, type } from "node:os";
14
11
  import { pathToFileURL } from "node:url";
15
12
  import { getHeapStatistics } from "node:v8";
16
- import { version } from "../package.json";
17
- import type { Expression } from "./ast";
18
- import { describeRange } from "./evaluate";
13
+ import { version } from "../../package.json";
14
+ import type { Expression } from "../ast";
15
+ import { describeRange } from "../evaluate";
19
16
  import type {
20
17
  CheckProgress,
21
18
  InitialStateViolation,
@@ -26,52 +23,58 @@ import type {
26
23
  SearchStatistics,
27
24
  TraceStep,
28
25
  Violation,
29
- } from "./check";
30
- import { defineCommand, type ParsedArgs } from "./cli-options";
31
- import { parseConfig } from "./config";
26
+ } from "../check";
27
+ import { parseConfig } from "../config";
32
28
  import {
33
29
  getErrorExitCode,
34
30
  TlaConfigError,
35
31
  TlaError,
36
32
  TlaEvaluationError,
37
- TlaProofError,
38
33
  TlaSyntaxError,
39
34
  getUnexpectedException,
40
- TlaJavaException,
41
35
  UNEXPECTED_EXCEPTION,
42
36
  TlaSanyFatalError,
43
- TlaUnsupportedError,
44
- } from "./errors";
45
- import { EXIT_STATUS, setExitCode } from "./exit-codes";
46
- import type { LineRange } from "./obligation-generate";
47
- import { getAtPrefix, getLocusText } from "./obligation-expression";
48
- import { formatSummary, getObligations, WHOLE_MODULE, type ModuleObligations } from "./obligations";
49
- import { check } from "./parallel";
50
- import { parseModule } from "./parser";
51
- import type { StateDump } from "./state-graph";
37
+ } from "../errors";
38
+ import { EXIT_STATUS, setExitCode } from "../exit-codes";
39
+ import { check } from "../parallel";
40
+ import { parseModule } from "../parser";
41
+ import type { StateDump } from "../state-graph";
52
42
  import {
53
43
  formatProbability,
54
44
  getActualProbability,
55
45
  getOptimisticProbability,
56
46
  getOutDegreeSummary,
57
- } from "./tlc-summary";
58
- import type { SanySpecification } from "./sany-generator";
59
- import { SANY_174_STANDARD_MODULES, SANY_STANDARD_MODULES } from "./sany-modules";
60
- import { getSanyModuleName, getSanyReport, type SanyModuleOrigin } from "./sany-report";
61
- import { exportSanyXml, XML_EXPORT_EXIT_CODE, type XmlExportOptions } from "./sany-xml";
62
- import { getTlcVersion, type TlcVersion } from "./tlc-version";
47
+ } from "../tlc/summary";
48
+ import { SANY_174_STANDARD_MODULES, SANY_STANDARD_MODULES } from "../sany/modules";
49
+ import { getSanyReport, type SanyModuleOrigin } from "../sany/report";
50
+ import { getTlcFingerprint } from "../tlc/fingerprint";
51
+ import type { TlcVersion } from "../tlc/version";
63
52
  import {
64
53
  createMessagePrinter,
65
54
  formatTlcDate,
66
55
  formatInnerMessage,
67
56
  formatNestedMessage,
68
57
  formatTlcDuration,
69
- getCodedMessage,
70
58
  MESSAGE_CODE,
71
59
  MESSAGE_LEVEL,
72
60
  type MessagePrinter,
73
- } from "./tlc-messages";
74
- import { formatState } from "./values";
61
+ } from "../tlc/messages";
62
+ import { formatState } from "../values";
63
+ import { CHECK_COMMAND, USAGE, type ParsedArgs } from "./options";
64
+ import {
65
+ createModuleLoader,
66
+ findModuleFile,
67
+ getInputPaths,
68
+ getToolsJar,
69
+ getStandardModulesUrl,
70
+ printError,
71
+ printMissingFile,
72
+ printMissingFile174,
73
+ reportErrors,
74
+ reportMissingModules174,
75
+ toLibraryPath,
76
+ type JavaProperties,
77
+ } from "./shared";
75
78
 
76
79
  const EXIT_CODES: Record<CheckStatus, number> = {
77
80
  success: EXIT_STATUS.success,
@@ -84,110 +87,6 @@ const EXIT_CODES: Record<CheckStatus, number> = {
84
87
  error: EXIT_STATUS.error,
85
88
  };
86
89
 
87
- const CHECK_COMMAND = defineCommand("tla-ts <Spec.tla|Spec.cfg|glob>... {options}", [
88
- { flag: "-config <Spec.cfg>" },
89
- { flag: "-deadlock" },
90
- // Like TLC, -dump takes a format only when the next argument starts with dot and a file follows.
91
- {
92
- flag: "-dump [<format>] <file>",
93
- getArity: (rest) => (rest.length > 1 && rest[0].startsWith("dot") ? 2 : 1),
94
- },
95
- { flag: "-fp <num>" },
96
- { flag: "-lncheck <final|default>" },
97
- { flag: "-metadir <directory>" },
98
- { flag: "-nowarning" },
99
- { flag: "-seed <num>" },
100
- { flag: "-tool" },
101
- { flag: "-workers <count|auto>" },
102
- ]);
103
-
104
- const PROVE_COMMAND = defineCommand("tla-ts prove {options} <Module.tla|glob>...", [
105
- { flag: "-N", isRequired: true },
106
- { flag: "--toolbox <start> <end>" },
107
- { flag: "--line <num>" },
108
- { flag: "--printallobs" },
109
- { flag: "--summary" },
110
- { flag: "--strict" },
111
- { flag: "-I <directory>", isRepeatable: true },
112
- ]);
113
-
114
- const XML_EXPORT_FLAGS = new Set(["-o", "-t", "-r", "-u"]);
115
-
116
- const XML_EXPORT_174_FLAGS = new Set(["-o"]);
117
-
118
- // The usage that XMLExporter.printUsage prints with UsageGenerator.
119
- const XML_EXPORT_USAGE = (() => {
120
- const bold = (text: string) => `\x1b[1m${text}\x1b[0m`;
121
- const options = [
122
- ["-I", "Include; use given directory path to resolve module dependencies."],
123
- ["-help", "Print this usage information."],
124
- ["-o", "Offline mode; skip XML schema validation step."],
125
- [
126
- "-r",
127
- "Restrict mode; include only declarations and definitions of the specified module, excluding extended or instantiated modules.",
128
- ],
129
- ["-t", "Terse; format XML output without tabs or newlines."],
130
- [
131
- "-u",
132
- "Uncomment; process boxed comments and single-line comments (\\*) in pre-comments to extract their content.",
133
- ],
134
- ];
135
- const tips = [
136
- "Only one root TLA+ file can be parsed per run.",
137
- "Multiple directory search paths can be given by providing multiple -I arguments.",
138
- "XML schema validation does not require network access.",
139
- ];
140
- return [
141
- "",
142
- bold("NAME"),
143
- "",
144
- "\ttla2sany.xml.XMLExporter - Emit SANY's parse tree as XML - Version 2.2 created 08 July 2020",
145
- "",
146
- "",
147
- bold("SYNOPSIS"),
148
- "",
149
- `\t${bold("tla2sany.xml.XMLExporter")} [${bold("-Iortu")}] [${bold("-help")}] FILE`,
150
- "",
151
- bold("DESCRIPTION"),
152
- "",
153
- "\tGiven a TLA+ file, parse that file with SANY then translate the module's semantic parse tree to XML, including all the modules depended on. The XML is printed to stdout and its output format is given by an XML Schema file (.xsd) found at https://proofs.tlapl.us/doc/web/sany.xsd.",
154
- "",
155
- bold("OPTIONS"),
156
- "",
157
- ...options.map(([flag, description]) => `\t${bold(flag)}\n\t\t${description}`),
158
- "",
159
- bold("TIPS"),
160
- "",
161
- ...tips.flatMap((tip) => [`\t${tip}`, ""]),
162
- "",
163
- ].join("\n");
164
- })();
165
-
166
- const USAGE = [
167
- `Usage: ${CHECK_COMMAND.usage}`,
168
- ` ${PROVE_COMMAND.usage}`,
169
- " tla-ts prove [<tlapm option>]... <Module.tla|glob>...",
170
- " tla-ts [<JVM option>]... tlc2.TLC <TLC option>... <Spec>",
171
- " (-cp tla2tools.jar or -Dtla-ts.tlc=1.7.4 picks the TLC to reproduce)",
172
- " tla-ts [<JVM option>]... tla2sany.xml.XMLExporter [-I <directory>]... [-o] [-t] [-r] [-u] <Module.tla>",
173
- ].join("\n");
174
-
175
- const GLOB_CHARACTERS = /[*?[{]/;
176
-
177
- interface InputPath {
178
- path: string;
179
- isGlobbed: boolean;
180
- }
181
-
182
- const getInputPaths = (paths: string[]): InputPath[] =>
183
- paths.flatMap((arg): InputPath[] =>
184
- GLOB_CHARACTERS.test(arg)
185
- ? globSync(arg)
186
- .sort()
187
- .map((path) => ({ path, isGlobbed: true }))
188
- : [{ path: arg, isGlobbed: false }],
189
- );
190
-
191
90
  const isJavaLong = (text: string) =>
192
91
  /^[+-]?\d+$/.test(text) && BigInt.asIntN(64, BigInt(text)) === BigInt(text);
193
92
 
@@ -204,7 +103,7 @@ const UNSUPPORTED_DUMP_FORMATS = ["constrained", "stuttering", "strict"];
204
103
  const getDumpPath = (path: string, extension: string) =>
205
104
  path.endsWith(extension) ? path : `${path}${extension}`;
206
105
 
207
- const getDump = (values: string[]): StateDump => {
106
+ const getStateDump = (values: string[]): StateDump => {
208
107
  if (values.length === 1) return { path: getDumpPath(values[0], ".dump") };
209
108
  const format = values[0].toLowerCase();
210
109
  return {
@@ -216,7 +115,6 @@ const getDump = (values: string[]): StateDump => {
216
115
  };
217
116
  };
218
117
 
219
- // What the spec prints as TLC rebuilds a trace, before it prints the states or after.
220
118
  const printInitialStatesProgress = (printer: MessagePrinter, count: number) =>
221
119
  printer.print(
222
120
  MESSAGE_CODE.computingInitProgress,
@@ -238,6 +136,7 @@ const getInitialViolationHeadline = (
238
136
  text: `Property ${name} is violated by the initial state:`,
239
137
  };
240
138
 
139
+ // What the spec prints as TLC rebuilds a trace, before it prints the states or after.
241
140
  const printTraceOutput = (printer: MessagePrinter, lines: OutputLine[] | undefined) =>
242
141
  lines?.forEach((line) => {
243
142
  if (typeof line === "string") return console.log(line);
@@ -329,35 +228,32 @@ const printInitialStates = (printer: MessagePrinter, initialStates: InitialState
329
228
  };
330
229
 
331
230
  interface Timing {
332
- start: number;
231
+ startTime: number;
333
232
  // Whether TLC has printed that SANY finished.
334
233
  isParsed: boolean;
335
- // When TLC started to check the temporal properties on the complete state graph.
336
- liveness: number | undefined;
234
+ livenessStartTime: number | undefined;
337
235
  }
338
236
 
339
- // TLC reports how far the search got when it prints messages for a program to read, at level 1 or
340
- // deeper even before it finds a state. As the search goes and when it ends, it adds how many
341
- // states it generated and found a minute.
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.
342
239
  const printProgress = (
343
240
  printer: MessagePrinter,
344
241
  statistics: SearchStatistics,
345
242
  startTime?: number,
346
243
  ) => {
347
244
  const minutes = Math.max(Date.now() - (startTime ?? 0), 1) / 60_000;
348
- const format = (count: number) => count.toLocaleString("en-US");
245
+ const formatCount = (count: number) => count.toLocaleString("en-US");
349
246
  const getRate = (count: number, unit: string) =>
350
- startTime === undefined ? "" : ` (${format(Math.floor(count / minutes))} ${unit}/min)`;
247
+ startTime === undefined ? "" : ` (${formatCount(Math.floor(count / minutes))} ${unit}/min)`;
351
248
  printer.print(
352
249
  MESSAGE_CODE.progress,
353
250
  MESSAGE_LEVEL.none,
354
- `Progress(${Math.max(statistics.depth, 1)}) at ${formatTlcDate(new Date())}: ${format(statistics.generatedStates)} states generated${getRate(statistics.generatedStates, "s")}, ${format(statistics.distinctStates)} distinct states found${getRate(statistics.distinctStates, "ds")}, ${format(statistics.queuedStates)} states left on queue.`,
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.`,
355
252
  );
356
253
  };
357
254
 
358
255
  const getClassPath = (directory: string, module: string) => join(directory, `${module}.class`);
359
256
 
360
- // The messages TLC prints as the search goes.
361
257
  const printCheckProgress = (
362
258
  printer: MessagePrinter,
363
259
  progress: CheckProgress,
@@ -436,10 +332,10 @@ const printCheckProgress = (
436
332
  printInitialStates(printer, progress.initialStates);
437
333
  return;
438
334
  case "progress":
439
- printProgress(printer, progress.statistics, timing.start);
335
+ printProgress(printer, progress.statistics, timing.startTime);
440
336
  return;
441
337
  case "liveness-started": {
442
- timing.liveness = Date.now();
338
+ timing.livenessStartTime = Date.now();
443
339
  // TLC reports how far the search got before it checks the complete state graph.
444
340
  if (progress.isComplete) printProgress(printer, progress.statistics);
445
341
  const branches = progress.branches > 1 ? `${progress.branches} branches of ` : "";
@@ -461,13 +357,13 @@ const printCheckProgress = (
461
357
  };
462
358
 
463
359
  const printLivenessEnd = (printer: MessagePrinter, timing: Timing) => {
464
- if (timing.liveness === undefined) return;
360
+ if (timing.livenessStartTime === undefined) return;
465
361
  printer.print(
466
362
  MESSAGE_CODE.checkingTemporalEnd,
467
363
  MESSAGE_LEVEL.none,
468
- `Finished checking temporal properties in ${formatTlcDuration(Date.now() - timing.liveness)} at ${formatTlcDate(new Date())}`,
364
+ `Finished checking temporal properties in ${formatTlcDuration(Date.now() - timing.livenessStartTime)} at ${formatTlcDate(new Date())}`,
469
365
  );
470
- timing.liveness = undefined;
366
+ timing.livenessStartTime = undefined;
471
367
  };
472
368
 
473
369
  // Prints a violation, and returns whether TLC goes on to print the statistics of the search.
@@ -638,8 +534,8 @@ const printResult = (result: CheckResult, printer: MessagePrinter, timing: Timin
638
534
  if (!printViolation(result.status, result.violation, printer)) return;
639
535
  // TLC adds a deadlocked state to the behavior graph after it reports the deadlock, which can
640
536
  // violate a temporal property too.
641
- const additional = result.additionalViolation;
642
- if (additional) printViolation("property-violation", additional, printer);
537
+ const additionalViolation = result.additionalViolation;
538
+ if (additionalViolation) printViolation("property-violation", additionalViolation, printer);
643
539
  if (result.liveCallStack) printNestedExpressions(printer, result.liveCallStack);
644
540
  } else {
645
541
  printLivenessEnd(printer, timing);
@@ -664,7 +560,7 @@ const printResult = (result: CheckResult, printer: MessagePrinter, timing: Timin
664
560
  }
665
561
  if (result.failure?.isWithoutStatistics) return;
666
562
  if (result.status !== "success") printLivenessEnd(printer, timing);
667
- if (printer.isTool) printProgress(printer, result, timing.start);
563
+ if (printer.isTool) printProgress(printer, result, timing.startTime);
668
564
  print(
669
565
  MESSAGE_CODE.stats,
670
566
  MESSAGE_LEVEL.none,
@@ -685,29 +581,10 @@ const printResult = (result: CheckResult, printer: MessagePrinter, timing: Timin
685
581
  if (outDegree) print(MESSAGE_CODE.stateGraphOutdegree, MESSAGE_LEVEL.none, outDegree);
686
582
  };
687
583
 
688
- // Like TLC, tla-ts finds a module in the directory of the spec, then in each library directory.
689
- const findModuleFile = (directories: string[], name: string) =>
690
- directories.map((directory) => join(directory, `${name}.tla`)).find(existsSync);
691
-
692
- const createModuleLoader = (directories: string[]) => (name: string) => {
693
- const path = findModuleFile(directories, name);
694
- return path === undefined ? undefined : readFileSync(path, "utf8");
695
- };
696
-
697
- // SimpleFilenameToStream: SANY names the file of a module it can't find, and where it looked.
698
- const printMissingFile = (userDirectory: string, fileName: string, directories: string[]) =>
699
- console.error(
700
- `File does not exist: ${userDirectory}/${fileName} while looking in these directories: ${userDirectory}, ${directories.join(", ")}, classpath:/tla2sany/StandardModules, classpath:/`,
701
- );
702
-
703
- // The URL of the directory of SANY's standard modules in a tla2tools.jar.
704
- const getStandardModulesUrl = (jar: string) =>
705
- `jar:file:${pathToFileURL(resolve(jar)).pathname}!/tla2sany/StandardModules/`;
706
-
707
584
  // Java's Files.createTempDirectory names a directory by a random unsigned long. tla-ts derives it
708
- // from what the directory holds, so that each run of a spec prints the same files.
709
- const getTemporaryName = (contents: string) =>
710
- createHash("sha256").update(contents).digest().readBigUInt64BE().toString();
585
+ // from TLC's fingerprint of what the directory holds, so that each run of a spec prints the same
586
+ // files.
587
+ const getTemporaryName = (contents: string) => getTlcFingerprint([contents]).toString();
711
588
 
712
589
  // The file TLC's SANY says it parses each module from: the real path of a module's own file, or a
713
590
  // copy in a temporary directory of a module from the root module's file or from the jar on the
@@ -722,7 +599,7 @@ const createFileDescriber = (
722
599
  const temporary = java.temporaryDirectory ?? tmpdir();
723
600
  const temporaryDirectory = existsSync(temporary) ? realpathSync(temporary) : resolve(temporary);
724
601
  const libraryDirectory = join(temporaryDirectory, `tlc-${getTemporaryName(resolve(specPath))}`);
725
- const jar = getJar(java);
602
+ const jar = getToolsJar(java);
726
603
  return (name: string, origin: SanyModuleOrigin) => {
727
604
  const fileName = `${name}.tla`;
728
605
  if (origin === "file") return realpathSync(findModuleFile(directories, name) ?? specPath);
@@ -767,12 +644,12 @@ const printStartupBanner = (printer: MessagePrinter, seed: string, workers: numb
767
644
  // -noGenerateSpecTEBin and -noTEBin turn off the binary trace. TLC 1.7.4 records no such trace.
768
645
  const isTraceRecorded = (args: ParsedArgs, version: TlcVersion) => {
769
646
  const flags = [...args.unknown, ...args.options.map((option) => option.name)];
770
- const has = (name: string, alias = name) =>
647
+ const hasFlag = (name: string, alias = name) =>
771
648
  flags.some((flag) => flag === name || flag.toLowerCase() === alias.toLowerCase());
772
649
  const isSpecGenerated =
773
- has("-generateSpecTE") ||
774
- (!has("-noGenerateSpecTE", "-noTE") && !has("-tool") && !has("-continue"));
775
- return version !== "1.7.4" && isSpecGenerated && !has("-noGenerateSpecTEBin", "-noTEBin");
650
+ hasFlag("-generateSpecTE") ||
651
+ (!hasFlag("-noGenerateSpecTE", "-noTE") && !hasFlag("-tool") && !hasFlag("-continue"));
652
+ return version !== "1.7.4" && isSpecGenerated && !hasFlag("-noGenerateSpecTEBin", "-noTEBin");
776
653
  };
777
654
 
778
655
  const checkSpec = async (
@@ -808,11 +685,10 @@ const checkSpec = async (
808
685
  console.error(`Error: tla-ts does not support the -dump format ${unsupportedFormat}.`);
809
686
  return 1;
810
687
  }
811
- // tla-ts fingerprints states as TLC does with -fp 0.
812
- const fingerprint = args.get("-fp")?.[0];
813
- if (fingerprint !== undefined && Number(fingerprint) !== 0) {
688
+ const fingerprintIndex = args.get("-fp")?.[0];
689
+ if (fingerprintIndex !== undefined && Number(fingerprintIndex) !== 0) {
814
690
  console.error(
815
- `Error: tla-ts fingerprints states as TLC does with -fp 0, not -fp ${fingerprint}.`,
691
+ `Error: tla-ts fingerprints states as TLC does with -fp 0, not -fp ${fingerprintIndex}.`,
816
692
  );
817
693
  return 1;
818
694
  }
@@ -832,10 +708,10 @@ const checkSpec = async (
832
708
  return EXIT_STATUS.configParseError;
833
709
  }
834
710
  const fileName = basename(specPath, ".tla");
835
- const timing: Timing = { start: Date.now(), liveness: undefined, isParsed: false };
711
+ const timing: Timing = { startTime: Date.now(), livenessStartTime: undefined, isParsed: false };
836
712
  // Without -tool, TLC prints how long it ran for a person to read.
837
713
  const printFinished = () => {
838
- const runtime = Date.now() - timing.start;
714
+ const runtime = Date.now() - timing.startTime;
839
715
  printer.print(
840
716
  MESSAGE_CODE.finished,
841
717
  MESSAGE_LEVEL.none,
@@ -884,44 +760,6 @@ const checkSpec = async (
884
760
  const directories = [directory, ...java.libraries];
885
761
  const loadModule = createModuleLoader(directories);
886
762
  const isRecorded = isTraceRecorded(args, version);
887
- const run = async () => {
888
- const source = readFileSync(specPath, "utf8");
889
- const moduleName = parseModule(source).name;
890
- if (moduleName !== fileName) {
891
- throw new TlaSanyFatalError(
892
- `File name '${fileName}' does not match the name '${moduleName}' of the top level module it contains.`,
893
- undefined,
894
- );
895
- }
896
- const result = await check({
897
- workers,
898
- livenessCheck: ["final", "seqfinal", "off"].includes(livenessCheck) ? "final" : "default",
899
- seed: BigInt(seed),
900
- dump: dumpValues && getDump(dumpValues),
901
- isTool: printer.isTool,
902
- isTraceRecorded: isRecorded,
903
- isSanyReported: true,
904
- isWarningEnabled: !args.has("-nowarning"),
905
- version,
906
- onProgress: (progress) => printCheckProgress(printer, progress, timing, directory),
907
- source,
908
- config,
909
- onPause: () => readSync(0, Buffer.alloc(1)),
910
- loadModule,
911
- loadClass: (name) => {
912
- const classPath = getClassPath(directory, name);
913
- return existsSync(classPath) ? readFileSync(classPath) : undefined;
914
- },
915
- readFile: (path) => (existsSync(path) ? readFileSync(path, "utf8") : undefined),
916
- writeFile: (path, content) => {
917
- mkdirSync(dirname(resolve(path)), { recursive: true });
918
- writeFileSync(path, content);
919
- },
920
- });
921
- printResult(result, printer, timing);
922
- printFinished();
923
- return result.failure?.exitCode ?? EXIT_CODES[result.status];
924
- };
925
763
  if (printer.isTool) {
926
764
  printer.print(MESSAGE_CODE.startingSany, MESSAGE_LEVEL.none, "Starting SANY...");
927
765
  }
@@ -930,7 +768,7 @@ const checkSpec = async (
930
768
  // the spec's modules in the spec's directory and the TLA-Library directories.
931
769
  const isAbsoluteSpec = isAbsolute(specPath);
932
770
  const specName = isAbsoluteSpec ? fileName : specPath.replace(/\.tla$/, "");
933
- const jar = getJar(java);
771
+ const jar = getToolsJar(java);
934
772
  const reportMissingFile =
935
773
  version === "1.7.4" ? createMissingFilePrinter174(specPath, java, jar) : undefined;
936
774
  if (reportMissingFile) {
@@ -971,7 +809,42 @@ const checkSpec = async (
971
809
  return EXIT_STATUS.specParseError;
972
810
  }
973
811
  try {
974
- return await run();
812
+ const source = readFileSync(specPath, "utf8");
813
+ const moduleName = parseModule(source).name;
814
+ if (moduleName !== fileName) {
815
+ throw new TlaSanyFatalError(
816
+ `File name '${fileName}' does not match the name '${moduleName}' of the top level module it contains.`,
817
+ undefined,
818
+ );
819
+ }
820
+ const result = await check({
821
+ workers,
822
+ livenessCheck: ["final", "seqfinal", "off"].includes(livenessCheck) ? "final" : "default",
823
+ seed: BigInt(seed),
824
+ dump: dumpValues && getStateDump(dumpValues),
825
+ isTool: printer.isTool,
826
+ isTraceRecorded: isRecorded,
827
+ isSanyReported: true,
828
+ isWarningEnabled: !args.has("-nowarning"),
829
+ version,
830
+ onProgress: (progress) => printCheckProgress(printer, progress, timing, directory),
831
+ source,
832
+ config,
833
+ onPause: () => readSync(0, Buffer.alloc(1)),
834
+ loadModule,
835
+ loadClass: (name) => {
836
+ const classPath = getClassPath(directory, name);
837
+ return existsSync(classPath) ? readFileSync(classPath) : undefined;
838
+ },
839
+ readFile: (path) => (existsSync(path) ? readFileSync(path, "utf8") : undefined),
840
+ writeFile: (path, content) => {
841
+ mkdirSync(dirname(resolve(path)), { recursive: true });
842
+ writeFileSync(path, content);
843
+ },
844
+ });
845
+ printResult(result, printer, timing);
846
+ printFinished();
847
+ return result.failure?.exitCode ?? EXIT_CODES[result.status];
975
848
  } catch (error) {
976
849
  if (!(error instanceof TlaError)) throw error;
977
850
  if (error instanceof TlaSyntaxError) console.log(formatSanyErrors(error, fileName));
@@ -995,225 +868,7 @@ const formatSanyErrors = (error: TlaSyntaxError, specName: string) => {
995
868
  return `${parseError}\nFatal errors while parsing TLA+ spec in file ${specName}\n\n${report}\n*** Errors: 1\n\n${report}\n\n\n`;
996
869
  };
997
870
 
998
- // TLC prints the errors it raises itself. tla-ts names the others, such as a module SANY rejects.
999
- const printError = (error: TlaError, printer: MessagePrinter) => {
1000
- if (error instanceof TlaConfigError || error instanceof TlaEvaluationError) {
1001
- // TLC prints an error it raises with a message code, such as a configuration error, with
1002
- // that code.
1003
- const coded = getCodedMessage(error.message);
1004
- const code = coded && !coded.isEvalException ? coded.code : MESSAGE_CODE.general;
1005
- return printer.print(
1006
- code,
1007
- MESSAGE_LEVEL.error,
1008
- formatInnerMessage(code, error.message, printer.isTool),
1009
- );
1010
- }
1011
- console.error(`${error.name}: ${error.message}`);
1012
- };
1013
-
1014
- // Prints a TlaError and returns its exit code.
1015
- const reportErrors = async (
1016
- run: () => number | Promise<number>,
1017
- printer = createMessagePrinter(false),
1018
- ) => {
1019
- try {
1020
- return await run();
1021
- } catch (error) {
1022
- if (!(error instanceof TlaError)) throw error;
1023
- printError(error, printer);
1024
- return getErrorExitCode(error);
1025
- }
1026
- };
1027
-
1028
- // Runs each path in turn, as TLC runs in a process of its own, so an error in one leaves the others
1029
- // to report. The exit code is the first that is not success.
1030
- const runEach = async (
1031
- paths: string[],
1032
- runPath: (path: string, printer: MessagePrinter) => number | Promise<number>,
1033
- createPrinter: () => MessagePrinter,
1034
- ) => {
1035
- const exitCodes: number[] = [];
1036
- for (const [index, path] of paths.entries()) {
1037
- if (index > 0) console.log("");
1038
- const printer = createPrinter();
1039
- exitCodes.push(await reportErrors(() => runPath(path, printer), printer));
1040
- }
1041
- return exitCodes.find((exitCode) => exitCode !== EXIT_STATUS.success) ?? EXIT_STATUS.success;
1042
- };
1043
-
1044
- // tlapm installs its standard library, with modules such as TLAPS, at lib/tlapm/stdlib beside
1045
- // bin/tlapm.
1046
- const getTlapmPaths = () =>
1047
- (process.env.PATH ?? "")
1048
- .split(delimiter)
1049
- .map((directory) => join(directory, "tlapm"))
1050
- .filter((path) => existsSync(path));
1051
-
1052
- const getTlapmLibrary = () =>
1053
- getTlapmPaths()
1054
- .map((path) => join(dirname(dirname(realpathSync(path))), "lib/tlapm/stdlib"))
1055
- .find((path) => existsSync(path));
1056
-
1057
- const expandGlobs = (paths: string[]) =>
1058
- paths.flatMap((path) => (GLOB_CHARACTERS.test(path) ? globSync(path).sort() : [path]));
1059
-
1060
- const proveWithTlapm = (args: string[]) => {
1061
- const tlapm = getTlapmPaths()[0];
1062
- if (tlapm === undefined) {
1063
- console.error(
1064
- "Error: tla-ts prove runs tlapm to prove obligations, but tlapm isn't on your PATH. Install tlapm, or pass -N to only generate the obligations.",
1065
- );
1066
- return 1;
1067
- }
1068
- return spawnSync(tlapm, expandGlobs(args), { stdio: "inherit" }).status ?? 1;
1069
- };
1070
-
1071
- const readModule = (path: string) =>
1072
- existsSync(path) ? { file: path, source: readFileSync(path, "utf8") } : undefined;
1073
-
1074
- // A message of tlapm's toolbox protocol, which it writes to stderr.
1075
- const printToolboxMessage = (fields: string[]) =>
1076
- console.error(`@!!BEGIN\n${fields.map((field) => `@!!${field}\n`).join("")}@!!END\n`);
1077
-
1078
- const TLAPM_VERSION = "5f5037f";
1079
-
1080
- const quoteArgument = (arg: string) =>
1081
- /^[+,\-./0-9:=@A-Z_a-z]+$/.test(arg) ? arg : `'${arg.replaceAll("'", "'\\''")}'`;
1082
-
1083
- const printToolboxHeader = (args: string[]) =>
1084
- console.log(
1085
- `\n\\* TLAPM version ${TLAPM_VERSION}\n\\* launched at ${formatTlcDate(new Date())} with command line:\n\\* ${["tla-ts", "prove", ...args].map(quoteArgument).join(" ")}\n`,
1086
- );
1087
-
1088
- const STRICT_EXIT_STATUS = { incomplete: 11, emptyTarget: 12 };
1089
-
1090
- const checkStrictly = (result: ModuleObligations, isTargeted: boolean, isSummary: boolean) => {
1091
- const summary = result.summary;
1092
- if (!isSummary) {
1093
- summary.absent.forEach((locus) => console.error(`Missing proof at ${getLocusText(locus)}`));
1094
- summary.omitted.forEach((locus) => console.error(`Omitted proof at ${getLocusText(locus)}`));
1095
- }
1096
- const isIncomplete = summary.absent.length + summary.omitted.length > 0;
1097
- if (isIncomplete) {
1098
- console.error(
1099
- `${getAtPrefix(result.location)}[ERROR]: Proof incomplete in module ${JSON.stringify(result.name)}: ${summary.absent.length} missing, ${summary.omitted.length} omitted proof step(s).`,
1100
- );
1101
- }
1102
- const isEmpty = isTargeted && result.obligations.length === 0;
1103
- if (isEmpty) {
1104
- console.error(
1105
- `${getAtPrefix(result.location)}[ERROR]: No proof obligation found for the selected target.`,
1106
- );
1107
- }
1108
- return [
1109
- ...(isIncomplete ? [STRICT_EXIT_STATUS.incomplete] : []),
1110
- ...(isEmpty ? [STRICT_EXIT_STATUS.emptyTarget] : []),
1111
- ];
1112
- };
1113
-
1114
- const TLAPM_FAILURE_STATUS = 3;
1115
-
1116
- const generateObligations = (generate: () => ModuleObligations[]) => {
1117
- try {
1118
- return generate();
1119
- } catch (error) {
1120
- if (!(error instanceof TlaProofError)) throw error;
1121
- console.error(` tlapm ending abnormally with ${error.exception}\n`);
1122
- return undefined;
1123
- }
1124
- };
1125
-
1126
- const prove = (args: string[]) => {
1127
- if (!args.includes("-N") && !args.includes("--summary")) return proveWithTlapm(args);
1128
- const parsed = PROVE_COMMAND.parse(args);
1129
- const unsupported = parsed.unknown[0];
1130
- if (unsupported !== undefined) {
1131
- console.error(`Error: tla-ts prove does not support the tlapm option ${unsupported}.`);
1132
- return 1;
1133
- }
1134
- if (parsed.incomplete) {
1135
- console.error(`Error: option '${parsed.incomplete.name}' needs an argument.`);
1136
- return 1;
1137
- }
1138
- const nonInteger = parsed.options.find(
1139
- (option) => option.name !== "-I" && option.values.some((value) => !/^-?\d+$/.test(value)),
1140
- );
1141
- if (nonInteger) {
1142
- console.error(`Error: option '${nonInteger.name}' expects an integer.`);
1143
- return 1;
1144
- }
1145
- const files = expandGlobs(parsed.positionals);
1146
- const modulePaths = files.map((path) => (path.endsWith(".tla") ? path : `${path}.tla`));
1147
- if (modulePaths.length === 0) {
1148
- console.error(USAGE);
1149
- return 1;
1150
- }
1151
- const isToolbox = parsed.has("--toolbox") || parsed.has("--line");
1152
- if (isToolbox) printToolboxHeader(args);
1153
- // Like tlapm, the last of --toolbox and --line wins, and a 0 means the whole module.
1154
- const lines = parsed.options.reduce<LineRange>((range, option) => {
1155
- const [start, end] = option.values.map(Number);
1156
- if (option.name === "--toolbox") return { start, end: end === 0 ? Infinity : end };
1157
- if (option.name === "--line") return start === 0 ? WHOLE_MODULE : { start, end: start };
1158
- return range;
1159
- }, WHOLE_MODULE);
1160
- // tlapm searches the current directory and each module's, then its library, then each -I
1161
- // directory, the last given first.
1162
- const tlapmLibrary = getTlapmLibrary();
1163
- const includes = parsed.options.flatMap((option) => (option.name === "-I" ? option.values : []));
1164
- const directories = modulePaths.reduce(
1165
- (found, path) => (found.includes(dirname(path)) ? found : [dirname(path), ...found]),
1166
- [".", ...(tlapmLibrary ? [tlapmLibrary] : []), ...includes.toReversed()],
1167
- );
1168
- // tlapm names each file it reads by joining a search directory and the name, as in ./Module.tla.
1169
- const results = generateObligations(() => {
1170
- const missingIndex = modulePaths.findIndex((path) => !existsSync(path));
1171
- if (missingIndex !== -1) {
1172
- const missing = files[missingIndex];
1173
- console.error(`File "<unknown>":\nError: File ${JSON.stringify(missing)} not found`);
1174
- throw new TlaProofError(`File ${missing} not found`, { failure: "Module.Parser.parse_file" });
1175
- }
1176
- return getObligations(
1177
- modulePaths.map((path) => ({ file: `./${path}`, source: readFileSync(path, "utf8") })),
1178
- (name) =>
1179
- directories.map((directory) => readModule(`${directory}/${name}.tla`)).find(Boolean),
1180
- {
1181
- lines,
1182
- onWarning: (warning) => {
1183
- if (warning.channel === "stdout") return console.log(warning.text);
1184
- const isToolboxMessage =
1185
- warning.channel === "toolbox" || warning.channel === "toolboxOnly";
1186
- if (isToolbox && isToolboxMessage)
1187
- return printToolboxMessage(["type:warning", `msg:${warning.text}`]);
1188
- if (warning.channel !== "toolboxOnly") console.error(warning.text);
1189
- },
1190
- },
1191
- );
1192
- });
1193
- if (!results) return TLAPM_FAILURE_STATUS;
1194
- const failures = results.flatMap((result) => {
1195
- if (parsed.has("--summary")) console.log(formatSummary(result));
1196
- if (isToolbox) {
1197
- result.obligations.forEach((obligation) =>
1198
- printToolboxMessage([
1199
- "type:obligation",
1200
- `id:${obligation.id}`,
1201
- `loc:${obligation.location}`,
1202
- "status:to be proved",
1203
- ...(parsed.has("--printallobs") ? [`obl:${obligation.text}`] : []),
1204
- ]),
1205
- );
1206
- printToolboxMessage(["type:obligationsnumber", `count:${result.obligations.length}`]);
1207
- }
1208
- if (!parsed.has("--strict")) return [];
1209
- return checkStrictly(result, lines.start > 0 || lines.end < Infinity, parsed.has("--summary"));
1210
- });
1211
- return failures.includes(STRICT_EXIT_STATUS.incomplete)
1212
- ? STRICT_EXIT_STATUS.incomplete
1213
- : (failures[0] ?? EXIT_STATUS.success);
1214
- };
1215
-
1216
- const checkSpecs = async (args: string[], java: JavaProperties) => {
871
+ export const checkSpecs = async (args: string[], java: JavaProperties) => {
1217
872
  const parsed = CHECK_COMMAND.parse(args);
1218
873
  const inputs = getInputPaths(parsed.positionals);
1219
874
  const isConfigured = parsed.has("-config");
@@ -1247,123 +902,24 @@ const checkSpecs = async (args: string[], java: JavaProperties) => {
1247
902
  ? path
1248
903
  : (java.libraries.map((directory) => join(directory, path)).find(existsSync) ?? path);
1249
904
  const paths = [...new Set(specPaths.map(findSpec))];
1250
- const tlcVersion = getJavaTlcVersion(java);
1251
- return runEach(
1252
- paths,
1253
- (path, printer) => {
1254
- // TLC checks one spec, so tla-ts names each of several it checks.
1255
- if (paths.length > 1)
1256
- console.log(`Checking ${basename(path)} with ${basename(path, ".tla")}.cfg`);
1257
- return checkSpec(path, parsed, java, printer);
1258
- },
1259
- () => createMessagePrinter(parsed.has("-tool"), !parsed.has("-nowarning"), tlcVersion),
1260
- );
1261
- };
1262
-
1263
- // XMLExporter.run prints why it cannot parse its arguments, and its usage.
1264
- const printXmlExportUsageError = (message: string) => {
1265
- process.stderr.write(`ERROR: ${message}\n${XML_EXPORT_USAGE}`);
1266
- return XML_EXPORT_EXIT_CODE.argsParsingFailure;
1267
- };
1268
-
1269
- // XMLExporter.run writes the XML of a specification, and why it can't when it can't.
1270
- const writeXml = (specification: SanySpecification, options: XmlExportOptions) => {
1271
- try {
1272
- process.stdout.write(exportSanyXml(specification, options));
1273
- return EXIT_STATUS.success;
1274
- } catch (error) {
1275
- if (!(error instanceof TlaUnsupportedError)) throw error;
1276
- const exitCode = getErrorExitCode(error);
1277
- const unwound = error instanceof TlaJavaException ? error.unwound : "";
1278
- console.error(
1279
- exitCode === XML_EXPORT_EXIT_CODE.uncaughtException
1280
- ? `${unwound}Exception in thread "main" ${error.message}`
1281
- : `ERROR: ${error.message}`,
1282
- );
1283
- return exitCode;
1284
- }
1285
- };
1286
-
1287
- interface XmlExportArgs {
1288
- flags: Set<string>;
1289
- includes: string[];
1290
- error: "missing-include" | "several-files" | undefined;
1291
- }
1292
-
1293
- // XMLExporter reads the flags before the last argument, which names the module, and skips an
1294
- // argument it does not know, which then counts as another module.
1295
- const parseXmlExportArgs = (args: string[], flagNames: Set<string>): XmlExportArgs => {
1296
- const parsed: XmlExportArgs = { flags: new Set(), includes: [], error: undefined };
1297
- const last = { flag: -1 };
1298
- for (let index = 0; index < args.length - 1; index++) {
1299
- if (flagNames.has(args[index])) {
1300
- parsed.flags.add(args[index]);
1301
- last.flag = index;
1302
- continue;
1303
- }
1304
- if (args[index] !== "-I") continue;
1305
- index++;
1306
- if (index > args.length - 2) return { ...parsed, error: "missing-include" };
1307
- parsed.includes.push(args[index]);
1308
- last.flag = index;
1309
- }
1310
- return last.flag === args.length - 2 ? parsed : { ...parsed, error: "several-files" };
1311
- };
1312
-
1313
- const exportXml = (args: string[]) => {
1314
- if (args.length === 0) return printXmlExportUsageError("at least one .tla file must be given");
1315
- const parsed = parseXmlExportArgs(args, XML_EXPORT_FLAGS);
1316
- if (parsed.error === "missing-include") {
1317
- return printXmlExportUsageError(
1318
- "the -I flag must be followed by a directory and at least one .tla file",
905
+ // Each spec is checked as TLC would in a process of its own, so an error in one leaves the others
906
+ // to report. The exit code is the first that is not success.
907
+ const exitCodes: number[] = [];
908
+ for (const [index, path] of paths.entries()) {
909
+ if (index > 0) console.log("");
910
+ // TLC checks one spec, so tla-ts names each of several it checks.
911
+ if (paths.length > 1)
912
+ console.log(`Checking ${basename(path)} with ${basename(path, ".tla")}.cfg`);
913
+ const printer = createMessagePrinter(
914
+ parsed.has("-tool"),
915
+ !parsed.has("-nowarning"),
916
+ java.tlcVersion ?? "master",
1319
917
  );
918
+ exitCodes.push(await reportErrors(() => checkSpec(path, parsed, java, printer), printer));
1320
919
  }
1321
- if (parsed.error === "several-files") {
1322
- return printXmlExportUsageError("Only one TLA file to check allowed!");
1323
- }
1324
- const name = args[args.length - 1];
1325
- if (name === "-help") {
1326
- process.stdout.write(XML_EXPORT_USAGE);
1327
- return EXIT_STATUS.success;
1328
- }
1329
- const fileName = name.endsWith(".tla") ? name : `${name}.tla`;
1330
- // SANY looks for each module in the working directory, then in the -I directories, which
1331
- // XMLExporter passes in place of TLA-Library, then among its standard modules.
1332
- const directories = [".", ...parsed.includes];
1333
- const path = directories.map((directory) => resolve(directory, fileName)).find(existsSync);
1334
- if (path === undefined && !SANY_STANDARD_MODULES.has(fileName.slice(0, -".tla".length))) {
1335
- printMissingFile(process.cwd(), `./${fileName}`, parsed.includes);
1336
- }
1337
- // XMLExporter.parseSpec prints SANY's errors, and XMLExporter.run why it fails.
1338
- const sany = getSanyReport(path ?? fileName, createModuleLoader(directories), {
1339
- fileName: name,
1340
- isXmlExport: true,
1341
- });
1342
- process.stderr.write(sany.text);
1343
- if (sany.isFailed || sany.specification === undefined) {
1344
- console.error("ERROR: Failed to parse module.");
1345
- return XML_EXPORT_EXIT_CODE.specParsingFailure;
1346
- }
1347
- return writeXml(sany.specification, {
1348
- version: "master",
1349
- isRestricted: parsed.flags.has("-r"),
1350
- isUncommented: parsed.flags.has("-u"),
1351
- isTerse: parsed.flags.has("-t"),
1352
- });
920
+ return exitCodes.find((exitCode) => exitCode !== EXIT_STATUS.success) ?? EXIT_STATUS.success;
1353
921
  };
1354
922
 
1355
- // TLC 1.7.4's FileUtil.createNamedInputStream names the last file that SimpleFilenameToStream
1356
- // looked for a module in, and the directories it looks in, the standard modules in the jar last,
1357
- // which tla-ts leaves out without a jar.
1358
- const printMissingFile174 = (path: string, libraries: string[], jar: string | undefined) =>
1359
- console.error(
1360
- `File does not exist: ${isAbsolute(path) ? path : `${process.cwd()}/${path}`} while looking in these directories: ${[...libraries, ...(jar === undefined ? [] : [getStandardModulesUrl(jar)])].join(", ")}`,
1361
- );
1362
-
1363
- // SimpleFilenameToStream ends a library directory with a separator.
1364
- const toLibraryPath = (directory: string) =>
1365
- directory.endsWith("/") ? directory : `${directory}/`;
1366
-
1367
923
  // TLC 1.7.4's SimpleFilenameToStream looks for a module in the directory of a spec that TLC is
1368
924
  // given by an absolute path, then in the directory that a relative path names, or else in the
1369
925
  // TLA-Library directories.
@@ -1383,165 +939,3 @@ const createMissingFilePrinter174 = (
1383
939
  : "";
1384
940
  return (fileName: string) => printMissingFile174(`${lastDirectory}${fileName}`, libraries, jar);
1385
941
  };
1386
-
1387
- // TLC 1.7.4's SANY reports each module it can't find as it looks for it.
1388
- const reportMissingModules174 =
1389
- (loadModule: (name: string) => string | undefined, onMissing: (fileName: string) => void) =>
1390
- (name: string) => {
1391
- const text = loadModule(name);
1392
- if (text === undefined && !SANY_174_STANDARD_MODULES.has(name)) onMissing(`${name}.tla`);
1393
- return text;
1394
- };
1395
-
1396
- // TLC 1.7.4's XMLExporter.main throws an exception for an argument it can't take or a
1397
- // specification without a root module.
1398
- const printXmlExporterException = (exception: string, line: number) => {
1399
- console.error(
1400
- `Exception in thread "main" ${exception}\n\tat tla2sany.xml.XMLExporter.main(XMLExporter.java:${line})`,
1401
- );
1402
- return XML_EXPORT_EXIT_CODE.uncaughtException;
1403
- };
1404
-
1405
- // TLC 1.7.4's XMLExporter.main, which takes only -o, as it can't validate the XML without
1406
- // fetching its schema, and -I, and exports a specification that SANY finds errors in.
1407
- const exportXml174 = (args: string[], jar: string | undefined) => {
1408
- if (args.length === 0) {
1409
- return printXmlExporterException(
1410
- "java.lang.IllegalArgumentException: at least one .tla file must be given",
1411
- 59,
1412
- );
1413
- }
1414
- const parsed = parseXmlExportArgs(args, XML_EXPORT_174_FLAGS);
1415
- if (parsed.error === "missing-include") {
1416
- return printXmlExporterException(
1417
- "java.lang.IllegalArgumentException: the -I flag must be followed by a directory and at least one .tla file",
1418
- 71,
1419
- );
1420
- }
1421
- if (parsed.error === "several-files") {
1422
- return printXmlExporterException(
1423
- "java.lang.IllegalArgumentException: Only one TLA file to check allowed!",
1424
- 83,
1425
- );
1426
- }
1427
- const name = args[args.length - 1];
1428
- const fileName = `${name.replace(/\.tla$/i, "")}.tla`;
1429
- // SimpleFilenameToStream looks for a module in the working directory, then in the -I
1430
- // directories, or the root directory when there are none, then among the standard modules.
1431
- const libraries = (parsed.includes.length === 0 ? ["/"] : parsed.includes).map(toLibraryPath);
1432
- const directories = [".", ...libraries];
1433
- const printMissingFile = (moduleFileName: string) =>
1434
- printMissingFile174(`${libraries[libraries.length - 1]}${moduleFileName}`, libraries, jar);
1435
- const path = directories.map((directory) => resolve(directory, fileName)).find(existsSync);
1436
- if (path === undefined && !SANY_174_STANDARD_MODULES.has(basename(fileName, ".tla"))) {
1437
- printMissingFile(fileName);
1438
- return EXIT_STATUS.success;
1439
- }
1440
- const sany = getSanyReport(
1441
- path ?? fileName,
1442
- reportMissingModules174(createModuleLoader(directories), printMissingFile),
1443
- {
1444
- fileName: name,
1445
- isXmlExport: true,
1446
- version: "1.7.4",
1447
- },
1448
- );
1449
- process.stderr.write(sany.text);
1450
- if (sany.specification === undefined) {
1451
- return printXmlExporterException(
1452
- `tla2sany.xml.XMLExportingException: spec ${(path && getSanyModuleName(readFileSync(path, "utf8"), "1.7.4")) ?? "null"} is malformed - does not have a root module`,
1453
- 110,
1454
- );
1455
- }
1456
- return writeXml(sany.specification, {
1457
- version: "1.7.4",
1458
- isRestricted: false,
1459
- isUncommented: false,
1460
- isTerse: true,
1461
- });
1462
- };
1463
-
1464
- // Tools that run TLC with Java, such as the statechart skill of pstack, can run tla-ts in place of
1465
- // java, as in `tla-ts -DTLA-Library=lib -cp tla2tools.jar tlc2.TLC Spec`. tla-ts searches the
1466
- // TLA-Library directories for modules as TLC does, though not as XMLExporter, which ignores them,
1467
- // names the files in java.io.tmpdir and the jar on the class path that TLC would copy and read
1468
- // modules from, and ignores the other options. It reproduces the TLC of that jar, or the one that
1469
- // -Dtla-ts.tlc names without a jar, as in `tla-ts -Dtla-ts.tlc=1.7.4 tlc2.TLC Spec`.
1470
- const JAVA_MAIN_CLASSES = ["tlc2.TLC", "tla2sany.xml.XMLExporter"];
1471
-
1472
- const TLA_LIBRARY_PROPERTY = "-DTLA-Library=";
1473
-
1474
- const TEMPORARY_DIRECTORY_PROPERTY = "-Djava.io.tmpdir=";
1475
-
1476
- const TLC_VERSION_PROPERTY = "-Dtla-ts.tlc=";
1477
-
1478
- // What the java command sets for TLC: the TLA-Library directories it searches for modules, the
1479
- // class path it finds its standard modules on, and java.io.tmpdir, where it copies them.
1480
- interface JavaProperties {
1481
- libraries: string[];
1482
- classPath?: string;
1483
- temporaryDirectory?: string;
1484
- tlcVersion?: TlcVersion;
1485
- }
1486
-
1487
- // The tla2tools.jar on the class path.
1488
- const getJar = (java: JavaProperties) =>
1489
- java.classPath?.split(delimiter).find((entry) => entry.endsWith(".jar"));
1490
-
1491
- // The TLC that -Dtla-ts.tlc names, or else the one of the jar on the class path.
1492
- const getJavaTlcVersion = (java: JavaProperties) => java.tlcVersion ?? getTlcVersion(getJar(java));
1493
-
1494
- interface JavaLaunch {
1495
- mainClass: string;
1496
- args: string[];
1497
- java: JavaProperties;
1498
- }
1499
-
1500
- const getJavaLaunch = (args: string[]): JavaLaunch | undefined => {
1501
- const java: JavaProperties = { libraries: [] };
1502
- for (let index = 0; index < args.length; index++) {
1503
- const arg = args[index];
1504
- if (arg === "-cp" || arg === "-classpath" || arg === "--class-path") {
1505
- index++;
1506
- java.classPath = args[index];
1507
- } else if (arg === "-jar") {
1508
- java.classPath = args[index + 1];
1509
- return { mainClass: "tlc2.TLC", args: args.slice(index + 2), java };
1510
- } else if (arg.startsWith(TLA_LIBRARY_PROPERTY)) {
1511
- java.libraries.push(...arg.slice(TLA_LIBRARY_PROPERTY.length).split(delimiter));
1512
- } else if (arg.startsWith(TEMPORARY_DIRECTORY_PROPERTY)) {
1513
- java.temporaryDirectory = arg.slice(TEMPORARY_DIRECTORY_PROPERTY.length);
1514
- } else if (arg.startsWith(TLC_VERSION_PROPERTY)) {
1515
- java.tlcVersion = arg.slice(TLC_VERSION_PROPERTY.length) === "1.7.4" ? "1.7.4" : "master";
1516
- } else if (!arg.startsWith("-D") && !arg.startsWith("-X")) {
1517
- const isLaunch = index > 0 || JAVA_MAIN_CLASSES.includes(arg);
1518
- return isLaunch ? { mainClass: arg, args: args.slice(index + 1), java } : undefined;
1519
- }
1520
- }
1521
- return undefined;
1522
- };
1523
-
1524
- const runJavaClass = (launch: JavaLaunch) => {
1525
- if (launch.mainClass === "tlc2.TLC") return checkSpecs(launch.args, launch.java);
1526
- if (launch.mainClass === "tla2sany.xml.XMLExporter") {
1527
- return reportErrors(() =>
1528
- getJavaTlcVersion(launch.java) === "1.7.4"
1529
- ? exportXml174(launch.args, getJar(launch.java))
1530
- : exportXml(launch.args),
1531
- );
1532
- }
1533
- console.error(
1534
- `Error: tla-ts runs the Java classes ${JAVA_MAIN_CLASSES.join(" and ")}, not ${launch.mainClass}.`,
1535
- );
1536
- return 1;
1537
- };
1538
-
1539
- const run = async (args: string[]) => {
1540
- if (args[0] === "prove") return reportErrors(() => prove(args.slice(1)));
1541
- const launch = getJavaLaunch(args);
1542
- return launch ? runJavaClass(launch) : checkSpecs(args, { libraries: [] });
1543
- };
1544
-
1545
- export const runCli = async () => {
1546
- process.exitCode = await run(process.argv.slice(2));
1547
- };