tla-ts 0.0.8-dev.d9bffda → 0.0.9-dev.0493be549

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (390) hide show
  1. package/README.md +30 -0
  2. package/dist/compile.cjs +23 -0
  3. package/dist/compile.js +23 -0
  4. package/dist/deciders.cjs +28 -28
  5. package/dist/deciders.js +43 -43
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +80 -10
  8. package/dist/index.d.ts +80 -10
  9. package/dist/index.js +1 -1
  10. package/dist/parallel-worker.cjs +1 -1
  11. package/dist/parallel-worker.js +1 -1
  12. package/dist/prove-worker.cjs +1 -1
  13. package/dist/prove-worker.js +1 -1
  14. package/dist/prove.cjs +116 -36
  15. package/dist/prove.js +116 -36
  16. package/dist/run.cjs +143 -31
  17. package/dist/run.js +143 -31
  18. package/dist/tlapm.cjs +2 -2
  19. package/dist/tlapm.js +2 -2
  20. package/dist/transfer.cjs +128 -103
  21. package/dist/transfer.js +128 -103
  22. package/dist/worker.cjs +7 -7
  23. package/dist/worker.js +7 -7
  24. package/package.json +3 -1
  25. package/src/ast.ts +7 -21
  26. package/src/bags.ts +99 -99
  27. package/src/builtins.ts +44 -75
  28. package/src/bundled-modules.ts +1 -8
  29. package/src/check.ts +605 -311
  30. package/src/cli/options.ts +12 -6
  31. package/src/cli/run.ts +2 -2
  32. package/src/cli/runtime-invariants.ts +135 -0
  33. package/src/cli/shared.ts +20 -9
  34. package/src/cli/tlapm.ts +0 -12
  35. package/src/cli/tlc-arguments.ts +646 -0
  36. package/src/cli/tlc-usage.ts +362 -0
  37. package/src/cli/tlc.ts +545 -218
  38. package/src/cli/typescript.ts +23 -0
  39. package/src/cli/xml-exporter.ts +4 -16
  40. package/src/cli.ts +0 -1
  41. package/src/codegen.ts +191 -64
  42. package/src/config.ts +140 -109
  43. package/src/coverage.ts +837 -0
  44. package/src/dependencies.ts +6 -40
  45. package/src/dfid.ts +618 -0
  46. package/src/environment.ts +240 -118
  47. package/src/errors.ts +70 -55
  48. package/src/evaluate.ts +632 -298
  49. package/src/exit-codes.ts +37 -3
  50. package/src/fingerprints.ts +10 -10
  51. package/src/index.ts +3 -0
  52. package/src/instances.ts +79 -11
  53. package/src/java-overrides.ts +2 -12
  54. package/src/json-reader.ts +456 -0
  55. package/src/json.ts +262 -139
  56. package/src/levels.ts +2 -3
  57. package/src/lexer.ts +17 -26
  58. package/src/liveness-checker.ts +10 -18
  59. package/src/liveness.ts +121 -49
  60. package/src/obligations/action.ts +4 -28
  61. package/src/obligations/anonymize.ts +84 -80
  62. package/src/obligations/equality.ts +1 -1
  63. package/src/obligations/expression.ts +2 -19
  64. package/src/obligations/format.ts +1 -9
  65. package/src/obligations/generate.ts +1 -11
  66. package/src/obligations/index.ts +0 -11
  67. package/src/obligations/levels.ts +4 -8
  68. package/src/obligations/module.ts +1 -15
  69. package/src/obligations/normalize.ts +5 -24
  70. package/src/obligations/operators.ts +1 -2
  71. package/src/obligations/pragma.ts +1 -10
  72. package/src/obligations/printer.ts +47 -46
  73. package/src/obligations/proof.ts +1 -5
  74. package/src/obligations/regroup.ts +1 -4
  75. package/src/obligations/simplify.ts +3 -14
  76. package/src/obligations/source.ts +1 -21
  77. package/src/obligations/subexpression.ts +5 -11
  78. package/src/obligations/substitution.ts +1 -3
  79. package/src/obligations/temporal.ts +8 -14
  80. package/src/obligations/tuples.ts +3 -9
  81. package/src/parallel-worker.ts +31 -38
  82. package/src/parallel.ts +41 -17
  83. package/src/parser.ts +436 -90
  84. package/src/pcal/ast.ts +7 -28
  85. package/src/pcal/parse.ts +11 -39
  86. package/src/pcal/tokenize.ts +4 -20
  87. package/src/pcal/translate.ts +10 -42
  88. package/src/pcal/validate.ts +3 -21
  89. package/src/pretty-print.ts +1 -2
  90. package/src/prover/decide-pool.ts +5 -10
  91. package/src/prover/deciders.ts +0 -4
  92. package/src/prover/first-order.ts +0 -11
  93. package/src/prover/isabelle/decide.ts +0 -6
  94. package/src/prover/isabelle/encode.ts +11 -23
  95. package/src/prover/isabelle/isar/inner-syntax.ts +108 -114
  96. package/src/prover/isabelle/isar/method.ts +25 -38
  97. package/src/prover/isabelle/isar/proof.ts +1 -10
  98. package/src/prover/isabelle/isar/statement.ts +1 -6
  99. package/src/prover/isabelle/isar/theory.ts +15 -26
  100. package/src/prover/isabelle/isar/type-check.ts +11 -25
  101. package/src/prover/isabelle/provers/blast/blast.ts +10 -41
  102. package/src/prover/isabelle/provers/blast/branch.ts +1 -32
  103. package/src/prover/isabelle/provers/blast/prove.ts +1 -35
  104. package/src/prover/isabelle/provers/blast/rules.ts +6 -44
  105. package/src/prover/isabelle/provers/blast/state.ts +2 -28
  106. package/src/prover/isabelle/provers/blast/term.ts +9 -36
  107. package/src/prover/isabelle/provers/clasimp.ts +1 -13
  108. package/src/prover/isabelle/provers/classical.ts +14 -42
  109. package/src/prover/isabelle/provers/hypsubst.ts +11 -25
  110. package/src/prover/isabelle/pure/bicompose.ts +16 -13
  111. package/src/prover/isabelle/pure/consts.ts +1 -7
  112. package/src/prover/isabelle/pure/conv.ts +1 -9
  113. package/src/prover/isabelle/pure/drule.ts +24 -40
  114. package/src/prover/isabelle/pure/envir.ts +3 -52
  115. package/src/prover/isabelle/pure/goal.ts +1 -7
  116. package/src/prover/isabelle/pure/interrupt.ts +0 -5
  117. package/src/prover/isabelle/pure/list.ts +0 -3
  118. package/src/prover/isabelle/pure/logic.ts +1 -14
  119. package/src/prover/isabelle/pure/name.ts +2 -9
  120. package/src/prover/isabelle/pure/net.ts +3 -59
  121. package/src/prover/isabelle/pure/object-logic.ts +3 -10
  122. package/src/prover/isabelle/pure/pattern.ts +2 -19
  123. package/src/prover/isabelle/pure/raw-simplifier.ts +13 -49
  124. package/src/prover/isabelle/pure/rewriter.ts +26 -58
  125. package/src/prover/isabelle/pure/search.ts +3 -10
  126. package/src/prover/isabelle/pure/seq.ts +1 -10
  127. package/src/prover/isabelle/pure/simplifier.ts +4 -12
  128. package/src/prover/isabelle/pure/table.ts +1 -31
  129. package/src/prover/isabelle/pure/tactic.ts +12 -22
  130. package/src/prover/isabelle/pure/tactical.ts +6 -12
  131. package/src/prover/isabelle/pure/term-ord.ts +2 -6
  132. package/src/prover/isabelle/pure/term.ts +2 -43
  133. package/src/prover/isabelle/pure/thm.ts +13 -36
  134. package/src/prover/isabelle/pure/type.ts +2 -15
  135. package/src/prover/isabelle/pure/unify.ts +20 -30
  136. package/src/prover/isabelle/pure/variable.ts +3 -7
  137. package/src/prover/isabelle/tla/classical-setup.ts +9 -19
  138. package/src/prover/isabelle/tla/context.ts +8 -16
  139. package/src/prover/isabelle/tla/logic.ts +4 -11
  140. package/src/prover/isabelle/tla/simpdata.ts +46 -34
  141. package/src/prover/isabelle/tools/intuitionistic.ts +1 -10
  142. package/src/prover/ocaml.ts +0 -6
  143. package/src/prover/prep/action.ts +4 -36
  144. package/src/prover/prep/enabled-axioms.ts +12 -19
  145. package/src/prover/prep/fingerprint.ts +0 -16
  146. package/src/prover/prep/level-comparison.ts +8 -12
  147. package/src/prover/prep/md5.ts +0 -2
  148. package/src/prover/prep/methods.ts +9 -36
  149. package/src/prover/prep/normalize.ts +4 -28
  150. package/src/prover/prove-worker.ts +0 -2
  151. package/src/prover/prove.ts +0 -36
  152. package/src/prover/ptl/decide.ts +7 -12
  153. package/src/prover/ptl/encode.ts +14 -36
  154. package/src/prover/ptl/sat.ts +24 -32
  155. package/src/prover/ptl/tableau.ts +12 -26
  156. package/src/prover/smt/axioms.ts +0 -7
  157. package/src/prover/smt/context.ts +19 -26
  158. package/src/prover/smt/data.ts +51 -54
  159. package/src/prover/smt/encode.ts +14 -35
  160. package/src/prover/smt/extensionality.ts +0 -10
  161. package/src/prover/smt/flatten.ts +3 -22
  162. package/src/prover/smt/format.ts +5 -10
  163. package/src/prover/smt/instances.ts +0 -10
  164. package/src/prover/smt/rewrite.ts +66 -101
  165. package/src/prover/smt/solver/act-cache.ts +0 -15
  166. package/src/prover/smt/solver/arith-rewriter.ts +3 -48
  167. package/src/prover/smt/solver/array.ts +1 -3
  168. package/src/prover/smt/solver/asserted-formulas.ts +1 -43
  169. package/src/prover/smt/solver/ast-lt.ts +1 -11
  170. package/src/prover/smt/solver/ast-util.ts +1 -6
  171. package/src/prover/smt/solver/ast.ts +1 -143
  172. package/src/prover/smt/solver/auf-solver.ts +6 -39
  173. package/src/prover/smt/solver/case-split-queue.ts +1 -9
  174. package/src/prover/smt/solver/cg-table.ts +1 -18
  175. package/src/prover/smt/solver/clause.ts +1 -27
  176. package/src/prover/smt/solver/conflict-resolution.ts +0 -9
  177. package/src/prover/smt/solver/context.ts +4 -61
  178. package/src/prover/smt/solver/ctx-simplify.ts +14 -41
  179. package/src/prover/smt/solver/der.ts +2 -21
  180. package/src/prover/smt/solver/dyn-ack.ts +1 -11
  181. package/src/prover/smt/solver/e-matching.ts +3 -34
  182. package/src/prover/smt/solver/enode.ts +1 -21
  183. package/src/prover/smt/solver/expr-ref.ts +1 -5
  184. package/src/prover/smt/solver/expr-safe-replace.ts +0 -5
  185. package/src/prover/smt/solver/fingerprints.ts +1 -12
  186. package/src/prover/smt/solver/flat-literals.ts +1 -9
  187. package/src/prover/smt/solver/goal.ts +2 -14
  188. package/src/prover/smt/solver/hash.ts +0 -8
  189. package/src/prover/smt/solver/hashtable.ts +1 -12
  190. package/src/prover/smt/solver/internalizer.ts +6 -98
  191. package/src/prover/smt/solver/lbool.ts +1 -2
  192. package/src/prover/smt/solver/literal.ts +0 -3
  193. package/src/prover/smt/solver/lp/bound-propagator.ts +8 -26
  194. package/src/prover/smt/solver/lp/constraints.ts +2 -8
  195. package/src/prover/smt/solver/lp/containers.ts +12 -30
  196. package/src/prover/smt/solver/lp/core-solver.ts +10 -31
  197. package/src/prover/smt/solver/lp/cross-nested.ts +6 -20
  198. package/src/prover/smt/solver/lp/dep-intervals.ts +7 -22
  199. package/src/prover/smt/solver/lp/dependency.ts +1 -4
  200. package/src/prover/smt/solver/lp/dioph-eq.ts +12 -98
  201. package/src/prover/smt/solver/lp/explanation.ts +1 -6
  202. package/src/prover/smt/solver/lp/gomory.ts +9 -22
  203. package/src/prover/smt/solver/lp/hnf-cutter.ts +17 -23
  204. package/src/prover/smt/solver/lp/hnf.ts +11 -26
  205. package/src/prover/smt/solver/lp/int-cube.ts +15 -36
  206. package/src/prover/smt/solver/lp/int-solver.ts +4 -34
  207. package/src/prover/smt/solver/lp/lar-solver.ts +32 -81
  208. package/src/prover/smt/solver/lp/lar-term.ts +1 -5
  209. package/src/prover/smt/solver/lp/lp-settings.ts +1 -14
  210. package/src/prover/smt/solver/lp/maximize-term.ts +20 -45
  211. package/src/prover/smt/solver/lp/nex-creator.ts +5 -28
  212. package/src/prover/smt/solver/lp/nex.ts +1 -6
  213. package/src/prover/smt/solver/lp/nla-backoff.ts +1 -4
  214. package/src/prover/smt/solver/lp/nla-basics.ts +5 -30
  215. package/src/prover/smt/solver/lp/nla-core.ts +35 -130
  216. package/src/prover/smt/solver/lp/nla-divisions.ts +32 -42
  217. package/src/prover/smt/solver/lp/nla-emonics.ts +4 -21
  218. package/src/prover/smt/solver/lp/nla-factorization.ts +1 -4
  219. package/src/prover/smt/solver/lp/nla-grobner.ts +15 -69
  220. package/src/prover/smt/solver/lp/nla-horner.ts +3 -11
  221. package/src/prover/smt/solver/lp/nla-intervals.ts +2 -12
  222. package/src/prover/smt/solver/lp/nla-monomial-bounds.ts +16 -41
  223. package/src/prover/smt/solver/lp/nla-monotone.ts +2 -6
  224. package/src/prover/smt/solver/lp/nla-order.ts +2 -13
  225. package/src/prover/smt/solver/lp/nla-patcher.ts +4 -7
  226. package/src/prover/smt/solver/lp/nla-tangents.ts +1 -9
  227. package/src/prover/smt/solver/lp/nla-throttle.ts +1 -6
  228. package/src/prover/smt/solver/lp/nla-types.ts +1 -11
  229. package/src/prover/smt/solver/lp/nla-var-eqs.ts +4 -25
  230. package/src/prover/smt/solver/lp/nra-solver.ts +5 -52
  231. package/src/prover/smt/solver/lp/numeric-pair.ts +1 -4
  232. package/src/prover/smt/solver/lp/pdd-interval.ts +1 -3
  233. package/src/prover/smt/solver/lp/pdd-simplifier.ts +2 -14
  234. package/src/prover/smt/solver/lp/pdd-solver.ts +4 -33
  235. package/src/prover/smt/solver/lp/pdd.ts +7 -70
  236. package/src/prover/smt/solver/lp/random-updater.ts +1 -8
  237. package/src/prover/smt/solver/lp/static-matrix.ts +9 -19
  238. package/src/prover/smt/solver/lp/union-find.ts +1 -6
  239. package/src/prover/smt/solver/mam-compiler.ts +14 -56
  240. package/src/prover/smt/solver/mam-interpreter.ts +1 -21
  241. package/src/prover/smt/solver/maximize-ac-sharing.ts +2 -17
  242. package/src/prover/smt/solver/model-checker.ts +2 -36
  243. package/src/prover/smt/solver/model-evaluator.ts +3 -29
  244. package/src/prover/smt/solver/model-finder.ts +3 -15
  245. package/src/prover/smt/solver/model-generator.ts +1 -12
  246. package/src/prover/smt/solver/model-macro-solver.ts +12 -69
  247. package/src/prover/smt/solver/nlsat/algebraic.ts +55 -151
  248. package/src/prover/smt/solver/nlsat/atoms.ts +5 -19
  249. package/src/prover/smt/solver/nlsat/evaluator.ts +17 -22
  250. package/src/prover/smt/solver/nlsat/explain.ts +3 -47
  251. package/src/prover/smt/solver/nlsat/interval-set.ts +9 -50
  252. package/src/prover/smt/solver/nlsat/levelwise.ts +48 -129
  253. package/src/prover/smt/solver/nlsat/mpbq.ts +3 -14
  254. package/src/prover/smt/solver/nlsat/polynomial.ts +17 -156
  255. package/src/prover/smt/solver/nlsat/solver.ts +7 -67
  256. package/src/prover/smt/solver/nlsat/types.ts +1 -8
  257. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +1 -44
  258. package/src/prover/smt/solver/nlsat/upolynomial.ts +11 -92
  259. package/src/prover/smt/solver/nnf.ts +3 -38
  260. package/src/prover/smt/solver/pattern-inference.ts +2 -15
  261. package/src/prover/smt/solver/poly-rewriter.ts +3 -23
  262. package/src/prover/smt/solver/propagate-values.ts +1 -10
  263. package/src/prover/smt/solver/proto-model.ts +3 -48
  264. package/src/prover/smt/solver/pull-quant.ts +1 -12
  265. package/src/prover/smt/solver/qe-lite-der.ts +1 -29
  266. package/src/prover/smt/solver/qe-lite-fm.ts +2 -25
  267. package/src/prover/smt/solver/qe-lite.ts +3 -33
  268. package/src/prover/smt/solver/qi-queue.ts +1 -16
  269. package/src/prover/smt/solver/quant-tactics.ts +5 -22
  270. package/src/prover/smt/solver/quantifier-analyzer.ts +17 -37
  271. package/src/prover/smt/solver/quantifier-manager.ts +1 -8
  272. package/src/prover/smt/solver/random-gen.ts +1 -2
  273. package/src/prover/smt/solver/rational.ts +1 -8
  274. package/src/prover/smt/solver/ref-vector.ts +1 -6
  275. package/src/prover/smt/solver/relevancy.ts +2 -15
  276. package/src/prover/smt/solver/rewriter-tpl.ts +3 -147
  277. package/src/prover/smt/solver/rewriter.ts +3 -85
  278. package/src/prover/smt/solver/rlimit.ts +2 -20
  279. package/src/prover/smt/solver/smtlib-parser.ts +2 -37
  280. package/src/prover/smt/solver/solver.ts +23 -34
  281. package/src/prover/smt/solver/sort.ts +1 -5
  282. package/src/prover/smt/solver/sticky-generations.ts +0 -5
  283. package/src/prover/smt/solver/theory-lra-axioms.ts +3 -24
  284. package/src/prover/smt/solver/theory-lra-bounds.ts +0 -5
  285. package/src/prover/smt/solver/theory-lra-final-check.ts +4 -22
  286. package/src/prover/smt/solver/theory-lra-internalize.ts +1 -27
  287. package/src/prover/smt/solver/theory-lra-model.ts +4 -19
  288. package/src/prover/smt/solver/theory-lra-propagate.ts +1 -15
  289. package/src/prover/smt/solver/theory-lra-state.ts +3 -8
  290. package/src/prover/smt/solver/theory-lra.ts +1 -8
  291. package/src/prover/smt/solver/var-subst.ts +2 -26
  292. package/src/prover/smt/table.ts +0 -8
  293. package/src/prover/tlapm/cache.ts +20 -25
  294. package/src/prover/tlapm/ocaml-marshal.ts +19 -21
  295. package/src/prover/tlapm/tlapm.ts +12 -17
  296. package/src/prover/verdict.ts +0 -2
  297. package/src/prover/zenon/check/check.ts +0 -9
  298. package/src/prover/zenon/check/definitions.ts +5 -15
  299. package/src/prover/zenon/check/equality.ts +0 -8
  300. package/src/prover/zenon/check/functions.ts +0 -4
  301. package/src/prover/zenon/check/keys.ts +0 -7
  302. package/src/prover/zenon/check/propositional.ts +0 -3
  303. package/src/prover/zenon/check/records.ts +0 -5
  304. package/src/prover/zenon/check/relations.ts +0 -13
  305. package/src/prover/zenon/check/rewrites.ts +0 -6
  306. package/src/prover/zenon/check/sets.ts +0 -3
  307. package/src/prover/zenon/check/terms.ts +0 -17
  308. package/src/prover/zenon/check/tla.ts +0 -6
  309. package/src/prover/zenon/decide.ts +0 -12
  310. package/src/prover/zenon/encode.ts +1 -8
  311. package/src/prover/zenon/eqrel.ts +0 -13
  312. package/src/prover/zenon/equality-rules.ts +0 -4
  313. package/src/prover/zenon/expr.ts +1 -26
  314. package/src/prover/zenon/index-table.ts +17 -38
  315. package/src/prover/zenon/isar-case.ts +9 -19
  316. package/src/prover/zenon/isar.ts +1 -29
  317. package/src/prover/zenon/limits.ts +0 -4
  318. package/src/prover/zenon/llproof.ts +0 -9
  319. package/src/prover/zenon/mltoll.ts +54 -76
  320. package/src/prover/zenon/node.ts +1 -11
  321. package/src/prover/zenon/ocaml.ts +1 -17
  322. package/src/prover/zenon/parse.ts +2 -7
  323. package/src/prover/zenon/phrase.ts +1 -11
  324. package/src/prover/zenon/proof.ts +0 -9
  325. package/src/prover/zenon/propositional-rules.ts +0 -5
  326. package/src/prover/zenon/rules.ts +2 -6
  327. package/src/prover/zenon/search.ts +1 -17
  328. package/src/prover/zenon/tla/functions.ts +57 -29
  329. package/src/prover/zenon/tla/llproof.ts +63 -70
  330. package/src/prover/zenon/tla/records.ts +56 -27
  331. package/src/prover/zenon/tla/rewrites.ts +12 -19
  332. package/src/prover/zenon/tla/sets.ts +68 -39
  333. package/src/prover/zenon/tla/terms.ts +0 -6
  334. package/src/prover/zenon/tla/tla.ts +59 -58
  335. package/src/randomization.ts +84 -35
  336. package/src/resolve.ts +18 -60
  337. package/src/runtime.ts +11 -4
  338. package/src/sany/builtins.ts +3 -4
  339. package/src/sany/generator.ts +128 -176
  340. package/src/sany/levels.ts +6 -30
  341. package/src/sany/lexer.ts +7 -23
  342. package/src/sany/linter.ts +31 -29
  343. package/src/sany/modules.ts +1 -5
  344. package/src/sany/nodes.ts +0 -31
  345. package/src/sany/parse-error.ts +39 -117
  346. package/src/sany/report.ts +29 -63
  347. package/src/sany/selectors.ts +15 -39
  348. package/src/sany/source.ts +1 -17
  349. package/src/sany/xml.ts +13 -63
  350. package/src/search.ts +533 -174
  351. package/src/simulate.ts +694 -0
  352. package/src/spec-description.ts +166 -48
  353. package/src/standard-definitions.ts +2 -3
  354. package/src/standard-modules.ts +264 -68
  355. package/src/state-graph.ts +51 -18
  356. package/src/subexpressions.ts +31 -5
  357. package/src/substitution-levels.ts +2 -3
  358. package/src/successors.ts +267 -77
  359. package/src/symmetry.ts +31 -8
  360. package/src/tableau.ts +27 -24
  361. package/src/tlc/fingerprint.ts +183 -61
  362. package/src/tlc/jar-data.ts +113 -6
  363. package/src/tlc/messages.ts +122 -37
  364. package/src/tlc/order.ts +33 -38
  365. package/src/tlc/random.ts +16 -16
  366. package/src/tlc/replay.ts +563 -211
  367. package/src/tlc/summary.ts +2 -4
  368. package/src/tlc/tlc-operators.ts +81 -36
  369. package/src/tlc/tlcext-operators.ts +138 -117
  370. package/src/tlc/trace-spec.ts +273 -0
  371. package/src/tlc/value-stream.ts +143 -0
  372. package/src/tlc/version.ts +2 -4
  373. package/src/transfer.ts +22 -25
  374. package/src/typescript/actions.ts +481 -0
  375. package/src/typescript/collections.ts +600 -0
  376. package/src/typescript/compile.ts +65 -0
  377. package/src/typescript/context.ts +94 -0
  378. package/src/typescript/emit.ts +121 -0
  379. package/src/typescript/expressions.ts +496 -0
  380. package/src/typescript/formula.ts +152 -0
  381. package/src/typescript/functions.ts +284 -0
  382. package/src/typescript/model.ts +163 -0
  383. package/src/typescript/names.ts +114 -0
  384. package/src/typescript/program.ts +48 -0
  385. package/src/typescript/properties.ts +139 -0
  386. package/src/typescript/scope.ts +112 -0
  387. package/src/typescript/steps.ts +165 -0
  388. package/src/typescript/types.ts +171 -0
  389. package/src/values.ts +832 -255
  390. package/src/worker.ts +7 -8
package/src/values.ts CHANGED
@@ -1,5 +1,13 @@
1
- import { TlaEvaluationError } from "./errors";
1
+ import {
2
+ isStackOverflow,
3
+ TlaAliasFormatError,
4
+ TlaEvaluationError,
5
+ TlaFeatureUnsupportedError,
6
+ TlaModuleError,
7
+ TlaSetBoundError,
8
+ } from "./errors";
2
9
  import { prettyPrint } from "./pretty-print";
10
+ import { isEvalException } from "./tlc/messages";
3
11
  import type { TlcVersion } from "./tlc/version";
4
12
 
5
13
  export interface ModelValue {
@@ -11,8 +19,6 @@ export interface ModelValue {
11
19
  fingerprint: number;
12
20
  }
13
21
 
14
- // What TLC keeps on a set it builds lazily: the enumeration it converted to and cached, as
15
- // SetPredValue#convertAndCache does, whether it has cached it, and whether it has fingerprinted it.
16
22
  interface LazySet {
17
23
  enumerated?: SetValue;
18
24
  isCached?: boolean;
@@ -22,13 +28,16 @@ interface LazySet {
22
28
  export interface SetValue {
23
29
  kind: "Set";
24
30
  elements: Value[];
31
+ // A set enumeration's unsorted elements, duplicates included, until TLC normalizes it.
32
+ writtenElements: Value[] | undefined;
33
+ // Once normalized, TLC checks membership by binary search with compareTo, not with equals.
34
+ isNormalized: boolean;
25
35
  hash: number;
26
36
  fingerprint: number;
27
37
  isFingerprinted: boolean;
28
38
  }
29
39
 
30
- // A set enumeration whose elements TLC can't sort, such as {1, "a"}. TLC sorts a set enumeration
31
- // only when it has to, so it still checks membership in one element by element.
40
+ // TLC sorts a set enumeration only when it has to, so it checks membership element by element.
32
41
  export interface MixedSetValue extends LazySet {
33
42
  kind: "MixedSet";
34
43
  elements: Value[];
@@ -42,6 +51,8 @@ export interface FunctionValue {
42
51
  fingerprint: number;
43
52
  writtenKeys: Value[] | undefined;
44
53
  functionClass: FunctionClass | undefined;
54
+ // The set a lambda ranges over, which TLC's DOMAIN returns until it builds the function.
55
+ lambdaDomain: Value | undefined;
45
56
  isFingerprinted: boolean;
46
57
  }
47
58
 
@@ -99,7 +110,7 @@ interface FilteredSetSource {
99
110
  export interface FilteredSetValue extends LazySet {
100
111
  kind: "FilteredSet";
101
112
  base: Value;
102
- test: (element: Value) => boolean;
113
+ test: (element: Value, isMember: boolean) => boolean;
103
114
  source?: FilteredSetSource;
104
115
  }
105
116
 
@@ -119,12 +130,13 @@ export interface LazyFunctionSource {
119
130
  body: string;
120
131
  }
121
132
 
122
- // enumerated is the FcnRcdValue TLC converts the function to and keeps, as FcnLambdaValue#toFcnRcd
123
- // does, from the first time it compares or fingerprints the function.
133
+ // enumerated is the FcnRcdValue TLC converts the function to once it compares or fingerprints it.
124
134
  export interface LazyFunctionValue {
125
135
  kind: "LazyFunction";
126
136
  domain: Value;
127
137
  apply: (argument: Value) => Value;
138
+ // The length of each bound's tuple pattern, or undefined for a name.
139
+ boundTupleLengths?: (number | undefined)[];
128
140
  source?: LazyFunctionSource;
129
141
  functionClass?: FunctionClass;
130
142
  enumerated?: FunctionValue;
@@ -153,7 +165,6 @@ export type Value =
153
165
 
154
166
  export type ObjectValue = Exclude<Value, boolean | number | string>;
155
167
 
156
- // The sets TLC builds lazily, which it converts and caches as it uses them.
157
168
  type ConvertibleSetValue =
158
169
  | MixedSetValue
159
170
  | SubsetValue
@@ -174,8 +185,42 @@ const isLazySet = (value: ObjectValue): value is ConvertibleSetValue =>
174
185
  value.kind !== "LazyFunction";
175
186
 
176
187
  export const MAXIMUM_INTEGER = 2147483647;
188
+
189
+ const DEFAULT_SET_BOUND = 1000000;
190
+ const VALUE_VEC_CAPACITY = 10;
191
+
192
+ const setBound = { size: DEFAULT_SET_BOUND };
193
+
194
+ export const getSetBound = () => setBound.size;
195
+
196
+ // A ValueVec that TLC grows one element at a time starts with room for 10, and fails to grow once
197
+ // its room reaches the bound.
198
+ export const getMaximumSetSize = () => Math.max(setBound.size, VALUE_VEC_CAPACITY);
199
+
200
+ export const getSetBoundMessage = () =>
201
+ `Attempted to construct a set with too many elements (>${setBound.size}).`;
202
+
203
+ export const addBoundedElement = (elements: Value[], element: Value) => {
204
+ if (elements.length === getMaximumSetSize()) throw new TlaSetBoundError(getSetBoundMessage());
205
+ elements.push(element);
206
+ };
207
+
208
+ export const isBeyondSetBound = (value: Value): value is IntervalValue =>
209
+ typeof value === "object" &&
210
+ value.kind === "Interval" &&
211
+ value.high - value.low >= getMaximumSetSize();
212
+
213
+ // TLC steps through an interval without building its elements.
214
+ export const forEachElement = (
215
+ elements: IntervalValue | Value[],
216
+ visit: (element: Value) => void,
217
+ ) => {
218
+ if (Array.isArray(elements)) return elements.forEach(visit);
219
+ for (let element = elements.low; element <= elements.high; element++) visit(element);
220
+ };
177
221
  export const MINIMUM_INTEGER = -2147483648;
178
222
  const MAXIMUM_ENUMERATED_SUBSET_BASE = 30;
223
+ const MAXIMUM_BUILT_SUBSET_BASE = 20;
179
224
 
180
225
  export const isSetValue = (value: Value) =>
181
226
  typeof value === "object" &&
@@ -183,8 +228,6 @@ export const isSetValue = (value: Value) =>
183
228
  value.kind !== "Function" &&
184
229
  value.kind !== "LazyFunction";
185
230
 
186
- // TLC's Reducible values, SetEnumValue and IntervalValue, which combine with another set element by
187
- // element.
188
231
  export const isReducibleSet = (value: Value): value is SetValue | MixedSetValue | IntervalValue =>
189
232
  typeof value === "object" &&
190
233
  (value.kind === "Set" || value.kind === "MixedSet" || value.kind === "Interval");
@@ -209,9 +252,9 @@ export const describeKind = (value: Value) => {
209
252
  export const isTlcInteger = (value: number) =>
210
253
  Number.isInteger(value) && value <= MAXIMUM_INTEGER && value >= MINIMUM_INTEGER;
211
254
 
212
- // TLC keeps a record, or a function with string keys that @@ builds, in the order the spec writes
213
- // it until it sorts the value to compare or fingerprint it. ToString, Assert, and error messages
214
- // show that order.
255
+ // TLC keeps a record, or a function @@ builds, in written order until it sorts it to compare or
256
+ // fingerprint it. It searches the function in that order, and ToString, Assert, and error
257
+ // messages show it, unless every key is an integer.
215
258
  const writtenOrderUse = { isUsed: false };
216
259
 
217
260
  const setWrittenOrder = (functionValue: FunctionValue, keys: Value[]) => {
@@ -220,16 +263,27 @@ const setWrittenOrder = (functionValue: FunctionValue, keys: Value[]) => {
220
263
  return functionValue;
221
264
  };
222
265
 
223
- export const getWrittenPairs = (functionValue: FunctionValue): [Value, Value][] => {
224
- const keys = functionValue.writtenKeys ?? functionValue.domain;
225
- return keys.map((key) => [key, functionValue.range[findSortedIndex(functionValue.domain, key)]]);
226
- };
266
+ const getWrittenKeys = (functionValue: FunctionValue) =>
267
+ (functionValue.hash !== 0 || functionValue.fingerprint !== 0
268
+ ? undefined
269
+ : functionValue.writtenKeys) ?? functionValue.domain;
270
+
271
+ export const getWrittenPairs = (functionValue: FunctionValue): [Value, Value][] =>
272
+ getWrittenKeys(functionValue).map((key) => [
273
+ key,
274
+ functionValue.range[functionValue.domain.indexOf(key)],
275
+ ]);
276
+
277
+ // TLC sorts a function whose keys are all integers to check whether it is a tuple.
278
+ export const getPrintedPairs = (functionValue: FunctionValue): [Value, Value][] =>
279
+ functionValue.domain.every((key) => typeof key === "number")
280
+ ? functionValue.domain.map((key, index) => [key, functionValue.range[index]])
281
+ : getWrittenPairs(functionValue);
227
282
 
228
283
  export const createWrittenRecord = (names: Value[], range: Value[], writtenNames: Value[]) =>
229
284
  setWrittenOrder(createSortedRecord(names, range), writtenNames);
230
285
 
231
- // TLC sorts a value it compares even with itself, and every value inside it, so a value it has
232
- // hashed or fingerprinted is already sorted.
286
+ // TLC sorts a value it compares, even with itself, so a hashed or fingerprinted value is sorted.
233
287
  const forgetWrittenOrder = (value: Value): void => {
234
288
  if (typeof value !== "object" || (value.kind !== "Function" && value.kind !== "Set")) return;
235
289
  if (value.hash !== 0 || value.fingerprint !== 0) return;
@@ -240,8 +294,7 @@ const forgetWrittenOrder = (value: Value): void => {
240
294
 
241
295
  const isRecordDomain = (domain: Value[]) => domain.every((key) => typeof key === "string");
242
296
 
243
- // TLC compares a record only with another record, so comparing one with a function of another size
244
- // can fail before the sizes decide.
297
+ // TLC compares a record only with a record, so this can fail before the sizes decide.
245
298
  const isRecordMismatch = (left: Value[], right: Value[]) =>
246
299
  left.length > 0 && right.length > 0 && isRecordDomain(left) !== isRecordDomain(right);
247
300
 
@@ -315,26 +368,71 @@ const checkModelValueTypes = (left: Value, right: Value, isEquality: boolean) =>
315
368
  );
316
369
  };
317
370
 
318
- // TLC orders strings and model value names by when it first interned the text, so every
319
- // check sets the order of its spec's strings before it builds any value.
320
- const stringOrder: { ranks: Record<string, number>; size: number } = {
371
+ interface StringOrder {
372
+ ranks: Record<string, number>;
373
+ size: number;
374
+ // A parallel search's workers rank the strings they create in different orders, so the search
375
+ // notes the first string it orders against another string ranked from this rank on.
376
+ searchRank: number | undefined;
377
+ unorderedString: string | undefined;
378
+ }
379
+
380
+ // TLC orders strings and model values by first interning, so each check sets its order first.
381
+ const stringOrder: StringOrder = {
321
382
  ranks: Object.create(null),
322
383
  size: 0,
384
+ searchRank: undefined,
385
+ unorderedString: undefined,
323
386
  };
324
387
 
325
388
  export const setStringOrder = (texts: Iterable<string>) => {
326
389
  stringOrder.ranks = Object.create(null);
327
390
  stringOrder.size = 0;
391
+ stringOrder.searchRank = undefined;
392
+ stringOrder.unorderedString = undefined;
328
393
  modelValues.clear();
329
394
  for (const text of texts) rankString(text);
330
395
  };
331
396
 
332
- // TLC 1.7.4 prints an empty function that isn't a tuple with a space between its brackets, and
333
- // looks a key up in a function differently, so every check also sets the version its values follow.
397
+ export const freezeStringOrder = () => {
398
+ stringOrder.searchRank = stringOrder.size;
399
+ };
400
+
401
+ export const getUnorderedString = () => stringOrder.unorderedString;
402
+
403
+ // TLC 1.7.4 prints and looks keys up in functions differently, so each check sets the version.
334
404
  const valueVersion = { is174: false };
335
405
 
336
- export const setValueVersion = (version: TlcVersion | undefined) => {
337
- valueVersion.is174 = version === "1.7.4";
406
+ const printing = { isExpanded: true, isViewPrinted: false };
407
+
408
+ export interface ValueOptions {
409
+ version?: TlcVersion;
410
+ maxSetSize?: number;
411
+ isLazyValueExpanded?: boolean;
412
+ isViewPrinted?: boolean;
413
+ }
414
+
415
+ export const setValueOptions = (options: ValueOptions) => {
416
+ valueVersion.is174 = options.version === "1.7.4";
417
+ setBound.size = options.maxSetSize ?? DEFAULT_SET_BOUND;
418
+ printing.isExpanded = options.isLazyValueExpanded ?? true;
419
+ printing.isViewPrinted = options.isViewPrinted ?? false;
420
+ };
421
+
422
+ // TLC evaluates the VIEW of a state it prints as it prints it.
423
+ const viewTexts = new WeakMap<Record<string, Value>, () => string>();
424
+
425
+ export const setViewText = (state: Record<string, Value>, getText: () => string) => {
426
+ if (printing.isViewPrinted) viewTexts.set(state, getText);
427
+ return state;
428
+ };
429
+
430
+ // TLC prints by its _format only the state an ALIAS gives.
431
+ const aliasNames = new WeakMap<Record<string, Value>, string>();
432
+
433
+ export const setAliasName = (state: Record<string, Value>, alias: string) => {
434
+ aliasNames.set(state, alias);
435
+ return state;
338
436
  };
339
437
 
340
438
  export const rankString = (text: string) => {
@@ -342,8 +440,6 @@ export const rankString = (text: string) => {
342
440
  return text;
343
441
  };
344
442
 
345
- export const getRankedStringCount = () => stringOrder.size;
346
-
347
443
  export const getStringRank = (text: string) => stringOrder.ranks[rankString(text)];
348
444
 
349
445
  const compareStrings = (left: string, right: string) => {
@@ -351,6 +447,14 @@ const compareStrings = (left: string, right: string) => {
351
447
  const ranks = stringOrder.ranks;
352
448
  const leftRank = ranks[left];
353
449
  const rightRank = ranks[right];
450
+ const searchRank = stringOrder.searchRank;
451
+ if (
452
+ searchRank !== undefined &&
453
+ (leftRank === undefined || leftRank >= searchRank) &&
454
+ (rightRank === undefined || rightRank >= searchRank)
455
+ ) {
456
+ stringOrder.unorderedString ??= left;
457
+ }
354
458
  if (leftRank !== undefined && rightRank !== undefined) return leftRank - rightRank;
355
459
  if (leftRank !== undefined) return -1;
356
460
  if (rightRank !== undefined) return 1;
@@ -369,9 +473,15 @@ const isOverriddenComparison = (left: Value, right: Value) =>
369
473
  right.kind === "SequenceSet"
370
474
  );
371
475
 
372
- // TLC implements Nat, Int, STRING, Seq(S), and Any in Java classes that compare only with each
373
- // other and with model values. Comparing one with any other set is an error, worded by the class of
374
- // the left operand.
476
+ const createComparisonError = (left: Value, right: Value) =>
477
+ new TlaEvaluationError(
478
+ isOverriddenSet(left)
479
+ ? `Attempted to compare overridden value ${formatValue(left, true)} with non-overridden value:\n${formatValue(right)}`
480
+ : `Attempted to compare ${describeKind(left)} ${formatValue(left)} with ${describeKind(right)} ${formatValue(right)}`,
481
+ );
482
+
483
+ // TLC's Nat, Int, STRING, Seq(S), and Any compare only with each other and with model values,
484
+ // and fail with any other set, worded by the class of the left operand.
375
485
  const compareOverriddenSets = (
376
486
  left: Value,
377
487
  right: Value,
@@ -382,18 +492,14 @@ const compareOverriddenSets = (
382
492
  `Attempted to ${verb} the set ${formatValue(isEnumerable(left) ? toFiniteSet(left) : left, true)} with the value:\n${formatValue(right, true)}`,
383
493
  );
384
494
  }
385
- if (!isOverriddenSet(right)) {
386
- throw new TlaEvaluationError(
387
- `Attempted to compare overridden value ${formatValue(left, true)} with non-overridden value:\n${formatValue(right, true)}`,
388
- );
389
- }
495
+ if (!isOverriddenSet(right)) throw createComparisonError(left, right);
390
496
  const leftName = left.kind === "InfiniteSet" ? left.name : undefined;
391
497
  const rightName = right.kind === "InfiniteSet" ? right.name : undefined;
392
498
  if (leftName !== undefined && leftName === rightName) return 0;
393
499
  if ((leftName === "Nat" && rightName === "Int") || (leftName === "Int" && rightName === "Nat")) {
394
500
  return leftName === "Nat" ? -1 : 1;
395
501
  }
396
- throw new TlaEvaluationError(
502
+ throw new TlaModuleError(
397
503
  `Attempted to compare ${formatValue(left, true)} with the value\n${formatValue(right, true)}`,
398
504
  );
399
505
  };
@@ -401,13 +507,20 @@ const compareOverriddenSets = (
401
507
  export const ANY_SET: InfiniteSetValue = { kind: "InfiniteSet", name: "Any" };
402
508
 
403
509
  const compareAny = (other: Value): never => {
404
- throw new TlaEvaluationError(`Attempted to compare ANY with the value\n${formatValue(other)}`);
510
+ throw new TlaModuleError(`Attempted to compare ANY with the value\n${formatValue(other)}`);
511
+ };
512
+
513
+ // TLC enumerates a lambda to compare it, even with itself.
514
+ const compareWithItself = (value: Value) => {
515
+ if (writtenOrderUse.isUsed) forgetWrittenOrder(value);
516
+ if (value === ANY_SET) compareAny(value);
517
+ if (typeof value === "object" && value.kind === "LazyFunction") toFiniteFunction(value);
405
518
  };
406
519
 
407
520
  export const compareValues = (left: Value, right: Value): number => {
408
521
  if (left === right) {
409
- if (writtenOrderUse.isUsed) forgetWrittenOrder(left);
410
- return left === ANY_SET ? compareAny(left) : 0;
522
+ compareWithItself(left);
523
+ return 0;
411
524
  }
412
525
  if (typeof left === "object" && typeof right === "object") {
413
526
  const leftKind = left.kind;
@@ -435,9 +548,16 @@ export const compareValues = (left: Value, right: Value): number => {
435
548
  }
436
549
  const isLeftSet = isSetValue(left);
437
550
  if (isLeftSet !== isSetValue(right)) {
438
- throw new TlaEvaluationError(
439
- `Attempted to compare ${describeKind(left)} ${formatValue(left)} with ${describeKind(right)} ${formatValue(right)}`,
440
- );
551
+ throw createComparisonError(left, right);
552
+ }
553
+ // The sizes decide first, so an interval of another size never needs its elements.
554
+ if (leftKind === "Interval" && rightKind === "Set") {
555
+ const difference = getCardinality(left) - right.elements.length;
556
+ if (difference !== 0) return difference;
557
+ }
558
+ if (leftKind === "Set" && rightKind === "Interval") {
559
+ const difference = left.elements.length - getCardinality(right);
560
+ if (difference !== 0) return difference;
441
561
  }
442
562
  if (isLeftSet) return compareSets(toFiniteSet(left), toFiniteSet(right));
443
563
  return compareFunctions(toFiniteFunction(left), toFiniteFunction(right));
@@ -448,17 +568,23 @@ export const compareValues = (left: Value, right: Value): number => {
448
568
  checkModelValueTypes(left, right, false);
449
569
  if (isModelValue(left)) return -1;
450
570
  if (isModelValue(right)) return 1;
451
- throw new TlaEvaluationError(
452
- `Attempted to compare ${describeKind(left)} ${formatValue(left)} with ${describeKind(right)} ${formatValue(right)}`,
453
- );
571
+ throw createComparisonError(left, right);
454
572
  };
455
573
 
456
574
  const modelValues = new Map<string, ModelValue>();
457
575
 
576
+ // ModelValue's index is a short.
577
+ const MAXIMUM_MODEL_VALUES = 32768;
578
+
458
579
  // setStringOrder clears the model values, so each check ranks and creates its own.
459
580
  export const createModelValue = (name: string): ModelValue => {
460
581
  const known = modelValues.get(name);
461
582
  if (known) return known;
583
+ if (modelValues.size === MAXIMUM_MODEL_VALUES) {
584
+ throw new TlaFeatureUnsupportedError(
585
+ `TLC supports at most ${MAXIMUM_MODEL_VALUES} model values, but model value ${name} exceeds this limit.`,
586
+ );
587
+ }
462
588
  const value: ModelValue = {
463
589
  kind: "ModelValue",
464
590
  name,
@@ -471,14 +597,24 @@ export const createModelValue = (name: string): ModelValue => {
471
597
  return value;
472
598
  };
473
599
 
600
+ export const getModelValues = () => [...modelValues.values()];
601
+
474
602
  export const createSortedSet = (elements: Value[]): SetValue => ({
475
603
  kind: "Set",
476
604
  elements,
605
+ writtenElements: undefined,
606
+ isNormalized: false,
477
607
  hash: 0,
478
608
  fingerprint: 0,
479
609
  isFingerprinted: false,
480
610
  });
481
611
 
612
+ export const createNormalizedSet = (elements: Value[]): SetValue => {
613
+ const set = createSortedSet(elements);
614
+ set.isNormalized = true;
615
+ return set;
616
+ };
617
+
482
618
  export const createSortedFunction = (domain: Value[], range: Value[]): FunctionValue => ({
483
619
  kind: "Function",
484
620
  domain,
@@ -487,12 +623,12 @@ export const createSortedFunction = (domain: Value[], range: Value[]): FunctionV
487
623
  fingerprint: 0,
488
624
  writtenKeys: undefined,
489
625
  functionClass: undefined,
626
+ lambdaDomain: undefined,
490
627
  isFingerprinted: false,
491
628
  });
492
629
 
493
- // TLC words a failed function application by the Java class of the function: FcnLambdaValue for
494
- // [x \in S |-> e], TupleValue for <<...>> and what the sequence operators build, RecordValue for
495
- // [a |-> e], and FcnRcdValue for any other function.
630
+ // TLC words a failed application by the function's Java class: FcnLambdaValue, TupleValue,
631
+ // RecordValue, or FcnRcdValue.
496
632
  export type FunctionClass = "lambda" | "tuple" | "record";
497
633
 
498
634
  // Whether a lambda exists for markFingerprinted to find, so that a spec without one skips the walk.
@@ -516,12 +652,11 @@ export const markLambdaFunction = <FunctionLike extends FunctionValue | LazyFunc
516
652
  functionValue: FunctionLike,
517
653
  ) => setFunctionClass(functionValue, "lambda");
518
654
 
519
- // TLC caches a lazy set as the receiver of compareTo, equals, size, and fingerPrint, not as their
520
- // argument, and enumerates the sets an uncached one combines, duplicates and all.
655
+ // TLC caches a lazy set as the receiver of compareTo, equals, size, and fingerPrint, not as
656
+ // their argument, and enumerates the sets an uncached one combines, duplicates and all.
521
657
  const isCachedSet = (value: ObjectValue) => isLazySet(value) && value.isCached === true;
522
658
 
523
- // Whether the spec has built a UNION or \cup set, the sets that stream duplicates, so that a spec
524
- // without one skips tracking what TLC caches.
659
+ // Lets a spec without a UNION or \cup set, which stream duplicates, skip tracking TLC's caches.
525
660
  const streamedSetPresence = { isPresent: false };
526
661
 
527
662
  export const markStreamedSet = <Streamed extends UnionValue | SetOperationValue>(
@@ -531,7 +666,6 @@ export const markStreamedSet = <Streamed extends UnionValue | SetOperationValue>
531
666
  return value;
532
667
  };
533
668
 
534
- // The sets that stream their elements apart from the normalized set until TLC caches them.
535
669
  const STREAMING_KINDS = new Set<ObjectValue["kind"]>([
536
670
  "Union",
537
671
  "SetOperation",
@@ -552,8 +686,7 @@ const cacheSet = (value: Value) => {
552
686
  }
553
687
  };
554
688
 
555
- // FcnLambdaValue#fingerPrint caches the FcnRcdValue the function enumerates to, which applies it
556
- // from then on, so a function TLC has fingerprinted is no longer a lambda.
689
+ // Fingerprinting caches the FcnRcdValue a lambda enumerates to, so it is no longer a lambda.
557
690
  export const markFingerprinted = (value: Value): void => {
558
691
  if ((!lambdaPresence.isPresent && !streamedSetPresence.isPresent) || typeof value !== "object") {
559
692
  return;
@@ -578,8 +711,8 @@ export const markFingerprinted = (value: Value): void => {
578
711
  export const valuesEqual = (left: Value, right: Value): boolean => {
579
712
  cacheSet(left);
580
713
  if (left === right) {
581
- if (writtenOrderUse.isUsed) forgetWrittenOrder(left);
582
- return left !== ANY_SET || compareAny(left);
714
+ compareWithItself(left);
715
+ return true;
583
716
  }
584
717
  if (typeof left !== "object" || typeof right !== "object") {
585
718
  if (typeof left === typeof right) return false;
@@ -588,16 +721,19 @@ export const valuesEqual = (left: Value, right: Value): boolean => {
588
721
  }
589
722
  return compareValues(left, right) === 0;
590
723
  }
591
- const isHashed =
592
- (left.kind === "Set" || left.kind === "Function") &&
593
- (right.kind === "Set" || right.kind === "Function") &&
594
- left.hash !== 0 &&
595
- right.hash !== 0;
596
- if (isHashed && left.hash !== right.hash) return false;
597
724
  if (left.kind === "Function" && right.kind === "Function")
598
725
  return compareFunctions(left, right) === 0;
599
726
  if (left.kind === "Set" && right.kind === "Set") return compareSets(left, right) === 0;
727
+ // The sizes decide first, so an interval of another size never needs its elements.
728
+ if (left.kind === "Interval" && right.kind === "Set") {
729
+ if (getCardinality(left) !== right.elements.length) return false;
730
+ }
731
+ if (left.kind === "Set" && right.kind === "Interval") {
732
+ if (left.elements.length !== getCardinality(right)) return false;
733
+ }
600
734
  if (isModelValue(left) || isModelValue(right)) {
735
+ // TLC enumerates a lambda, which can fail, before it compares it.
736
+ if (left.kind === "LazyFunction") toFiniteFunction(left);
601
737
  checkModelValueTypes(left, right, true);
602
738
  return isModelValue(left) && isModelValue(right) && left.name === right.name;
603
739
  }
@@ -650,8 +786,7 @@ export const valuesEqual = (left: Value, right: Value): boolean => {
650
786
  return compareValues(left, right) === 0;
651
787
  };
652
788
 
653
- // TLC prints and words errors about an equal function by its Java class, so a value can stand for
654
- // another in a state only if each function in it has the same class.
789
+ // TLC words errors by each function's Java class, so a stand-in must match each function's class.
655
790
  const createSameValueCheck = (isClassSensitive: boolean) => {
656
791
  const areSameValues = (left: Value[], right: Value[]) => {
657
792
  if (left === right) return true;
@@ -691,8 +826,7 @@ const canonicalizeElements = (elements: Value[], canonicalize: (value: Value) =>
691
826
  }
692
827
  };
693
828
 
694
- // Replaces each set and function in a state with the first interchangeable one it has seen, so that
695
- // the states it keeps share their values.
829
+ // So that the states it keeps share their values.
696
830
  export const createCanonicalizer = () => {
697
831
  const canonicalValues = new Map<number, Value | Value[]>();
698
832
  const canonicalize = (value: Value): Value => {
@@ -726,21 +860,17 @@ export const createCanonicalizer = () => {
726
860
  };
727
861
  };
728
862
 
729
- // The comparisons above fail with their own messages. These follow the compareTo and equals
730
- // methods of TLC's Java value classes, which word a failure by the class of the left operand, so a
731
- // failed comparison runs again through them to fail as TLC does.
863
+ // These follow TLC's compareTo and equals, which word a failure by the left operand's class,
864
+ // so a failed comparison above runs again through them to fail as TLC does.
732
865
  interface TlcFunction {
733
866
  domain: Value[];
734
867
  range: Value[];
735
868
  low: number | undefined;
736
869
  }
737
870
 
738
- const getIntervalLow = (domain: Value[]) => {
739
- const first = domain.length === 0 ? 1 : domain[0];
740
- return typeof first === "number" && domain.every((key, index) => key === first + index)
741
- ? first
742
- : undefined;
743
- };
871
+ // TLC compares a domain it keeps as an interval apart from one it keeps as an array.
872
+ const getIntervalLow = (value: Value, domain: Value[]) =>
873
+ domain.length === 0 || getFunctionClass(value) === "tuple" ? 1 : getDomainInterval(domain)?.low;
744
874
 
745
875
  const toTlcFunction = (value: Value) => {
746
876
  if (!isFunctionValue(value)) return undefined;
@@ -748,7 +878,7 @@ const toTlcFunction = (value: Value) => {
748
878
  return {
749
879
  domain: functionValue.domain,
750
880
  range: functionValue.range,
751
- low: getIntervalLow(functionValue.domain),
881
+ low: getIntervalLow(value, functionValue.domain),
752
882
  };
753
883
  };
754
884
 
@@ -841,8 +971,7 @@ const compareElementsLikeTlc = (left: Value[], right: Value[]) => {
841
971
 
842
972
  const compareFunctionLikeTlc = (left: FunctionValue | LazyFunctionValue, right: Value) => {
843
973
  const functionValue = toFiniteFunction(left);
844
- const isTuple = left.kind === "Function" && getSequenceElements(functionValue) !== undefined;
845
- if (isTuple) {
974
+ if (getFunctionClass(left) === "tuple") {
846
975
  const tuple = isFunctionValue(right) ? getSequenceElements(right) : undefined;
847
976
  if (!tuple) return compareTlcFunctions({ ...functionValue, low: 1 }, left, right);
848
977
  return (
@@ -865,14 +994,13 @@ const compareFunctionLikeTlc = (left: FunctionValue | LazyFunctionValue, right:
865
994
  );
866
995
  }
867
996
  return compareTlcFunctions(
868
- { ...functionValue, low: getIntervalLow(functionValue.domain) },
997
+ { ...functionValue, low: getIntervalLow(left, functionValue.domain) },
869
998
  left,
870
999
  right,
871
1000
  );
872
1001
  };
873
1002
 
874
- // TLC compares a lazy set, or a set it overrides in Java, through its own class before it compares
875
- // elements. The comparisons above already fail as those classes do.
1003
+ // TLC compares a lazy or Java-overridden set through its own class before it compares elements.
876
1004
  const isComparedByClass = (left: ObjectValue, right: Value) =>
877
1005
  isOverriddenSet(left) ||
878
1006
  isOverriddenSet(right) ||
@@ -956,8 +1084,7 @@ const equalsTlcFunctions = (functionValue: TlcFunction, left: Value, right: Valu
956
1084
 
957
1085
  const equalsFunctionLikeTlc = (left: FunctionValue | LazyFunctionValue, right: Value) => {
958
1086
  const functionValue = toFiniteFunction(left);
959
- const isTuple = left.kind === "Function" && getSequenceElements(functionValue) !== undefined;
960
- if (isTuple) {
1087
+ if (getFunctionClass(left) === "tuple") {
961
1088
  const tuple = isFunctionValue(right) ? getSequenceElements(right) : undefined;
962
1089
  if (!tuple) return equalsTlcFunctions({ ...functionValue, low: 1 }, left, right);
963
1090
  return (
@@ -980,7 +1107,7 @@ const equalsFunctionLikeTlc = (left: FunctionValue | LazyFunctionValue, right: V
980
1107
  );
981
1108
  }
982
1109
  return equalsTlcFunctions(
983
- { ...functionValue, low: getIntervalLow(functionValue.domain) },
1110
+ { ...functionValue, low: getIntervalLow(left, functionValue.domain) },
984
1111
  left,
985
1112
  right,
986
1113
  );
@@ -1023,7 +1150,6 @@ const sortLikeTlc = (elements: Value[]) => {
1023
1150
  return sorted;
1024
1151
  };
1025
1152
 
1026
- // Calls a method of a value as TLC does, whose failure the value heads when it has a source.
1027
1153
  const callTracedMethod = <Result>(receiver: Value, method: () => Result) => {
1028
1154
  const sets = setTrace.sets;
1029
1155
  if (sets === undefined) return method();
@@ -1033,8 +1159,7 @@ const callTracedMethod = <Result>(receiver: Value, method: () => Result) => {
1033
1159
  return result;
1034
1160
  };
1035
1161
 
1036
- // ValueVec.search on sorted elements: a binary search with compareTo, which ends where the element
1037
- // is or would go.
1162
+ // A binary search with compareTo, which ends where the element is or would go.
1038
1163
  const searchLikeTlc = (element: Value, sorted: Value[]) => {
1039
1164
  const bounds = { low: 0, high: sorted.length };
1040
1165
  while (bounds.low < bounds.high) {
@@ -1047,21 +1172,18 @@ const searchLikeTlc = (element: Value, sorted: Value[]) => {
1047
1172
  return { index: bounds.low, isFound: false };
1048
1173
  };
1049
1174
 
1050
- // TLC checks membership in a set enumeration it hasn't sorted element by element, with the equals
1051
- // method of each member.
1052
1175
  const isElementOfLikeTlc = (element: Value, elements: Value[]) =>
1053
1176
  elements.some((member) => callTracedMethod(member, () => equalsLikeTlc(member, element)));
1054
1177
 
1055
- // The sets TLC has normalized, whose membership ValueVec.search checks by binary search with
1056
- // compareTo instead of element by element.
1057
- const normalizedSets = new WeakSet<SetValue>();
1178
+ export const getWrittenElements = (set: SetValue | MixedSetValue) =>
1179
+ set.kind === "MixedSet" || set.isNormalized
1180
+ ? set.elements
1181
+ : (set.writtenElements ?? set.elements);
1058
1182
 
1059
- // IValue.deepNormalize, which TLC applies to the constants of the config and the constant
1060
- // definitions it computes as it starts.
1061
1183
  export const markNormalized = (value: Value): void => {
1062
1184
  if (typeof value !== "object") return;
1063
1185
  if (value.kind === "Set") {
1064
- normalizedSets.add(value);
1186
+ value.isNormalized = true;
1065
1187
  value.elements.forEach(markNormalized);
1066
1188
  }
1067
1189
  if (value.kind === "Function") {
@@ -1070,6 +1192,33 @@ export const markNormalized = (value: Value): void => {
1070
1192
  }
1071
1193
  };
1072
1194
 
1195
+ // TLC's Value.normalize sorts a set enumeration, and the sets a lazy set it hasn't cached combines.
1196
+ export const normalizeShallowly = (value: Value): void => {
1197
+ if (typeof value !== "object" || isCachedSet(value)) return;
1198
+ switch (value.kind) {
1199
+ case "Set":
1200
+ value.isNormalized = true;
1201
+ return;
1202
+ case "MixedSet":
1203
+ toFiniteSet(value);
1204
+ return;
1205
+ case "FilteredSet":
1206
+ case "Subset":
1207
+ return normalizeShallowly(value.base);
1208
+ case "SetOperation":
1209
+ if (value.operator === "\\cup") return;
1210
+ normalizeShallowly(value.left);
1211
+ return normalizeShallowly(value.right);
1212
+ case "FunctionSet":
1213
+ normalizeShallowly(value.domain);
1214
+ return normalizeShallowly(value.range);
1215
+ case "RecordSet":
1216
+ return value.sets.forEach(normalizeShallowly);
1217
+ case "ProductSet":
1218
+ return value.factors.forEach(normalizeShallowly);
1219
+ }
1220
+ };
1221
+
1073
1222
  export const isEqualLikeTlc = (left: Value, right: Value) =>
1074
1223
  computeLikeTlcOnFailure(valuesEqual, equalsLikeTlc, left, right);
1075
1224
 
@@ -1080,8 +1229,19 @@ const isStrictlySorted = (elements: Value[]) => {
1080
1229
  return true;
1081
1230
  };
1082
1231
 
1232
+ const isAscendingIntegers = (elements: Value[]) => {
1233
+ for (let index = 0; index < elements.length; index++) {
1234
+ const element = elements[index];
1235
+ const previous = index > 0 ? elements[index - 1] : undefined;
1236
+ if (typeof element !== "number" || (typeof previous === "number" && previous >= element)) {
1237
+ return false;
1238
+ }
1239
+ }
1240
+ return true;
1241
+ };
1242
+
1083
1243
  export const createSet = (elements: Value[]): SetValue => {
1084
- // ValueVec.sort compares each element after the first with those before it.
1244
+ // TLC's sort compares each element after the first with those before it.
1085
1245
  for (let index = 1; index < elements.length; index++) cacheSet(elements[index]);
1086
1246
  if (elements.length < 2 || isStrictlySorted(elements)) return createSortedSet(elements);
1087
1247
  const sorted = [...elements].sort(compareValues);
@@ -1092,15 +1252,18 @@ export const createSet = (elements: Value[]): SetValue => {
1092
1252
  return createSortedSet(unique);
1093
1253
  };
1094
1254
 
1095
- // TLC builds a set enumeration without sorting it, so one whose elements it can't compare still
1096
- // evaluates.
1097
- export const createEnumeratedSet = (elements: Value[]): SetValue | MixedSetValue =>
1098
- computeLikeTlcOnFailure<Value[], undefined, SetValue | MixedSetValue>(
1255
+ // TLC builds a set enumeration unsorted, so one whose elements it can't compare still evaluates.
1256
+ export const createEnumeratedSet = (elements: Value[]): SetValue | MixedSetValue => {
1257
+ if (isAscendingIntegers(elements)) return createSortedSet(elements);
1258
+ const set = computeLikeTlcOnFailure<Value[], undefined, SetValue | MixedSetValue>(
1099
1259
  createSet,
1100
1260
  (mixed) => ({ kind: "MixedSet", elements: mixed }),
1101
1261
  elements,
1102
1262
  undefined,
1103
1263
  );
1264
+ if (set.kind === "Set" && set.elements !== elements) set.writtenElements = elements;
1265
+ return set;
1266
+ };
1104
1267
 
1105
1268
  export const EMPTY_SET = createSortedSet([]);
1106
1269
 
@@ -1216,7 +1379,6 @@ export const createWrittenFunction = (pairs: [Value, Value][]) => {
1216
1379
  const functionValue = createFunction(pairs);
1217
1380
  const isWrittenSorted =
1218
1381
  functionValue.domain.length !== pairs.length ||
1219
- pairs.some((pair) => typeof pair[0] !== "string") ||
1220
1382
  pairs.every((pair, index) => pair[0] === functionValue.domain[index]);
1221
1383
  return isWrittenSorted
1222
1384
  ? functionValue
@@ -1226,23 +1388,26 @@ export const createWrittenFunction = (pairs: [Value, Value][]) => {
1226
1388
  );
1227
1389
  };
1228
1390
 
1391
+ const MAX_SHARED_INTERVAL_LENGTH = 1024;
1229
1392
  const intervalDomains: Value[][] = [];
1393
+ const longIntervalDomains = new Map<number, WeakRef<Value[]>>();
1230
1394
  const intervalValues: IntervalValue[] = [];
1231
1395
  const intervalArrays = new WeakMap<Value[], IntervalValue>();
1232
1396
 
1233
- // TLC keeps the domain of a tuple, or of a function built over an interval, as an interval. Every
1234
- // function over 1..n shares one domain array per length, and the elements of any other interval
1235
- // map to it, so the array's identity records it. Callers must not mutate the returned array.
1397
+ // Every function over 1..n shares one domain array per length, so the array's identity records
1398
+ // the interval. Callers must not mutate the returned array. Longer domains are held weakly: a
1399
+ // sequence that grows one element at a time would otherwise keep an array of every length it
1400
+ // passed through, n * n / 2 numbers in all.
1236
1401
  const getIntervalDomain = (length: number): Value[] => {
1237
- const cached = intervalDomains[length];
1402
+ const cached = intervalDomains[length] ?? longIntervalDomains.get(length)?.deref();
1238
1403
  if (cached) return cached;
1239
1404
  const domain = Array.from({ length }, (_, index) => index + 1);
1240
- intervalDomains[length] = domain;
1405
+ if (length > MAX_SHARED_INTERVAL_LENGTH) longIntervalDomains.set(length, new WeakRef(domain));
1406
+ else intervalDomains[length] = domain;
1241
1407
  return domain;
1242
1408
  };
1243
1409
 
1244
- // The elements of an interval for a caller that only iterates them, so they need not record
1245
- // the interval for DOMAIN.
1410
+ // The caller only iterates the elements, so they need not record the interval for DOMAIN.
1246
1411
  export const getIntervalElements = (value: IntervalValue): Value[] => {
1247
1412
  getCardinality(value);
1248
1413
  if (value.low === 1 && value.high >= 1) return getIntervalDomain(value.high);
@@ -1252,10 +1417,12 @@ export const getIntervalElements = (value: IntervalValue): Value[] => {
1252
1417
  };
1253
1418
 
1254
1419
  const isIntervalDomain = (domain: Value[]) =>
1255
- domain.length > 0 && (domain === intervalDomains[domain.length] || intervalArrays.has(domain));
1420
+ (domain.length > 0 &&
1421
+ (domain === intervalDomains[domain.length] ||
1422
+ domain === longIntervalDomains.get(domain.length)?.deref())) ||
1423
+ intervalArrays.has(domain);
1256
1424
 
1257
- // TLC keeps an interval domain only for a function built over an interval itself, so a set
1258
- // such as (1..2) \cap S, whose elements are the shared array, gets a copy.
1425
+ // A set such as (1..2) \cap S, whose elements are the shared array, gets a copy.
1259
1426
  export const getFunctionDomain = (set: Value): Value[] => {
1260
1427
  const elements = toFiniteSet(set).elements;
1261
1428
  return isIntervalDomain(elements) && !(typeof set === "object" && set.kind === "Interval")
@@ -1280,7 +1447,6 @@ export const createRecord = (fields: [string, Value][]): FunctionValue =>
1280
1447
  export const createSortedRecord = (names: Value[], range: Value[]) =>
1281
1448
  setFunctionClass(createSortedFunction(names, range), "record");
1282
1449
 
1283
- // TLC's Enumerable classes: every set except the ones it implements in Java.
1284
1450
  export const isTlcEnumerable = (value: Value) => isSetValue(value) && !isOverriddenSet(value);
1285
1451
 
1286
1452
  const formatUnion = (value: UnionValue, isStrict = false) =>
@@ -1331,7 +1497,13 @@ export const isEnumerable = (value: Value): boolean => {
1331
1497
  case "ProductSet":
1332
1498
  return value.factors.every(isEnumerable) || getEmptiness(value) === true;
1333
1499
  case "Union":
1334
- return isEnumerable(value.base) && getStreamedElements(value.base).every(isEnumerable);
1500
+ return (
1501
+ isEnumerable(value.base) &&
1502
+ (isEnumeratedSet(value.base)
1503
+ ? getWrittenElements(value.base)
1504
+ : getStreamedElements(value.base)
1505
+ ).every(isEnumerable)
1506
+ );
1335
1507
  case "SetOperation":
1336
1508
  if (value.operator === "\\cup") return isEnumerable(value.left) && isEnumerable(value.right);
1337
1509
  if (value.operator === "\\cap") return isEnumerable(value.left) || isEnumerable(value.right);
@@ -1404,15 +1576,14 @@ const advanceCombination = (indices: number[], length: number) => {
1404
1576
  return false;
1405
1577
  };
1406
1578
 
1407
- // TLC enumerates SUBSET S lazily, by size and then in the order of S, so a quantifier that finds
1408
- // its witness early never builds the rest. For a power set too large to build, the elements are
1409
- // computed in that order as a loop reads them.
1579
+ // TLC enumerates SUBSET S lazily, by size and then in the order of S, so a quantifier that
1580
+ // finds its witness early never builds the rest.
1410
1581
  export const getLazySubsets = (value: Value): Value[] | undefined => {
1411
1582
  if (typeof value !== "object" || value.kind !== "Subset" || isOverriddenSet(value.base)) {
1412
1583
  return undefined;
1413
1584
  }
1414
1585
  const base = toFiniteSet(value.base).elements;
1415
- if (base.length <= MAXIMUM_ENUMERATED_SUBSET_BASE) return undefined;
1586
+ if (base.length <= MAXIMUM_BUILT_SUBSET_BASE) return undefined;
1416
1587
  const cursor = { index: -1, indices: [0] };
1417
1588
  const getSubset = (index: number) => {
1418
1589
  if (index <= cursor.index) cursor.index = -1;
@@ -1450,9 +1621,8 @@ const getSortedSubsets = (base: Value[]) => {
1450
1621
  return subsets;
1451
1622
  };
1452
1623
 
1453
- // The Enumerator of a set of records or tuples enumerates its sets in turn and stops at the first
1454
- // empty one, which leaves the product empty. Later versions of TLC decide that the set is empty
1455
- // before they enumerate it.
1624
+ // TLC enumerates the sets in turn and stops at the first empty one. Later versions decide
1625
+ // that the set is empty before they enumerate it.
1456
1626
  const getComponentElements = (
1457
1627
  sets: Value[],
1458
1628
  getElements: (set: Value) => Value[],
@@ -1469,7 +1639,6 @@ const getComponentElements = (
1469
1639
  return lists;
1470
1640
  };
1471
1641
 
1472
- // getElements enumerates the sets a set of functions, records, or tuples combines.
1473
1642
  const enumerateSet = (
1474
1643
  value: Value,
1475
1644
  getElements = (set: Value) => toFiniteSet(set).elements,
@@ -1487,8 +1656,7 @@ const enumerateSet = (
1487
1656
  return elements;
1488
1657
  }
1489
1658
  case "Subset": {
1490
- // SubsetValue.toSetEnum sizes the set before it enumerates it, and enumerates only the empty
1491
- // set of a value of size 0, a function with an empty domain among them.
1659
+ // TLC sizes the set before it enumerates it, and enumerates a set of size 0 as {{}}.
1492
1660
  if (getCardinality(value.base) === 0) return getSortedSubsets([]);
1493
1661
  if (!isSetValue(value.base)) {
1494
1662
  throw new TlaEvaluationError(
@@ -1548,22 +1716,21 @@ const enumerateSet = (
1548
1716
  `Attempted to enumerate { x \\in S : p(x) } when S:\n${formatValue(value.base)}\nis not enumerable`,
1549
1717
  );
1550
1718
  }
1551
- return toFiniteSet(value.base).elements.filter(value.test);
1719
+ return toFiniteSet(
1720
+ createEnumeratedSet(
1721
+ getStreamedElements(value.base).filter((element) => value.test(element, false)),
1722
+ ),
1723
+ ).elements;
1552
1724
  case "Union": {
1553
- const elements = getUnionSets(value).flatMap(
1554
- (set, index) => toFiniteSet(getUnionSet(set, index, value)).elements,
1555
- );
1725
+ const elements: Value[] = [];
1726
+ getUnionSets(value).forEach((set, index) => {
1727
+ const unionSet = getUnionSet(set, index, value);
1728
+ if (isBeyondSetBound(unionSet)) throw new TlaSetBoundError(getSetBoundMessage());
1729
+ getStreamedElements(unionSet).forEach((element) => addBoundedElement(elements, element));
1730
+ });
1556
1731
  return toFiniteSet(createEnumeratedSet(elements)).elements;
1557
1732
  }
1558
1733
  case "SetOperation": {
1559
- if (
1560
- value.operator === "\\cup" &&
1561
- (!isTlcEnumerable(value.left) || !isTlcEnumerable(value.right))
1562
- ) {
1563
- throw new TlaEvaluationError(
1564
- `Attempted to enumerate S \\cup T when S:\n${formatValue(value.left)}\nand T:\n${formatValue(value.right)}\nare not both enumerable`,
1565
- );
1566
- }
1567
1734
  if (
1568
1735
  value.operator === "\\cap" &&
1569
1736
  !isTlcEnumerable(value.left) &&
@@ -1578,14 +1745,24 @@ const enumerateSet = (
1578
1745
  `Attempted to enumerate S \\ T when S:\n${formatValue(value.left)}\nis not enumerable.`,
1579
1746
  );
1580
1747
  }
1581
- if (value.operator === "\\cup")
1582
- return getSortedUnion(toFiniteSet(value.left), toFiniteSet(value.right)).elements;
1748
+ if (value.operator === "\\cup") {
1749
+ return toFiniteSet(createEnumeratedSet(listUnionLikeTlc(value))).elements;
1750
+ }
1583
1751
  const isLeftEnumerated = value.operator === "\\" || isTlcEnumerable(value.left);
1584
1752
  const enumerated = isLeftEnumerated ? value.left : value.right;
1585
1753
  const other = isLeftEnumerated ? value.right : value.left;
1586
- return toFiniteSet(enumerated).elements.filter(
1587
- (element) => isElementOf(element, other) === (value.operator === "\\cap"),
1754
+ const kept: Value[] = [];
1755
+ forEachElement(
1756
+ typeof enumerated === "object" && enumerated.kind === "Interval"
1757
+ ? enumerated
1758
+ : getStreamedElements(enumerated),
1759
+ (element) => {
1760
+ if (isElementOf(element, other) === (value.operator === "\\cap")) {
1761
+ addBoundedElement(kept, element);
1762
+ }
1763
+ },
1588
1764
  );
1765
+ return toFiniteSet(createEnumeratedSet(kept)).elements;
1589
1766
  }
1590
1767
  case "InfiniteSet":
1591
1768
  case "SequenceSet":
@@ -1622,14 +1799,99 @@ export const toFiniteSet = (value: Value): SetValue => {
1622
1799
  return set;
1623
1800
  };
1624
1801
 
1625
- // TLC's Enumerator for a lazy set streams the sets it combines until the set caches its elements,
1626
- // so an element that two of them share comes up once for each.
1627
- export const getStreamedElements = (value: Value): Value[] => {
1628
- if (typeof value !== "object" || isCachedSet(value)) return toFiniteSet(value).elements;
1802
+ // TLC's enumerator of a set sorts the set enumerations it streams, and fails on a set it can't
1803
+ // enumerate, before it yields an element, so S \cup T fails on T before it streams S.
1804
+ const openStream = (value: Value): void => {
1805
+ if (typeof value !== "object" || isCachedSet(value)) return;
1806
+ switch (value.kind) {
1807
+ case "MixedSet":
1808
+ toFiniteSet(value);
1809
+ return;
1810
+ case "FilteredSet":
1811
+ if (!isTlcEnumerable(value.base)) toFiniteSet(value);
1812
+ return openStream(value.base);
1813
+ case "Union":
1814
+ if (!isEnumeratedSet(value.base) && isTlcEnumerable(value.base)) {
1815
+ return openStream(value.base);
1816
+ }
1817
+ getUnionSets(value)
1818
+ .slice(0, 1)
1819
+ .forEach((set) => openStream(getUnionSet(set, 0, value)));
1820
+ return;
1821
+ case "SetOperation":
1822
+ if (value.operator === "\\" && !isTlcEnumerable(value.left)) toFiniteSet(value);
1823
+ if (
1824
+ value.operator === "\\cup" &&
1825
+ (!isTlcEnumerable(value.left) || !isTlcEnumerable(value.right))
1826
+ ) {
1827
+ toFiniteSet(value);
1828
+ }
1829
+ if (value.operator !== "\\cap" || isTlcEnumerable(value.left)) openStream(value.left);
1830
+ else openStream(value.right);
1831
+ if (value.operator === "\\cup") openStream(value.right);
1832
+ }
1833
+ };
1834
+
1835
+ const listUnionLikeTlc = (union: SetOperationValue) => {
1836
+ if (!isTlcEnumerable(union.left) || !isTlcEnumerable(union.right)) {
1837
+ throw new TlaEvaluationError(
1838
+ `Attempted to enumerate S \\cup T when S:\n${formatValue(union.left)}\nand T:\n${formatValue(union.right)}\nare not both enumerable`,
1839
+ );
1840
+ }
1841
+ openStream(union.left);
1842
+ openStream(union.right);
1843
+ if (isBeyondSetBound(union.left)) throw new TlaSetBoundError(getSetBoundMessage());
1844
+ const left = getStreamedElements(union.left);
1845
+ const right = isBeyondSetBound(union.right) ? undefined : getStreamedElements(union.right);
1846
+ if (!right || left.length + right.length > getMaximumSetSize()) {
1847
+ throw new TlaSetBoundError(getSetBoundMessage());
1848
+ }
1849
+ return [...left, ...right];
1850
+ };
1851
+
1852
+ // EnumerableValue#elements(NORMALIZED) sorts a union outside its methods, so a failed comparison
1853
+ // isn't a fingerprint failure.
1854
+ export const getNormalizedSetElements = (value: Value) => {
1855
+ if (
1856
+ typeof value !== "object" ||
1857
+ value.kind !== "SetOperation" ||
1858
+ value.operator !== "\\cup" ||
1859
+ value.enumerated
1860
+ ) {
1861
+ return toFiniteSet(value).elements;
1862
+ }
1863
+ const listed = callTracedMethod(value, () => listUnionLikeTlc(value));
1864
+ const elements = toFiniteSet(createEnumeratedSet(listed)).elements;
1865
+ value.enumerated = createSortedSet(elements);
1866
+ return elements;
1867
+ };
1868
+
1869
+ // TLC streams the sets a lazy set combines until it caches it, so a shared element repeats. Like
1870
+ // its enumerators, the stream stops at the first element visit accepts.
1871
+ export const someStreamedElement = (value: Value, visit: (element: Value) => boolean): boolean => {
1872
+ if (typeof value !== "object" || isCachedSet(value)) {
1873
+ return toFiniteSet(value).elements.some(visit);
1874
+ }
1629
1875
  const sets = setTrace.sets;
1630
1876
  sets?.push(value);
1631
- const elements = streamElements(value);
1877
+ openStream(value);
1878
+ // The set is enumerated only while it computes an element, not while visit looks at one.
1879
+ const isFound = someElementOfStream(value, (element) => {
1880
+ sets?.pop();
1881
+ const isAccepted = visit(element);
1882
+ sets?.push(value);
1883
+ return isAccepted;
1884
+ });
1632
1885
  sets?.pop();
1886
+ return isFound;
1887
+ };
1888
+
1889
+ export const getStreamedElements = (value: Value) => {
1890
+ const elements: Value[] = [];
1891
+ someStreamedElement(value, (element) => {
1892
+ elements.push(element);
1893
+ return false;
1894
+ });
1633
1895
  return elements;
1634
1896
  };
1635
1897
 
@@ -1642,10 +1904,9 @@ const getCombinedSets = (value: ObjectValue) =>
1642
1904
  ? [value.range]
1643
1905
  : undefined;
1644
1906
 
1645
- // Whether a value TLC builds alike at each evaluation and that enumerating, comparing or
1646
- // fingerprinting it leaves alike, so that one evaluation can stand for the next. It holds no UNION or
1647
- // \cup, which streams until TLC caches it, no lambda, which fingerprinting turns into a record, and
1648
- // no record a comparison reorders.
1907
+ // Whether one evaluation can stand for the next: no UNION or \cup, which streams until TLC
1908
+ // caches it, no lambda, which fingerprinting turns into a record, and no record a
1909
+ // comparison reorders.
1649
1910
  export const isSettledValue = (value: Value): boolean => {
1650
1911
  if (typeof value !== "object") return true;
1651
1912
  switch (value.kind) {
@@ -1674,8 +1935,7 @@ export const isSettledValue = (value: Value): boolean => {
1674
1935
  }
1675
1936
  };
1676
1937
 
1677
- // Whether a set streams its elements in another order than the normalized set, so that a set of
1678
- // tuples, records, or functions it is a component of has to stream too.
1938
+ // A set of tuples, records, or functions with such a component has to stream too.
1679
1939
  const isStreamedApart = (value: Value): boolean => {
1680
1940
  if (typeof value !== "object" || isCachedSet(value)) return false;
1681
1941
  if (value.kind === "Union") return true;
@@ -1688,31 +1948,36 @@ const isStreamedApart = (value: Value): boolean => {
1688
1948
  return getCombinedSets(value)?.some(isStreamedApart) ?? false;
1689
1949
  };
1690
1950
 
1691
- const streamElements = (value: ObjectValue): Value[] => {
1692
- // TLC streams the sets of a UNION it hasn't enumerated, so a set that appears twice there yields
1693
- // its elements twice.
1951
+ const someElementOfStream = (value: ObjectValue, visit: (element: Value) => boolean): boolean => {
1952
+ // TLC streams the sets of a UNION it hasn't enumerated, so a repeated set yields them twice.
1694
1953
  if (value.kind === "Union") {
1695
- return getUnionSets(value, getStreamedElements).flatMap((set, index) =>
1696
- getStreamedElements(getUnionSet(set, index, value)),
1954
+ return getUnionSets(value, getStreamedElements).some((set, index) =>
1955
+ someStreamedElement(getUnionSet(set, index, value), visit),
1697
1956
  );
1698
1957
  }
1699
- if (value.kind === "FilteredSet" && !isOverriddenSet(value.base)) {
1700
- return getStreamedElements(value.base).filter(value.test);
1958
+ if (value.kind === "FilteredSet" && isTlcEnumerable(value.base)) {
1959
+ return someStreamedElement(
1960
+ value.base,
1961
+ (element) => value.test(element, false) && visit(element),
1962
+ );
1701
1963
  }
1702
1964
  const components = getCombinedSets(value);
1703
- if (components?.some(isStreamedApart)) return enumerateSet(value, getStreamedElements);
1704
- if (value.kind !== "SetOperation") return toFiniteSet(value).elements;
1965
+ if (components?.some(isStreamedApart)) {
1966
+ return enumerateSet(value, getStreamedElements).some(visit);
1967
+ }
1968
+ if (value.kind !== "SetOperation") return toFiniteSet(value).elements.some(visit);
1705
1969
  if (value.operator === "\\cup") {
1706
1970
  return !isTlcEnumerable(value.left) || !isTlcEnumerable(value.right)
1707
- ? toFiniteSet(value).elements
1708
- : [...getStreamedElements(value.left), ...getStreamedElements(value.right)];
1971
+ ? toFiniteSet(value).elements.some(visit)
1972
+ : someStreamedElement(value.left, visit) || someStreamedElement(value.right, visit);
1709
1973
  }
1710
1974
  const isLeftEnumerated = value.operator === "\\" || isTlcEnumerable(value.left);
1711
1975
  const enumerated = isLeftEnumerated ? value.left : value.right;
1712
1976
  const other = isLeftEnumerated ? value.right : value.left;
1713
- if (!isTlcEnumerable(enumerated)) return toFiniteSet(value).elements;
1714
- return getStreamedElements(enumerated).filter(
1715
- (element) => isElementOf(element, other) === (value.operator === "\\cap"),
1977
+ if (!isTlcEnumerable(enumerated)) return toFiniteSet(value).elements.some(visit);
1978
+ return someStreamedElement(
1979
+ enumerated,
1980
+ (element) => isElementOf(element, other) === (value.operator === "\\cap") && visit(element),
1716
1981
  );
1717
1982
  };
1718
1983
 
@@ -1761,8 +2026,7 @@ const getProductCardinality = (
1761
2026
  const describeOverflow = (value: Value) =>
1762
2027
  `Overflow when computing the number of elements in:\n${formatValue(value)}`;
1763
2028
 
1764
- // TLC 1.7.4 sizes every component of a set of functions, records, or tuples without first
1765
- // checking whether one is empty, so an infinite component fails even beside an empty one.
2029
+ // TLC 1.7.4 sizes every component without checking for an empty one, so an infinite one fails.
1766
2030
  export const getCardinality = (value: Value, version?: TlcVersion): number => {
1767
2031
  if (typeof value !== "object") {
1768
2032
  throw new TlaEvaluationError(
@@ -1911,8 +2175,34 @@ const findSortedIndex = (sortedValues: Value[], target: Value, compare = compare
1911
2175
  return -1;
1912
2176
  };
1913
2177
 
2178
+ // A sorted set as TLC builds it unsorted, by adding each element it doesn't hold yet.
2179
+ export const createUnsortedCopy = (set: SetValue, added: Value[]): SetValue => {
2180
+ const elements = set.elements;
2181
+ if (elements.length > getMaximumSetSize()) throw new TlaSetBoundError(getSetBoundMessage());
2182
+ const isAdded = Array.from({ length: elements.length }, () => false);
2183
+ const written = added.filter((element) => {
2184
+ const index = findSortedIndex(elements, element);
2185
+ if (isAdded[index]) return false;
2186
+ isAdded[index] = true;
2187
+ return true;
2188
+ });
2189
+ const copy = createSortedSet(elements);
2190
+ if (written.some((element, index) => element !== elements[index])) {
2191
+ copy.writtenElements = written;
2192
+ }
2193
+ return copy;
2194
+ };
2195
+
1914
2196
  export const getSequenceElements = (value: Value): Value[] | undefined => {
1915
2197
  if (typeof value !== "object" || !isFunctionValue(value)) return undefined;
2198
+ if (
2199
+ value.kind === "LazyFunction" &&
2200
+ (!isSetValue(value.domain) || isOverriddenSet(value.domain))
2201
+ ) {
2202
+ throw new TlaEvaluationError(
2203
+ "To convert a function of form [x \\in S |-> f(x)] to a tuple, the set S must be enumerable.",
2204
+ );
2205
+ }
1916
2206
  const functionValue = toFiniteFunction(value);
1917
2207
  return functionValue.domain.every((key, index) => key === index + 1)
1918
2208
  ? functionValue.range
@@ -1930,24 +2220,21 @@ const describeNonSetMembership = (element: Value, value: Value) => {
1930
2220
  return `${prefix} function ${formatValue(value)}`;
1931
2221
  };
1932
2222
 
1933
- // The call stack of the replay, which a failed fast path leaves frozen.
1934
2223
  interface TracedCallStack {
1935
2224
  expressions: unknown[];
1936
2225
  isFrozen: boolean;
2226
+ sources: WeakMap<ObjectValue, unknown>;
1937
2227
  fingerprint?: unknown;
1938
2228
  }
1939
2229
 
1940
- // The sets whose membership is being checked or whose elements are being enumerated, and the
1941
- // members being compared, outermost first, while TLC's CallStackTool replays a computation. A failed
1942
- // check or enumeration leaves the values it was in, each of which TLC adds to the
1943
- // FingerprintException when it has a source.
2230
+ // The values being checked or enumerated, outermost first, as TLC's CallStackTool replays a
2231
+ // computation. TLC adds each one with a source to the FingerprintException.
1944
2232
  export const setTrace: { sets: Value[] | undefined; callStack?: TracedCallStack } = {
1945
2233
  sets: undefined,
1946
2234
  };
1947
2235
 
1948
- // Takes a fast path, and computes as TLC does where it fails. TLC never takes the fast path, so
1949
- // the failure's leftovers in the replay's trace go first. Both paths take their operands as
1950
- // arguments, so a hot caller passes functions it doesn't allocate.
2236
+ // TLC never takes the fast path, so the failure's leftovers in the replay's trace go first.
2237
+ // The operands are arguments so that a hot caller passes functions it doesn't allocate.
1951
2238
  export const computeLikeTlcOnFailure = <Left, Right, Result>(
1952
2239
  compute: (left: Left, right: Right) => Result,
1953
2240
  computeLikeTlc: (left: Left, right: Right, error: TlaEvaluationError) => Result,
@@ -1972,6 +2259,11 @@ export const computeLikeTlcOnFailure = <Left, Right, Result>(
1972
2259
  }
1973
2260
  };
1974
2261
 
2262
+ export const isFingerprintedSince = (depth: number) =>
2263
+ (setTrace.sets ?? [])
2264
+ .slice(depth)
2265
+ .some((set) => typeof set === "object" && setTrace.callStack?.sources.has(set) === true);
2266
+
1975
2267
  export const isElementOf = (element: Value, set: Value): boolean => {
1976
2268
  const sets = setTrace.sets;
1977
2269
  if (sets === undefined) return isElementOfSet(element, set);
@@ -1981,26 +2273,60 @@ export const isElementOf = (element: Value, set: Value): boolean => {
1981
2273
  return isElement;
1982
2274
  };
1983
2275
 
2276
+ // Integers compare by subtraction, so a search that meets only integers needs no other comparison.
2277
+ const isIntegerInSortedSet = (element: number, set: SetValue) => {
2278
+ const elements = set.elements;
2279
+ const bounds = { low: 0, high: elements.length - 1 };
2280
+ while (bounds.low <= bounds.high) {
2281
+ const middle = (bounds.low + bounds.high) >> 1;
2282
+ const probe = elements[middle];
2283
+ if (typeof probe !== "number") return undefined;
2284
+ if (probe === element) return true;
2285
+ if (probe < element) bounds.low = middle + 1;
2286
+ else bounds.high = middle - 1;
2287
+ }
2288
+ return false;
2289
+ };
2290
+
1984
2291
  const isInSortedSet = (element: Value, set: SetValue) =>
1985
2292
  findSortedIndex(set.elements, element) !== -1;
1986
2293
 
1987
2294
  const isInSortedSetLikeTlc = (element: Value, set: SetValue) =>
1988
- normalizedSets.has(set)
2295
+ set.isNormalized
1989
2296
  ? searchLikeTlc(element, set.elements).isFound
1990
- : isElementOfLikeTlc(element, set.elements);
2297
+ : isElementOfLikeTlc(element, getWrittenElements(set));
2298
+
2299
+ const isModelValueMember = (modelValue: ModelValue, set: Value) => {
2300
+ if (modelValue.type !== undefined) {
2301
+ throw new TlaEvaluationError(
2302
+ `Attempted to check if the typed model value ${prettyPrint(formatValue(modelValue))} is an element of\n${prettyPrint(formatValue(set))}`,
2303
+ );
2304
+ }
2305
+ return false;
2306
+ };
1991
2307
 
2308
+ // The common cases stay small enough for V8 to inline.
1992
2309
  const isElementOfSet = (element: Value, set: Value): boolean => {
2310
+ if (typeof element === "number" && typeof set === "object") {
2311
+ if (set.kind === "Set")
2312
+ return isIntegerInSortedSet(element, set) ?? isElementOfAnySet(element, set);
2313
+ if (set.kind === "Interval") return element >= set.low && element <= set.high;
2314
+ }
2315
+ return isElementOfAnySet(element, set);
2316
+ };
2317
+
2318
+ const isElementOfAnySet = (element: Value, set: Value): boolean => {
1993
2319
  if (!isSetValue(set)) throw new TlaEvaluationError(describeNonSetMembership(element, set));
1994
2320
  switch (set.kind) {
1995
2321
  case "Set":
1996
- // SetEnumValue.member compares the element with the set's.
2322
+ // TLC compares the element with the set's.
1997
2323
  cacheSet(element);
1998
2324
  return computeLikeTlcOnFailure(isInSortedSet, isInSortedSetLikeTlc, element, set);
1999
2325
  case "MixedSet":
2000
2326
  return isElementOfLikeTlc(element, set.elements);
2001
2327
  case "Interval":
2002
2328
  if (typeof element === "number") return element >= set.low && element <= set.high;
2003
- if (set.low <= set.high && !isModelValue(element)) {
2329
+ if (set.low <= set.high && (!isModelValue(element) || element.type !== undefined)) {
2004
2330
  throw new TlaEvaluationError(
2005
2331
  `Attempted to check if the value:\n${formatValue(element)}\nis in the integer interval ${formatValue(set)}`,
2006
2332
  );
@@ -2008,19 +2334,18 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2008
2334
  return false;
2009
2335
  case "InfiniteSet": {
2010
2336
  if (set.name === "Any") return true;
2011
- if (isModelValue(element)) return false;
2337
+ if (isModelValue(element)) return isModelValueMember(element, set);
2012
2338
  const isMemberType =
2013
2339
  set.name === "STRING" ? typeof element === "string" : typeof element === "number";
2014
2340
  if (!isMemberType) {
2015
- throw new TlaEvaluationError(
2341
+ throw new TlaModuleError(
2016
2342
  `Attempted to check if the value:\n${formatValue(element)}\nis an element of ${set.name}.`,
2017
2343
  );
2018
2344
  }
2019
2345
  return set.name !== "Nat" || (typeof element === "number" && element >= 0);
2020
2346
  }
2021
2347
  case "Subset":
2022
- // SubsetValue.member fails on any value that is not Enumerable, model values and the sets a
2023
- // Java class overrides included.
2348
+ // TLC fails on a value that isn't Enumerable, model values and Java-overridden sets included.
2024
2349
  if (!isSetValue(element) || isOverriddenSet(element)) {
2025
2350
  throw new TlaEvaluationError(
2026
2351
  `Attempted to check if the non-enumerable value\n${prettyPrint(formatValue(element))}\nis element of\n${prettyPrint(formatValue(set))}`,
@@ -2029,14 +2354,14 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2029
2354
  return toFiniteSet(element).elements.every((item) => isElementOf(item, set.base));
2030
2355
  case "FunctionSet": {
2031
2356
  if (!isFunctionValue(element)) {
2032
- if (isModelValue(element)) return false;
2033
- // SetOfFcnsValue.member prints the element without Values.ppr.
2357
+ if (isModelValue(element)) return isModelValueMember(element, set);
2358
+ // TLC prints the element without Values.ppr.
2034
2359
  throw new TlaEvaluationError(
2035
2360
  `Attempted to check if \n${formatValue(element)}\nwhich is not a TLC function value, is in the set of functions:\n${prettyPrint(formatValue(set))}`,
2036
2361
  );
2037
2362
  }
2038
2363
  const functionValue = toFiniteFunction(element);
2039
- const low = getIntervalLow(functionValue.domain);
2364
+ const low = getIntervalLow(element, functionValue.domain);
2040
2365
  const isDomain =
2041
2366
  low === undefined
2042
2367
  ? isEqualLikeTlc(set.domain, createSortedSet(functionValue.domain))
@@ -2049,7 +2374,7 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2049
2374
  case "RecordSet": {
2050
2375
  const functionValue = isFunctionValue(element) ? toFiniteFunction(element) : undefined;
2051
2376
  if (!functionValue || !isRecordDomain(functionValue.domain)) {
2052
- if (isModelValue(element)) return false;
2377
+ if (isModelValue(element)) return isModelValueMember(element, set);
2053
2378
  throw new TlaEvaluationError(
2054
2379
  `Attempted to check if non-record\n${formatValue(element)}\nis in the set of records:\n${formatValue(set)}`,
2055
2380
  );
@@ -2068,7 +2393,8 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2068
2393
  const isFunction =
2069
2394
  isFunctionValue(element) &&
2070
2395
  toFiniteFunction(element).domain.every((key) => typeof key === "number");
2071
- if (isFunction || isModelValue(element)) return false;
2396
+ if (isModelValue(element)) return isModelValueMember(element, set);
2397
+ if (isFunction) return false;
2072
2398
  throw new TlaEvaluationError(
2073
2399
  `Attempted to check if non-tuple\n${formatValue(element)}\nis in the set of tuples:\n${formatValue(set)}`,
2074
2400
  );
@@ -2079,14 +2405,29 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2079
2405
  );
2080
2406
  }
2081
2407
  case "FilteredSet":
2082
- return isElementOf(element, set.base) && set.test(element);
2083
- case "Union":
2408
+ try {
2409
+ return isElementOf(element, set.base) && set.test(element, true);
2410
+ } catch (error) {
2411
+ if (!(error instanceof TlaEvaluationError) || !isEvalException(error)) throw error;
2412
+ throw new TlaEvaluationError(
2413
+ `Cannot decide if element:\n${prettyPrint(formatValue(element))}\n is element of:\n${prettyPrint(formatValue(set.base))}\nand satisfies the predicate ${set.source?.predicate}`,
2414
+ );
2415
+ }
2416
+ case "Union": {
2084
2417
  if (!isTlcEnumerable(set.base)) {
2085
2418
  throw new TlaEvaluationError(
2086
2419
  `Attempted to check if:\n ${formatValue(element)}\nis an element of the non-enumerable set:\n ${formatUnion(set)}`,
2087
2420
  );
2088
2421
  }
2089
- return toFiniteSet(set.base).elements.some((inner) => isElementOf(element, inner));
2422
+ const sets = toFiniteSet(set.base).elements;
2423
+ // TLC sorts the sets to enumerate them, and comparing two sets normalizes both.
2424
+ if (sets.length > 1) {
2425
+ sets.forEach((inner) => {
2426
+ if (typeof inner === "object" && inner.kind === "Set") inner.isNormalized = true;
2427
+ });
2428
+ }
2429
+ return sets.some((inner) => isElementOf(element, inner));
2430
+ }
2090
2431
  case "SetOperation":
2091
2432
  if (set.operator === "\\cup")
2092
2433
  return isElementOf(element, set.left) || isElementOf(element, set.right);
@@ -2097,9 +2438,9 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2097
2438
  case "SequenceSet": {
2098
2439
  const elements = getSequenceElements(element);
2099
2440
  if (elements === undefined) {
2100
- if (isModelValue(element)) return false;
2101
- // Sequences.member raises TLC_MODULE_CHECK_MEMBER_OF.
2102
- throw new TlaEvaluationError(
2441
+ if (isModelValue(element)) return isModelValueMember(element, set);
2442
+ // TLC raises TLC_MODULE_CHECK_MEMBER_OF.
2443
+ throw new TlaModuleError(
2103
2444
  `Attempted to check if the value:\n${prettyPrint(formatValue(element))}\nis an element of ${prettyPrint(formatValue(set))}.`,
2104
2445
  );
2105
2446
  }
@@ -2110,8 +2451,6 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2110
2451
  }
2111
2452
  };
2112
2453
 
2113
- // A function that agrees with a member of a function set outside some entries is a member when
2114
- // those entries are.
2115
2454
  export const isUpdatedElementOf = (element: Value, member: Value, set: Value): boolean => {
2116
2455
  if (element === member) return true;
2117
2456
  if (
@@ -2134,6 +2473,9 @@ export const toFiniteFunction = (value: Value): FunctionValue => {
2134
2473
  if (typeof value === "object" && value.kind === "LazyFunction") {
2135
2474
  if (value.enumerated) return value.enumerated;
2136
2475
  if (!isEnumerable(value.domain)) getCardinality(value.domain);
2476
+ if (!isSetValue(value.domain)) {
2477
+ throw new TlaEvaluationError("The domains of formal parameters must be enumerable.");
2478
+ }
2137
2479
  const domain = getFunctionDomain(value.domain);
2138
2480
  value.enumerated = setFunctionClass(
2139
2481
  createSortedFunction(
@@ -2205,22 +2547,29 @@ export const createNonIntegerKeyError = (argument: Value) =>
2205
2547
  `Attempted to apply function with integer domain to the non-integer argument ${prettyPrint(formatValue(argument))}`,
2206
2548
  );
2207
2549
 
2208
- // TLC's FcnRcdValue searches a domain this small linearly with equals, and a larger normalized one by
2209
- // binary search with compareTo.
2550
+ // TLC searches a domain this small linearly with equals, and a larger one with compareTo.
2210
2551
  const LINEAR_SEARCH_LIMIT = 32;
2211
2552
 
2212
- const failKeyLikeTlc = (domain: Value[], argument: Value, error: TlaEvaluationError): never => {
2213
- if (valueVersion.is174 || domain.length < LINEAR_SEARCH_LIMIT) {
2214
- domain.forEach((key) => equalsLikeTlc(key, argument));
2553
+ const findDomainIndex = (functionValue: FunctionValue, argument: Value) =>
2554
+ findSortedIndex(functionValue.domain, argument);
2555
+
2556
+ // TLC searches a function it hasn't normalized linearly, in the order its keys were written.
2557
+ const failKeyLikeTlc = (
2558
+ functionValue: FunctionValue,
2559
+ argument: Value,
2560
+ error: TlaEvaluationError,
2561
+ ): never => {
2562
+ const keys = getWrittenKeys(functionValue);
2563
+ if (valueVersion.is174 || keys !== functionValue.domain || keys.length < LINEAR_SEARCH_LIMIT) {
2564
+ keys.forEach((key) => equalsLikeTlc(key, argument));
2215
2565
  } else {
2216
- findSortedIndex(domain, argument, compareLikeTlc);
2566
+ findSortedIndex(keys, argument, compareLikeTlc);
2217
2567
  }
2218
2568
  throw error;
2219
2569
  };
2220
2570
 
2221
- // TLC looks a key up by the Java class of the function: a tuple or a record rejects a key of the
2222
- // wrong type, and another function rejects a non-integer for a domain it keeps as an interval, which
2223
- // TLC 1.7.4 doesn't. A key of another type than the domain's keys otherwise fails TLC's comparison.
2571
+ // A tuple or a record rejects a key of the wrong type, and another function a non-integer for
2572
+ // an interval domain, which TLC 1.7.4 doesn't. Any other key type fails TLC's comparison.
2224
2573
  const findKeyIndexLikeTlc = (
2225
2574
  functionValue: FunctionValue,
2226
2575
  argument: Value,
@@ -2234,21 +2583,87 @@ const findKeyIndexLikeTlc = (
2234
2583
  if (keyType !== undefined && typeof argument !== keyType) {
2235
2584
  throw new TlaEvaluationError(describeWrongKey(functionValue, argument));
2236
2585
  }
2237
- if (keyType === undefined && !valueVersion.is174 && isIntervalDomain(domain)) {
2586
+ if (
2587
+ keyType === undefined &&
2588
+ !valueVersion.is174 &&
2589
+ typeof argument !== "number" &&
2590
+ isIntervalDomain(domain)
2591
+ ) {
2238
2592
  throw createNonIntegerKeyError(argument);
2239
2593
  }
2240
2594
  }
2241
2595
  const identical = findIdenticalKey(domain, argument);
2242
2596
  if (identical !== -1) return identical;
2243
- return computeLikeTlcOnFailure(findSortedIndex, failKeyLikeTlc, domain, argument);
2597
+ return computeLikeTlcOnFailure(findDomainIndex, failKeyLikeTlc, functionValue, argument);
2244
2598
  };
2245
2599
 
2600
+ // TLC checks each argument against its bound in turn. FcnLambdaValue#apply then indexes past an
2601
+ // argument tuple shorter than the bounds and ignores one longer, where this rejects the list.
2602
+ const checkBoundArguments = (
2603
+ functionValue: LazyFunctionValue,
2604
+ tupleLengths: (number | undefined)[],
2605
+ argument: Value,
2606
+ ) => {
2607
+ const domain = functionValue.domain;
2608
+ const elements = getSequenceElements(argument);
2609
+ const describe = (position: string, shown: Value, problem: string) =>
2610
+ `In applying the function\n${prettyPrint(formatValue(functionValue))},\nthe ${position} is:\n${prettyPrint(formatValue(shown))}\nwhich ${problem}.\n`;
2611
+ const createListError = () =>
2612
+ new TlaEvaluationError(
2613
+ describe("argument list", argument, "does not match its formal parameter"),
2614
+ );
2615
+ if (elements === undefined) throw createListError();
2616
+ if (typeof domain !== "object" || domain.kind !== "ProductSet") {
2617
+ throw new TlaEvaluationError(
2618
+ `Attempted to apply a function to ${formatValue(argument)}, which is not in its domain`,
2619
+ );
2620
+ }
2621
+ tupleLengths.forEach((tupleLength, index) => {
2622
+ if (index >= elements.length) throw createListError();
2623
+ const element = elements[index];
2624
+ const position = `argument number ${index + 1}`;
2625
+ if (!isElementOf(element, domain.factors[index])) {
2626
+ throw new TlaEvaluationError(
2627
+ describe(
2628
+ position,
2629
+ element,
2630
+ tupleLength === undefined
2631
+ ? `is not in the function's domain ${formatValue(domain)}`
2632
+ : "is not in its domain",
2633
+ ),
2634
+ );
2635
+ }
2636
+ if (tupleLength !== undefined && getSequenceElements(element)?.length !== tupleLength) {
2637
+ throw new TlaEvaluationError(
2638
+ describe(position, element, "does not match its formal parameter"),
2639
+ );
2640
+ }
2641
+ });
2642
+ if (elements.length > tupleLengths.length) throw createListError();
2643
+ };
2644
+
2645
+ // TLC checks that a FcnLambdaValue's domain holds the argument, and searches only the FcnRcdValue
2646
+ // it converts the lambda to when it fingerprints it.
2647
+ const isOutsideLambdaDomain = (functionValue: FunctionValue, argument: Value) =>
2648
+ functionValue.lambdaDomain !== undefined &&
2649
+ functionValue.hash === 0 &&
2650
+ functionValue.fingerprint === 0 &&
2651
+ !isElementOf(argument, functionValue.lambdaDomain);
2652
+
2246
2653
  export const applyFunction = (
2247
2654
  functionValue: Value,
2248
2655
  argument: Value,
2249
2656
  describeMissing?: (functionValue: FunctionValue, argument: Value) => string,
2250
2657
  ): Value => {
2251
2658
  if (typeof functionValue === "object" && functionValue.kind === "LazyFunction") {
2659
+ if (functionValue.enumerated) {
2660
+ return applyFunction(functionValue.enumerated, argument, describeMissing);
2661
+ }
2662
+ const tupleLengths = functionValue.boundTupleLengths;
2663
+ if (tupleLengths !== undefined) {
2664
+ checkBoundArguments(functionValue, tupleLengths, argument);
2665
+ return functionValue.apply(argument);
2666
+ }
2252
2667
  if (!isElementOf(argument, functionValue.domain)) {
2253
2668
  throw new TlaEvaluationError(
2254
2669
  getFunctionClass(functionValue) === "lambda"
@@ -2264,6 +2679,9 @@ export const applyFunction = (
2264
2679
  );
2265
2680
  }
2266
2681
  const describe = describeMissing ?? describeMissingArgument;
2682
+ if (isOutsideLambdaDomain(functionValue, argument)) {
2683
+ throw new TlaEvaluationError(describe(functionValue, argument));
2684
+ }
2267
2685
  const position = findKeyIndexLikeTlc(functionValue, argument, describe);
2268
2686
  if (position === -1) throw new TlaEvaluationError(describe(functionValue, argument));
2269
2687
  return functionValue.range[position];
@@ -2277,8 +2695,18 @@ export const getDomainInterval = (domain: Value[]) =>
2277
2695
  export const getDomain = (functionValue: Value): Value => {
2278
2696
  if (typeof functionValue === "object" && functionValue.kind === "LazyFunction")
2279
2697
  return functionValue.domain;
2280
- const domain = toFiniteFunction(functionValue).domain;
2281
- return getDomainInterval(domain) ?? createSortedSet(domain);
2698
+ const finite = toFiniteFunction(functionValue);
2699
+ if (finite.functionClass === "lambda" && finite.lambdaDomain) return finite.lambdaDomain;
2700
+ const interval = getDomainInterval(finite.domain);
2701
+ if (interval) return interval;
2702
+ const set = createSortedSet(finite.domain);
2703
+ // TLC keeps a record's domain in written order and sorts any other function's.
2704
+ if (finite.functionClass === "record") {
2705
+ if (finite.writtenKeys) set.writtenElements = finite.writtenKeys;
2706
+ return set;
2707
+ }
2708
+ set.isNormalized = true;
2709
+ return set;
2282
2710
  };
2283
2711
 
2284
2712
  export const updateFunction = (
@@ -2290,7 +2718,7 @@ export const updateFunction = (
2290
2718
  const isLazy =
2291
2719
  typeof functionValue === "object" &&
2292
2720
  functionValue.kind === "LazyFunction" &&
2293
- (isKeptLazy || !isEnumerable(functionValue.domain));
2721
+ (isKeptLazy || functionValue.enumerated === undefined);
2294
2722
  if (isLazy) {
2295
2723
  if (!isElementOf(argument, functionValue.domain)) return functionValue;
2296
2724
  const updated = update(functionValue.apply(argument));
@@ -2300,6 +2728,7 @@ export const updateFunction = (
2300
2728
  domain: functionValue.domain,
2301
2729
  apply: (key) => (isEqualLikeTlc(argument, key) ? updated : functionValue.apply(key)),
2302
2730
  source: functionValue.source,
2731
+ boundTupleLengths: functionValue.boundTupleLengths,
2303
2732
  },
2304
2733
  getFunctionClass(functionValue),
2305
2734
  );
@@ -2310,6 +2739,7 @@ export const updateFunction = (
2310
2739
  );
2311
2740
  }
2312
2741
  const finite = toFiniteFunction(functionValue);
2742
+ if (isOutsideLambdaDomain(finite, argument)) return finite;
2313
2743
  const position = findKeyIndexLikeTlc(finite, argument, describeExceptKey);
2314
2744
  if (position === -1) return finite;
2315
2745
  const range = [...finite.range];
@@ -2321,6 +2751,7 @@ export const updateFunction = (
2321
2751
  getFunctionClass(finite),
2322
2752
  );
2323
2753
  updated.writtenKeys = finite.writtenKeys;
2754
+ updated.lambdaDomain = finite.lambdaDomain;
2324
2755
  if (finite.hash !== 0 && finite.hash !== UNFINGERPRINTABLE_HASH) {
2325
2756
  const nextHash = getValueHash(next);
2326
2757
  if (nextHash !== UNFINGERPRINTABLE_HASH) {
@@ -2373,9 +2804,8 @@ const getElementContribution = (elementHash: number) =>
2373
2804
  const getEntryContribution = (keyHash: number, valueHash: number) =>
2374
2805
  finalizeHash((Math.imul(keyHash, 0x27d4eb2d) + valueHash) | 0);
2375
2806
 
2376
- // The hash of each value that TLC fails to fingerprint, such as Nat or a set that holds it. Calls
2377
- // with such a value as an argument still share their result, and a state that holds one fails
2378
- // when TLC fingerprints it.
2807
+ // The hash of a value TLC fails to fingerprint, such as Nat. Calls with one as an argument still
2808
+ // share their result, and a state that holds one fails when TLC fingerprints it.
2379
2809
  const UNFINGERPRINTABLE_HASH = 0x2f6b1c4d;
2380
2810
 
2381
2811
  const computeValueHash = (value: SetValue | FunctionValue) => {
@@ -2401,8 +2831,7 @@ const computeValueHash = (value: SetValue | FunctionValue) => {
2401
2831
  return hash;
2402
2832
  };
2403
2833
 
2404
- // TLC's fingerPrint enumerates each set and function a value holds, and fails on Nat, Seq(S) and
2405
- // the like, which it never enumerates.
2834
+ // TLC enumerates each set and function, and fails on Nat, Seq(S) and the like.
2406
2835
  const fingerprintValue = (value: Value): void => {
2407
2836
  if (typeof value !== "object" || value.kind === "ModelValue") return;
2408
2837
  if (value.kind === "InfiniteSet" || value.kind === "SequenceSet") {
@@ -2419,8 +2848,7 @@ const fingerprintValue = (value: Value): void => {
2419
2848
  functionValue.range.forEach(fingerprintValue);
2420
2849
  };
2421
2850
 
2422
- // The error TLC raises as it fingerprints a value: one that hashing the value raises, as for a set
2423
- // too large to enumerate, or one of a value with the hash of the values TLC fails on.
2851
+ // Hashing can fail, as for a set too large to enumerate, and so can a value TLC fails on.
2424
2852
  export const getFingerprintError = (value: Value) => {
2425
2853
  if (typeof value !== "object" || value.kind === "ModelValue") return undefined;
2426
2854
  try {
@@ -2432,7 +2860,6 @@ export const getFingerprintError = (value: Value) => {
2432
2860
  }
2433
2861
  };
2434
2862
 
2435
- // The values a value holds, which TLC fingerprints as it fingerprints the value.
2436
2863
  export const getHeldValues = (value: ObjectValue): Value[] => {
2437
2864
  switch (value.kind) {
2438
2865
  case "Set":
@@ -2553,8 +2980,17 @@ const computeValueKey = (value: ObjectValue) => {
2553
2980
  return `(${functionValue.domain.map((key, index) => `${getValueKey(key)}:${getValueKey(functionValue.range[index])}`).join(",")})`;
2554
2981
  };
2555
2982
 
2983
+ const PRINTED_ESCAPES: Record<string, string> = {
2984
+ '"': '\\"',
2985
+ "\\": "\\\\",
2986
+ "\t": "\\t",
2987
+ "\n": "\\n",
2988
+ "\f": "\\f",
2989
+ "\r": "\\r",
2990
+ };
2991
+
2556
2992
  const formatString = (value: string) =>
2557
- `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\t/g, "\\t")}"`;
2993
+ `"${value.replace(/["\\\t\n\f\r]/g, (character) => PRINTED_ESCAPES[character])}"`;
2558
2994
 
2559
2995
  type LazySetValue =
2560
2996
  | SubsetValue
@@ -2580,23 +3016,27 @@ const expandLazySet = (value: LazySetValue) => {
2580
3016
  if (value.kind === "SetOperation" || value.kind === "FilteredSet" || value.kind === "Union") {
2581
3017
  return toFiniteSet(value);
2582
3018
  }
2583
- if (
2584
- value.kind === "FunctionSet" &&
2585
- isEnumerable(value.domain) &&
2586
- getCardinality(value.domain) === 0
2587
- ) {
2588
- return createSortedSet([createSortedFunction([], [])]);
3019
+ // TLC asks whether the domain is empty before it sizes it.
3020
+ if (value.kind === "FunctionSet") {
3021
+ const domainSize = isEmptySet(value.domain) ? 0 : getCardinality(value.domain);
3022
+ const size = domainSize === 0 ? 1 : getCardinality(value.range) ** domainSize;
3023
+ return size <= MAXIMUM_EXPANDED_PRODUCT ? toFiniteSet(value) : undefined;
2589
3024
  }
2590
- const size =
2591
- value.kind === "FunctionSet"
2592
- ? getCardinality(value.range) ** getCardinality(value.domain)
2593
- : getProductSize(value.kind === "RecordSet" ? value.sets : value.factors);
2594
- if (size === 0) return EMPTY_SET;
3025
+ const size = getProductSize(value.kind === "RecordSet" ? value.sets : value.factors);
2595
3026
  return size <= MAXIMUM_EXPANDED_PRODUCT ? toFiniteSet(value) : undefined;
2596
3027
  };
2597
3028
 
2598
3029
  const getExpandedLazySet = (value: LazySetValue, isStrict: boolean) => {
2599
- if (isStrict) return expandLazySet(value);
3030
+ // UnionValue alone of TLC's lazy sets doesn't swallow the failure to enumerate itself.
3031
+ if (isStrict || value.kind === "Union") return expandLazySet(value);
3032
+ // TLC sizes the base of SUBSET before it enumerates it, and only a failure to size it is quiet.
3033
+ if (
3034
+ value.kind === "Subset" &&
3035
+ isFunctionValue(value.base) &&
3036
+ (value.base.kind === "Function" || isEnumerable(value.base.domain))
3037
+ ) {
3038
+ return expandLazySet(value);
3039
+ }
2600
3040
  // TLC prints a set it can't enumerate symbolically, except in Print, PrintT, and ToString.
2601
3041
  if (!isEnumerable(value)) return undefined;
2602
3042
  try {
@@ -2631,24 +3071,78 @@ const formatLazySet = (value: LazySetValue, isStrict: boolean): string => {
2631
3071
  }
2632
3072
  };
2633
3073
 
2634
- // FcnRcdValue#isName: TLC prints a function as a record when every key consists of letters,
2635
- // decimal digits, and underscores, with at least one letter.
3074
+ // TLC prints a record when every key is letters, digits, and underscores, with a letter.
2636
3075
  const isFieldName = (name: string) =>
2637
3076
  /^[\p{L}\p{Nd}_]*$/u.test(name) &&
2638
3077
  /\p{L}/u.test(name) &&
2639
3078
  (name.length < 4 || !/^[WS]F_/.test(name));
2640
3079
 
2641
- // FcnLambdaValue#toString prints a function it fails to enumerate as its parameters and body.
2642
3080
  const toPrintedFunction = (value: LazyFunctionValue) => {
2643
3081
  if (!isEnumerable(value.domain)) return undefined;
2644
3082
  try {
2645
3083
  return toFiniteFunction(value);
2646
3084
  } catch (error) {
2647
- if (error instanceof TlaEvaluationError) return undefined;
3085
+ if (error instanceof TlaEvaluationError || isStackOverflow(error)) return undefined;
2648
3086
  throw error;
2649
3087
  }
2650
3088
  };
2651
3089
 
3090
+ // TLC prints normalized copies, so the printed values themselves stay unnormalized.
3091
+ export const formatNormalizedCopies = (values: Value[]) => {
3092
+ const markedSets: SetValue[] = [];
3093
+ const normalize = (value: Value): void => {
3094
+ if (typeof value !== "object") return;
3095
+ switch (value.kind) {
3096
+ case "Set":
3097
+ value.elements.forEach(normalize);
3098
+ if (value.isNormalized) return;
3099
+ value.isNormalized = true;
3100
+ markedSets.push(value);
3101
+ return;
3102
+ case "MixedSet":
3103
+ value.elements.forEach(normalize);
3104
+ toFiniteSet(value);
3105
+ return;
3106
+ case "Function":
3107
+ value.range.forEach(normalize);
3108
+ return;
3109
+ case "LazyFunction":
3110
+ normalize(value.enumerated ?? value.domain);
3111
+ return;
3112
+ case "SetOperation":
3113
+ normalize(value.left);
3114
+ normalize(value.right);
3115
+ return;
3116
+ case "FunctionSet":
3117
+ normalize(value.domain);
3118
+ normalize(value.range);
3119
+ return;
3120
+ case "RecordSet":
3121
+ value.sets.forEach(normalize);
3122
+ return;
3123
+ case "ProductSet":
3124
+ value.factors.forEach(normalize);
3125
+ return;
3126
+ case "Subset":
3127
+ case "Union":
3128
+ case "FilteredSet":
3129
+ case "SequenceSet":
3130
+ normalize(value.base);
3131
+ return;
3132
+ default:
3133
+ return;
3134
+ }
3135
+ };
3136
+ try {
3137
+ values.forEach(normalize);
3138
+ return values.map((value) => formatValue(value, true, true));
3139
+ } finally {
3140
+ markedSets.forEach((set) => {
3141
+ set.isNormalized = false;
3142
+ });
3143
+ }
3144
+ };
3145
+
2652
3146
  export const formatValue = (value: Value, isStrict = false, isNormalized = false): string => {
2653
3147
  const format = (inner: Value) => formatValue(inner, isStrict, isNormalized);
2654
3148
  if (typeof value === "boolean") return value ? "TRUE" : "FALSE";
@@ -2672,7 +3166,7 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
2672
3166
  case "SetOperation":
2673
3167
  case "FilteredSet":
2674
3168
  case "Union": {
2675
- const expanded = getExpandedLazySet(value, isStrict);
3169
+ const expanded = printing.isExpanded ? getExpandedLazySet(value, isStrict) : undefined;
2676
3170
  return expanded ? format(expanded) : formatLazySet(value, isStrict);
2677
3171
  }
2678
3172
 
@@ -2680,7 +3174,12 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
2680
3174
  return `Seq(${format(value.base)})`;
2681
3175
  case "Function":
2682
3176
  case "LazyFunction": {
2683
- const functionValue = value.kind === "LazyFunction" ? toPrintedFunction(value) : value;
3177
+ const functionValue =
3178
+ value.kind !== "LazyFunction"
3179
+ ? value
3180
+ : printing.isExpanded || !value.source
3181
+ ? toPrintedFunction(value)
3182
+ : undefined;
2684
3183
  if (functionValue === undefined) {
2685
3184
  const source = value.kind === "LazyFunction" ? value.source : undefined;
2686
3185
  if (!source) return "<function>";
@@ -2699,34 +3198,112 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
2699
3198
  // TLC normalizes a lambda's domain to print it, but evaluates its body afterward.
2700
3199
  const formatRange = (inner: Value) =>
2701
3200
  formatValue(inner, isStrict, isNormalized && getFunctionClass(value) !== "lambda");
3201
+ if (functionValue.domain.length === 0 && getFunctionClass(value) === "record") return "[]";
2702
3202
  if (functionValue.domain.every((key, index) => key === index + 1)) {
2703
3203
  return `<<${functionValue.range.map(formatRange).join(", ")}>>`;
2704
3204
  }
2705
- // A RecordValue prints as a record whatever its fields, and a FcnRcdValue only if each key
2706
- // is a name.
3205
+ const pairs = isNormalized
3206
+ ? functionValue.domain.map((key, index) => [key, functionValue.range[index]])
3207
+ : getPrintedPairs(functionValue);
3208
+ // A RecordValue always prints as a record, a FcnRcdValue only if its keys are names.
2707
3209
  if (
2708
3210
  getFunctionClass(value) === "record" ||
2709
3211
  functionValue.domain.every((key) => typeof key === "string" && isFieldName(key))
2710
3212
  ) {
2711
- const isSorted =
2712
- isNormalized || functionValue.hash !== 0 || functionValue.fingerprint !== 0;
2713
- const pairs = isSorted
2714
- ? functionValue.domain.map((key, index) => [key, functionValue.range[index]])
2715
- : getWrittenPairs(functionValue);
2716
3213
  return `[${pairs.map((pair) => `${String(pair[0])} |-> ${formatRange(pair[1])}`).join(", ")}]`;
2717
3214
  }
2718
- return `(${functionValue.domain.map((key, index) => `${format(key)} :> ${formatRange(functionValue.range[index])}`).join(" @@ ")})`;
3215
+ return `(${pairs.map((pair) => `${format(pair[0])} :> ${formatRange(pair[1])}`).join(" @@ ")})`;
2719
3216
  }
2720
3217
  }
2721
3218
  };
2722
3219
 
2723
- // TLC's TLCState.toString: a line per variable, as a conjunction when there are several.
2724
- export const formatState = (state: Record<string, Value>) => {
3220
+ // TLC counts a value it can't compare with the previous one as changed.
3221
+ const isUnchanged = (previous: Value | undefined, value: Value) => {
3222
+ if (previous === undefined) return false;
3223
+ try {
3224
+ return valuesEqual(previous, value);
3225
+ } catch (error) {
3226
+ if (error instanceof TlaEvaluationError) return false;
3227
+ throw error;
3228
+ }
3229
+ };
3230
+
3231
+ const JAVA_FORMAT_SPECIFIER = /%(\d+\$)?([-#+ 0,(<]*)(\d+)?(\.\d+)?(.?)/gs;
3232
+
3233
+ const getJavaHashCode = (text: string) =>
3234
+ Array.from({ length: text.length }, (_, index) => text.charCodeAt(index)).reduce(
3235
+ (hash, unit) => (Math.imul(hash, 31) + unit) | 0,
3236
+ 0,
3237
+ );
3238
+
3239
+ const formatJava = (format: string, args: string[]) => {
3240
+ const indices = { next: 0, last: -1 };
3241
+ const isFitting = { value: true };
3242
+ const text = format.replace(
3243
+ JAVA_FORMAT_SPECIFIER,
3244
+ (match, explicit?: string, flags = "", width?: string, precision?: string, conversion = "") => {
3245
+ const pad = (value: string) =>
3246
+ flags.includes("-") ? value.padEnd(Number(width)) : value.padStart(Number(width ?? 0));
3247
+ const isRelative = flags.includes("<");
3248
+ const otherFlags = flags.replace("<", "");
3249
+ if (conversion === "n" && match === "%n") return "\n";
3250
+ if (conversion === "%" && precision === undefined && /^-?$/.test(otherFlags)) {
3251
+ if (otherFlags === "-" && width === undefined) isFitting.value = false;
3252
+ return pad("%");
3253
+ }
3254
+ const index = isRelative
3255
+ ? indices.last
3256
+ : explicit === undefined
3257
+ ? indices.next++
3258
+ : Number(explicit.slice(0, -1)) - 1;
3259
+ indices.last = index;
3260
+ const arg = args[index];
3261
+ if (
3262
+ !"sSbBhH".includes(conversion) ||
3263
+ conversion === "" ||
3264
+ !/^-?$/.test(otherFlags) ||
3265
+ (otherFlags === "-" && width === undefined) ||
3266
+ arg === undefined
3267
+ ) {
3268
+ isFitting.value = false;
3269
+ return match;
3270
+ }
3271
+ const lower = conversion.toLowerCase();
3272
+ const value =
3273
+ lower === "s" ? arg : lower === "b" ? "true" : (getJavaHashCode(arg) >>> 0).toString(16);
3274
+ const shown = pad(
3275
+ precision === undefined ? value : value.slice(0, Number(precision.slice(1))),
3276
+ );
3277
+ return conversion === lower ? shown : shown.toUpperCase();
3278
+ },
3279
+ );
3280
+ return isFitting.value ? text : undefined;
3281
+ };
3282
+
3283
+ // TLC prints the VIEW of a state, but not of one it prints as a difference from the previous.
3284
+ export const formatState = (state: Record<string, Value>, previous?: Record<string, Value>) => {
3285
+ const getViewText = previous ? undefined : viewTexts.get(state);
3286
+ if (getViewText) return getViewText();
2725
3287
  const entries = Object.entries(state);
3288
+ const alias = aliasNames.get(state);
3289
+ const isFormatted = alias !== undefined && "_format" in state;
3290
+ const format = isFormatted ? state._format : entries.length === 1 ? "%s = %s\n" : "/\\ %s = %s\n";
3291
+ if (typeof format !== "string") {
3292
+ throw new TlaAliasFormatError(
3293
+ `The _format field of the ALIAS ${alias} is ${formatValue(format)}, but it must be a string.`,
3294
+ );
3295
+ }
2726
3296
  return entries
2727
- .map(
2728
- ([name, value]) =>
2729
- `${entries.length === 1 ? "" : "/\\ "}${name} = ${prettyPrint(formatValue(value))}\n`,
2730
- )
3297
+ .filter(([name]) => !(isFormatted && name === "_format"))
3298
+ .filter(([name, value]) => !previous || !isUnchanged(previous[name], value))
3299
+ .map(([name, value]) => {
3300
+ const text = formatJava(format, [name, prettyPrint(formatValue(value))]);
3301
+ if (text === undefined) {
3302
+ throw new TlaAliasFormatError(
3303
+ `The _format field of the ALIAS ${alias} is ${formatValue(format)}, but it must format two strings, the name and the value of a field.`,
3304
+ );
3305
+ }
3306
+ return text;
3307
+ })
2731
3308
  .join("");
2732
3309
  };