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
package/src/values.ts CHANGED
@@ -1,10 +1,12 @@
1
- import { TlaEvaluationError, TlaModuleError } from "./errors";
1
+ import { TlaEvaluationError } from "./errors";
2
2
  import { prettyPrint } from "./pretty-print";
3
+ import type { TlcVersion } from "./tlc/version";
3
4
 
4
5
  export interface ModelValue {
5
6
  kind: "ModelValue";
6
7
  name: string;
7
8
  type: string | undefined;
9
+ rank: number;
8
10
  }
9
11
 
10
12
  export interface SetValue {
@@ -12,6 +14,7 @@ export interface SetValue {
12
14
  elements: Value[];
13
15
  hash: number;
14
16
  fingerprint: number;
17
+ isFingerprinted: boolean;
15
18
  }
16
19
 
17
20
  // A set enumeration whose elements TLC can't sort, such as {1, "a"}. TLC sorts a set enumeration
@@ -28,6 +31,8 @@ export interface FunctionValue {
28
31
  hash: number;
29
32
  fingerprint: number;
30
33
  writtenKeys: Value[] | undefined;
34
+ functionClass: FunctionClass | undefined;
35
+ isFingerprinted: boolean;
31
36
  }
32
37
 
33
38
  export interface IntervalValue {
@@ -75,10 +80,17 @@ export interface SetOperationValue {
75
80
  right: Value;
76
81
  }
77
82
 
83
+ // TLC prints a set filter as its bound names and the location of its predicate.
84
+ interface FilteredSetSource {
85
+ names: string;
86
+ predicate: string;
87
+ }
88
+
78
89
  export interface FilteredSetValue {
79
90
  kind: "FilteredSet";
80
91
  base: Value;
81
92
  test: (element: Value) => boolean;
93
+ source?: FilteredSetSource;
82
94
  }
83
95
 
84
96
  // UNION S when some element of S isn't a set enumeration. TLC enumerates it only when it has to.
@@ -102,6 +114,7 @@ export interface LazyFunctionValue {
102
114
  domain: Value;
103
115
  apply: (argument: Value) => Value;
104
116
  source?: LazyFunctionSource;
117
+ functionClass?: FunctionClass;
105
118
  }
106
119
 
107
120
  export type Value =
@@ -136,12 +149,21 @@ export const isSetValue = (value: Value) =>
136
149
  value.kind !== "Function" &&
137
150
  value.kind !== "LazyFunction";
138
151
 
152
+ // TLC's Reducible values, SetEnumValue and IntervalValue, which combine with another set element by
153
+ // element.
154
+ export const isReducibleSet = (value: Value): value is SetValue | MixedSetValue | IntervalValue =>
155
+ typeof value === "object" &&
156
+ (value.kind === "Set" || value.kind === "MixedSet" || value.kind === "Interval");
157
+
139
158
  export const isFunctionValue = (value: Value): value is FunctionValue | LazyFunctionValue =>
140
159
  typeof value === "object" && (value.kind === "Function" || value.kind === "LazyFunction");
141
160
 
142
161
  export const isModelValue = (value: Value): value is ModelValue =>
143
162
  typeof value === "object" && value.kind === "ModelValue";
144
163
 
164
+ export const isEnumeratedSet = (value: Value): value is SetValue | MixedSetValue =>
165
+ typeof value === "object" && (value.kind === "Set" || value.kind === "MixedSet");
166
+
145
167
  export const describeKind = (value: Value) => {
146
168
  if (typeof value === "boolean") return "boolean";
147
169
  if (typeof value === "number") return "integer";
@@ -150,12 +172,8 @@ export const describeKind = (value: Value) => {
150
172
  return isSetValue(value) ? "set" : "function";
151
173
  };
152
174
 
153
- export const checkInteger = (value: number) => {
154
- if (!Number.isInteger(value) || value > MAXIMUM_INTEGER || value < MINIMUM_INTEGER) {
155
- throw new TlaModuleError(`Integer overflow: ${value} is outside TLC's 32-bit range`);
156
- }
157
- return value;
158
- };
175
+ export const isTlcInteger = (value: number) =>
176
+ Number.isInteger(value) && value <= MAXIMUM_INTEGER && value >= MINIMUM_INTEGER;
159
177
 
160
178
  // TLC keeps a record, or a function with string keys that @@ builds, in the order the spec writes
161
179
  // it until it sorts the value to compare or fingerprint it. ToString, Assert, and error messages
@@ -170,11 +188,11 @@ const setWrittenOrder = (functionValue: FunctionValue, keys: Value[]) => {
170
188
 
171
189
  export const getWrittenPairs = (functionValue: FunctionValue): [Value, Value][] => {
172
190
  const keys = functionValue.writtenKeys ?? functionValue.domain;
173
- return keys.map((key) => [key, functionValue.range[findIndex(functionValue.domain, key)]]);
191
+ return keys.map((key) => [key, functionValue.range[findSortedIndex(functionValue.domain, key)]]);
174
192
  };
175
193
 
176
194
  export const createWrittenRecord = (names: Value[], range: Value[], writtenNames: Value[]) =>
177
- setWrittenOrder(createSortedFunction(names, range), writtenNames);
195
+ setWrittenOrder(createSortedRecord(names, range), writtenNames);
178
196
 
179
197
  // TLC sorts a value it compares even with itself, and every value inside it, so a value it has
180
198
  // hashed or fingerprinted is already sorted.
@@ -215,7 +233,13 @@ const compareFunctions = (left: FunctionValue, right: FunctionValue) => {
215
233
  const rightRange = right.range;
216
234
  if (leftRange === rightRange) return 0;
217
235
  for (let index = 0; index < leftRange.length; index++) {
218
- const valueComparison = compareValues(leftRange[index], rightRange[index]);
236
+ const leftValue = leftRange[index];
237
+ const rightValue = rightRange[index];
238
+ // V8 can't inline the recursive compareValues here, so two numbers skip the call.
239
+ const valueComparison =
240
+ typeof leftValue === "number" && typeof rightValue === "number"
241
+ ? leftValue - rightValue
242
+ : compareValues(leftValue, rightValue);
219
243
  if (valueComparison !== 0) return valueComparison;
220
244
  }
221
245
  return 0;
@@ -259,14 +283,26 @@ const checkModelValueTypes = (left: Value, right: Value, isEquality: boolean) =>
259
283
 
260
284
  // TLC orders strings and model value names by when it first interned the text, so every
261
285
  // check sets the order of its spec's strings before it builds any value.
262
- const stringOrder = { ranks: Object.create(null) as Record<string, number>, size: 0 };
286
+ const stringOrder: { ranks: Record<string, number>; size: number } = {
287
+ ranks: Object.create(null),
288
+ size: 0,
289
+ };
263
290
 
264
291
  export const setStringOrder = (texts: Iterable<string>) => {
265
292
  stringOrder.ranks = Object.create(null);
266
293
  stringOrder.size = 0;
294
+ modelValues.clear();
267
295
  for (const text of texts) rankString(text);
268
296
  };
269
297
 
298
+ // TLC 1.7.4 prints an empty function that isn't a tuple with a space between its brackets, and
299
+ // looks a key up in a function differently, so every check also sets the version its values follow.
300
+ const valueVersion = { is174: false };
301
+
302
+ export const setValueVersion = (version: TlcVersion | undefined) => {
303
+ valueVersion.is174 = version === "1.7.4";
304
+ };
305
+
270
306
  export const rankString = (text: string) => {
271
307
  if (stringOrder.ranks[text] === undefined) stringOrder.ranks[text] = stringOrder.size++;
272
308
  return text;
@@ -353,7 +389,7 @@ export const compareValues = (left: Value, right: Value): number => {
353
389
  if (left.type !== undefined && right.type !== undefined) {
354
390
  checkModelValueTypes(left, right, false);
355
391
  }
356
- return compareStrings(left.name, right.name);
392
+ return left.rank - right.rank;
357
393
  }
358
394
  if (leftKind === "ModelValue" || rightKind === "ModelValue") {
359
395
  checkModelValueTypes(left, right, false);
@@ -385,14 +421,15 @@ export const compareValues = (left: Value, right: Value): number => {
385
421
 
386
422
  const modelValues = new Map<string, ModelValue>();
387
423
 
424
+ // setStringOrder clears the model values, so each check ranks and creates its own.
388
425
  export const createModelValue = (name: string): ModelValue => {
389
- rankString(name);
390
426
  const known = modelValues.get(name);
391
427
  if (known) return known;
392
428
  const value: ModelValue = {
393
429
  kind: "ModelValue",
394
430
  name,
395
431
  type: name.length > 2 && name[1] === "_" ? name[0] : undefined,
432
+ rank: getStringRank(name),
396
433
  };
397
434
  modelValues.set(name, value);
398
435
  return value;
@@ -403,6 +440,7 @@ export const createSortedSet = (elements: Value[]): SetValue => ({
403
440
  elements,
404
441
  hash: 0,
405
442
  fingerprint: 0,
443
+ isFingerprinted: false,
406
444
  });
407
445
 
408
446
  export const createSortedFunction = (domain: Value[], range: Value[]): FunctionValue => ({
@@ -412,9 +450,101 @@ export const createSortedFunction = (domain: Value[], range: Value[]): FunctionV
412
450
  hash: 0,
413
451
  fingerprint: 0,
414
452
  writtenKeys: undefined,
453
+ functionClass: undefined,
454
+ isFingerprinted: false,
415
455
  });
416
456
 
457
+ // TLC words a failed function application by the Java class of the function: FcnLambdaValue for
458
+ // [x \in S |-> e], TupleValue for <<...>> and what the sequence operators build, RecordValue for
459
+ // [a |-> e], and FcnRcdValue for any other function.
460
+ export type FunctionClass = "lambda" | "tuple" | "record";
461
+
462
+ // Whether a lambda exists for markFingerprinted to find, so that a spec without one skips the walk.
463
+ const lambdaPresence = { isPresent: false };
464
+
465
+ export const setFunctionClass = <FunctionLike extends FunctionValue | LazyFunctionValue>(
466
+ functionValue: FunctionLike,
467
+ functionClass: FunctionClass | undefined,
468
+ ) => {
469
+ if (functionClass === "lambda") lambdaPresence.isPresent = true;
470
+ if (functionClass !== undefined) functionValue.functionClass = functionClass;
471
+ return functionValue;
472
+ };
473
+
474
+ export const getFunctionClass = (value: Value) =>
475
+ typeof value === "object" && (value.kind === "Function" || value.kind === "LazyFunction")
476
+ ? value.functionClass
477
+ : undefined;
478
+
479
+ export const markLambdaFunction = <FunctionLike extends FunctionValue | LazyFunctionValue>(
480
+ functionValue: FunctionLike,
481
+ ) => setFunctionClass(functionValue, "lambda");
482
+
483
+ const fingerprintedValues = new WeakSet<ObjectValue>();
484
+
485
+ // The lazy sets TLC has cached the elements of. TLC caches a set as the receiver of compareTo,
486
+ // equals, size, and fingerPrint, not as their argument, and enumerates the sets an uncached one
487
+ // combines, duplicates and all.
488
+ const cachedSets = new WeakSet<ObjectValue>();
489
+
490
+ // Whether the spec has built a UNION or \cup set, the sets that stream duplicates, so that a spec
491
+ // without one skips tracking what TLC caches.
492
+ const streamedSetPresence = { isPresent: false };
493
+
494
+ export const markStreamedSet = <Streamed extends UnionValue | SetOperationValue>(
495
+ value: Streamed,
496
+ ) => {
497
+ streamedSetPresence.isPresent = true;
498
+ return value;
499
+ };
500
+
501
+ // The sets that stream their elements apart from the normalized set until TLC caches them.
502
+ const STREAMING_KINDS = new Set<ObjectValue["kind"]>([
503
+ "Union",
504
+ "SetOperation",
505
+ "FilteredSet",
506
+ "ProductSet",
507
+ "RecordSet",
508
+ "FunctionSet",
509
+ ]);
510
+
511
+ const cacheSet = (value: Value) => {
512
+ if (
513
+ streamedSetPresence.isPresent &&
514
+ typeof value === "object" &&
515
+ STREAMING_KINDS.has(value.kind)
516
+ ) {
517
+ cachedSets.add(value);
518
+ }
519
+ };
520
+
521
+ // FcnLambdaValue#fingerPrint caches the FcnRcdValue the function enumerates to, which applies it
522
+ // from then on, so a function TLC has fingerprinted is no longer a lambda.
523
+ export const markFingerprinted = (value: Value): void => {
524
+ if ((!lambdaPresence.isPresent && !streamedSetPresence.isPresent) || typeof value !== "object") {
525
+ return;
526
+ }
527
+ if (value.kind === "Function" || value.kind === "Set") {
528
+ if (value.isFingerprinted) return;
529
+ value.isFingerprinted = true;
530
+ } else {
531
+ if (fingerprintedValues.has(value)) return;
532
+ fingerprintedValues.add(value);
533
+ }
534
+ if (value.kind === "Function") {
535
+ if (value.functionClass === "lambda") value.functionClass = undefined;
536
+ value.domain.forEach(markFingerprinted);
537
+ value.range.forEach(markFingerprinted);
538
+ } else if (value.kind === "Set" || value.kind === "MixedSet") {
539
+ value.elements.forEach(markFingerprinted);
540
+ } else if (isSetValue(value) && isEnumerable(value)) {
541
+ cacheSet(value);
542
+ toFiniteSet(value).elements.forEach(markFingerprinted);
543
+ }
544
+ };
545
+
417
546
  export const valuesEqual = (left: Value, right: Value): boolean => {
547
+ cacheSet(left);
418
548
  if (left === right) {
419
549
  if (writtenOrderUse.isUsed) forgetWrittenOrder(left);
420
550
  return left !== ANY_SET || compareAny(left);
@@ -488,26 +618,80 @@ export const valuesEqual = (left: Value, right: Value): boolean => {
488
618
  return compareValues(left, right) === 0;
489
619
  };
490
620
 
491
- const areSameValues = (left: Value[], right: Value[]) =>
492
- left === right ||
493
- (left.length === right.length &&
494
- left.every((element, index) => isSameValue(element, right[index])));
621
+ // TLC prints and words errors about an equal function by its Java class, so a value can stand for
622
+ // another in a state only if each function in it has the same class.
623
+ const createSameValueCheck = (isClassSensitive: boolean) => {
624
+ const areSameValues = (left: Value[], right: Value[]) => {
625
+ if (left === right) return true;
626
+ if (left.length !== right.length) return false;
627
+ for (let index = 0; index < left.length; index++) {
628
+ if (!isSame(left[index], right[index])) return false;
629
+ }
630
+ return true;
631
+ };
632
+ const isSame = (left: Value, right: Value): boolean => {
633
+ if (left === right) return true;
634
+ if (typeof left !== "object" || typeof right !== "object") return false;
635
+ if (left.kind === "Set" && right.kind === "Set")
636
+ return (
637
+ (left.hash === 0 || right.hash === 0 || left.hash === right.hash) &&
638
+ areSameValues(left.elements, right.elements)
639
+ );
640
+ if (left.kind === "Function" && right.kind === "Function")
641
+ return (
642
+ (!isClassSensitive || left.functionClass === right.functionClass) &&
643
+ (left.hash === 0 || right.hash === 0 || left.hash === right.hash) &&
644
+ areSameValues(left.domain, right.domain) &&
645
+ areSameValues(left.range, right.range)
646
+ );
647
+ return getValueKey(left) === getValueKey(right);
648
+ };
649
+ return isSame;
650
+ };
651
+
652
+ export const isSameValue = createSameValueCheck(false);
495
653
 
496
- export const isSameValue = (left: Value, right: Value): boolean => {
497
- if (left === right) return true;
498
- if (typeof left !== "object" || typeof right !== "object") return false;
499
- if (left.kind === "Set" && right.kind === "Set")
500
- return (
501
- (left.hash === 0 || right.hash === 0 || left.hash === right.hash) &&
502
- areSameValues(left.elements, right.elements)
503
- );
504
- if (left.kind === "Function" && right.kind === "Function")
505
- return (
506
- (left.hash === 0 || right.hash === 0 || left.hash === right.hash) &&
507
- areSameValues(left.domain, right.domain) &&
508
- areSameValues(left.range, right.range)
509
- );
510
- return getValueKey(left) === getValueKey(right);
654
+ const isInterchangeableValue = createSameValueCheck(true);
655
+
656
+ const canonicalizeElements = (elements: Value[], canonicalize: (value: Value) => Value) => {
657
+ for (let index = 0; index < elements.length; index++) {
658
+ elements[index] = canonicalize(elements[index]);
659
+ }
660
+ };
661
+
662
+ // Replaces each set and function in a state with the first interchangeable one it has seen, so that
663
+ // the states it keeps share their values.
664
+ export const createCanonicalizer = () => {
665
+ const canonicalValues = new Map<number, Value | Value[]>();
666
+ const canonicalize = (value: Value): Value => {
667
+ if (typeof value !== "object" || (value.kind !== "Set" && value.kind !== "Function")) {
668
+ return value;
669
+ }
670
+ const hash = getValueHash(value);
671
+ const bucket = canonicalValues.get(hash);
672
+ if (bucket !== undefined && !Array.isArray(bucket)) {
673
+ if (bucket === value || isInterchangeableValue(bucket, value)) return bucket;
674
+ }
675
+ if (Array.isArray(bucket)) {
676
+ for (let index = 0; index < bucket.length; index++) {
677
+ if (bucket[index] === value || isInterchangeableValue(bucket[index], value))
678
+ return bucket[index];
679
+ }
680
+ }
681
+ if (value.kind === "Set") canonicalizeElements(value.elements, canonicalize);
682
+ else {
683
+ canonicalizeElements(value.domain, canonicalize);
684
+ canonicalizeElements(value.range, canonicalize);
685
+ }
686
+ if (bucket === undefined) canonicalValues.set(hash, value);
687
+ else if (Array.isArray(bucket)) bucket.push(value);
688
+ else canonicalValues.set(hash, [bucket, value]);
689
+ return value;
690
+ };
691
+ return (state: Value[]) => {
692
+ for (let index = 0; index < state.length; index++) state[index] = canonicalize(state[index]);
693
+ return state;
694
+ };
511
695
  };
512
696
 
513
697
  // The comparisons above fail with their own messages. These follow the compareTo and equals
@@ -542,56 +726,25 @@ const toTlcRecord = (value: Value) => {
542
726
  return functionValue.domain.every((key) => typeof key === "string") ? functionValue : undefined;
543
727
  };
544
728
 
729
+ // A model value compared with a value of another kind. The other value is never a model value.
545
730
  const compareModelValueWith = (modelValue: ModelValue, other: Value) => {
546
- if (getModelValueType(modelValue) !== undefined) {
547
- throw new TlaEvaluationError(
548
- `Attempted to compare the typed model value ${formatValue(modelValue)} and the non-model value\n${formatValue(other)}`,
549
- );
550
- }
731
+ checkModelValueTypes(other, modelValue, false);
551
732
  return 1;
552
733
  };
553
734
 
554
735
  const equalsModelValueWith = (modelValue: ModelValue, other: Value) => {
555
- if (getModelValueType(modelValue) !== undefined) {
556
- throw new TlaEvaluationError(
557
- `Attempted to check equality of the typed model value ${formatValue(modelValue)} and the non-model value\n${formatValue(other)}`,
558
- );
559
- }
736
+ checkModelValueTypes(other, modelValue, true);
560
737
  return false;
561
738
  };
562
739
 
563
740
  const compareModelValue = (left: ModelValue, right: Value) => {
564
- const type = getModelValueType(left);
565
- if (type === undefined) return isModelValue(right) ? compareStrings(left.name, right.name) : -1;
566
- if (!isModelValue(right)) {
567
- throw new TlaEvaluationError(
568
- `Attempted to compare the typed model value ${formatValue(left)} and non-model value\n${formatValue(right)}`,
569
- );
570
- }
571
- const otherType = getModelValueType(right);
572
- if (otherType !== undefined && otherType !== type) {
573
- throw new TlaEvaluationError(
574
- `Attempted to compare the differently-typed model values ${formatValue(left)} and ${formatValue(right)}`,
575
- );
576
- }
577
- return compareStrings(left.name, right.name);
741
+ if (left.type !== undefined) checkModelValueTypes(left, right, false);
742
+ return isModelValue(right) ? left.rank - right.rank : -1;
578
743
  };
579
744
 
580
745
  const equalsModelValue = (left: ModelValue, right: Value) => {
581
- const type = getModelValueType(left);
582
- if (type === undefined) return isModelValue(right) && left.name === right.name;
583
- if (!isModelValue(right)) {
584
- throw new TlaEvaluationError(
585
- `Attempted to check equality of typed model value ${formatValue(left)} and non-model value\n${formatValue(right)}`,
586
- );
587
- }
588
- const otherType = getModelValueType(right);
589
- if (otherType !== undefined && otherType !== type) {
590
- throw new TlaEvaluationError(
591
- `Attempted to check equality of the differently-typed model values ${formatValue(left)} and ${formatValue(right)}`,
592
- );
593
- }
594
- return left.name === right.name;
746
+ if (left.type !== undefined) checkModelValueTypes(left, right, true);
747
+ return isModelValue(right) && left.name === right.name;
595
748
  };
596
749
 
597
750
  const SCALAR_KINDS = {
@@ -665,7 +818,7 @@ const compareFunctionLikeTlc = (left: FunctionValue | LazyFunctionValue, right:
665
818
  compareElementsLikeTlc(functionValue.range, tuple)
666
819
  );
667
820
  }
668
- if (left.kind === "Function" && functionValue.domain.every((key) => typeof key === "string")) {
821
+ if (getFunctionClass(left) === "record") {
669
822
  const record = toTlcRecord(right);
670
823
  if (!record) {
671
824
  if (isModelValue(right)) return compareModelValueWith(right, left);
@@ -686,9 +839,6 @@ const compareFunctionLikeTlc = (left: FunctionValue | LazyFunctionValue, right:
686
839
  );
687
840
  };
688
841
 
689
- export const isEnumeratedSet = (value: Value): value is SetValue | MixedSetValue =>
690
- typeof value === "object" && (value.kind === "Set" || value.kind === "MixedSet");
691
-
692
842
  // TLC compares a lazy set, or a set it overrides in Java, through its own class before it compares
693
843
  // elements. The comparisons above already fail as those classes do.
694
844
  const isComparedByClass = (left: ObjectValue, right: Value) =>
@@ -783,7 +933,7 @@ const equalsFunctionLikeTlc = (left: FunctionValue | LazyFunctionValue, right: V
783
933
  equalsElementsLikeTlc(functionValue.range, tuple)
784
934
  );
785
935
  }
786
- if (left.kind === "Function" && functionValue.domain.every((key) => typeof key === "string")) {
936
+ if (getFunctionClass(left) === "record") {
787
937
  const record = toTlcRecord(right);
788
938
  if (!record) {
789
939
  if (isModelValue(right)) return equalsModelValueWith(right, left);
@@ -835,32 +985,62 @@ const equalsLikeTlc = (left: Value, right: Value): boolean => {
835
985
  const sortLikeTlc = (elements: Value[]) => {
836
986
  const sorted: Value[] = [];
837
987
  for (const element of elements) {
838
- const bounds = { low: 0, high: sorted.length, comparison: 1 };
839
- while (bounds.low < bounds.high) {
840
- const middle = bounds.low + ((bounds.high - bounds.low) >> 1);
841
- bounds.comparison = compareLikeTlc(element, sorted[middle]);
842
- if (bounds.comparison === 0) break;
843
- if (bounds.comparison < 0) bounds.high = middle;
844
- else bounds.low = middle + 1;
845
- }
846
- if (bounds.comparison !== 0) sorted.splice(bounds.low, 0, element);
988
+ const found = searchLikeTlc(element, sorted);
989
+ if (!found.isFound) sorted.splice(found.index, 0, element);
847
990
  }
848
991
  return sorted;
849
992
  };
850
993
 
851
- // TLC checks membership in a set enumeration it hasn't sorted element by element.
994
+ // Calls a method of a value as TLC does, whose failure the value heads when it has a source.
995
+ const callTracedMethod = <Result>(receiver: Value, method: () => Result) => {
996
+ const sets = setTrace.sets;
997
+ if (sets === undefined) return method();
998
+ sets.push(receiver);
999
+ const result = method();
1000
+ sets.pop();
1001
+ return result;
1002
+ };
1003
+
1004
+ // ValueVec.search on sorted elements: a binary search with compareTo, which ends where the element
1005
+ // is or would go.
1006
+ const searchLikeTlc = (element: Value, sorted: Value[]) => {
1007
+ const bounds = { low: 0, high: sorted.length };
1008
+ while (bounds.low < bounds.high) {
1009
+ const middle = bounds.low + ((bounds.high - bounds.low) >> 1);
1010
+ const comparison = callTracedMethod(element, () => compareLikeTlc(element, sorted[middle]));
1011
+ if (comparison === 0) return { index: middle, isFound: true };
1012
+ if (comparison < 0) bounds.high = middle;
1013
+ else bounds.low = middle + 1;
1014
+ }
1015
+ return { index: bounds.low, isFound: false };
1016
+ };
1017
+
1018
+ // TLC checks membership in a set enumeration it hasn't sorted element by element, with the equals
1019
+ // method of each member.
852
1020
  const isElementOfLikeTlc = (element: Value, elements: Value[]) =>
853
- elements.some((member) => equalsLikeTlc(member, element));
1021
+ elements.some((member) => callTracedMethod(member, () => equalsLikeTlc(member, element)));
854
1022
 
855
- export const isEqualLikeTlc = (left: Value, right: Value) => {
856
- try {
857
- return valuesEqual(left, right);
858
- } catch (error) {
859
- if (!(error instanceof TlaEvaluationError)) throw error;
860
- return equalsLikeTlc(left, right);
1023
+ // The sets TLC has normalized, whose membership ValueVec.search checks by binary search with
1024
+ // compareTo instead of element by element.
1025
+ const normalizedSets = new WeakSet<SetValue>();
1026
+
1027
+ // IValue.deepNormalize, which TLC applies to the constants of the config and the constant
1028
+ // definitions it computes as it starts.
1029
+ export const markNormalized = (value: Value): void => {
1030
+ if (typeof value !== "object") return;
1031
+ if (value.kind === "Set") {
1032
+ normalizedSets.add(value);
1033
+ value.elements.forEach(markNormalized);
1034
+ }
1035
+ if (value.kind === "Function") {
1036
+ value.domain.forEach(markNormalized);
1037
+ value.range.forEach(markNormalized);
861
1038
  }
862
1039
  };
863
1040
 
1041
+ export const isEqualLikeTlc = (left: Value, right: Value) =>
1042
+ computeLikeTlcOnFailure(valuesEqual, equalsLikeTlc, left, right);
1043
+
864
1044
  const isStrictlySorted = (elements: Value[]) => {
865
1045
  for (let index = 1; index < elements.length; index++) {
866
1046
  if (compareValues(elements[index - 1], elements[index]) >= 0) return false;
@@ -869,6 +1049,8 @@ const isStrictlySorted = (elements: Value[]) => {
869
1049
  };
870
1050
 
871
1051
  export const createSet = (elements: Value[]): SetValue => {
1052
+ // ValueVec.sort compares each element after the first with those before it.
1053
+ for (let index = 1; index < elements.length; index++) cacheSet(elements[index]);
872
1054
  if (elements.length < 2 || isStrictlySorted(elements)) return createSortedSet(elements);
873
1055
  const sorted = [...elements].sort(compareValues);
874
1056
  const unique = [sorted[0]];
@@ -880,18 +1062,17 @@ export const createSet = (elements: Value[]): SetValue => {
880
1062
 
881
1063
  // TLC builds a set enumeration without sorting it, so one whose elements it can't compare still
882
1064
  // evaluates.
883
- export const createEnumeratedSet = (elements: Value[]): SetValue | MixedSetValue => {
884
- try {
885
- return createSet(elements);
886
- } catch (error) {
887
- if (!(error instanceof TlaEvaluationError)) throw error;
888
- return { kind: "MixedSet", elements };
889
- }
890
- };
1065
+ export const createEnumeratedSet = (elements: Value[]): SetValue | MixedSetValue =>
1066
+ computeLikeTlcOnFailure<Value[], undefined, SetValue | MixedSetValue>(
1067
+ createSet,
1068
+ (mixed) => ({ kind: "MixedSet", elements: mixed }),
1069
+ elements,
1070
+ undefined,
1071
+ );
891
1072
 
892
1073
  export const EMPTY_SET = createSortedSet([]);
893
1074
 
894
- export const differenceSorted = (left: SetValue, right: SetValue): SetValue => {
1075
+ export const getSortedDifference = (left: SetValue, right: SetValue): SetValue => {
895
1076
  if (left.elements.length === 0 || right.elements.length === 0) return left;
896
1077
  const leftElements = left.elements;
897
1078
  const rightElements = right.elements;
@@ -916,7 +1097,7 @@ export const differenceSorted = (left: SetValue, right: SetValue): SetValue => {
916
1097
  return kept.length === leftElements.length ? left : createSortedSet(kept);
917
1098
  };
918
1099
 
919
- export const intersectSorted = (left: SetValue, right: SetValue): SetValue => {
1100
+ export const getSortedIntersection = (left: SetValue, right: SetValue): SetValue => {
920
1101
  const leftElements = left.elements;
921
1102
  const rightElements = right.elements;
922
1103
  const kept: Value[] = [];
@@ -939,7 +1120,7 @@ export const intersectSorted = (left: SetValue, right: SetValue): SetValue => {
939
1120
  return kept.length === leftElements.length ? left : createSortedSet(kept);
940
1121
  };
941
1122
 
942
- export const unionSorted = (left: SetValue, right: SetValue): SetValue => {
1123
+ export const getSortedUnion = (left: SetValue, right: SetValue): SetValue => {
943
1124
  if (left.elements.length === 0) return right;
944
1125
  if (right.elements.length === 0) return left;
945
1126
  const leftElements = left.elements;
@@ -966,12 +1147,15 @@ export const unionSorted = (left: SetValue, right: SetValue): SetValue => {
966
1147
  }
967
1148
  if (added.length === 0) return left;
968
1149
  const union = createSortedSet(merged);
969
- if (left.hash !== 0) {
1150
+ if (left.hash !== 0 && left.hash !== UNFINGERPRINTABLE_HASH) {
970
1151
  let hash = left.hash;
971
- for (let index = 0; index < added.length; index++) {
972
- hash = (hash + getElementContribution(added[index])) | 0;
1152
+ let index = 0;
1153
+ for (; index < added.length; index++) {
1154
+ const elementHash = getValueHash(added[index]);
1155
+ if (elementHash === UNFINGERPRINTABLE_HASH) break;
1156
+ hash = (hash + getElementContribution(elementHash)) | 0;
973
1157
  }
974
- union.hash = hash;
1158
+ if (index === added.length) union.hash = hash;
975
1159
  }
976
1160
  if (left.fingerprint !== 0) {
977
1161
  let fingerprint = left.fingerprint;
@@ -1056,23 +1240,30 @@ const getIntervalValue = (high: number): IntervalValue => {
1056
1240
  };
1057
1241
 
1058
1242
  export const createTuple = (elements: Value[]): FunctionValue =>
1059
- createSortedFunction(getIntervalDomain(elements.length), elements);
1243
+ setFunctionClass(createSortedFunction(getIntervalDomain(elements.length), elements), "tuple");
1060
1244
 
1061
- export const createRecord = (fields: [string, Value][]): FunctionValue => createFunction(fields);
1245
+ export const createRecord = (fields: [string, Value][]): FunctionValue =>
1246
+ setFunctionClass(createFunction(fields), "record");
1247
+
1248
+ export const createSortedRecord = (names: Value[], range: Value[]) =>
1249
+ setFunctionClass(createSortedFunction(names, range), "record");
1062
1250
 
1063
1251
  // TLC's Enumerable classes: every set except the ones it implements in Java.
1064
- const isTlcEnumerable = (value: Value) => isSetValue(value) && !isOverriddenSet(value);
1252
+ export const isTlcEnumerable = (value: Value) => isSetValue(value) && !isOverriddenSet(value);
1065
1253
 
1066
1254
  const formatUnion = (value: UnionValue, isStrict = false) =>
1067
1255
  `UNION(${formatValue(value.base, isStrict)})`;
1068
1256
 
1069
- const getUnionSets = (value: UnionValue) => {
1257
+ const getUnionSets = (
1258
+ value: UnionValue,
1259
+ getElements = (set: Value) => toFiniteSet(set).elements,
1260
+ ) => {
1070
1261
  if (!isTlcEnumerable(value.base)) {
1071
1262
  throw new TlaEvaluationError(
1072
1263
  `Attempted to enumerate the nonenumerable set:\n${formatUnion(value)}`,
1073
1264
  );
1074
1265
  }
1075
- return toFiniteSet(value.base).elements;
1266
+ return getElements(value.base);
1076
1267
  };
1077
1268
 
1078
1269
  const getUnionSet = (set: Value, index: number, union: UnionValue) => {
@@ -1108,7 +1299,7 @@ export const isEnumerable = (value: Value): boolean => {
1108
1299
  case "ProductSet":
1109
1300
  return value.factors.every(isEnumerable) || getEmptiness(value) === true;
1110
1301
  case "Union":
1111
- return isEnumerable(value.base) && toFiniteSet(value.base).elements.every(isEnumerable);
1302
+ return isEnumerable(value.base) && getStreamedElements(value.base).every(isEnumerable);
1112
1303
  case "SetOperation":
1113
1304
  if (value.operator === "\\cup") return isEnumerable(value.left) && isEnumerable(value.right);
1114
1305
  if (value.operator === "\\cap") return isEnumerable(value.left) || isEnumerable(value.right);
@@ -1181,6 +1372,41 @@ const advanceCombination = (indices: number[], length: number) => {
1181
1372
  return false;
1182
1373
  };
1183
1374
 
1375
+ // TLC enumerates SUBSET S lazily, by size and then in the order of S, so a quantifier that finds
1376
+ // its witness early never builds the rest. For a power set too large to build, the elements are
1377
+ // computed in that order as a loop reads them.
1378
+ export const getLazySubsets = (value: Value): Value[] | undefined => {
1379
+ if (typeof value !== "object" || value.kind !== "Subset" || isOverriddenSet(value.base)) {
1380
+ return undefined;
1381
+ }
1382
+ const base = toFiniteSet(value.base).elements;
1383
+ if (base.length <= MAXIMUM_ENUMERATED_SUBSET_BASE) return undefined;
1384
+ const cursor = { index: -1, indices: [0] };
1385
+ const getSubset = (index: number) => {
1386
+ if (index <= cursor.index) cursor.index = -1;
1387
+ while (cursor.index < index) {
1388
+ if (cursor.index === -1) cursor.indices = [];
1389
+ else if (!advanceCombination(cursor.indices, base.length)) {
1390
+ cursor.indices = Array.from({ length: cursor.indices.length + 1 }, (_, item) => item);
1391
+ }
1392
+ cursor.index++;
1393
+ }
1394
+ return createSortedSet(cursor.indices.map((item) => base[item]));
1395
+ };
1396
+ const length = 2 ** base.length;
1397
+ const isIndex = (property: string | symbol) =>
1398
+ typeof property === "string" && /^\d+$/.test(property) && Number(property) < length;
1399
+ return new Proxy<Value[]>([], {
1400
+ get: (target, property, receiver) => {
1401
+ if (property === "length") return length;
1402
+ return isIndex(property)
1403
+ ? getSubset(Number(property))
1404
+ : Reflect.get(target, property, receiver);
1405
+ },
1406
+ has: (target, property) => isIndex(property) || Reflect.has(target, property),
1407
+ });
1408
+ };
1409
+
1184
1410
  const getSortedSubsets = (base: Value[]) => {
1185
1411
  const subsets: Value[] = [];
1186
1412
  for (let size = 0; size <= base.length; size++) {
@@ -1192,7 +1418,30 @@ const getSortedSubsets = (base: Value[]) => {
1192
1418
  return subsets;
1193
1419
  };
1194
1420
 
1195
- const enumerateSet = (value: Value): Value[] => {
1421
+ // The Enumerator of a set of records or tuples enumerates its sets in turn and stops at the first
1422
+ // empty one, which leaves the product empty. Later versions of TLC decide that the set is empty
1423
+ // before they enumerate it.
1424
+ const getComponentElements = (
1425
+ sets: Value[],
1426
+ getElements: (set: Value) => Value[],
1427
+ describeUnenumerable: (set: Value, index: number) => string,
1428
+ ) => {
1429
+ const lists: Value[][] = [];
1430
+ for (let index = 0; index < sets.length; index++) {
1431
+ const set = sets[index];
1432
+ if (isOverriddenSet(set)) throw new TlaEvaluationError(describeUnenumerable(set, index));
1433
+ const elements = getElements(set);
1434
+ if (elements.length === 0) return [[]];
1435
+ lists.push(elements);
1436
+ }
1437
+ return lists;
1438
+ };
1439
+
1440
+ // getElements enumerates the sets a set of functions, records, or tuples combines.
1441
+ const enumerateSet = (
1442
+ value: Value,
1443
+ getElements = (set: Value) => toFiniteSet(set).elements,
1444
+ ): Value[] => {
1196
1445
  if (typeof value !== "object")
1197
1446
  throw new TlaEvaluationError(`Expected a set but found ${formatValue(value)}`);
1198
1447
  switch (value.kind) {
@@ -1206,61 +1455,63 @@ const enumerateSet = (value: Value): Value[] => {
1206
1455
  return elements;
1207
1456
  }
1208
1457
  case "Subset": {
1209
- if (isOverriddenSet(value.base)) getCardinality(value.base);
1210
- const base = toFiniteSet(value.base).elements;
1211
- if (base.length > MAXIMUM_ENUMERATED_SUBSET_BASE) {
1458
+ // SubsetValue.toSetEnum sizes the set before it enumerates it, and enumerates only the empty
1459
+ // set of a value of size 0, a function with an empty domain among them.
1460
+ if (getCardinality(value.base) === 0) return getSortedSubsets([]);
1461
+ if (!isSetValue(value.base)) {
1212
1462
  throw new TlaEvaluationError(
1213
- `SUBSET of a set with ${base.length} elements is too large to enumerate`,
1463
+ `Attempted to compute the value of an expression of form\nSUBSET S, but S is a non-enumerable value:\n${prettyPrint(formatValue(value.base))}`,
1214
1464
  );
1215
1465
  }
1466
+ const base = toFiniteSet(value.base).elements;
1467
+ if (base.length > MAXIMUM_ENUMERATED_SUBSET_BASE) {
1468
+ throw new TlaEvaluationError(describeOverflow(value));
1469
+ }
1216
1470
  return getSortedSubsets(base);
1217
1471
  }
1218
1472
  case "FunctionSet": {
1219
- if (isEmptySet(value)) return [];
1473
+ if (!valueVersion.is174 && isEmptySet(value)) return [];
1220
1474
  if (isOverriddenSet(value.domain)) {
1221
1475
  throw new TlaEvaluationError(
1222
1476
  `Attempted to enumerate a set of the form [D -> R],but the domain D:\n${formatValue(value.domain)}\ncannot be enumerated.`,
1223
1477
  );
1224
1478
  }
1225
1479
  const domain = getFunctionDomain(value.domain);
1226
- if (domain.length > 0 && isOverriddenSet(value.range)) {
1480
+ // TLC 1.7.4 requires an enumerable range even of an empty domain.
1481
+ if ((domain.length > 0 || valueVersion.is174) && isOverriddenSet(value.range)) {
1227
1482
  throw new TlaEvaluationError(
1228
1483
  `Attempted to enumerate a set of the form [D -> R],but the range R:\n${formatValue(value.range)}\ncannot be enumerated.`,
1229
1484
  );
1230
1485
  }
1231
- const range = domain.length === 0 ? [] : toFiniteSet(value.range).elements;
1486
+ const range = domain.length === 0 ? [] : getElements(value.range);
1232
1487
  return getCartesianProduct(domain.map(() => range)).map((combination): Value =>
1233
1488
  createSortedFunction(domain, combination),
1234
1489
  );
1235
1490
  }
1236
1491
  case "RecordSet": {
1237
- if (isEmptySet(value)) return [];
1238
- const fields = value.sets.map((set, index) => {
1239
- if (isOverriddenSet(set)) {
1240
- throw new TlaEvaluationError(
1241
- `Attempted to enumerate a set of the form [l1 : v1, ..., ln : vn],\nbut can't enumerate the value of the \`${value.names[index]}' field:\n${formatValue(set)}`,
1242
- );
1243
- }
1244
- return toFiniteSet(set).elements;
1245
- });
1492
+ if (!valueVersion.is174 && isEmptySet(value)) return [];
1493
+ const fields = getComponentElements(
1494
+ value.sets,
1495
+ getElements,
1496
+ (set, index) =>
1497
+ `Attempted to enumerate a set of the form [l1 : v1, ..., ln : vn],\nbut can't enumerate the value of the \`${value.names[index]}' field:\n${formatValue(set)}`,
1498
+ );
1246
1499
  return getCartesianProduct(fields).map((combination) =>
1247
1500
  createRecord(value.names.map((name, index): [string, Value] => [name, combination[index]])),
1248
1501
  );
1249
1502
  }
1250
1503
  case "ProductSet": {
1251
- if (isEmptySet(value)) return [];
1252
- const factors = value.factors.map((factor, index) => {
1253
- if (isOverriddenSet(factor)) {
1254
- throw new TlaEvaluationError(
1255
- `Attempted to enumerate a set of the form s1 \\X s2 ... \\X sn,\nbut can't enumerate s${index}:\n${formatValue(factor)}`,
1256
- );
1257
- }
1258
- return toFiniteSet(factor).elements;
1259
- });
1504
+ if (!valueVersion.is174 && isEmptySet(value)) return [];
1505
+ const factors = getComponentElements(
1506
+ value.factors,
1507
+ getElements,
1508
+ (factor, index) =>
1509
+ `Attempted to enumerate a set of the form s1 \\X s2 ... \\X sn,\nbut can't enumerate s${index}:\n${formatValue(factor)}`,
1510
+ );
1260
1511
  return getCartesianProduct(factors).map(createTuple);
1261
1512
  }
1262
1513
  case "FilteredSet":
1263
- if (isOverriddenSet(value.base)) {
1514
+ if (!isSetValue(value.base) || isOverriddenSet(value.base)) {
1264
1515
  throw new TlaEvaluationError(
1265
1516
  `Attempted to enumerate { x \\in S : p(x) } when S:\n${formatValue(value.base)}\nis not enumerable`,
1266
1517
  );
@@ -1275,7 +1526,7 @@ const enumerateSet = (value: Value): Value[] => {
1275
1526
  case "SetOperation": {
1276
1527
  if (
1277
1528
  value.operator === "\\cup" &&
1278
- (isOverriddenSet(value.left) || isOverriddenSet(value.right))
1529
+ (!isTlcEnumerable(value.left) || !isTlcEnumerable(value.right))
1279
1530
  ) {
1280
1531
  throw new TlaEvaluationError(
1281
1532
  `Attempted to enumerate S \\cup T when S:\n${formatValue(value.left)}\nand T:\n${formatValue(value.right)}\nare not both enumerable`,
@@ -1283,21 +1534,21 @@ const enumerateSet = (value: Value): Value[] => {
1283
1534
  }
1284
1535
  if (
1285
1536
  value.operator === "\\cap" &&
1286
- isOverriddenSet(value.left) &&
1287
- isOverriddenSet(value.right)
1537
+ !isTlcEnumerable(value.left) &&
1538
+ !isTlcEnumerable(value.right)
1288
1539
  ) {
1289
1540
  throw new TlaEvaluationError(
1290
1541
  `Attempted to enumerate S \\cap T when neither S:\n${formatValue(value.left)}\nnor T:\n${formatValue(value.right)}\nis enumerable`,
1291
1542
  );
1292
1543
  }
1293
- if (value.operator === "\\" && isOverriddenSet(value.left)) {
1544
+ if (value.operator === "\\" && !isTlcEnumerable(value.left)) {
1294
1545
  throw new TlaEvaluationError(
1295
1546
  `Attempted to enumerate S \\ T when S:\n${formatValue(value.left)}\nis not enumerable.`,
1296
1547
  );
1297
1548
  }
1298
1549
  if (value.operator === "\\cup")
1299
- return unionSorted(toFiniteSet(value.left), toFiniteSet(value.right)).elements;
1300
- const isLeftEnumerated = value.operator === "\\" || isEnumerable(value.left);
1550
+ return getSortedUnion(toFiniteSet(value.left), toFiniteSet(value.right)).elements;
1551
+ const isLeftEnumerated = value.operator === "\\" || isTlcEnumerable(value.left);
1301
1552
  const enumerated = isLeftEnumerated ? value.left : value.right;
1302
1553
  const other = isLeftEnumerated ? value.right : value.left;
1303
1554
  return toFiniteSet(enumerated).elements.filter(
@@ -1323,7 +1574,10 @@ export const toFiniteSet = (value: Value): SetValue => {
1323
1574
  }
1324
1575
  const cached = typeof value === "object" ? finiteSets.get(value) : undefined;
1325
1576
  if (cached) return cached;
1577
+ const sets = setTrace.sets;
1578
+ sets?.push(value);
1326
1579
  const elements = enumerateSet(value);
1580
+ sets?.pop();
1327
1581
  const isSorted =
1328
1582
  typeof value === "object" &&
1329
1583
  (value.kind === "MixedSet" ||
@@ -1341,25 +1595,92 @@ export const toFiniteSet = (value: Value): SetValue => {
1341
1595
  // TLC's Enumerator for a lazy set streams the sets it combines until the set caches its elements,
1342
1596
  // so an element that two of them share comes up once for each.
1343
1597
  export const getStreamedElements = (value: Value): Value[] => {
1344
- if (typeof value !== "object" || finiteSets.has(value)) return toFiniteSet(value).elements;
1598
+ if (typeof value !== "object" || cachedSets.has(value)) return toFiniteSet(value).elements;
1599
+ const sets = setTrace.sets;
1600
+ sets?.push(value);
1601
+ const elements = streamElements(value);
1602
+ sets?.pop();
1603
+ return elements;
1604
+ };
1605
+
1606
+ const getCombinedSets = (value: ObjectValue) =>
1607
+ value.kind === "ProductSet"
1608
+ ? value.factors
1609
+ : value.kind === "RecordSet"
1610
+ ? value.sets
1611
+ : value.kind === "FunctionSet"
1612
+ ? [value.range]
1613
+ : undefined;
1614
+
1615
+ // Whether a value TLC builds alike at each evaluation and that enumerating, comparing or
1616
+ // fingerprinting it leaves alike, so that one evaluation can stand for the next. It holds no UNION or
1617
+ // \cup, which streams until TLC caches it, no lambda, which fingerprinting turns into a record, and
1618
+ // no record a comparison reorders.
1619
+ export const isSettledValue = (value: Value): boolean => {
1620
+ if (typeof value !== "object") return true;
1621
+ switch (value.kind) {
1622
+ case "ModelValue":
1623
+ case "Interval":
1624
+ return true;
1625
+ case "Set":
1626
+ return value.elements.every(isSettledValue);
1627
+ case "Function":
1628
+ return (
1629
+ value.functionClass !== "lambda" &&
1630
+ value.writtenKeys === undefined &&
1631
+ value.domain.every(isSettledValue) &&
1632
+ value.range.every(isSettledValue)
1633
+ );
1634
+ case "SetOperation":
1635
+ return (
1636
+ value.operator !== "\\cup" && isSettledValue(value.left) && isSettledValue(value.right)
1637
+ );
1638
+ case "FilteredSet":
1639
+ return isSettledValue(value.base);
1640
+ case "ProductSet":
1641
+ return value.factors.every(isSettledValue);
1642
+ default:
1643
+ return false;
1644
+ }
1645
+ };
1646
+
1647
+ // Whether a set streams its elements in another order than the normalized set, so that a set of
1648
+ // tuples, records, or functions it is a component of has to stream too.
1649
+ const isStreamedApart = (value: Value): boolean => {
1650
+ if (typeof value !== "object" || cachedSets.has(value)) return false;
1651
+ if (value.kind === "Union") return true;
1652
+ if (value.kind === "FilteredSet") return isStreamedApart(value.base);
1653
+ if (value.kind === "SetOperation") {
1654
+ return (
1655
+ value.operator === "\\cup" || isStreamedApart(value.left) || isStreamedApart(value.right)
1656
+ );
1657
+ }
1658
+ return getCombinedSets(value)?.some(isStreamedApart) ?? false;
1659
+ };
1660
+
1661
+ const streamElements = (value: ObjectValue): Value[] => {
1662
+ // TLC streams the sets of a UNION it hasn't enumerated, so a set that appears twice there yields
1663
+ // its elements twice.
1345
1664
  if (value.kind === "Union") {
1346
- return getUnionSets(value).flatMap((set, index) =>
1665
+ return getUnionSets(value, getStreamedElements).flatMap((set, index) =>
1347
1666
  getStreamedElements(getUnionSet(set, index, value)),
1348
1667
  );
1349
1668
  }
1350
1669
  if (value.kind === "FilteredSet" && !isOverriddenSet(value.base)) {
1351
1670
  return getStreamedElements(value.base).filter(value.test);
1352
1671
  }
1672
+ const components = getCombinedSets(value);
1673
+ if (components?.some(isStreamedApart)) return enumerateSet(value, getStreamedElements);
1353
1674
  if (value.kind !== "SetOperation") return toFiniteSet(value).elements;
1354
1675
  if (value.operator === "\\cup") {
1355
- return isOverriddenSet(value.left) || isOverriddenSet(value.right)
1676
+ return !isTlcEnumerable(value.left) || !isTlcEnumerable(value.right)
1356
1677
  ? toFiniteSet(value).elements
1357
1678
  : [...getStreamedElements(value.left), ...getStreamedElements(value.right)];
1358
1679
  }
1359
- const isLeftEnumerated = value.operator === "\\" || isEnumerable(value.left);
1680
+ const isLeftEnumerated = value.operator === "\\" || isTlcEnumerable(value.left);
1360
1681
  const enumerated = isLeftEnumerated ? value.left : value.right;
1361
1682
  const other = isLeftEnumerated ? value.right : value.left;
1362
- if (isOverriddenSet(enumerated)) return toFiniteSet(value).elements;
1683
+ if (!isTlcEnumerable(enumerated)) return toFiniteSet(value).elements;
1363
1684
  return getStreamedElements(enumerated).filter(
1364
1685
  (element) => isElementOf(element, other) === (value.operator === "\\cap"),
1365
1686
  );
@@ -1396,9 +1717,13 @@ export const isEmptySet = (value: Value): boolean => {
1396
1717
  }
1397
1718
  };
1398
1719
 
1399
- const getProductCardinality = (sets: Value[], describe: () => string) =>
1720
+ const getProductCardinality = (
1721
+ sets: Value[],
1722
+ version: TlcVersion | undefined,
1723
+ describe: () => string,
1724
+ ) =>
1400
1725
  sets.reduce<number>((product, set) => {
1401
- const size = product * getCardinality(set);
1726
+ const size = product * getCardinality(set, version);
1402
1727
  if (size > MAXIMUM_INTEGER) throw new TlaEvaluationError(describe());
1403
1728
  return size;
1404
1729
  }, 1);
@@ -1406,9 +1731,23 @@ const getProductCardinality = (sets: Value[], describe: () => string) =>
1406
1731
  const describeOverflow = (value: Value) =>
1407
1732
  `Overflow when computing the number of elements in:\n${formatValue(value)}`;
1408
1733
 
1409
- export const getCardinality = (value: Value): number => {
1410
- if (typeof value !== "object") return toFiniteSet(value).elements.length;
1734
+ // TLC 1.7.4 sizes every component of a set of functions, records, or tuples without first
1735
+ // checking whether one is empty, so an infinite component fails even beside an empty one.
1736
+ export const getCardinality = (value: Value, version?: TlcVersion): number => {
1737
+ if (typeof value !== "object") {
1738
+ throw new TlaEvaluationError(
1739
+ `Attempted to compute the number of elements in the ${describeKind(value)} ${formatValue(value)}.`,
1740
+ );
1741
+ }
1411
1742
  switch (value.kind) {
1743
+ case "ModelValue":
1744
+ throw new TlaEvaluationError(
1745
+ `Attempted to compute the number of elements in the model value ${formatValue(value)}.`,
1746
+ );
1747
+ case "Function":
1748
+ return value.domain.length;
1749
+ case "LazyFunction":
1750
+ return getCardinality(value.domain, version);
1412
1751
  case "Interval": {
1413
1752
  const size = Math.max(0, value.high - value.low + 1);
1414
1753
  if (size > MAXIMUM_INTEGER) {
@@ -1424,16 +1763,19 @@ export const getCardinality = (value: Value): number => {
1424
1763
  `Attempted to compute the number of elements in the overridden value ${formatValue(value)}.`,
1425
1764
  );
1426
1765
  case "Subset": {
1427
- const size = getCardinality(value.base);
1766
+ const size = getCardinality(value.base, version);
1428
1767
  if (size >= 31) throw new TlaEvaluationError(describeOverflow(value));
1429
1768
  return 2 ** size;
1430
1769
  }
1431
1770
  case "FunctionSet": {
1432
- if (isEmptySet(value.domain)) return 1;
1433
- if (isEmptySet(value.range)) return 0;
1434
- const rangeSize = getCardinality(value.range);
1435
- if (rangeSize === 1) return 1;
1436
- const domainSize = getCardinality(value.domain);
1771
+ if (version !== "1.7.4") {
1772
+ if (isEmptySet(value.domain)) return 1;
1773
+ if (isEmptySet(value.range)) return 0;
1774
+ if (getCardinality(value.range, version) === 1) return 1;
1775
+ }
1776
+ const domainSize = getCardinality(value.domain, version);
1777
+ const rangeSize = getCardinality(value.range, version);
1778
+ if (rangeSize <= 1) return domainSize === 0 ? 1 : rangeSize;
1437
1779
  const size = { value: 1 };
1438
1780
  for (let index = 0; index < domainSize; index++) {
1439
1781
  size.value *= rangeSize;
@@ -1442,15 +1784,17 @@ export const getCardinality = (value: Value): number => {
1442
1784
  return size.value;
1443
1785
  }
1444
1786
  case "RecordSet":
1445
- if (isEmptySet(value)) return 0;
1446
- return getProductCardinality(value.sets, () => describeOverflow(value));
1787
+ if (version !== "1.7.4" && isEmptySet(value)) return 0;
1788
+ return getProductCardinality(value.sets, version, () => describeOverflow(value));
1447
1789
  case "ProductSet":
1448
- if (isEmptySet(value)) return 0;
1790
+ if (version !== "1.7.4" && isEmptySet(value)) return 0;
1449
1791
  return getProductCardinality(
1450
1792
  value.factors,
1793
+ version,
1451
1794
  () => `Overflow when computing the number of elements in ${formatValue(value)}`,
1452
1795
  );
1453
1796
  default:
1797
+ cacheSet(value);
1454
1798
  return toFiniteSet(value).elements.length;
1455
1799
  }
1456
1800
  };
@@ -1525,11 +1869,11 @@ export const isFiniteSet = (value: Value): boolean => {
1525
1869
  }
1526
1870
  };
1527
1871
 
1528
- const findIndex = (sortedValues: Value[], target: Value) => {
1872
+ const findSortedIndex = (sortedValues: Value[], target: Value, compare = compareValues) => {
1529
1873
  const bounds = { low: 0, high: sortedValues.length - 1 };
1530
1874
  while (bounds.low <= bounds.high) {
1531
1875
  const middle = (bounds.low + bounds.high) >> 1;
1532
- const comparison = compareValues(sortedValues[middle], target);
1876
+ const comparison = compare(sortedValues[middle], target);
1533
1877
  if (comparison === 0) return middle;
1534
1878
  if (comparison < 0) bounds.low = middle + 1;
1535
1879
  else bounds.high = middle - 1;
@@ -1545,33 +1889,83 @@ export const getSequenceElements = (value: Value): Value[] | undefined => {
1545
1889
  : undefined;
1546
1890
  };
1547
1891
 
1548
- const describeMembership = (element: Value, set: Value) =>
1549
- `Attempted to check if the value ${formatValue(element)} is an element of ${formatValue(set)}`;
1550
-
1551
1892
  const describeNonSetMembership = (element: Value, value: Value) => {
1552
1893
  const prefix = `Attempted to check if the value:\n${formatValue(element)}\nis an element of the`;
1553
1894
  if (!isFunctionValue(value)) return `${prefix} ${describeKind(value)} ${formatValue(value)}`;
1554
- const domain =
1555
- value.kind === "Function" || isEnumerable(value.domain) ? toFiniteFunction(value).domain : [];
1556
- if (domain.length > 0 && domain.every((key) => typeof key === "string")) {
1895
+ const functionClass = getFunctionClass(value);
1896
+ if (functionClass === "record") {
1557
1897
  return `Attempted to check if element:\n${formatValue(element)}\nis in the record:\n${formatValue(value)}`;
1558
1898
  }
1559
- if (domain.every((key, index) => key === index + 1)) {
1560
- return "Attempted to check set membership in a tuple value.";
1561
- }
1899
+ if (functionClass === "tuple") return "Attempted to check set membership in a tuple value.";
1562
1900
  return `${prefix} function ${formatValue(value)}`;
1563
1901
  };
1564
1902
 
1903
+ // The call stack of the replay, which a failed fast path leaves frozen.
1904
+ interface TracedCallStack {
1905
+ expressions: unknown[];
1906
+ isFrozen: boolean;
1907
+ fingerprint?: unknown;
1908
+ }
1909
+
1910
+ // The sets whose membership is being checked or whose elements are being enumerated, and the
1911
+ // members being compared, outermost first, while TLC's CallStackTool replays a computation. A failed
1912
+ // check or enumeration leaves the values it was in, each of which TLC adds to the
1913
+ // FingerprintException when it has a source.
1914
+ export const setTrace: { sets: Value[] | undefined; callStack?: TracedCallStack } = {
1915
+ sets: undefined,
1916
+ };
1917
+
1918
+ // Takes a fast path, and computes as TLC does where it fails. TLC never takes the fast path, so
1919
+ // the failure's leftovers in the replay's trace go first. Both paths take their operands as
1920
+ // arguments, so a hot caller passes functions it doesn't allocate.
1921
+ export const computeLikeTlcOnFailure = <Left, Right, Result>(
1922
+ compute: (left: Left, right: Right) => Result,
1923
+ computeLikeTlc: (left: Left, right: Right, error: TlaEvaluationError) => Result,
1924
+ left: Left,
1925
+ right: Right,
1926
+ ): Result => {
1927
+ const sets = setTrace.sets;
1928
+ const callStack = setTrace.callStack;
1929
+ const depth = sets?.length ?? 0;
1930
+ const trace = callStack && { ...callStack, length: callStack.expressions.length };
1931
+ try {
1932
+ return compute(left, right);
1933
+ } catch (error) {
1934
+ if (!(error instanceof TlaEvaluationError)) throw error;
1935
+ if (sets) sets.length = depth;
1936
+ if (callStack && trace) {
1937
+ callStack.expressions.length = trace.length;
1938
+ callStack.isFrozen = trace.isFrozen;
1939
+ callStack.fingerprint = trace.fingerprint;
1940
+ }
1941
+ return computeLikeTlc(left, right, error);
1942
+ }
1943
+ };
1944
+
1565
1945
  export const isElementOf = (element: Value, set: Value): boolean => {
1946
+ const sets = setTrace.sets;
1947
+ if (sets === undefined) return isElementOfSet(element, set);
1948
+ sets.push(set);
1949
+ const isElement = isElementOfSet(element, set);
1950
+ sets.pop();
1951
+ return isElement;
1952
+ };
1953
+
1954
+ const isInSortedSet = (element: Value, set: SetValue) =>
1955
+ findSortedIndex(set.elements, element) !== -1;
1956
+
1957
+ const isInSortedSetLikeTlc = (element: Value, set: SetValue) =>
1958
+ normalizedSets.has(set)
1959
+ ? searchLikeTlc(element, set.elements).isFound
1960
+ : isElementOfLikeTlc(element, set.elements);
1961
+
1962
+ const isElementOfSet = (element: Value, set: Value): boolean => {
1566
1963
  if (!isSetValue(set)) throw new TlaEvaluationError(describeNonSetMembership(element, set));
1567
1964
  switch (set.kind) {
1568
1965
  case "Set":
1569
- try {
1570
- return findIndex(set.elements, element) !== -1;
1571
- } catch (error) {
1572
- if (!(error instanceof TlaEvaluationError)) throw error;
1573
- return isElementOfLikeTlc(element, set.elements);
1574
- }
1966
+ // SetEnumValue.member compares the element with the set's.
1967
+ cacheSet(element);
1968
+ return computeLikeTlcOnFailure(isInSortedSet, isInSortedSetLikeTlc, element, set);
1575
1969
  case "MixedSet":
1576
1970
  return isElementOfLikeTlc(element, set.elements);
1577
1971
  case "Interval":
@@ -1595,12 +1989,21 @@ export const isElementOf = (element: Value, set: Value): boolean => {
1595
1989
  return set.name !== "Nat" || (typeof element === "number" && element >= 0);
1596
1990
  }
1597
1991
  case "Subset":
1598
- if (!isSetValue(element)) throw new TlaEvaluationError(describeMembership(element, set));
1992
+ // SubsetValue.member fails on any value that is not Enumerable, model values and the sets a
1993
+ // Java class overrides included.
1994
+ if (!isSetValue(element) || isOverriddenSet(element)) {
1995
+ throw new TlaEvaluationError(
1996
+ `Attempted to check if the non-enumerable value\n${prettyPrint(formatValue(element))}\nis element of\n${prettyPrint(formatValue(set))}`,
1997
+ );
1998
+ }
1599
1999
  return toFiniteSet(element).elements.every((item) => isElementOf(item, set.base));
1600
2000
  case "FunctionSet": {
1601
2001
  if (!isFunctionValue(element)) {
1602
2002
  if (isModelValue(element)) return false;
1603
- throw new TlaEvaluationError(describeMembership(element, set));
2003
+ // SetOfFcnsValue.member prints the element without Values.ppr.
2004
+ throw new TlaEvaluationError(
2005
+ `Attempted to check if \n${formatValue(element)}\nwhich is not a TLC function value, is in the set of functions:\n${prettyPrint(formatValue(set))}`,
2006
+ );
1604
2007
  }
1605
2008
  const functionValue = toFiniteFunction(element);
1606
2009
  const low = getIntervalLow(functionValue.domain);
@@ -1624,7 +2027,7 @@ export const isElementOf = (element: Value, set: Value): boolean => {
1624
2027
  return (
1625
2028
  functionValue.domain.length === set.names.length &&
1626
2029
  set.names.every((name, index) => {
1627
- const position = findIndex(functionValue.domain, name);
2030
+ const position = findSortedIndex(functionValue.domain, name);
1628
2031
  return position !== -1 && isElementOf(functionValue.range[position], set.sets[index]);
1629
2032
  })
1630
2033
  );
@@ -1665,7 +2068,10 @@ export const isElementOf = (element: Value, set: Value): boolean => {
1665
2068
  const elements = getSequenceElements(element);
1666
2069
  if (elements === undefined) {
1667
2070
  if (isModelValue(element)) return false;
1668
- throw new TlaEvaluationError(describeMembership(element, set));
2071
+ // Sequences.member raises TLC_MODULE_CHECK_MEMBER_OF.
2072
+ throw new TlaEvaluationError(
2073
+ `Attempted to check if the value:\n${prettyPrint(formatValue(element))}\nis an element of ${prettyPrint(formatValue(set))}.`,
2074
+ );
1669
2075
  }
1670
2076
  return elements.every((item) => isElementOf(item, set.base));
1671
2077
  }
@@ -1698,50 +2104,122 @@ export const toFiniteFunction = (value: Value): FunctionValue => {
1698
2104
  if (typeof value === "object" && value.kind === "LazyFunction") {
1699
2105
  if (!isEnumerable(value.domain)) getCardinality(value.domain);
1700
2106
  const domain = getFunctionDomain(value.domain);
1701
- return createSortedFunction(
1702
- domain,
1703
- domain.map((key) => value.apply(key)),
2107
+ return setFunctionClass(
2108
+ createSortedFunction(
2109
+ domain,
2110
+ domain.map((key) => value.apply(key)),
2111
+ ),
2112
+ getFunctionClass(value),
1704
2113
  );
1705
2114
  }
1706
2115
  throw new TlaEvaluationError(`Expected a function but found ${formatValue(value)}`);
1707
2116
  };
1708
2117
 
1709
- const lambdaFunctions = new WeakSet<ObjectValue>();
1710
-
1711
- export const markLambdaFunction = <FunctionLike extends FunctionValue | LazyFunctionValue>(
1712
- functionValue: FunctionLike,
2118
+ export const describeMissingArgument = (
2119
+ functionValue: Value,
2120
+ argument: Value,
2121
+ version?: TlcVersion,
1713
2122
  ) => {
1714
- lambdaFunctions.add(functionValue);
1715
- return functionValue;
2123
+ const shown = prettyPrint(formatValue(functionValue));
2124
+ const shownArgument = prettyPrint(formatValue(argument));
2125
+ const is174 = version === "1.7.4";
2126
+ switch (getFunctionClass(functionValue)) {
2127
+ case "lambda":
2128
+ return `In applying the function\n${shown},\nthe first argument is:\n${shownArgument}\nwhich is not in its domain.\n`;
2129
+ case "tuple":
2130
+ if (typeof argument !== "number") {
2131
+ return is174
2132
+ ? "Attempted to apply tuple to a non-integer argument."
2133
+ : `Attempted to access tuple at a non integral index: ${shownArgument}`;
2134
+ }
2135
+ return is174
2136
+ ? `Attempted to apply tuple\n${shown}\nto integer ${argument} which is out of domain.`
2137
+ : `Attempted to access index ${argument} of tuple\n${shown}\nwhich is out of bounds.`;
2138
+ case "record":
2139
+ if (typeof argument !== "string") {
2140
+ return is174
2141
+ ? `Attempted to apply record to a non-string value ${shownArgument}.`
2142
+ : `Attempted to access record by a non-string argument: ${shownArgument}`;
2143
+ }
2144
+ return is174
2145
+ ? `Attempted to apply the record\n${shown}\nto nonexistent record field ${argument}.`
2146
+ : `Attempted to access nonexistent field '${argument}' of record\n${shown}`;
2147
+ default:
2148
+ return `Attempted to apply function:\n${shown}\nto argument ${shownArgument}, which is not in the domain of the function.`;
2149
+ }
1716
2150
  };
1717
2151
 
1718
- const describeMissingArgument = (functionValue: Value, argument: Value) =>
1719
- typeof functionValue === "object" && lambdaFunctions.has(functionValue)
1720
- ? `In applying the function\n${prettyPrint(formatValue(functionValue))},\nthe first argument is:\n${prettyPrint(formatValue(argument))}\nwhich is not in its domain.\n`
1721
- : `Attempted to apply function ${formatValue(functionValue)} to ${formatValue(argument)}, which is not in its domain`;
2152
+ // TLC 1.7.4 words a key of the wrong type in an EXCEPT, which selects rather than applies, apart.
2153
+ const describeExceptKey = (functionValue: FunctionValue, argument: Value) => {
2154
+ if (!valueVersion.is174) return describeMissingArgument(functionValue, argument);
2155
+ const shown = prettyPrint(formatValue(argument));
2156
+ return getFunctionClass(functionValue) === "tuple"
2157
+ ? `Attempted to apply tuple to a non-integer argument ${shown}.`
2158
+ : `Attempted to apply record to a non-string argument ${shown}.`;
2159
+ };
1722
2160
 
1723
- const findKeyIndex = (domain: Value[], argument: Value) => {
2161
+ // A key the domain holds itself, which TLC finds without a comparison that can fail.
2162
+ const findIdenticalKey = (domain: Value[], argument: Value) => {
1724
2163
  const first = domain[0];
1725
2164
  if (typeof argument === "number" && typeof first === "number") {
1726
2165
  const offset = argument - first;
1727
2166
  if (domain[offset] === argument) return offset;
1728
2167
  }
1729
- if (domain.length <= 8) {
1730
- for (let index = 0; index < domain.length; index++)
1731
- if (domain[index] === argument) return index;
2168
+ return domain.length <= 8 ? domain.indexOf(argument) : -1;
2169
+ };
2170
+
2171
+ export const createNonIntegerKeyError = (argument: Value) =>
2172
+ new TlaEvaluationError(
2173
+ `Attempted to apply function with integer domain to the non-integer argument ${prettyPrint(formatValue(argument))}`,
2174
+ );
2175
+
2176
+ // TLC's FcnRcdValue searches a domain this small linearly with equals, and a larger normalized one by
2177
+ // binary search with compareTo.
2178
+ const LINEAR_SEARCH_LIMIT = 32;
2179
+
2180
+ const failKeyLikeTlc = (domain: Value[], argument: Value, error: TlaEvaluationError): never => {
2181
+ if (valueVersion.is174 || domain.length < LINEAR_SEARCH_LIMIT) {
2182
+ domain.forEach((key) => equalsLikeTlc(key, argument));
2183
+ } else {
2184
+ findSortedIndex(domain, argument, compareLikeTlc);
2185
+ }
2186
+ throw error;
2187
+ };
2188
+
2189
+ // TLC looks a key up by the Java class of the function: a tuple or a record rejects a key of the
2190
+ // wrong type, and another function rejects a non-integer for a domain it keeps as an interval, which
2191
+ // TLC 1.7.4 doesn't. A key of another type than the domain's keys otherwise fails TLC's comparison.
2192
+ const findKeyIndexLikeTlc = (
2193
+ functionValue: FunctionValue,
2194
+ argument: Value,
2195
+ describeWrongKey: (functionValue: FunctionValue, argument: Value) => string,
2196
+ ) => {
2197
+ const domain = functionValue.domain;
2198
+ if (typeof argument !== typeof domain[0]) {
2199
+ const functionClass = getFunctionClass(functionValue);
2200
+ const keyType =
2201
+ functionClass === "tuple" ? "number" : functionClass === "record" ? "string" : undefined;
2202
+ if (keyType !== undefined && typeof argument !== keyType) {
2203
+ throw new TlaEvaluationError(describeWrongKey(functionValue, argument));
2204
+ }
2205
+ if (keyType === undefined && !valueVersion.is174 && isIntervalDomain(domain)) {
2206
+ throw createNonIntegerKeyError(argument);
2207
+ }
1732
2208
  }
1733
- return findIndex(domain, argument);
2209
+ const identical = findIdenticalKey(domain, argument);
2210
+ if (identical !== -1) return identical;
2211
+ return computeLikeTlcOnFailure(findSortedIndex, failKeyLikeTlc, domain, argument);
1734
2212
  };
1735
2213
 
1736
2214
  export const applyFunction = (
1737
2215
  functionValue: Value,
1738
2216
  argument: Value,
1739
- describeMissing?: (functionValue: FunctionValue) => string,
2217
+ describeMissing?: (functionValue: FunctionValue, argument: Value) => string,
1740
2218
  ): Value => {
1741
2219
  if (typeof functionValue === "object" && functionValue.kind === "LazyFunction") {
1742
2220
  if (!isElementOf(argument, functionValue.domain)) {
1743
2221
  throw new TlaEvaluationError(
1744
- lambdaFunctions.has(functionValue)
2222
+ getFunctionClass(functionValue) === "lambda"
1745
2223
  ? describeMissingArgument(functionValue, argument)
1746
2224
  : `Attempted to apply a function to ${formatValue(argument)}, which is not in its domain`,
1747
2225
  );
@@ -1753,12 +2231,9 @@ export const applyFunction = (
1753
2231
  `Attempted to apply ${formatValue(functionValue)}, which is not a function`,
1754
2232
  );
1755
2233
  }
1756
- const position = findKeyIndex(functionValue.domain, argument);
1757
- if (position === -1) {
1758
- throw new TlaEvaluationError(
1759
- describeMissing?.(functionValue) ?? describeMissingArgument(functionValue, argument),
1760
- );
1761
- }
2234
+ const describe = describeMissing ?? describeMissingArgument;
2235
+ const position = findKeyIndexLikeTlc(functionValue, argument, describe);
2236
+ if (position === -1) throw new TlaEvaluationError(describe(functionValue, argument));
1762
2237
  return functionValue.range[position];
1763
2238
  };
1764
2239
 
@@ -1787,28 +2262,45 @@ export const updateFunction = (
1787
2262
  if (isLazy) {
1788
2263
  if (!isElementOf(argument, functionValue.domain)) return functionValue;
1789
2264
  const updated = update(functionValue.apply(argument));
1790
- return {
1791
- kind: "LazyFunction",
1792
- domain: functionValue.domain,
1793
- apply: (key) => (isEqualLikeTlc(argument, key) ? updated : functionValue.apply(key)),
1794
- source: functionValue.source,
1795
- };
2265
+ return setFunctionClass<LazyFunctionValue>(
2266
+ {
2267
+ kind: "LazyFunction",
2268
+ domain: functionValue.domain,
2269
+ apply: (key) => (isEqualLikeTlc(argument, key) ? updated : functionValue.apply(key)),
2270
+ source: functionValue.source,
2271
+ },
2272
+ getFunctionClass(functionValue),
2273
+ );
2274
+ }
2275
+ if (!isFunctionValue(functionValue)) {
2276
+ throw new TlaEvaluationError(
2277
+ `Attempted to apply EXCEPT construct to the value ${prettyPrint(formatValue(functionValue))}.`,
2278
+ );
1796
2279
  }
1797
2280
  const finite = toFiniteFunction(functionValue);
1798
- const position = findKeyIndex(finite.domain, argument);
2281
+ const position = findKeyIndexLikeTlc(finite, argument, describeExceptKey);
1799
2282
  if (position === -1) return finite;
1800
2283
  const range = [...finite.range];
1801
2284
  const previous = finite.range[position];
1802
2285
  const next = update(previous);
1803
2286
  range[position] = next;
1804
- const updated = createSortedFunction(finite.domain, range);
2287
+ const updated = setFunctionClass(
2288
+ createSortedFunction(finite.domain, range),
2289
+ getFunctionClass(finite),
2290
+ );
1805
2291
  updated.writtenKeys = finite.writtenKeys;
1806
- if (finite.hash !== 0) {
1807
- const key = finite.domain[position];
1808
- updated.hash =
1809
- previous === next
1810
- ? finite.hash
1811
- : (finite.hash - getEntryContribution(key, previous) + getEntryContribution(key, next)) | 0;
2292
+ if (finite.hash !== 0 && finite.hash !== UNFINGERPRINTABLE_HASH) {
2293
+ const nextHash = getValueHash(next);
2294
+ if (nextHash !== UNFINGERPRINTABLE_HASH) {
2295
+ const keyHash = getValueHash(finite.domain[position]);
2296
+ updated.hash =
2297
+ previous === next
2298
+ ? finite.hash
2299
+ : (finite.hash -
2300
+ getEntryContribution(keyHash, getValueHash(previous)) +
2301
+ getEntryContribution(keyHash, nextHash)) |
2302
+ 0;
2303
+ }
1812
2304
  }
1813
2305
  if (finite.fingerprint !== 0) {
1814
2306
  const key = finite.domain[position];
@@ -1845,32 +2337,103 @@ const hashString = (value: string) => {
1845
2337
  const SET_HASH_SEED = 0x73a5c3e1;
1846
2338
  const FUNCTION_HASH_SEED = 0x66d1b4f7;
1847
2339
 
1848
- const getElementContribution = (element: Value) =>
1849
- finalizeHash((getValueHash(element) + 0x9e3779b9) | 0);
2340
+ const getElementContribution = (elementHash: number) =>
2341
+ finalizeHash((elementHash + 0x9e3779b9) | 0);
2342
+
2343
+ const getEntryContribution = (keyHash: number, valueHash: number) =>
2344
+ finalizeHash((Math.imul(keyHash, 0x27d4eb2d) + valueHash) | 0);
1850
2345
 
1851
- const getEntryContribution = (key: Value, value: Value) =>
1852
- finalizeHash((Math.imul(getValueHash(key), 0x27d4eb2d) + getValueHash(value)) | 0);
2346
+ // The hash of each value that TLC fails to fingerprint, such as Nat or a set that holds it. Calls
2347
+ // with such a value as an argument still share their result, and a state that holds one fails
2348
+ // when TLC fingerprints it.
2349
+ const UNFINGERPRINTABLE_HASH = 0x2f6b1c4d;
1853
2350
 
1854
2351
  const computeValueHash = (value: ObjectValue) => {
1855
2352
  if (value.kind === "ModelValue") return finalizeHash(combineHash(hashString(value.name), 0x6d));
1856
2353
  if (isSetValue(value)) {
1857
- if (!isEnumerable(value)) return hashString(getValueKey(value));
2354
+ if (!isEnumerable(value)) return UNFINGERPRINTABLE_HASH;
1858
2355
  const elements = toFiniteSet(value).elements;
1859
2356
  let hash = SET_HASH_SEED;
1860
2357
  for (let index = 0; index < elements.length; index++) {
1861
- hash = (hash + getElementContribution(elements[index])) | 0;
2358
+ const elementHash = getValueHash(elements[index]);
2359
+ if (elementHash === UNFINGERPRINTABLE_HASH) return UNFINGERPRINTABLE_HASH;
2360
+ hash = (hash + getElementContribution(elementHash)) | 0;
1862
2361
  }
1863
2362
  return hash;
1864
2363
  }
2364
+ if (value.kind === "LazyFunction" && !isEnumerable(value.domain)) return UNFINGERPRINTABLE_HASH;
1865
2365
  const functionValue = toFiniteFunction(value);
1866
2366
  let hash = FUNCTION_HASH_SEED;
1867
2367
  for (let index = 0; index < functionValue.domain.length; index++) {
1868
- hash =
1869
- (hash + getEntryContribution(functionValue.domain[index], functionValue.range[index])) | 0;
2368
+ const keyHash = getValueHash(functionValue.domain[index]);
2369
+ const itemHash = getValueHash(functionValue.range[index]);
2370
+ if (keyHash === UNFINGERPRINTABLE_HASH || itemHash === UNFINGERPRINTABLE_HASH) {
2371
+ return UNFINGERPRINTABLE_HASH;
2372
+ }
2373
+ hash = (hash + getEntryContribution(keyHash, itemHash)) | 0;
1870
2374
  }
1871
2375
  return hash;
1872
2376
  };
1873
2377
 
2378
+ // TLC's fingerPrint enumerates each set and function a value holds, and fails on Nat, Seq(S) and
2379
+ // the like, which it never enumerates.
2380
+ const fingerprintValue = (value: Value): void => {
2381
+ if (typeof value !== "object" || value.kind === "ModelValue") return;
2382
+ if (value.kind === "InfiniteSet" || value.kind === "SequenceSet") {
2383
+ throw new TlaEvaluationError(
2384
+ `TLC has found a state in which the value of a variable contains ${formatValue(value)}`,
2385
+ );
2386
+ }
2387
+ if (isSetValue(value)) {
2388
+ toFiniteSet(value).elements.forEach(fingerprintValue);
2389
+ return;
2390
+ }
2391
+ const functionValue = toFiniteFunction(value);
2392
+ functionValue.domain.forEach(fingerprintValue);
2393
+ functionValue.range.forEach(fingerprintValue);
2394
+ };
2395
+
2396
+ // The error TLC raises as it fingerprints a value: one that hashing the value raises, as for a set
2397
+ // too large to enumerate, or one of a value with the hash of the values TLC fails on.
2398
+ export const getFingerprintError = (value: Value) => {
2399
+ if (typeof value !== "object" || value.kind === "ModelValue") return undefined;
2400
+ try {
2401
+ if (getValueHash(value) === UNFINGERPRINTABLE_HASH) fingerprintValue(value);
2402
+ return undefined;
2403
+ } catch (error) {
2404
+ if (!(error instanceof TlaEvaluationError)) throw error;
2405
+ return error;
2406
+ }
2407
+ };
2408
+
2409
+ // The values a value holds, which TLC fingerprints as it fingerprints the value.
2410
+ export const getHeldValues = (value: ObjectValue): Value[] => {
2411
+ switch (value.kind) {
2412
+ case "Set":
2413
+ case "MixedSet":
2414
+ return value.elements;
2415
+ case "Function":
2416
+ return [...value.domain, ...value.range];
2417
+ case "Subset":
2418
+ case "SequenceSet":
2419
+ case "FilteredSet":
2420
+ case "Union":
2421
+ return [value.base];
2422
+ case "FunctionSet":
2423
+ return [value.domain, value.range];
2424
+ case "RecordSet":
2425
+ return value.sets;
2426
+ case "ProductSet":
2427
+ return value.factors;
2428
+ case "SetOperation":
2429
+ return [value.left, value.right];
2430
+ case "LazyFunction":
2431
+ return [value.domain];
2432
+ default:
2433
+ return [];
2434
+ }
2435
+ };
2436
+
1874
2437
  export const getValueHash = (value: Value): number => {
1875
2438
  if (typeof value === "number") return finalizeHash(value ^ 0x5bd1e995);
1876
2439
  if (typeof value === "boolean") return value ? 0x2b7e1516 : 0x28aed2a6;
@@ -2045,7 +2608,9 @@ const formatLazySet = (value: LazySetValue, isStrict: boolean): string => {
2045
2608
  case "SetOperation":
2046
2609
  return `${format(value.left)} ${value.operator} ${format(value.right)}`;
2047
2610
  case "FilteredSet":
2048
- return `{x \\in ${format(value.base)} : ...}`;
2611
+ return value.source
2612
+ ? `{${value.source.names} \\in ${format(value.base)} : <expression ${value.source.predicate}> }`
2613
+ : `{x \\in ${format(value.base)} : ...}`;
2049
2614
  case "Union":
2050
2615
  return formatUnion(value, isStrict);
2051
2616
  }
@@ -2058,6 +2623,17 @@ const isFieldName = (name: string) =>
2058
2623
  /\p{L}/u.test(name) &&
2059
2624
  (name.length < 4 || !/^[WS]F_/.test(name));
2060
2625
 
2626
+ // FcnLambdaValue#toString prints a function it fails to enumerate as its parameters and body.
2627
+ const toPrintedFunction = (value: LazyFunctionValue) => {
2628
+ if (!isEnumerable(value.domain)) return undefined;
2629
+ try {
2630
+ return toFiniteFunction(value);
2631
+ } catch (error) {
2632
+ if (error instanceof TlaEvaluationError) return undefined;
2633
+ throw error;
2634
+ }
2635
+ };
2636
+
2061
2637
  export const formatValue = (value: Value, isStrict = false, isNormalized = false): string => {
2062
2638
  const format = (inner: Value) => formatValue(inner, isStrict, isNormalized);
2063
2639
  if (typeof value === "boolean") return value ? "TRUE" : "FALSE";
@@ -2089,27 +2665,53 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
2089
2665
  return `Seq(${format(value.base)})`;
2090
2666
  case "Function":
2091
2667
  case "LazyFunction": {
2092
- if (value.kind === "LazyFunction" && !isEnumerable(value.domain)) {
2093
- const source = value.source;
2668
+ const functionValue = value.kind === "LazyFunction" ? toPrintedFunction(value) : value;
2669
+ if (functionValue === undefined) {
2670
+ const source = value.kind === "LazyFunction" ? value.source : undefined;
2094
2671
  if (!source) return "<function>";
2095
2672
  const parameters = source.parameters
2096
2673
  .map((parameter) => `${parameter.name} \\in ${formatValue(parameter.domain)}`)
2097
2674
  .join(", ");
2098
2675
  return `[${parameters} |-> <expression ${source.body}>]`;
2099
2676
  }
2100
- const functionValue = toFiniteFunction(value);
2677
+ if (
2678
+ functionValue.domain.length === 0 &&
2679
+ valueVersion.is174 &&
2680
+ getFunctionClass(value) !== "tuple"
2681
+ ) {
2682
+ return "<< >>";
2683
+ }
2684
+ // TLC normalizes a lambda's domain to print it, but evaluates its body afterward.
2685
+ const formatRange = (inner: Value) =>
2686
+ formatValue(inner, isStrict, isNormalized && getFunctionClass(value) !== "lambda");
2101
2687
  if (functionValue.domain.every((key, index) => key === index + 1)) {
2102
- return `<<${functionValue.range.map(format).join(", ")}>>`;
2688
+ return `<<${functionValue.range.map(formatRange).join(", ")}>>`;
2103
2689
  }
2104
- if (functionValue.domain.every((key) => typeof key === "string" && isFieldName(key))) {
2690
+ // A RecordValue prints as a record whatever its fields, and a FcnRcdValue only if each key
2691
+ // is a name.
2692
+ if (
2693
+ getFunctionClass(value) === "record" ||
2694
+ functionValue.domain.every((key) => typeof key === "string" && isFieldName(key))
2695
+ ) {
2105
2696
  const isSorted =
2106
2697
  isNormalized || functionValue.hash !== 0 || functionValue.fingerprint !== 0;
2107
2698
  const pairs = isSorted
2108
2699
  ? functionValue.domain.map((key, index) => [key, functionValue.range[index]])
2109
2700
  : getWrittenPairs(functionValue);
2110
- return `[${pairs.map((pair) => `${String(pair[0])} |-> ${format(pair[1])}`).join(", ")}]`;
2701
+ return `[${pairs.map((pair) => `${String(pair[0])} |-> ${formatRange(pair[1])}`).join(", ")}]`;
2111
2702
  }
2112
- return `(${functionValue.domain.map((key, index) => `${format(key)} :> ${format(functionValue.range[index])}`).join(" @@ ")})`;
2703
+ return `(${functionValue.domain.map((key, index) => `${format(key)} :> ${formatRange(functionValue.range[index])}`).join(" @@ ")})`;
2113
2704
  }
2114
2705
  }
2115
2706
  };
2707
+
2708
+ // TLC's TLCState.toString: a line per variable, as a conjunction when there are several.
2709
+ export const formatState = (state: Record<string, Value>) => {
2710
+ const entries = Object.entries(state);
2711
+ return entries
2712
+ .map(
2713
+ ([name, value]) =>
2714
+ `${entries.length === 1 ? "" : "/\\ "}${name} = ${prettyPrint(formatValue(value))}\n`,
2715
+ )
2716
+ .join("");
2717
+ };