tla-ts 0.0.3 → 0.0.4-dev.1a3acf6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (381) hide show
  1. package/README.md +46 -115
  2. package/dist/cli.cjs +1 -1
  3. package/dist/cli.js +1 -1
  4. package/dist/deciders.cjs +366 -0
  5. package/dist/deciders.js +366 -0
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +194 -8
  8. package/dist/index.d.ts +194 -8
  9. package/dist/index.js +1 -1
  10. package/dist/parallel-worker.cjs +1 -4
  11. package/dist/parallel-worker.js +1 -4
  12. package/dist/prove-worker.cjs +9 -0
  13. package/dist/prove-worker.d.cts +9 -0
  14. package/dist/prove-worker.d.ts +9 -0
  15. package/dist/prove-worker.js +9 -0
  16. package/dist/prove.cjs +1006 -0
  17. package/dist/prove.js +1006 -0
  18. package/dist/run.cjs +45 -0
  19. package/dist/run.js +45 -0
  20. package/dist/tlapm.cjs +10 -0
  21. package/dist/tlapm.js +10 -0
  22. package/dist/transfer.cjs +1377 -18
  23. package/dist/transfer.js +1377 -18
  24. package/dist/worker.cjs +21 -0
  25. package/dist/worker.js +21 -0
  26. package/package.json +24 -11
  27. package/src/ast.ts +149 -8
  28. package/src/bags.ts +26 -30
  29. package/src/builtins.ts +45 -19
  30. package/src/bundled-modules.ts +3 -3
  31. package/src/check.ts +1182 -900
  32. package/src/cli/options.ts +109 -0
  33. package/src/cli/run.ts +63 -0
  34. package/src/cli/shared.ts +106 -0
  35. package/src/cli/tlapm.ts +374 -0
  36. package/src/cli/tlc.ts +941 -0
  37. package/src/cli/xml-exporter.ts +221 -0
  38. package/src/cli.ts +9 -2
  39. package/src/codegen.ts +112 -51
  40. package/src/config.ts +254 -181
  41. package/src/dependencies.ts +5 -7
  42. package/src/environment.ts +579 -184
  43. package/src/errors.ts +287 -4
  44. package/src/evaluate.ts +1095 -365
  45. package/src/exit-codes.ts +22 -43
  46. package/src/fingerprints.ts +49 -14
  47. package/src/index.ts +11 -0
  48. package/src/instances.ts +73 -60
  49. package/src/java-overrides.ts +183 -66
  50. package/src/json.ts +31 -36
  51. package/src/levels.ts +197 -54
  52. package/src/lexer.ts +127 -30
  53. package/src/liveness-checker.ts +894 -0
  54. package/src/liveness.ts +246 -596
  55. package/src/{obligation-action.ts → obligations/action.ts} +248 -74
  56. package/src/{obligation-anon.ts → obligations/anonymize.ts} +55 -57
  57. package/src/obligations/equality.ts +260 -0
  58. package/src/obligations/expression.ts +618 -0
  59. package/src/{obligation-format.ts → obligations/format.ts} +7 -8
  60. package/src/obligations/generate.ts +457 -0
  61. package/src/{obligations.ts → obligations/index.ts} +46 -32
  62. package/src/{obligation-levels.ts → obligations/levels.ts} +44 -40
  63. package/src/obligations/module.ts +445 -0
  64. package/src/obligations/normalize.ts +554 -0
  65. package/src/obligations/operators.ts +176 -0
  66. package/src/obligations/pragma.ts +195 -0
  67. package/src/{obligation-printer.ts → obligations/printer.ts} +65 -230
  68. package/src/{obligation-proof.ts → obligations/proof.ts} +7 -2
  69. package/src/obligations/regroup.ts +100 -0
  70. package/src/{obligation-generate.ts → obligations/simplify.ts} +130 -536
  71. package/src/{obligation-source.ts → obligations/source.ts} +174 -216
  72. package/src/{obligation-deref.ts → obligations/subexpression.ts} +84 -115
  73. package/src/obligations/substitution.ts +261 -0
  74. package/src/obligations/temporal.ts +321 -0
  75. package/src/{obligation-tuples.ts → obligations/tuples.ts} +38 -54
  76. package/src/parallel-worker.ts +184 -235
  77. package/src/parallel.ts +156 -91
  78. package/src/parser.ts +490 -188
  79. package/src/pcal/ast.ts +755 -0
  80. package/src/pcal/parse.ts +1487 -0
  81. package/src/pcal/tokenize.ts +487 -0
  82. package/src/pcal/translate.ts +1151 -0
  83. package/src/pcal/validate.ts +444 -0
  84. package/src/prover/decide-pool.ts +95 -0
  85. package/src/prover/deciders.ts +33 -0
  86. package/src/prover/first-order.ts +175 -0
  87. package/src/prover/isabelle/LICENSE +36 -0
  88. package/src/prover/isabelle/LICENSE-tlapm +26 -0
  89. package/src/prover/isabelle/decide.ts +44 -0
  90. package/src/prover/isabelle/encode.ts +445 -0
  91. package/src/prover/isabelle/isar/inner-syntax.ts +579 -0
  92. package/src/prover/isabelle/isar/method.ts +367 -0
  93. package/src/prover/isabelle/isar/proof.ts +28 -0
  94. package/src/prover/isabelle/isar/statement.ts +57 -0
  95. package/src/prover/isabelle/isar/theory.ts +192 -0
  96. package/src/prover/isabelle/isar/type-check.ts +278 -0
  97. package/src/prover/isabelle/provers/blast/blast.ts +258 -0
  98. package/src/prover/isabelle/provers/blast/branch.ts +322 -0
  99. package/src/prover/isabelle/provers/blast/prove.ts +347 -0
  100. package/src/prover/isabelle/provers/blast/rules.ts +330 -0
  101. package/src/prover/isabelle/provers/blast/state.ts +180 -0
  102. package/src/prover/isabelle/provers/blast/term.ts +546 -0
  103. package/src/prover/isabelle/provers/clasimp.ts +150 -0
  104. package/src/prover/isabelle/provers/classical.ts +389 -0
  105. package/src/prover/isabelle/provers/hypsubst.ts +433 -0
  106. package/src/prover/isabelle/pure/bicompose.ts +174 -0
  107. package/src/prover/isabelle/pure/consts.ts +32 -0
  108. package/src/prover/isabelle/pure/conv.ts +79 -0
  109. package/src/prover/isabelle/pure/drule.ts +264 -0
  110. package/src/prover/isabelle/pure/envir.ts +331 -0
  111. package/src/prover/isabelle/pure/goal.ts +53 -0
  112. package/src/prover/isabelle/pure/interrupt.ts +16 -0
  113. package/src/prover/isabelle/pure/list.ts +12 -0
  114. package/src/prover/isabelle/pure/logic.ts +330 -0
  115. package/src/prover/isabelle/pure/name.ts +98 -0
  116. package/src/prover/isabelle/pure/net.ts +215 -0
  117. package/src/prover/isabelle/pure/object-logic.ts +41 -0
  118. package/src/prover/isabelle/pure/pattern.ts +631 -0
  119. package/src/prover/isabelle/pure/raw-simplifier.ts +338 -0
  120. package/src/prover/isabelle/pure/rewriter.ts +602 -0
  121. package/src/prover/isabelle/pure/search.ts +68 -0
  122. package/src/prover/isabelle/pure/seq.ts +133 -0
  123. package/src/prover/isabelle/pure/simplifier.ts +106 -0
  124. package/src/prover/isabelle/pure/table.ts +201 -0
  125. package/src/prover/isabelle/pure/tactic.ts +168 -0
  126. package/src/prover/isabelle/pure/tactical.ts +264 -0
  127. package/src/prover/isabelle/pure/term-ord.ts +105 -0
  128. package/src/prover/isabelle/pure/term.ts +688 -0
  129. package/src/prover/isabelle/pure/thm.ts +783 -0
  130. package/src/prover/isabelle/pure/type.ts +121 -0
  131. package/src/prover/isabelle/pure/unify.ts +753 -0
  132. package/src/prover/isabelle/pure/variable.ts +25 -0
  133. package/src/prover/isabelle/tla/classical-setup.ts +101 -0
  134. package/src/prover/isabelle/tla/context.ts +74 -0
  135. package/src/prover/isabelle/tla/logic-data.ts +5 -0
  136. package/src/prover/isabelle/tla/logic.ts +215 -0
  137. package/src/prover/isabelle/tla/simpdata.ts +241 -0
  138. package/src/prover/isabelle/tools/intuitionistic.ts +132 -0
  139. package/src/prover/ocaml.ts +22 -0
  140. package/src/prover/prep/action.ts +508 -0
  141. package/src/prover/prep/enabled-axioms.ts +189 -0
  142. package/src/prover/prep/fingerprint.ts +388 -0
  143. package/src/prover/prep/level-comparison.ts +529 -0
  144. package/src/prover/prep/md5.ts +60 -0
  145. package/src/prover/prep/methods.ts +221 -0
  146. package/src/prover/prep/normalize.ts +309 -0
  147. package/src/prover/prove-worker.ts +22 -0
  148. package/src/prover/prove.ts +492 -0
  149. package/src/prover/ptl/decide.ts +68 -0
  150. package/src/prover/ptl/encode.ts +244 -0
  151. package/src/prover/ptl/sat.ts +151 -0
  152. package/src/prover/ptl/tableau.ts +276 -0
  153. package/src/prover/smt/axioms.ts +209 -0
  154. package/src/prover/smt/context.ts +108 -0
  155. package/src/prover/smt/data.ts +636 -0
  156. package/src/prover/smt/encode.ts +275 -0
  157. package/src/prover/smt/extensionality.ts +65 -0
  158. package/src/prover/smt/flatten.ts +112 -0
  159. package/src/prover/smt/format.ts +154 -0
  160. package/src/prover/smt/instances.ts +181 -0
  161. package/src/prover/smt/rewrite.ts +766 -0
  162. package/src/prover/smt/solver/act-cache.ts +265 -0
  163. package/src/prover/smt/solver/arith-rewriter.ts +962 -0
  164. package/src/prover/smt/solver/array.ts +22 -0
  165. package/src/prover/smt/solver/asserted-formulas.ts +469 -0
  166. package/src/prover/smt/solver/ast-lt.ts +157 -0
  167. package/src/prover/smt/solver/ast-util.ts +91 -0
  168. package/src/prover/smt/solver/ast.ts +1315 -0
  169. package/src/prover/smt/solver/auf-solver.ts +572 -0
  170. package/src/prover/smt/solver/case-split-queue.ts +178 -0
  171. package/src/prover/smt/solver/cg-table.ts +175 -0
  172. package/src/prover/smt/solver/clause.ts +276 -0
  173. package/src/prover/smt/solver/conflict-resolution.ts +343 -0
  174. package/src/prover/smt/solver/context.ts +1292 -0
  175. package/src/prover/smt/solver/ctx-simplify.ts +334 -0
  176. package/src/prover/smt/solver/der.ts +224 -0
  177. package/src/prover/smt/solver/dyn-ack.ts +141 -0
  178. package/src/prover/smt/solver/e-matching.ts +659 -0
  179. package/src/prover/smt/solver/enode.ts +259 -0
  180. package/src/prover/smt/solver/expr-ref.ts +21 -0
  181. package/src/prover/smt/solver/expr-safe-replace.ts +172 -0
  182. package/src/prover/smt/solver/fingerprints.ts +92 -0
  183. package/src/prover/smt/solver/flat-literals.ts +51 -0
  184. package/src/prover/smt/solver/goal.ts +138 -0
  185. package/src/prover/smt/solver/hash.ts +173 -0
  186. package/src/prover/smt/solver/hashtable.ts +166 -0
  187. package/src/prover/smt/solver/internalizer.ts +1381 -0
  188. package/src/prover/smt/solver/lbool.ts +5 -0
  189. package/src/prover/smt/solver/literal.ts +24 -0
  190. package/src/prover/smt/solver/lp/bound-propagator.ts +391 -0
  191. package/src/prover/smt/solver/lp/constraints.ts +78 -0
  192. package/src/prover/smt/solver/lp/containers.ts +296 -0
  193. package/src/prover/smt/solver/lp/core-solver.ts +504 -0
  194. package/src/prover/smt/solver/lp/cross-nested.ts +224 -0
  195. package/src/prover/smt/solver/lp/dep-intervals.ts +642 -0
  196. package/src/prover/smt/solver/lp/dependency.ts +51 -0
  197. package/src/prover/smt/solver/lp/dioph-eq.ts +1181 -0
  198. package/src/prover/smt/solver/lp/explanation.ts +46 -0
  199. package/src/prover/smt/solver/lp/gomory.ts +255 -0
  200. package/src/prover/smt/solver/lp/hnf-cutter.ts +125 -0
  201. package/src/prover/smt/solver/lp/hnf.ts +281 -0
  202. package/src/prover/smt/solver/lp/int-cube.ts +295 -0
  203. package/src/prover/smt/solver/lp/int-solver.ts +514 -0
  204. package/src/prover/smt/solver/lp/lar-solver.ts +816 -0
  205. package/src/prover/smt/solver/lp/lar-term.ts +62 -0
  206. package/src/prover/smt/solver/lp/lp-settings.ts +91 -0
  207. package/src/prover/smt/solver/lp/maximize-term.ts +347 -0
  208. package/src/prover/smt/solver/lp/nex-creator.ts +381 -0
  209. package/src/prover/smt/solver/lp/nex.ts +120 -0
  210. package/src/prover/smt/solver/lp/nla-backoff.ts +43 -0
  211. package/src/prover/smt/solver/lp/nla-basics.ts +398 -0
  212. package/src/prover/smt/solver/lp/nla-core.ts +968 -0
  213. package/src/prover/smt/solver/lp/nla-divisions.ts +332 -0
  214. package/src/prover/smt/solver/lp/nla-emonics.ts +373 -0
  215. package/src/prover/smt/solver/lp/nla-factorization.ts +30 -0
  216. package/src/prover/smt/solver/lp/nla-grobner.ts +904 -0
  217. package/src/prover/smt/solver/lp/nla-horner.ts +126 -0
  218. package/src/prover/smt/solver/lp/nla-intervals.ts +265 -0
  219. package/src/prover/smt/solver/lp/nla-monomial-bounds.ts +715 -0
  220. package/src/prover/smt/solver/lp/nla-monotone.ts +59 -0
  221. package/src/prover/smt/solver/lp/nla-order.ts +307 -0
  222. package/src/prover/smt/solver/lp/nla-patcher.ts +112 -0
  223. package/src/prover/smt/solver/lp/nla-tangents.ts +251 -0
  224. package/src/prover/smt/solver/lp/nla-throttle.ts +85 -0
  225. package/src/prover/smt/solver/lp/nla-types.ts +124 -0
  226. package/src/prover/smt/solver/lp/nla-var-eqs.ts +141 -0
  227. package/src/prover/smt/solver/lp/nra-solver.ts +440 -0
  228. package/src/prover/smt/solver/lp/numeric-pair.ts +65 -0
  229. package/src/prover/smt/solver/lp/pdd-interval.ts +31 -0
  230. package/src/prover/smt/solver/lp/pdd-simplifier.ts +184 -0
  231. package/src/prover/smt/solver/lp/pdd-solver.ts +408 -0
  232. package/src/prover/smt/solver/lp/pdd.ts +971 -0
  233. package/src/prover/smt/solver/lp/random-updater.ts +138 -0
  234. package/src/prover/smt/solver/lp/static-matrix.ts +246 -0
  235. package/src/prover/smt/solver/lp/union-find.ts +96 -0
  236. package/src/prover/smt/solver/mam-compiler.ts +847 -0
  237. package/src/prover/smt/solver/mam-interpreter.ts +400 -0
  238. package/src/prover/smt/solver/maximize-ac-sharing.ts +118 -0
  239. package/src/prover/smt/solver/model-checker.ts +347 -0
  240. package/src/prover/smt/solver/model-evaluator.ts +262 -0
  241. package/src/prover/smt/solver/model-finder.ts +155 -0
  242. package/src/prover/smt/solver/model-generator.ts +97 -0
  243. package/src/prover/smt/solver/model-macro-solver.ts +728 -0
  244. package/src/prover/smt/solver/nlsat/algebraic.ts +1161 -0
  245. package/src/prover/smt/solver/nlsat/atoms.ts +238 -0
  246. package/src/prover/smt/solver/nlsat/evaluator.ts +303 -0
  247. package/src/prover/smt/solver/nlsat/explain.ts +607 -0
  248. package/src/prover/smt/solver/nlsat/interval-set.ts +351 -0
  249. package/src/prover/smt/solver/nlsat/levelwise.ts +737 -0
  250. package/src/prover/smt/solver/nlsat/mpbq.ts +161 -0
  251. package/src/prover/smt/solver/nlsat/polynomial.ts +1722 -0
  252. package/src/prover/smt/solver/nlsat/solver.ts +911 -0
  253. package/src/prover/smt/solver/nlsat/types.ts +43 -0
  254. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +648 -0
  255. package/src/prover/smt/solver/nlsat/upolynomial.ts +996 -0
  256. package/src/prover/smt/solver/nnf.ts +469 -0
  257. package/src/prover/smt/solver/pattern-inference.ts +351 -0
  258. package/src/prover/smt/solver/poly-rewriter.ts +477 -0
  259. package/src/prover/smt/solver/propagate-values.ts +83 -0
  260. package/src/prover/smt/solver/proto-model.ts +551 -0
  261. package/src/prover/smt/solver/pull-quant.ts +139 -0
  262. package/src/prover/smt/solver/qe-lite-der.ts +526 -0
  263. package/src/prover/smt/solver/qe-lite-fm.ts +576 -0
  264. package/src/prover/smt/solver/qe-lite.ts +381 -0
  265. package/src/prover/smt/solver/qi-queue.ts +362 -0
  266. package/src/prover/smt/solver/quant-tactics.ts +117 -0
  267. package/src/prover/smt/solver/quantifier-analyzer.ts +562 -0
  268. package/src/prover/smt/solver/quantifier-manager.ts +186 -0
  269. package/src/prover/smt/solver/random-gen.ts +10 -0
  270. package/src/prover/smt/solver/rational.ts +165 -0
  271. package/src/prover/smt/solver/ref-vector.ts +62 -0
  272. package/src/prover/smt/solver/relevancy.ts +247 -0
  273. package/src/prover/smt/solver/rewriter-tpl.ts +1159 -0
  274. package/src/prover/smt/solver/rewriter.ts +843 -0
  275. package/src/prover/smt/solver/rlimit.ts +79 -0
  276. package/src/prover/smt/solver/smtlib-parser.ts +526 -0
  277. package/src/prover/smt/solver/solver.ts +71 -0
  278. package/src/prover/smt/solver/sort.ts +35 -0
  279. package/src/prover/smt/solver/sticky-generations.ts +69 -0
  280. package/src/prover/smt/solver/theory-lra-axioms.ts +340 -0
  281. package/src/prover/smt/solver/theory-lra-bounds.ts +226 -0
  282. package/src/prover/smt/solver/theory-lra-final-check.ts +252 -0
  283. package/src/prover/smt/solver/theory-lra-internalize.ts +476 -0
  284. package/src/prover/smt/solver/theory-lra-model.ts +243 -0
  285. package/src/prover/smt/solver/theory-lra-propagate.ts +405 -0
  286. package/src/prover/smt/solver/theory-lra-state.ts +43 -0
  287. package/src/prover/smt/solver/theory-lra.ts +56 -0
  288. package/src/prover/smt/solver/var-subst.ts +258 -0
  289. package/src/prover/smt/solver/z3-license.txt +10 -0
  290. package/src/prover/smt/table.ts +170 -0
  291. package/src/prover/tlapm/cache.ts +236 -0
  292. package/src/prover/tlapm/ocaml-marshal.ts +166 -0
  293. package/src/prover/tlapm/tlapm.ts +96 -0
  294. package/src/prover/tlaps-module.ts +510 -0
  295. package/src/prover/verdict.ts +13 -0
  296. package/src/prover/zenon/LICENSE +32 -0
  297. package/src/prover/zenon/check/check.ts +105 -0
  298. package/src/prover/zenon/check/definitions.ts +144 -0
  299. package/src/prover/zenon/check/equality.ts +182 -0
  300. package/src/prover/zenon/check/functions.ts +62 -0
  301. package/src/prover/zenon/check/keys.ts +125 -0
  302. package/src/prover/zenon/check/propositional.ts +104 -0
  303. package/src/prover/zenon/check/records.ts +188 -0
  304. package/src/prover/zenon/check/relations.ts +121 -0
  305. package/src/prover/zenon/check/rewrites.ts +224 -0
  306. package/src/prover/zenon/check/sets.ts +302 -0
  307. package/src/prover/zenon/check/terms.ts +127 -0
  308. package/src/prover/zenon/check/tla.ts +126 -0
  309. package/src/prover/zenon/decide.ts +107 -0
  310. package/src/prover/zenon/encode.ts +378 -0
  311. package/src/prover/zenon/eqrel.ts +300 -0
  312. package/src/prover/zenon/equality-rules.ts +435 -0
  313. package/src/prover/zenon/expr.ts +551 -0
  314. package/src/prover/zenon/index-table.ts +350 -0
  315. package/src/prover/zenon/isar-case.ts +513 -0
  316. package/src/prover/zenon/isar.ts +1249 -0
  317. package/src/prover/zenon/limits.ts +15 -0
  318. package/src/prover/zenon/llproof.ts +173 -0
  319. package/src/prover/zenon/mltoll.ts +1566 -0
  320. package/src/prover/zenon/node.ts +297 -0
  321. package/src/prover/zenon/ocaml.ts +169 -0
  322. package/src/prover/zenon/parse.ts +247 -0
  323. package/src/prover/zenon/phrase.ts +191 -0
  324. package/src/prover/zenon/proof.ts +198 -0
  325. package/src/prover/zenon/propositional-rules.ts +387 -0
  326. package/src/prover/zenon/rules.ts +94 -0
  327. package/src/prover/zenon/search.ts +288 -0
  328. package/src/prover/zenon/tla/functions.ts +151 -0
  329. package/src/prover/zenon/tla/llproof.ts +480 -0
  330. package/src/prover/zenon/tla/records.ts +225 -0
  331. package/src/prover/zenon/tla/rewrites.ts +447 -0
  332. package/src/prover/zenon/tla/sets.ts +304 -0
  333. package/src/prover/zenon/tla/terms.ts +162 -0
  334. package/src/prover/zenon/tla/tla.ts +506 -0
  335. package/src/randomization.ts +39 -27
  336. package/src/resolve.ts +1474 -426
  337. package/src/runtime.ts +25 -7
  338. package/src/sany/builtins.ts +147 -0
  339. package/src/sany/generator.ts +3111 -0
  340. package/src/sany/levels.ts +1205 -0
  341. package/src/sany/lexer.ts +544 -0
  342. package/src/sany/linter.ts +122 -0
  343. package/src/sany/modules.ts +1398 -0
  344. package/src/sany/nodes.ts +463 -0
  345. package/src/sany/parse-error.ts +2161 -0
  346. package/src/sany/report.ts +355 -0
  347. package/src/sany/selectors.ts +736 -0
  348. package/src/sany/source.ts +247 -0
  349. package/src/sany/xml.ts +1016 -0
  350. package/src/search.ts +969 -0
  351. package/src/spec-description.ts +66 -29
  352. package/src/{standard-levels.ts → standard-definitions.ts} +118 -2
  353. package/src/standard-modules.ts +215 -164
  354. package/src/state-graph.ts +181 -0
  355. package/src/subexpressions.ts +231 -171
  356. package/src/substitution-levels.ts +40 -19
  357. package/src/successors.ts +253 -125
  358. package/src/symmetry.ts +194 -54
  359. package/src/tableau.ts +60 -32
  360. package/src/tlc/fingerprint.ts +214 -0
  361. package/src/{tlc-modules.ts → tlc/jar-data.ts} +4 -0
  362. package/src/tlc/messages.ts +441 -0
  363. package/src/{tlc-order.ts → tlc/order.ts} +84 -16
  364. package/src/{tlc-random.ts → tlc/random.ts} +30 -189
  365. package/src/tlc/replay.ts +659 -0
  366. package/src/{tlc-summary.ts → tlc/summary.ts} +20 -5
  367. package/src/{tlc-module.ts → tlc/tlc-operators.ts} +59 -50
  368. package/src/{tlc-ext.ts → tlc/tlcext-operators.ts} +63 -45
  369. package/src/tlc/version.ts +19 -0
  370. package/src/transfer.ts +44 -32
  371. package/src/values.ts +843 -241
  372. package/src/worker.ts +62 -0
  373. package/dist/parallel.cjs +0 -12
  374. package/dist/parallel.js +0 -12
  375. package/dist/run-cli.cjs +0 -28
  376. package/dist/run-cli.js +0 -28
  377. package/src/canonical.ts +0 -39
  378. package/src/cli-options.ts +0 -58
  379. package/src/obligation-expression.ts +0 -1060
  380. package/src/obligation-module.ts +0 -1042
  381. package/src/run-cli.ts +0 -478
@@ -1,59 +1,89 @@
1
- import type {
2
- Assumption,
3
- Declaration,
4
- Definition,
5
- Expression,
6
- Instance,
7
- Module,
8
- OperatorParam,
9
- SourceLocation,
1
+ import {
2
+ getChildren,
3
+ type Assumption,
4
+ type Declaration,
5
+ type Definition,
6
+ type Expression,
7
+ type Instance,
8
+ type Module,
9
+ type OperatorParam,
10
+ type SourceLocation,
10
11
  } from "./ast";
11
12
  import { BUNDLED_MODULES } from "./bundled-modules";
12
13
  import type { ConfigValue, ModelConfig } from "./config";
13
14
  import type { FileSystem } from "./json";
14
- import { TlaConfigError, TlaEvaluationError, TlaSyntaxError } from "./errors";
15
+ import {
16
+ createSanyError,
17
+ createMissingModuleError,
18
+ formatRange,
19
+ formatSanyWarnings,
20
+ TlaConfigError,
21
+ TlaEvaluationError,
22
+ TlaModuleError,
23
+ TlaSyntaxError,
24
+ type SanyError,
25
+ } from "./errors";
15
26
  import { EXIT_STATUS, setExitCode } from "./exit-codes";
16
27
  import {
17
28
  createBigNumberError,
18
29
  createRealNumberError,
19
- getChildren,
20
- isConstantLevel,
21
- isTlcInteger,
30
+ evaluate,
31
+ getDefinition,
22
32
  type Builtin,
23
33
  type Environment,
24
34
  } from "./evaluate";
25
35
  import {
26
36
  createInstantiation,
37
+ createLocalArguments,
38
+ createLocalIdentifier,
27
39
  getEnabledVariableName,
28
40
  renameLocals,
29
41
  withLetInstances,
30
42
  } from "./instances";
31
- import { overrideDefinitions } from "./java-overrides";
43
+ import { overrideDefinitions, type JavaOverride } from "./java-overrides";
32
44
  import { extractModule, parseModule } from "./parser";
33
45
  import {
34
- checkRedefinitions,
35
46
  getArity,
47
+ getParamArities,
36
48
  isBefore,
49
+ isTheoremDefinition,
37
50
  KEY_SEPARATOR,
38
51
  LOCAL_RESOLUTION,
52
+ MODULE_START,
39
53
  resolveModule,
40
54
  resolveSubstitutions,
55
+ type ModuleReport,
41
56
  type ModuleSymbol,
57
+ type ModuleUnit,
58
+ type SymbolKind,
42
59
  type Symbols,
43
60
  } from "./resolve";
44
61
  import { createRuntime } from "./runtime";
45
- import { CORE_OPERATORS, getStandardModule, STANDARD_DEPENDENCIES } from "./standard-modules";
62
+ import { getSanyStandardModules } from "./sany/modules";
63
+ import { USER_STANDARD_MODULES } from "./tlc/jar-data";
64
+ import { getSanyParseError } from "./sany/parse-error";
65
+ import {
66
+ CORE_OPERATORS,
67
+ getStandardModule,
68
+ getTraceSpecArithmetic,
69
+ STANDARD_DEPENDENCIES,
70
+ } from "./standard-modules";
71
+ import { getStandardRange, STANDARD_LEVELS } from "./standard-definitions";
46
72
  import { resolveInstanceSubexpressions, resolveModuleSubexpressions } from "./subexpressions";
47
- import { checkModuleLevels } from "./levels";
48
- import { checkInstances, type InstanceCheck } from "./substitution-levels";
73
+ import { checkModuleLevels, createLevelAnalyzer } from "./levels";
74
+ import { createInstanceChecker, type InstanceCheck } from "./substitution-levels";
75
+ import { isEvalException } from "./tlc/messages";
76
+ import { createTlcDefinitionOrder, getTlcDeclarationOrder } from "./tlc/order";
49
77
  import {
50
- checkInteger,
78
+ isTlcInteger,
51
79
  createModelValue,
52
80
  createSet,
53
81
  formatValue,
54
82
  valuesEqual,
55
83
  type Value,
84
+ markNormalized,
56
85
  } from "./values";
86
+ import type { TlcVersion } from "./tlc/version";
57
87
 
58
88
  interface EnvironmentOptions {
59
89
  source: string;
@@ -62,6 +92,15 @@ interface EnvironmentOptions {
62
92
  print: (text: string) => void;
63
93
  files: FileSystem;
64
94
  seed?: bigint;
95
+ // Links the modules without a model, as SANY does, so a declared constant needs no value.
96
+ isUnconfigured?: boolean;
97
+ isTool?: boolean;
98
+ // TLC loads Integers for the binary trace of its trace exploration spec, and Integers' Java
99
+ // methods then compute the arithmetic of Naturals.
100
+ isTraceRecorded?: boolean;
101
+ isSanyReported?: boolean;
102
+ isWarningEnabled?: boolean;
103
+ version?: TlcVersion;
65
104
  }
66
105
 
67
106
  interface Specification {
@@ -69,6 +108,12 @@ interface Specification {
69
108
  assumptions: Assumption[];
70
109
  variableLocations: SourceLocation[];
71
110
  instanceActions: Map<string, InstanceAction>;
111
+ // The definitions TLC computes when it starts, in the order it computes them.
112
+ startupDefinitions: Definition[];
113
+ rootConstants: Declaration[];
114
+ rootSymbols: Symbols;
115
+ // The methods of the modules' classes, in the order TLC loads the classes.
116
+ javaOverrides: JavaOverride[];
72
117
  }
73
118
 
74
119
  export interface InstanceAction {
@@ -79,12 +124,14 @@ export interface InstanceAction {
79
124
  const toValue = (value: ConfigValue): Value => {
80
125
  switch (value.kind) {
81
126
  case "Number":
82
- try {
83
- return checkInteger(value.value);
84
- } catch (error) {
85
- // TLC fails with an unexpected exception on a configuration number too big for it.
86
- throw setExitCode(error, EXIT_STATUS.error);
127
+ // TLC fails with an unexpected exception on a configuration number too big for it.
128
+ if (!isTlcInteger(value.value)) {
129
+ throw setExitCode(
130
+ new TlaModuleError(`Integer overflow: ${value.value} is outside TLC's 32-bit range`),
131
+ EXIT_STATUS.error,
132
+ );
87
133
  }
134
+ return value.value;
88
135
  case "String":
89
136
  case "Boolean":
90
137
  return value.value;
@@ -104,25 +151,73 @@ interface LinkedModule {
104
151
  exported: Symbols;
105
152
  modules: Map<string, LinkedModule>;
106
153
  extended: LinkedModule[];
154
+ facts: Set<string>;
107
155
  }
108
156
 
157
+ // errors and warnings collect what SANY reports for the module, and levelChecks the level checks of
158
+ // the modules in its file, which SANY runs only when it reports no error.
109
159
  interface ModuleScope {
110
160
  id: string;
111
161
  symbols: Symbols;
112
162
  modules: Map<string, LinkedModule>;
113
163
  nested: Module[];
164
+ errors: SanyError[];
165
+ warnings: SanyError[];
166
+ levelChecks: (() => void)[];
114
167
  }
115
168
 
116
- const getDeclarations = (linked: LinkedModule) => [
169
+ const getDeclarations = (linked: LinkedModule): Declaration[] => [
117
170
  ...linked.constants,
118
- ...linked.variables.map((variable) => ({ name: variable, arity: 0 })),
171
+ ...linked.variables.map((variable, index) => ({
172
+ name: variable,
173
+ arity: 0,
174
+ location: linked.variableLocations[index],
175
+ })),
119
176
  ];
120
177
 
178
+ // Parses the module SANY reads from the file name.tla. A module SANY's parser rejects fails as it
179
+ // does in TLC: SANY's message, then a fatal error that names the module.
180
+ const parseModuleFile = (source: string, name: string) => {
181
+ try {
182
+ return parseModule(source);
183
+ } catch (error) {
184
+ if (!(error instanceof TlaSyntaxError)) throw error;
185
+ const parseError = getSanyParseError(source);
186
+ if (parseError === undefined) throw error;
187
+ throw createSanyError(
188
+ [
189
+ {
190
+ location: `In module ${name}`,
191
+ message: `Could not parse module ${name} from file ${name}.tla`,
192
+ },
193
+ ],
194
+ true,
195
+ parseError,
196
+ );
197
+ }
198
+ };
199
+
121
200
  const createModuleRedefinedError = (module: Module) =>
122
201
  new TlaSyntaxError(
123
202
  `Multiply-defined module '${module.name}' at line ${module.location.line}, column ${module.location.column}`,
124
203
  );
125
204
 
205
+ const getModuleRedefinition = (module: Module, existing: Module): SanyError | undefined =>
206
+ module.location.range &&
207
+ existing.location.range && {
208
+ location: formatRange(module.location.range),
209
+ message: `Multiply-defined module '${module.name}': this definition or declaration conflicts \nwith the one at ${formatRange(existing.location.range)}.`,
210
+ };
211
+
212
+ // Context.kindOfNode names a definition or a parameter a definition, and any other symbol a
213
+ // declaration.
214
+ const getNodeWord = (kind: SymbolKind) =>
215
+ ["Builtin", "Definition", "Instance", "Parameter"].includes(kind) ? "definition" : "declaration";
216
+
217
+ // The Java class of the node SANY binds a symbol to.
218
+ const getNodeClass = (kind: SymbolKind) =>
219
+ kind === "Theorem" ? "ThmOrAssumpDefNode" : getNodeWord(kind);
220
+
126
221
  const createLocalFunction = (definition: Definition, key: string): Definition => ({
127
222
  kind: "Operator",
128
223
  name: key,
@@ -130,12 +225,7 @@ const createLocalFunction = (definition: Definition, key: string): Definition =>
130
225
  body: {
131
226
  kind: "Let",
132
227
  definitions: [definition],
133
- body: {
134
- kind: "Identifier",
135
- name: definition.name,
136
- location: definition.location,
137
- resolution: LOCAL_RESOLUTION,
138
- },
228
+ body: createLocalIdentifier(definition.name, definition.location),
139
229
  location: definition.location,
140
230
  },
141
231
  isLocal: true,
@@ -143,7 +233,7 @@ const createLocalFunction = (definition: Definition, key: string): Definition =>
143
233
  location: definition.location,
144
234
  });
145
235
 
146
- const createOperatorConstant = (name: string, arity: number, rows: [Value[], Value][]): Builtin => {
236
+ const createOperatorTable = (name: string, arity: number, rows: [Value[], Value][]): Builtin => {
147
237
  const table = `{ ${rows.map((row) => `<${[...row[0], row[1]].map((value) => formatValue(value)).join(", ")}>`).join(", ")}}`;
148
238
  return {
149
239
  kind: "Builtin",
@@ -212,14 +302,22 @@ export const createEnvironment = (
212
302
  const root = parseModule(options.source);
213
303
  const definitions = new Map<string, Definition>();
214
304
  const parameterized = new Map<string, boolean>();
305
+ // The definition each instance copy came from, and the instance parameters the copy adds.
306
+ const copySources = new Map<string, { source: string; prefix: number }>();
307
+ const substitutedDefinitions = new Set<Definition>();
215
308
  const builtins = new Map<string, Builtin>(
216
309
  CORE_OPERATORS.map((operator) => [operator.name, operator]),
217
310
  );
218
311
  const standardExports = new Map<string, Symbols>();
219
312
  const runtime = createRuntime(config.checkDeadlock, options.seed);
313
+ runtime.isWarningEnabled = options.isWarningEnabled ?? true;
314
+ runtime.isTool = options.isTool ?? false;
315
+ runtime.version = options.version ?? "master";
220
316
  const linkedModules = new Map<string, LinkedModule>();
221
317
  const nestedModules = new Map<string, LinkedModule>();
222
- const linkedList: LinkedModule[] = [];
318
+ // Each module by name, from the time its level checks run.
319
+ const checkedModules = new Map<string, LinkedModule>();
320
+ const linkOrder: LinkedModule[] = [];
223
321
  const dependencies = new Map<string, Set<string>>();
224
322
  const loading: Set<string>[] = [];
225
323
  // The top-level modules being linked, to report a cycle of EXTENDS or INSTANCE.
@@ -233,13 +331,34 @@ export const createEnvironment = (
233
331
  const copyCount = { value: 0 };
234
332
  const createName = (name: string) => `${name}#${copyCount.value++}`;
235
333
  const instanceChecks: InstanceCheck[] = [];
334
+ const warnings: SanyError[] = [];
335
+ const checkInstance = createInstanceChecker((name) => {
336
+ const linked = checkedModules.get(name) ?? getLinkedModule(name, name);
337
+ return {
338
+ constants: linked.constants,
339
+ variables: linked.variables,
340
+ definitions: [
341
+ ...new Set(
342
+ [...linked.visible.values()].flatMap((symbol) => definitions.get(symbol.key) ?? []),
343
+ ),
344
+ ],
345
+ assumptions: linked.module.assumptions.map((assumption) => assumption.expression),
346
+ theorems: linked.module.theorems,
347
+ getDefinition: (symbol) => definitions.get(linked.visible.get(symbol)?.key ?? symbol),
348
+ };
349
+ });
236
350
  const instanceActions = new Map<string, InstanceAction>();
351
+ const instanceNames = new Map<string, string>();
352
+ const qualifiedNames = new Map<string, string>();
237
353
 
238
354
  const addStandardModule = (name: string): Symbols | undefined => {
239
355
  const cached = standardExports.get(name);
240
356
  if (cached) return cached;
241
- const standardModule = getStandardModule(name, options.print, runtime, options.files);
357
+ const standardModule = getStandardModule(name, options.print, runtime, options.files, builtins);
242
358
  if (!standardModule) return undefined;
359
+ // TLC loads the modules a standard module instantiates too, and the Java methods of each
360
+ // replace the operators of every module, as those of Integers replace those of Naturals.
361
+ STANDARD_DEPENDENCIES.get(name)?.forEach(addStandardModule);
243
362
  const exported: Symbols = new Map();
244
363
  standardModule.extends.forEach((extended) =>
245
364
  addStandardModule(extended)?.forEach((symbol, symbolName) =>
@@ -248,15 +367,28 @@ export const createEnvironment = (
248
367
  );
249
368
  standardModule.operators.forEach((operator) => {
250
369
  builtins.set(operator.name, operator);
251
- exported.set(operator.name, { key: operator.name, arity: operator.arity });
370
+ exported.set(operator.name, {
371
+ key: operator.name,
372
+ arity: operator.arity,
373
+ params: STANDARD_LEVELS.get(operator.name)?.formals.map((formal) => formal.arity),
374
+ kind: "Definition",
375
+ range: getStandardRange(name, operator.name) ?? exported.get(operator.name)?.range,
376
+ });
252
377
  });
253
378
  standardExports.set(name, exported);
254
379
  return exported;
255
380
  };
256
381
 
257
382
  const getStandardSymbols = (name: string) => {
383
+ // SANY reads a module from the user's directories before its standard modules.
384
+ if (USER_STANDARD_MODULES.has(name) && options.loadModule?.(name) !== undefined)
385
+ return undefined;
258
386
  const symbols = addStandardModule(name);
259
- if (symbols) useModule(name, STANDARD_DEPENDENCIES.get(name) ?? []);
387
+ const dependencies = STANDARD_DEPENDENCIES.get(name) ?? [];
388
+ if (symbols) useModule(name, dependencies);
389
+ // TLC loads the Java class of each module a standard module uses, so one that uses Integers
390
+ // overrides the arithmetic of Naturals.
391
+ if (symbols && dependencies.includes("Integers")) addStandardModule("Integers");
260
392
  return symbols;
261
393
  };
262
394
 
@@ -284,14 +416,17 @@ export const createEnvironment = (
284
416
  options.loadModule?.(name) ??
285
417
  BUNDLED_MODULES.get(name) ??
286
418
  extractModule(options.source, name);
287
- if (source === undefined)
288
- throw new TlaSyntaxError(
289
- `Cannot find source file for module ${name} imported in module ${importer}.`,
290
- );
291
- const module = parseModule(source);
419
+ if (source === undefined) throw createMissingModuleError(name, importer);
420
+ const module = parseModuleFile(source, name);
292
421
  if (module.name !== name) {
293
- throw new TlaSyntaxError(
294
- `File name '${name}' does not match the name '${module.name}' of the top level module it contains.`,
422
+ throw createSanyError(
423
+ [
424
+ {
425
+ location: "Unknown location",
426
+ message: `File name '${name}' does not match the name '${module.name}' of the top level module it contains.`,
427
+ },
428
+ ],
429
+ true,
295
430
  );
296
431
  }
297
432
  return rejectModuleLiterals(module);
@@ -307,6 +442,8 @@ export const createEnvironment = (
307
442
  }
308
443
  const closure = new Set<string>();
309
444
  const nested: Module[] = [];
445
+ const errors: SanyError[] = [];
446
+ const levelChecks: (() => void)[] = [];
310
447
  linking.push(parsed.name);
311
448
  loading.push(closure);
312
449
  const linked = linkModule(parsed, {
@@ -314,11 +451,19 @@ export const createEnvironment = (
314
451
  symbols: new Map(),
315
452
  modules: new Map(),
316
453
  nested,
454
+ errors,
455
+ warnings,
456
+ levelChecks,
317
457
  });
318
458
  loading.pop();
319
459
  linking.pop();
460
+ if (errors.length > 0) throw createSanyError(errors, false, undefined, warnings);
320
461
  const duplicate = nested.find((module) => closure.has(module.name));
462
+ const loaded = duplicate && linkedModules.get(duplicate.name);
463
+ const redefinition = loaded && getModuleRedefinition(duplicate, loaded.module);
464
+ if (redefinition) throw createSanyError([redefinition], false, undefined, warnings);
321
465
  if (duplicate) throw createModuleRedefinedError(duplicate);
466
+ levelChecks.forEach((check) => check());
322
467
  return { linked, closure };
323
468
  };
324
469
 
@@ -329,6 +474,17 @@ export const createEnvironment = (
329
474
  return cached;
330
475
  }
331
476
  const top = linkTopLevel(loadModule(name, importer));
477
+ // TLC replaces each definition of a module that has a standard module's name with the Java
478
+ // method of that name, so a user's Bags.tla keeps the definitions that Bags has no method for.
479
+ const standardModule = getSanyStandardModules(runtime.version).has(name)
480
+ ? getStandardModule(name, options.print, runtime, options.files, builtins)
481
+ : undefined;
482
+ standardModule?.operators.forEach((operator) => {
483
+ const symbol = top.linked.visible.get(operator.name);
484
+ if (symbol?.kind !== "Definition" || symbol.arity !== operator.arity) return;
485
+ builtins.set(symbol.key, operator);
486
+ definitions.delete(symbol.key);
487
+ });
332
488
  linkedModules.set(name, top.linked);
333
489
  dependencies.set(name, top.closure);
334
490
  useModule(name, top.closure);
@@ -338,23 +494,16 @@ export const createEnvironment = (
338
494
  const instantiate = (
339
495
  instance: Instance,
340
496
  module: Module,
341
- unit: {
342
- imported: Symbols;
343
- importedAt: Map<string, SourceLocation>;
344
- definitions: Map<string, Definition>;
345
- getKey: (definition: Definition) => string;
346
- },
497
+ unit: ModuleUnit,
347
498
  isParameterFree: boolean,
348
499
  nested: LinkedModule | undefined,
349
500
  ): Symbols => {
350
501
  const standardSymbols = nested ? undefined : getStandardSymbols(instance.module);
351
- if (standardSymbols) {
352
- if (instance.name === undefined) return standardSymbols;
353
- return new Map(
354
- [...standardSymbols].map(([name, symbol]) => [`${instance.name}!${name}`, symbol]),
355
- );
356
- }
502
+ if (standardSymbols) return getStandardInstanceSymbols(instance, standardSymbols);
357
503
  const linked = nested ?? getLinkedModule(instance.module, module.name);
504
+ linked.facts.forEach((name) =>
505
+ unit.facts.add(instance.name === undefined ? name : `${instance.name}!${name}`),
506
+ );
358
507
  const declarations = getDeclarations(linked);
359
508
  const suffix = `#${copyCount.value++}`;
360
509
  const renamed = new Map(instance.params.map((param) => [param.name, `${param.name}${suffix}`]));
@@ -379,44 +528,84 @@ export const createEnvironment = (
379
528
  variables: new Set(linked.variables),
380
529
  getDefinition: (key) => definitions.get(key),
381
530
  isParameterized: (key) => parameterized.get(key) === true,
382
- addDefinition: (name, create) => {
531
+ addDefinition: (source, name, create) => {
383
532
  const key = createName(`${name}@${module.name}`);
384
- definitions.set(key, create(key));
533
+ const definition = create(key);
534
+ definitions.set(key, definition);
535
+ if (declarations.length > 0) substitutedDefinitions.add(definition);
536
+ if (instance.name !== undefined) {
537
+ instanceNames.set(key, `${instance.name}!${instanceNames.get(source) ?? name}`);
538
+ }
385
539
  parameterized.set(key, !isParameterFree);
540
+ copySources.set(key, { source, prefix: instance.params.length });
386
541
  return key;
387
542
  },
388
543
  createName,
389
544
  });
390
- const declared = new Set(declarations.map((declaration) => declaration.name));
391
- const symbols: Symbols = new Map();
392
- linked.exported.forEach((symbol, name) => {
393
- if (declared.has(name)) return;
394
- if (instance.name === undefined) {
395
- const key = instantiation.getKey(symbol.key);
396
- if (declarations.length > 0)
397
- instanceActions.set(key, { name, location: instance.location });
398
- symbols.set(name, { key, arity: symbol.arity });
399
- return;
400
- }
401
- const key = instantiation.getQualifiedKey(symbol.key);
402
- if (declarations.length > 0) {
403
- instanceActions.set(key, { name: `${instance.name}!${name}`, location: instance.location });
404
- }
405
- symbols.set(`${instance.name}!${name}`, {
406
- key,
407
- arity: symbol.arity + instance.params.length,
408
- });
545
+ return getInstanceSymbols(instance, linked.exported, declarations, (key, name) => {
546
+ const copy =
547
+ instance.name === undefined
548
+ ? instantiation.getKey(key)
549
+ : instantiation.getQualifiedKey(key);
550
+ if (declarations.length > 0) instanceActions.set(copy, { name, location: instance.location });
551
+ if (instance.name !== undefined) qualifiedNames.set(copy, name);
552
+ return copy;
409
553
  });
410
- return symbols;
411
554
  };
412
555
 
413
- const getLocalArguments = (params: OperatorParam[], location: SourceLocation) =>
414
- params.map((param): Expression => ({
415
- kind: "Identifier",
416
- name: param.name,
417
- location,
418
- resolution: LOCAL_RESOLUTION,
419
- }));
556
+ const getStandardInstanceSymbols = (instance: Instance, standardSymbols: Symbols): Symbols =>
557
+ instance.name === undefined
558
+ ? standardSymbols
559
+ : new Map(
560
+ [...standardSymbols].map(([name, symbol]) => [
561
+ `${instance.name}!${name}`,
562
+ { key: symbol.key, arity: symbol.arity, params: symbol.params, kind: symbol.kind },
563
+ ]),
564
+ );
565
+
566
+ // The names an INSTANCE adds for the definitions of the module it instantiates, each with the key
567
+ // that getKey gives it. SANY binds a copy of a definition that depends on the parameters at the
568
+ // INSTANCE.
569
+ const getInstanceSymbols = (
570
+ instance: Instance,
571
+ exported: Symbols,
572
+ declarations: Declaration[],
573
+ getKey: (key: string, name: string) => string,
574
+ ): Symbols => {
575
+ const declared = new Set(declarations.map((declaration) => declaration.name));
576
+ return new Map(
577
+ [...exported]
578
+ .filter(([name]) => !declared.has(name))
579
+ .map(([name, symbol]): [string, ModuleSymbol] => {
580
+ if (instance.name === undefined) {
581
+ return [
582
+ name,
583
+ {
584
+ key: getKey(symbol.key, name),
585
+ arity: symbol.arity,
586
+ params: symbol.params,
587
+ kind: symbol.kind,
588
+ range:
589
+ parameterized.get(symbol.key) === true ? instance.location.range : symbol.range,
590
+ },
591
+ ];
592
+ }
593
+ const qualified = `${instance.name}!${name}`;
594
+ return [
595
+ qualified,
596
+ {
597
+ key: getKey(symbol.key, qualified),
598
+ arity: symbol.arity + instance.params.length,
599
+ params: symbol.params && [
600
+ ...instance.params.map((param) => param.arity),
601
+ ...symbol.params,
602
+ ],
603
+ kind: symbol.kind,
604
+ },
605
+ ];
606
+ }),
607
+ );
608
+ };
420
609
 
421
610
  const createLocalAlias = (
422
611
  name: string,
@@ -431,13 +620,18 @@ export const createEnvironment = (
431
620
  body:
432
621
  forwarded.length === 0
433
622
  ? { kind: "Identifier", name: key, location }
434
- : { kind: "Apply", operator: key, args: getLocalArguments(forwarded, location), location },
623
+ : {
624
+ kind: "Apply",
625
+ operator: key,
626
+ args: createLocalArguments(forwarded, location),
627
+ location,
628
+ },
435
629
  isLocal: true,
436
630
  isRecursive: false,
437
631
  location,
438
632
  });
439
633
 
440
- const getArguments = (arity: number) =>
634
+ const createArgumentParams = (arity: number) =>
441
635
  Array.from({ length: arity }, (_, index) => ({ name: `argument${index}`, arity: 0 }));
442
636
 
443
637
  const getSubstitutionBody = (
@@ -452,7 +646,7 @@ export const createEnvironment = (
452
646
  body: replacement.body,
453
647
  };
454
648
  }
455
- const params = getArguments(declaration.arity);
649
+ const params = createArgumentParams(declaration.arity);
456
650
  const operator =
457
651
  replacement.kind === "Identifier"
458
652
  ? replacement.name
@@ -461,7 +655,7 @@ export const createEnvironment = (
461
655
  : declaration.name;
462
656
  return {
463
657
  params,
464
- body: { kind: "Apply", operator, args: getLocalArguments(params, location), location },
658
+ body: { kind: "Apply", operator, args: createLocalArguments(params, location), location },
465
659
  };
466
660
  };
467
661
 
@@ -476,7 +670,7 @@ export const createEnvironment = (
476
670
  if (standardSymbols) {
477
671
  if (instance.name === undefined) return [];
478
672
  return [...standardSymbols].map(([name, symbol]) => {
479
- const forwarded = getArguments(symbol.arity);
673
+ const forwarded = createArgumentParams(symbol.arity);
480
674
  return createLocalAlias(
481
675
  `${instance.name}!${name}`,
482
676
  symbol.key,
@@ -488,10 +682,16 @@ export const createEnvironment = (
488
682
  }
489
683
  const linked = nested ?? getLinkedModule(instance.module, instancer);
490
684
  const suffix = `#${copyCount.value++}`;
491
- const explicit = new Map(instance.substitutions.map((item) => [item.name, item.expression]));
685
+ const explicitSubstitutions = new Map(
686
+ instance.substitutions.map((item) => [item.name, item.expression]),
687
+ );
492
688
  const declarations = getDeclarations(linked);
493
689
  const getReplacement = (declaration: OperatorParam): Expression =>
494
- explicit.get(declaration.name) ?? { kind: "Identifier", name: declaration.name, location };
690
+ explicitSubstitutions.get(declaration.name) ?? {
691
+ kind: "Identifier",
692
+ name: declaration.name,
693
+ location,
694
+ };
495
695
  instanceChecks.push({
496
696
  module: instance.module,
497
697
  instancer,
@@ -501,9 +701,9 @@ export const createEnvironment = (
501
701
  ),
502
702
  location,
503
703
  });
504
- const instanceNames = new Set(instance.params.map((param) => param.name));
704
+ const instanceParamNames = new Set(instance.params.map((param) => param.name));
505
705
  const isParameterDependent = (declaration: OperatorParam) =>
506
- mentionsName(getReplacement(declaration), instanceNames);
706
+ mentionsName(getReplacement(declaration), instanceParamNames);
507
707
  const substitutionDefinitions = declarations.map((declaration): Definition => {
508
708
  const substitution = getSubstitutionBody(getReplacement(declaration), declaration, location);
509
709
  return {
@@ -526,16 +726,11 @@ export const createEnvironment = (
526
726
  declarations.map((declaration): [string, Expression] => [
527
727
  declaration.name,
528
728
  !isParameterDependent(declaration)
529
- ? {
530
- kind: "Identifier",
531
- name: `${declaration.name}${suffix}`,
532
- location,
533
- resolution: LOCAL_RESOLUTION,
534
- }
729
+ ? createLocalIdentifier(`${declaration.name}${suffix}`, location)
535
730
  : {
536
731
  kind: "Apply",
537
732
  operator: `${declaration.name}${suffix}`,
538
- args: getLocalArguments(instance.params, location),
733
+ args: createLocalArguments(instance.params, location),
539
734
  location,
540
735
  resolution: LOCAL_RESOLUTION,
541
736
  },
@@ -544,7 +739,7 @@ export const createEnvironment = (
544
739
  variables: new Set(linked.variables),
545
740
  getDefinition: (key) => definitions.get(key),
546
741
  isParameterized: (key) => parameterized.get(key) === true,
547
- addDefinition: (name, create) => {
742
+ addDefinition: (_source, name, create) => {
548
743
  const key = `${name}${KEY_SEPARATOR}${instance.module}${suffix}.${copies.length}`;
549
744
  const definition = create(key);
550
745
  copies.push(
@@ -561,13 +756,13 @@ export const createEnvironment = (
561
756
  .filter(([name]) => !declared.has(name))
562
757
  .map(([name, symbol]) => {
563
758
  const key = instantiation.getKey(symbol.key);
564
- const own = getArguments(symbol.arity);
565
- const params = [...instance.params, ...own];
759
+ const ownParams = createArgumentParams(symbol.arity);
760
+ const params = [...instance.params, ...ownParams];
566
761
  return createLocalAlias(
567
762
  instance.name === undefined ? name : `${instance.name}!${name}`,
568
763
  key,
569
764
  params,
570
- key === symbol.key ? own : params,
765
+ key === symbol.key ? ownParams : params,
571
766
  location,
572
767
  );
573
768
  });
@@ -580,31 +775,70 @@ export const createEnvironment = (
580
775
  return definition ? [{ ...definition, name }] : [];
581
776
  });
582
777
 
778
+ const javaOverrides = new Map<string, JavaOverride[]>();
583
779
  const linkModule = (unlinked: Module, scope: ModuleScope): LinkedModule => {
584
- const parsed = overrideDefinitions(unlinked, options.loadClass?.(unlinked.name));
780
+ const overridden = overrideDefinitions(
781
+ unlinked,
782
+ options.loadClass?.(unlinked.name),
783
+ unlinked === root,
784
+ );
785
+ javaOverrides.set(unlinked.name, overridden.overrides);
786
+ const parsed = overridden.module;
787
+ const firstCheck = instanceChecks.length;
585
788
  const visible: Symbols = new Map([
586
789
  ...CORE_OPERATORS.map((operator): [string, ModuleSymbol] => [
587
790
  operator.name,
588
- { key: operator.name, arity: operator.arity },
791
+ { key: operator.name, arity: operator.arity, kind: "Builtin" },
589
792
  ]),
590
793
  ...scope.symbols,
591
794
  ]);
795
+ // Where an INSTANCE first made each name it adds visible.
796
+ const importedAt = new Map<string, SourceLocation>();
797
+ const extendsReport: ModuleReport = { location: MODULE_START, errors: [], warnings: [] };
798
+ const reports = [extendsReport];
799
+ // Context.mergeExtendContext keeps the first of the symbols the extended modules share by name,
800
+ // and warns of two definitions or two declarations but rejects a definition and a declaration.
801
+ const mergeExtended = (symbols: Symbols) =>
802
+ symbols.forEach((symbol, name) => {
803
+ const current = exported.get(name);
804
+ if (!current) {
805
+ visible.set(name, symbol);
806
+ exported.set(name, symbol);
807
+ return;
808
+ }
809
+ if (
810
+ !current.range ||
811
+ !symbol.range ||
812
+ formatRange(current.range) === formatRange(symbol.range)
813
+ ) {
814
+ return;
815
+ }
816
+ const location = formatRange(symbol.range);
817
+ const existing = formatRange(current.range);
818
+ if (getNodeClass(current.kind) === getNodeClass(symbol.kind)) {
819
+ extendsReport.warnings.push({
820
+ location,
821
+ message: `Warning: the ${getNodeWord(current.kind)} of '${name}' conflicts with \nits ${getNodeWord(current.kind)} at ${existing}.`,
822
+ });
823
+ return;
824
+ }
825
+ extendsReport.errors.push({
826
+ location,
827
+ message: `The ${getNodeWord(symbol.kind)} of '${name}' conflicts with \nits ${getNodeWord(current.kind)} at ${existing}.`,
828
+ });
829
+ });
592
830
  const exported: Symbols = new Map();
831
+ const facts = new Set<string>();
593
832
  const modules = new Map<string, LinkedModule>();
594
833
  const extended: LinkedModule[] = [];
595
834
  const constants = [...parsed.constants];
596
835
  const variables = parsed.variables.map((variable) => variable.name);
597
836
  const variableLocations = parsed.variables.map((variable) => variable.location);
598
- const addSymbols = (symbols: Symbols, isExported: boolean) =>
599
- symbols.forEach((symbol, name) => {
600
- visible.set(name, symbol);
601
- if (isExported) exported.set(name, symbol);
602
- });
603
837
  parsed.extends.forEach((name) => {
604
838
  const nested = scope.modules.get(name);
605
839
  const standardSymbols = nested ? undefined : getStandardSymbols(name);
606
840
  if (standardSymbols) {
607
- addSymbols(standardSymbols, true);
841
+ mergeExtended(standardSymbols);
608
842
  return;
609
843
  }
610
844
  const linked = nested ?? getLinkedModule(name, parsed.name);
@@ -618,61 +852,117 @@ export const createEnvironment = (
618
852
  variables.push(variable);
619
853
  variableLocations.push(linked.variableLocations[index]);
620
854
  });
621
- addSymbols(linked.exported, true);
855
+ mergeExtended(linked.exported);
856
+ linked.facts.forEach((name) => facts.add(name));
622
857
  linked.modules.forEach((module, moduleName) => modules.set(moduleName, module));
623
858
  extended.push(linked);
624
859
  });
625
- parsed.constants.forEach((constant) =>
626
- exported.set(constant.name, {
627
- key: constant.name,
628
- arity: constant.arity,
629
- declaration: "Constant",
630
- }),
631
- );
632
- parsed.variables.forEach((variable) =>
633
- exported.set(variable.name, { key: variable.name, arity: 0, declaration: "Variable" }),
860
+ const bound = new Map(visible);
861
+ const declarations = [
862
+ ...parsed.constants.map((constant) => ({ ...constant, kind: "Constant" as const })),
863
+ ...parsed.variables.map((variable) => ({ ...variable, kind: "Variable" as const })),
864
+ ];
865
+ const getDeclarationSymbol = (declaration: (typeof declarations)[number]): ModuleSymbol => ({
866
+ key: declaration.name,
867
+ arity: declaration.arity,
868
+ kind: declaration.kind,
869
+ range: declaration.location.range,
870
+ });
871
+ declarations.forEach((declaration) =>
872
+ exported.set(declaration.name, getDeclarationSymbol(declaration)),
634
873
  );
874
+ const getDefinitionSymbol = (definition: Definition): ModuleSymbol => ({
875
+ key: getKey(definition),
876
+ arity: getArity(definition),
877
+ params: getParamArities(definition),
878
+ kind: isTheoremDefinition(parsed, definition) ? "Theorem" : "Definition",
879
+ range: definition.location.range,
880
+ });
635
881
  const isParameterFree = constants.length === 0 && variables.length === 0;
636
882
  const getKey = (definition: Definition) =>
637
883
  parsed === root ? definition.name : `${definition.name}${KEY_SEPARATOR}${scope.id}`;
638
- const importedAt = new Map<string, SourceLocation>();
639
- const getUnit = (module: Module) => ({
884
+ const instanced = new Map<Instance, Symbols>();
885
+ const getVisibleModules = () => new Map([...scope.modules, ...modules]);
886
+ const isInstancedAfterDefinition = (nested: Module) => {
887
+ const first = parsed.instances.find((instance) => instance.module === nested.name);
888
+ return first !== undefined && isBefore(nested.location, first.location);
889
+ };
890
+ const getLetModule = (instance: Instance) => {
891
+ const ownModule = parsed.modules.find((nested) => nested.name === instance.module);
892
+ if (!ownModule) return getVisibleModules().get(instance.module);
893
+ return isInstancedAfterDefinition(ownModule) ? modules.get(ownModule.name) : undefined;
894
+ };
895
+ const getUnit = (module: Module): ModuleUnit => ({
640
896
  imported: visible,
641
- importedAt,
642
- definitions: new Map(module.definitions.map((definition) => [definition.name, definition])),
897
+ getInstance: (instance) => {
898
+ const nested = getLetModule(instance);
899
+ const standardSymbols = nested ? undefined : getStandardSymbols(instance.module);
900
+ if (standardSymbols) {
901
+ return {
902
+ declarations: [],
903
+ symbols: getStandardInstanceSymbols(instance, standardSymbols),
904
+ instancer: parsed.name,
905
+ };
906
+ }
907
+ const linked = nested ?? getLinkedModule(instance.module, parsed.name);
908
+ const declarations = getDeclarations(linked);
909
+ return {
910
+ declarations,
911
+ symbols: getInstanceSymbols(instance, linked.exported, declarations, (key) => key),
912
+ instancer: parsed.name,
913
+ };
914
+ },
915
+ bound,
916
+ // SANY keeps the first of two definitions of a name.
917
+ definitions: new Map(
918
+ module.definitions.toReversed().map((definition) => [definition.name, definition]),
919
+ ),
643
920
  getKey,
921
+ instanced,
922
+ facts,
923
+ reports,
924
+ warnings: scope.warnings,
644
925
  });
645
- const getVisibleModules = () => new Map([...scope.modules, ...modules]);
926
+ // SANY keeps the first of two symbols of a name.
646
927
  const getSymbolsBefore = (location: SourceLocation): Symbols =>
647
- new Map([
648
- ...visible,
649
- ...[
650
- ...parsed.constants.map((constant) => ({ ...constant, kind: "Constant" as const })),
651
- ...parsed.variables.map((variable) => ({ ...variable, kind: "Variable" as const })),
652
- ]
928
+ [
929
+ ...declarations
653
930
  .filter((declaration) => isBefore(declaration.location, location))
654
931
  .map((declaration): [string, ModuleSymbol] => [
655
932
  declaration.name,
656
- { key: declaration.name, arity: declaration.arity, declaration: declaration.kind },
933
+ getDeclarationSymbol(declaration),
657
934
  ]),
658
935
  ...parsed.definitions
659
936
  .filter((definition) => isBefore(definition.location, location))
660
937
  .map((definition): [string, ModuleSymbol] => [
661
938
  definition.name,
662
- { key: getKey(definition), arity: getArity(definition) },
939
+ getDefinitionSymbol(definition),
663
940
  ]),
664
- ]);
941
+ ].reduce(
942
+ (symbols, [name, symbol]) => (symbols.has(name) ? symbols : symbols.set(name, symbol)),
943
+ new Map(visible),
944
+ );
945
+ // Generator.generateModule reports the errors of a nested module and goes on, and then
946
+ // SymbolTable.addModule reports a module already defined.
665
947
  const linkNested = (nested: Module) => {
666
948
  const visibleModules = getVisibleModules();
667
- if (visibleModules.has(nested.name)) throw createModuleRedefinedError(nested);
949
+ const existing = visibleModules.get(nested.name);
950
+ const redefinition = existing && getModuleRedefinition(nested, existing.module);
951
+ if (existing && !redefinition) throw createModuleRedefinedError(nested);
668
952
  scope.nested.push(nested);
953
+ const report: ModuleReport = { location: nested.location, errors: [], warnings: [] };
954
+ reports.push(report);
669
955
  const linked = linkModule(nested, {
670
956
  id: `${scope.id}/${nested.name}`,
671
957
  symbols: getSymbolsBefore(nested.location),
672
958
  modules: visibleModules,
673
959
  nested: scope.nested,
960
+ errors: report.errors,
961
+ warnings: report.warnings,
962
+ levelChecks: scope.levelChecks,
674
963
  });
675
- modules.set(nested.name, linked);
964
+ if (redefinition) report.errors.push(redefinition);
965
+ if (!existing) modules.set(nested.name, linked);
676
966
  if (!nestedModules.has(nested.name)) nestedModules.set(nested.name, linked);
677
967
  };
678
968
  [
@@ -686,10 +976,13 @@ export const createEnvironment = (
686
976
  isParameterFree,
687
977
  getVisibleModules().get(instance.module),
688
978
  );
689
- symbols.forEach((_, name) => {
690
- if (!visible.has(name)) importedAt.set(name, instance.location);
979
+ instanced.set(instance, symbols);
980
+ symbols.forEach((symbol, name) => {
981
+ if (visible.has(name)) return;
982
+ importedAt.set(name, instance.location);
983
+ visible.set(name, symbol);
984
+ if (!instance.isLocal) exported.set(name, symbol);
691
985
  });
692
- addSymbols(symbols, !instance.isLocal);
693
986
  },
694
987
  })),
695
988
  ...parsed.modules.map((nested) => ({
@@ -699,36 +992,30 @@ export const createEnvironment = (
699
992
  ]
700
993
  .sort((left, right) => (isBefore(left.location, right.location) ? -1 : 1))
701
994
  .forEach((unit) => unit.link());
702
- checkRedefinitions(parsed, getUnit(parsed));
703
- const isInstancedAfterDefinition = (nested: Module) => {
704
- const first = parsed.instances.find((instance) => instance.module === nested.name);
705
- return first !== undefined && isBefore(nested.location, first.location);
706
- };
707
- const getLetModule = (instance: Instance) => {
708
- const own = parsed.modules.find((nested) => nested.name === instance.module);
709
- if (!own) return getVisibleModules().get(instance.module);
710
- return isInstancedAfterDefinition(own) ? modules.get(own.name) : undefined;
711
- };
712
995
  const module = resolveModuleSubexpressions(
713
996
  withLetInstances(parsed, (instance, lets) =>
714
997
  instantiateLocally(instance, lets, parsed.name, getLetModule(instance)),
715
998
  ),
716
999
  getAvailableDefinitions(visible),
717
1000
  );
718
- resolveModule(module, getUnit(module));
1001
+ scope.errors.push(...resolveModule(module, getUnit(module)));
719
1002
  module.definitions.forEach((definition) => {
720
1003
  const key = getKey(definition);
721
1004
  definitions.set(key, definition);
722
1005
  parameterized.set(key, !isParameterFree);
723
- const symbol = { key, arity: getArity(definition) };
1006
+ const symbol = getDefinitionSymbol(definition);
1007
+ const importedLocation = importedAt.get(definition.name);
1008
+ // SANY binds the name of a fact to a fact the module imports before it.
1009
+ if (
1010
+ symbol.kind === "Theorem" &&
1011
+ visible.get(definition.name)?.kind === "Theorem" &&
1012
+ (importedLocation === undefined || isBefore(importedLocation, definition.location))
1013
+ ) {
1014
+ return;
1015
+ }
724
1016
  visible.set(definition.name, symbol);
725
1017
  if (!definition.isLocal) exported.set(definition.name, symbol);
726
1018
  });
727
- checkModuleLevels(module, {
728
- constants: new Set(constants.map((constant) => constant.name)),
729
- variables: new Set(variables),
730
- getDefinition: (symbol) => definitions.get(visible.get(symbol)?.key ?? symbol),
731
- });
732
1019
  const linked = {
733
1020
  module,
734
1021
  constants,
@@ -738,12 +1025,36 @@ export const createEnvironment = (
738
1025
  exported,
739
1026
  modules,
740
1027
  extended,
1028
+ facts: new Set([
1029
+ ...facts,
1030
+ ...[...module.theorems, ...module.assumptions].flatMap((fact) => fact.name ?? []),
1031
+ ]),
741
1032
  };
742
- linkedList.push(linked);
1033
+ if (!checkedModules.has(parsed.name)) checkedModules.set(parsed.name, linked);
1034
+ // SANY checks the instances of a module with its definitions and theorems, so it reports their
1035
+ // errors together.
1036
+ const checks = instanceChecks
1037
+ .splice(firstCheck)
1038
+ .map((check) => ({ location: check.location, check: () => checkInstance(check) }));
1039
+ scope.levelChecks.push(() =>
1040
+ checkModuleLevels(
1041
+ module,
1042
+ {
1043
+ constants: new Set(constants.map((constant) => constant.name)),
1044
+ variables: new Set(variables),
1045
+ getDefinition: (symbol) => definitions.get(visible.get(symbol)?.key ?? symbol),
1046
+ getQualifiedName: (symbol) => qualifiedNames.get(visible.get(symbol)?.key ?? symbol),
1047
+ },
1048
+ checks,
1049
+ warnings,
1050
+ ),
1051
+ );
1052
+ linkOrder.push(linked);
743
1053
  return linked;
744
1054
  };
745
1055
 
746
1056
  const linkedRoot = linkTopLevel(root).linked;
1057
+ if (warnings.length > 0 && !options.isSanyReported) options.print(formatSanyWarnings(warnings));
747
1058
  const getRootKey = (name: string) => linkedRoot.visible.get(name)?.key ?? name;
748
1059
  linkedRoot.visible.forEach((symbol, name) => {
749
1060
  const definition = definitions.get(symbol.key);
@@ -785,6 +1096,7 @@ export const createEnvironment = (
785
1096
  .filter((assignment) => assignment.args === undefined)
786
1097
  .forEach((assignment) => {
787
1098
  const value = toValue(assignment.value);
1099
+ markNormalized(value);
788
1100
  getScopedKeys(assignment).forEach((key) => {
789
1101
  const arity = getKeyArity(key);
790
1102
  if (arity === 0) constants.set(key, value);
@@ -821,7 +1133,7 @@ export const createEnvironment = (
821
1133
  getScopedKeys(table).forEach((key) =>
822
1134
  setOperator(
823
1135
  key,
824
- createOperatorConstant(table.name, getKeyArity(key) || table.rows[0][0].length, table.rows),
1136
+ createOperatorTable(table.name, getKeyArity(key) || table.rows[0][0].length, table.rows),
825
1137
  ),
826
1138
  ),
827
1139
  );
@@ -872,11 +1184,58 @@ export const createEnvironment = (
872
1184
  );
873
1185
  }
874
1186
  });
875
- declaredConstants.forEach((name) => {
876
- if (!constants.has(name) && !substitutions.has(name) && !operatorKeys.has(name)) {
877
- throw new TlaConfigError(`The constant ${name} is not assigned a value by the configuration`);
878
- }
1187
+ // TLC sets a module-scoped entry on the body of the module's definition, which every instance of
1188
+ // the module shares.
1189
+ const scopedKeys = new Set(
1190
+ [...config.constants, ...config.substitutions]
1191
+ .filter((item) => item.module !== undefined)
1192
+ .flatMap(getScopedKeys),
1193
+ );
1194
+ const getOverride = (
1195
+ key: string,
1196
+ prefix: number,
1197
+ ): { key: string; prefix: number } | undefined => {
1198
+ if (scopedKeys.has(key)) return { key, prefix };
1199
+ const copy = copySources.get(key);
1200
+ return copy && getOverride(copy.source, prefix + copy.prefix);
1201
+ };
1202
+ copySources.forEach((copy, key) => {
1203
+ const override = getOverride(copy.source, copy.prefix);
1204
+ const definition = definitions.get(key);
1205
+ if (!override || !definition) return;
1206
+ const params = definition.kind === "Operator" ? definition.params : [];
1207
+ const alias = createLocalAlias(
1208
+ key,
1209
+ override.key,
1210
+ params,
1211
+ params.slice(override.prefix),
1212
+ definition.location,
1213
+ );
1214
+ definitions.set(key, alias);
1215
+ linkedRoot.visible.forEach((symbol, name) => {
1216
+ if (symbol.key === key && name !== key) definitions.set(name, alias);
1217
+ });
879
1218
  });
1219
+ const unassigned = declaredConstants.filter(
1220
+ (name) => !constants.has(name) && !substitutions.has(name) && !operatorKeys.has(name),
1221
+ );
1222
+ if (unassigned.length > 0 && !options.isUnconfigured) {
1223
+ // TLC reports the first constant it finds unassigned in SANY's order of declarations.
1224
+ const name =
1225
+ getTlcDeclarationOrder(options.source, options.loadModule, "constant").find((constant) =>
1226
+ unassigned.includes(constant),
1227
+ ) ?? unassigned[0];
1228
+ throw new TlaConfigError(
1229
+ `The constant parameter ${name} is not assigned a value by the configuration file.`,
1230
+ );
1231
+ }
1232
+
1233
+ if (options.isTraceRecorded) {
1234
+ builtins.forEach((builtin, name) => {
1235
+ const replacement = getTraceSpecArithmetic(builtin);
1236
+ if (replacement) builtins.set(name, replacement);
1237
+ });
1238
+ }
880
1239
 
881
1240
  const environment: Environment = {
882
1241
  runtime,
@@ -884,45 +1243,81 @@ export const createEnvironment = (
884
1243
  builtins,
885
1244
  constants,
886
1245
  substitutions,
1246
+ instanceNames,
887
1247
  variables,
888
1248
  variableIndex: getVariableIndex(
889
1249
  variables,
890
- linkedList.flatMap((linked) => linked.module.variables.map((variable) => variable.name)),
1250
+ linkOrder.flatMap((linked) => linked.module.variables.map((variable) => variable.name)),
891
1251
  ),
892
1252
  definitionValues: new Map(),
893
1253
  constantLevels: new Map(),
1254
+ substitutedDefinitions,
894
1255
  evaluators: new WeakMap(),
895
1256
  };
896
- checkInstances(instanceChecks, (name) => {
897
- const linked = linkedModules.get(name) ?? nestedModules.get(name) ?? linkedRoot;
898
- return {
899
- constants: linked.constants,
900
- variables: linked.variables,
901
- definitions: [
902
- ...new Set(
903
- [...linked.visible.values()].flatMap((symbol) => definitions.get(symbol.key) ?? []),
904
- ),
905
- ],
906
- assumptions: linked.module.assumptions.map((assumption) => assumption.expression),
907
- getDefinition: (symbol) => definitions.get(linked.visible.get(symbol)?.key ?? symbol),
908
- };
1257
+ // TLC evaluates a substitute at startup and rejects it only when that fails and the level bound it
1258
+ // computes is above constant. The bound counts the operators that TLC's Java code overrides with
1259
+ // a minimum level as state-level, so the analyzer takes them for variables.
1260
+ const analyzer = createLevelAnalyzer({
1261
+ constants: new Set(constants.keys()),
1262
+ variables: new Set([
1263
+ ...variables,
1264
+ ...["TLCGet", "Trace", "CounterExample"].filter((name) => builtins.has(name)),
1265
+ ]),
1266
+ getDefinition: (name) => getDefinition(name, environment),
909
1267
  });
1268
+ const getEvaluationError = (body: Expression) => {
1269
+ try {
1270
+ evaluate(body, { environment, scope: undefined, state: undefined, next: undefined });
1271
+ return undefined;
1272
+ } catch (error) {
1273
+ if (error instanceof TlaEvaluationError) return error;
1274
+ throw error;
1275
+ }
1276
+ };
910
1277
  substitutions.forEach((target, name) => {
911
1278
  const definition = definitions.get(target);
912
- if (
1279
+ const error =
913
1280
  declaredConstants.includes(name) &&
914
- definition &&
915
- !isConstantLevel(definition, environment)
916
- ) {
1281
+ definition?.kind === "Operator" &&
1282
+ definition.params.length === 0 &&
1283
+ analyzer.analyzeDefinition(definition, new Map()).level > 0
1284
+ ? getEvaluationError(definition.body)
1285
+ : undefined;
1286
+ if (error) {
1287
+ // TLC's SpecProcessor adds the message of a TLCRuntimeException, not of an EvalException.
1288
+ const addendum = isEvalException(error) ? "" : ` - specifically: ${error.message}`;
917
1289
  throw new TlaConfigError(
918
- `The configuration file substitutes constant ${name} with non-constant ${target}`,
1290
+ `The configuration file substitutes constant ${name} with non-constant ${target}${addendum}`,
919
1291
  );
920
1292
  }
921
1293
  });
1294
+ // TLC 1.7.4 processes the whole spec before it creates its model checker, which TLCGet reads.
1295
+ if (runtime.version !== "1.7.4") runtime.isStarted = true;
1296
+ // TLC computes the constant definitions of each module in the order SANY finishes the modules,
1297
+ // except those of a module that an INSTANCE gives parameters to.
1298
+ const instantiated = new Set(
1299
+ linkOrder.flatMap((linked) => linked.module.instances.map((instance) => instance.module)),
1300
+ );
1301
+ const getDefinitionOrder = createTlcDefinitionOrder(options.source, options.loadModule);
922
1302
  return {
923
1303
  environment,
924
1304
  assumptions,
925
1305
  variableLocations: linkedRoot.variableLocations,
926
1306
  instanceActions,
1307
+ startupDefinitions: linkOrder
1308
+ .filter(
1309
+ (linked) => !instantiated.has(linked.module.name) || getDeclarations(linked).length === 0,
1310
+ )
1311
+ .flatMap((linked) =>
1312
+ getDefinitionOrder(linked === linkedRoot ? undefined : linked.module.name).flatMap(
1313
+ (name) => {
1314
+ const definition = definitions.get(linked.visible.get(name)?.key ?? name);
1315
+ return definition ? [definition] : [];
1316
+ },
1317
+ ),
1318
+ ),
1319
+ rootConstants: linkedRoot.constants,
1320
+ rootSymbols: linkedRoot.visible,
1321
+ javaOverrides: linkOrder.flatMap((linked) => javaOverrides.get(linked.module.name) ?? []),
927
1322
  };
928
1323
  };