tla-ts 0.0.9 → 0.0.10-dev.b4a856304

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 +29 -1
  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 +72 -10
  8. package/dist/index.d.ts +72 -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 +576 -300
  30. package/src/cli/options.ts +11 -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 +538 -220
  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 +630 -297
  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 +29 -39
  82. package/src/parallel.ts +29 -13
  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 +119 -169
  340. package/src/sany/levels.ts +6 -30
  341. package/src/sany/lexer.ts +7 -23
  342. package/src/sany/linter.ts +1 -8
  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 +494 -154
  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 +826 -276
  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,11 +440,6 @@ export const rankString = (text: string) => {
342
440
  return text;
343
441
  };
344
442
 
345
- export const getRankedStringCount = () => stringOrder.size;
346
-
347
- export const getRankedString = (rank: number) =>
348
- Object.keys(stringOrder.ranks).find((text) => stringOrder.ranks[text] === rank);
349
-
350
443
  export const getStringRank = (text: string) => stringOrder.ranks[rankString(text)];
351
444
 
352
445
  const compareStrings = (left: string, right: string) => {
@@ -354,6 +447,14 @@ const compareStrings = (left: string, right: string) => {
354
447
  const ranks = stringOrder.ranks;
355
448
  const leftRank = ranks[left];
356
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
+ }
357
458
  if (leftRank !== undefined && rightRank !== undefined) return leftRank - rightRank;
358
459
  if (leftRank !== undefined) return -1;
359
460
  if (rightRank !== undefined) return 1;
@@ -372,9 +473,15 @@ const isOverriddenComparison = (left: Value, right: Value) =>
372
473
  right.kind === "SequenceSet"
373
474
  );
374
475
 
375
- // TLC implements Nat, Int, STRING, Seq(S), and Any in Java classes that compare only with each
376
- // other and with model values. Comparing one with any other set is an error, worded by the class of
377
- // 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.
378
485
  const compareOverriddenSets = (
379
486
  left: Value,
380
487
  right: Value,
@@ -385,18 +492,14 @@ const compareOverriddenSets = (
385
492
  `Attempted to ${verb} the set ${formatValue(isEnumerable(left) ? toFiniteSet(left) : left, true)} with the value:\n${formatValue(right, true)}`,
386
493
  );
387
494
  }
388
- if (!isOverriddenSet(right)) {
389
- throw new TlaEvaluationError(
390
- `Attempted to compare overridden value ${formatValue(left, true)} with non-overridden value:\n${formatValue(right, true)}`,
391
- );
392
- }
495
+ if (!isOverriddenSet(right)) throw createComparisonError(left, right);
393
496
  const leftName = left.kind === "InfiniteSet" ? left.name : undefined;
394
497
  const rightName = right.kind === "InfiniteSet" ? right.name : undefined;
395
498
  if (leftName !== undefined && leftName === rightName) return 0;
396
499
  if ((leftName === "Nat" && rightName === "Int") || (leftName === "Int" && rightName === "Nat")) {
397
500
  return leftName === "Nat" ? -1 : 1;
398
501
  }
399
- throw new TlaEvaluationError(
502
+ throw new TlaModuleError(
400
503
  `Attempted to compare ${formatValue(left, true)} with the value\n${formatValue(right, true)}`,
401
504
  );
402
505
  };
@@ -404,13 +507,20 @@ const compareOverriddenSets = (
404
507
  export const ANY_SET: InfiniteSetValue = { kind: "InfiniteSet", name: "Any" };
405
508
 
406
509
  const compareAny = (other: Value): never => {
407
- 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);
408
518
  };
409
519
 
410
520
  export const compareValues = (left: Value, right: Value): number => {
411
521
  if (left === right) {
412
- if (writtenOrderUse.isUsed) forgetWrittenOrder(left);
413
- return left === ANY_SET ? compareAny(left) : 0;
522
+ compareWithItself(left);
523
+ return 0;
414
524
  }
415
525
  if (typeof left === "object" && typeof right === "object") {
416
526
  const leftKind = left.kind;
@@ -438,9 +548,16 @@ export const compareValues = (left: Value, right: Value): number => {
438
548
  }
439
549
  const isLeftSet = isSetValue(left);
440
550
  if (isLeftSet !== isSetValue(right)) {
441
- throw new TlaEvaluationError(
442
- `Attempted to compare ${describeKind(left)} ${formatValue(left)} with ${describeKind(right)} ${formatValue(right)}`,
443
- );
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;
444
561
  }
445
562
  if (isLeftSet) return compareSets(toFiniteSet(left), toFiniteSet(right));
446
563
  return compareFunctions(toFiniteFunction(left), toFiniteFunction(right));
@@ -451,17 +568,23 @@ export const compareValues = (left: Value, right: Value): number => {
451
568
  checkModelValueTypes(left, right, false);
452
569
  if (isModelValue(left)) return -1;
453
570
  if (isModelValue(right)) return 1;
454
- throw new TlaEvaluationError(
455
- `Attempted to compare ${describeKind(left)} ${formatValue(left)} with ${describeKind(right)} ${formatValue(right)}`,
456
- );
571
+ throw createComparisonError(left, right);
457
572
  };
458
573
 
459
574
  const modelValues = new Map<string, ModelValue>();
460
575
 
576
+ // ModelValue's index is a short.
577
+ const MAXIMUM_MODEL_VALUES = 32768;
578
+
461
579
  // setStringOrder clears the model values, so each check ranks and creates its own.
462
580
  export const createModelValue = (name: string): ModelValue => {
463
581
  const known = modelValues.get(name);
464
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
+ }
465
588
  const value: ModelValue = {
466
589
  kind: "ModelValue",
467
590
  name,
@@ -474,14 +597,24 @@ export const createModelValue = (name: string): ModelValue => {
474
597
  return value;
475
598
  };
476
599
 
600
+ export const getModelValues = () => [...modelValues.values()];
601
+
477
602
  export const createSortedSet = (elements: Value[]): SetValue => ({
478
603
  kind: "Set",
479
604
  elements,
605
+ writtenElements: undefined,
606
+ isNormalized: false,
480
607
  hash: 0,
481
608
  fingerprint: 0,
482
609
  isFingerprinted: false,
483
610
  });
484
611
 
612
+ export const createNormalizedSet = (elements: Value[]): SetValue => {
613
+ const set = createSortedSet(elements);
614
+ set.isNormalized = true;
615
+ return set;
616
+ };
617
+
485
618
  export const createSortedFunction = (domain: Value[], range: Value[]): FunctionValue => ({
486
619
  kind: "Function",
487
620
  domain,
@@ -490,12 +623,12 @@ export const createSortedFunction = (domain: Value[], range: Value[]): FunctionV
490
623
  fingerprint: 0,
491
624
  writtenKeys: undefined,
492
625
  functionClass: undefined,
626
+ lambdaDomain: undefined,
493
627
  isFingerprinted: false,
494
628
  });
495
629
 
496
- // TLC words a failed function application by the Java class of the function: FcnLambdaValue for
497
- // [x \in S |-> e], TupleValue for <<...>> and what the sequence operators build, RecordValue for
498
- // [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.
499
632
  export type FunctionClass = "lambda" | "tuple" | "record";
500
633
 
501
634
  // Whether a lambda exists for markFingerprinted to find, so that a spec without one skips the walk.
@@ -519,12 +652,11 @@ export const markLambdaFunction = <FunctionLike extends FunctionValue | LazyFunc
519
652
  functionValue: FunctionLike,
520
653
  ) => setFunctionClass(functionValue, "lambda");
521
654
 
522
- // TLC caches a lazy set as the receiver of compareTo, equals, size, and fingerPrint, not as their
523
- // 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.
524
657
  const isCachedSet = (value: ObjectValue) => isLazySet(value) && value.isCached === true;
525
658
 
526
- // Whether the spec has built a UNION or \cup set, the sets that stream duplicates, so that a spec
527
- // 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.
528
660
  const streamedSetPresence = { isPresent: false };
529
661
 
530
662
  export const markStreamedSet = <Streamed extends UnionValue | SetOperationValue>(
@@ -534,7 +666,6 @@ export const markStreamedSet = <Streamed extends UnionValue | SetOperationValue>
534
666
  return value;
535
667
  };
536
668
 
537
- // The sets that stream their elements apart from the normalized set until TLC caches them.
538
669
  const STREAMING_KINDS = new Set<ObjectValue["kind"]>([
539
670
  "Union",
540
671
  "SetOperation",
@@ -555,8 +686,7 @@ const cacheSet = (value: Value) => {
555
686
  }
556
687
  };
557
688
 
558
- // FcnLambdaValue#fingerPrint caches the FcnRcdValue the function enumerates to, which applies it
559
- // 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.
560
690
  export const markFingerprinted = (value: Value): void => {
561
691
  if ((!lambdaPresence.isPresent && !streamedSetPresence.isPresent) || typeof value !== "object") {
562
692
  return;
@@ -581,8 +711,8 @@ export const markFingerprinted = (value: Value): void => {
581
711
  export const valuesEqual = (left: Value, right: Value): boolean => {
582
712
  cacheSet(left);
583
713
  if (left === right) {
584
- if (writtenOrderUse.isUsed) forgetWrittenOrder(left);
585
- return left !== ANY_SET || compareAny(left);
714
+ compareWithItself(left);
715
+ return true;
586
716
  }
587
717
  if (typeof left !== "object" || typeof right !== "object") {
588
718
  if (typeof left === typeof right) return false;
@@ -591,16 +721,19 @@ export const valuesEqual = (left: Value, right: Value): boolean => {
591
721
  }
592
722
  return compareValues(left, right) === 0;
593
723
  }
594
- const isHashed =
595
- (left.kind === "Set" || left.kind === "Function") &&
596
- (right.kind === "Set" || right.kind === "Function") &&
597
- left.hash !== 0 &&
598
- right.hash !== 0;
599
- if (isHashed && left.hash !== right.hash) return false;
600
724
  if (left.kind === "Function" && right.kind === "Function")
601
725
  return compareFunctions(left, right) === 0;
602
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
+ }
603
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);
604
737
  checkModelValueTypes(left, right, true);
605
738
  return isModelValue(left) && isModelValue(right) && left.name === right.name;
606
739
  }
@@ -653,8 +786,7 @@ export const valuesEqual = (left: Value, right: Value): boolean => {
653
786
  return compareValues(left, right) === 0;
654
787
  };
655
788
 
656
- // TLC prints and words errors about an equal function by its Java class, so a value can stand for
657
- // 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.
658
790
  const createSameValueCheck = (isClassSensitive: boolean) => {
659
791
  const areSameValues = (left: Value[], right: Value[]) => {
660
792
  if (left === right) return true;
@@ -694,8 +826,7 @@ const canonicalizeElements = (elements: Value[], canonicalize: (value: Value) =>
694
826
  }
695
827
  };
696
828
 
697
- // Replaces each set and function in a state with the first interchangeable one it has seen, so that
698
- // the states it keeps share their values.
829
+ // So that the states it keeps share their values.
699
830
  export const createCanonicalizer = () => {
700
831
  const canonicalValues = new Map<number, Value | Value[]>();
701
832
  const canonicalize = (value: Value): Value => {
@@ -729,21 +860,17 @@ export const createCanonicalizer = () => {
729
860
  };
730
861
  };
731
862
 
732
- // The comparisons above fail with their own messages. These follow the compareTo and equals
733
- // methods of TLC's Java value classes, which word a failure by the class of the left operand, so a
734
- // 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.
735
865
  interface TlcFunction {
736
866
  domain: Value[];
737
867
  range: Value[];
738
868
  low: number | undefined;
739
869
  }
740
870
 
741
- const getIntervalLow = (domain: Value[]) => {
742
- const first = domain.length === 0 ? 1 : domain[0];
743
- return typeof first === "number" && domain.every((key, index) => key === first + index)
744
- ? first
745
- : undefined;
746
- };
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;
747
874
 
748
875
  const toTlcFunction = (value: Value) => {
749
876
  if (!isFunctionValue(value)) return undefined;
@@ -751,7 +878,7 @@ const toTlcFunction = (value: Value) => {
751
878
  return {
752
879
  domain: functionValue.domain,
753
880
  range: functionValue.range,
754
- low: getIntervalLow(functionValue.domain),
881
+ low: getIntervalLow(value, functionValue.domain),
755
882
  };
756
883
  };
757
884
 
@@ -844,8 +971,7 @@ const compareElementsLikeTlc = (left: Value[], right: Value[]) => {
844
971
 
845
972
  const compareFunctionLikeTlc = (left: FunctionValue | LazyFunctionValue, right: Value) => {
846
973
  const functionValue = toFiniteFunction(left);
847
- const isTuple = left.kind === "Function" && getSequenceElements(functionValue) !== undefined;
848
- if (isTuple) {
974
+ if (getFunctionClass(left) === "tuple") {
849
975
  const tuple = isFunctionValue(right) ? getSequenceElements(right) : undefined;
850
976
  if (!tuple) return compareTlcFunctions({ ...functionValue, low: 1 }, left, right);
851
977
  return (
@@ -868,14 +994,13 @@ const compareFunctionLikeTlc = (left: FunctionValue | LazyFunctionValue, right:
868
994
  );
869
995
  }
870
996
  return compareTlcFunctions(
871
- { ...functionValue, low: getIntervalLow(functionValue.domain) },
997
+ { ...functionValue, low: getIntervalLow(left, functionValue.domain) },
872
998
  left,
873
999
  right,
874
1000
  );
875
1001
  };
876
1002
 
877
- // TLC compares a lazy set, or a set it overrides in Java, through its own class before it compares
878
- // 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.
879
1004
  const isComparedByClass = (left: ObjectValue, right: Value) =>
880
1005
  isOverriddenSet(left) ||
881
1006
  isOverriddenSet(right) ||
@@ -959,8 +1084,7 @@ const equalsTlcFunctions = (functionValue: TlcFunction, left: Value, right: Valu
959
1084
 
960
1085
  const equalsFunctionLikeTlc = (left: FunctionValue | LazyFunctionValue, right: Value) => {
961
1086
  const functionValue = toFiniteFunction(left);
962
- const isTuple = left.kind === "Function" && getSequenceElements(functionValue) !== undefined;
963
- if (isTuple) {
1087
+ if (getFunctionClass(left) === "tuple") {
964
1088
  const tuple = isFunctionValue(right) ? getSequenceElements(right) : undefined;
965
1089
  if (!tuple) return equalsTlcFunctions({ ...functionValue, low: 1 }, left, right);
966
1090
  return (
@@ -983,7 +1107,7 @@ const equalsFunctionLikeTlc = (left: FunctionValue | LazyFunctionValue, right: V
983
1107
  );
984
1108
  }
985
1109
  return equalsTlcFunctions(
986
- { ...functionValue, low: getIntervalLow(functionValue.domain) },
1110
+ { ...functionValue, low: getIntervalLow(left, functionValue.domain) },
987
1111
  left,
988
1112
  right,
989
1113
  );
@@ -1026,7 +1150,6 @@ const sortLikeTlc = (elements: Value[]) => {
1026
1150
  return sorted;
1027
1151
  };
1028
1152
 
1029
- // Calls a method of a value as TLC does, whose failure the value heads when it has a source.
1030
1153
  const callTracedMethod = <Result>(receiver: Value, method: () => Result) => {
1031
1154
  const sets = setTrace.sets;
1032
1155
  if (sets === undefined) return method();
@@ -1036,8 +1159,7 @@ const callTracedMethod = <Result>(receiver: Value, method: () => Result) => {
1036
1159
  return result;
1037
1160
  };
1038
1161
 
1039
- // ValueVec.search on sorted elements: a binary search with compareTo, which ends where the element
1040
- // is or would go.
1162
+ // A binary search with compareTo, which ends where the element is or would go.
1041
1163
  const searchLikeTlc = (element: Value, sorted: Value[]) => {
1042
1164
  const bounds = { low: 0, high: sorted.length };
1043
1165
  while (bounds.low < bounds.high) {
@@ -1050,21 +1172,18 @@ const searchLikeTlc = (element: Value, sorted: Value[]) => {
1050
1172
  return { index: bounds.low, isFound: false };
1051
1173
  };
1052
1174
 
1053
- // TLC checks membership in a set enumeration it hasn't sorted element by element, with the equals
1054
- // method of each member.
1055
1175
  const isElementOfLikeTlc = (element: Value, elements: Value[]) =>
1056
1176
  elements.some((member) => callTracedMethod(member, () => equalsLikeTlc(member, element)));
1057
1177
 
1058
- // The sets TLC has normalized, whose membership ValueVec.search checks by binary search with
1059
- // compareTo instead of element by element.
1060
- 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);
1061
1182
 
1062
- // IValue.deepNormalize, which TLC applies to the constants of the config and the constant
1063
- // definitions it computes as it starts.
1064
1183
  export const markNormalized = (value: Value): void => {
1065
1184
  if (typeof value !== "object") return;
1066
1185
  if (value.kind === "Set") {
1067
- normalizedSets.add(value);
1186
+ value.isNormalized = true;
1068
1187
  value.elements.forEach(markNormalized);
1069
1188
  }
1070
1189
  if (value.kind === "Function") {
@@ -1073,6 +1192,33 @@ export const markNormalized = (value: Value): void => {
1073
1192
  }
1074
1193
  };
1075
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
+
1076
1222
  export const isEqualLikeTlc = (left: Value, right: Value) =>
1077
1223
  computeLikeTlcOnFailure(valuesEqual, equalsLikeTlc, left, right);
1078
1224
 
@@ -1083,8 +1229,19 @@ const isStrictlySorted = (elements: Value[]) => {
1083
1229
  return true;
1084
1230
  };
1085
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
+
1086
1243
  export const createSet = (elements: Value[]): SetValue => {
1087
- // 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.
1088
1245
  for (let index = 1; index < elements.length; index++) cacheSet(elements[index]);
1089
1246
  if (elements.length < 2 || isStrictlySorted(elements)) return createSortedSet(elements);
1090
1247
  const sorted = [...elements].sort(compareValues);
@@ -1095,15 +1252,18 @@ export const createSet = (elements: Value[]): SetValue => {
1095
1252
  return createSortedSet(unique);
1096
1253
  };
1097
1254
 
1098
- // TLC builds a set enumeration without sorting it, so one whose elements it can't compare still
1099
- // evaluates.
1100
- export const createEnumeratedSet = (elements: Value[]): SetValue | MixedSetValue =>
1101
- 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>(
1102
1259
  createSet,
1103
1260
  (mixed) => ({ kind: "MixedSet", elements: mixed }),
1104
1261
  elements,
1105
1262
  undefined,
1106
1263
  );
1264
+ if (set.kind === "Set" && set.elements !== elements) set.writtenElements = elements;
1265
+ return set;
1266
+ };
1107
1267
 
1108
1268
  export const EMPTY_SET = createSortedSet([]);
1109
1269
 
@@ -1219,7 +1379,6 @@ export const createWrittenFunction = (pairs: [Value, Value][]) => {
1219
1379
  const functionValue = createFunction(pairs);
1220
1380
  const isWrittenSorted =
1221
1381
  functionValue.domain.length !== pairs.length ||
1222
- pairs.some((pair) => typeof pair[0] !== "string") ||
1223
1382
  pairs.every((pair, index) => pair[0] === functionValue.domain[index]);
1224
1383
  return isWrittenSorted
1225
1384
  ? functionValue
@@ -1229,23 +1388,26 @@ export const createWrittenFunction = (pairs: [Value, Value][]) => {
1229
1388
  );
1230
1389
  };
1231
1390
 
1391
+ const MAX_SHARED_INTERVAL_LENGTH = 1024;
1232
1392
  const intervalDomains: Value[][] = [];
1393
+ const longIntervalDomains = new Map<number, WeakRef<Value[]>>();
1233
1394
  const intervalValues: IntervalValue[] = [];
1234
1395
  const intervalArrays = new WeakMap<Value[], IntervalValue>();
1235
1396
 
1236
- // TLC keeps the domain of a tuple, or of a function built over an interval, as an interval. Every
1237
- // function over 1..n shares one domain array per length, and the elements of any other interval
1238
- // 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.
1239
1401
  const getIntervalDomain = (length: number): Value[] => {
1240
- const cached = intervalDomains[length];
1402
+ const cached = intervalDomains[length] ?? longIntervalDomains.get(length)?.deref();
1241
1403
  if (cached) return cached;
1242
1404
  const domain = Array.from({ length }, (_, index) => index + 1);
1243
- intervalDomains[length] = domain;
1405
+ if (length > MAX_SHARED_INTERVAL_LENGTH) longIntervalDomains.set(length, new WeakRef(domain));
1406
+ else intervalDomains[length] = domain;
1244
1407
  return domain;
1245
1408
  };
1246
1409
 
1247
- // The elements of an interval for a caller that only iterates them, so they need not record
1248
- // the interval for DOMAIN.
1410
+ // The caller only iterates the elements, so they need not record the interval for DOMAIN.
1249
1411
  export const getIntervalElements = (value: IntervalValue): Value[] => {
1250
1412
  getCardinality(value);
1251
1413
  if (value.low === 1 && value.high >= 1) return getIntervalDomain(value.high);
@@ -1255,10 +1417,12 @@ export const getIntervalElements = (value: IntervalValue): Value[] => {
1255
1417
  };
1256
1418
 
1257
1419
  const isIntervalDomain = (domain: Value[]) =>
1258
- 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);
1259
1424
 
1260
- // TLC keeps an interval domain only for a function built over an interval itself, so a set
1261
- // 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.
1262
1426
  export const getFunctionDomain = (set: Value): Value[] => {
1263
1427
  const elements = toFiniteSet(set).elements;
1264
1428
  return isIntervalDomain(elements) && !(typeof set === "object" && set.kind === "Interval")
@@ -1283,7 +1447,6 @@ export const createRecord = (fields: [string, Value][]): FunctionValue =>
1283
1447
  export const createSortedRecord = (names: Value[], range: Value[]) =>
1284
1448
  setFunctionClass(createSortedFunction(names, range), "record");
1285
1449
 
1286
- // TLC's Enumerable classes: every set except the ones it implements in Java.
1287
1450
  export const isTlcEnumerable = (value: Value) => isSetValue(value) && !isOverriddenSet(value);
1288
1451
 
1289
1452
  const formatUnion = (value: UnionValue, isStrict = false) =>
@@ -1334,7 +1497,13 @@ export const isEnumerable = (value: Value): boolean => {
1334
1497
  case "ProductSet":
1335
1498
  return value.factors.every(isEnumerable) || getEmptiness(value) === true;
1336
1499
  case "Union":
1337
- 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
+ );
1338
1507
  case "SetOperation":
1339
1508
  if (value.operator === "\\cup") return isEnumerable(value.left) && isEnumerable(value.right);
1340
1509
  if (value.operator === "\\cap") return isEnumerable(value.left) || isEnumerable(value.right);
@@ -1407,15 +1576,14 @@ const advanceCombination = (indices: number[], length: number) => {
1407
1576
  return false;
1408
1577
  };
1409
1578
 
1410
- // TLC enumerates SUBSET S lazily, by size and then in the order of S, so a quantifier that finds
1411
- // its witness early never builds the rest. For a power set too large to build, the elements are
1412
- // 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.
1413
1581
  export const getLazySubsets = (value: Value): Value[] | undefined => {
1414
1582
  if (typeof value !== "object" || value.kind !== "Subset" || isOverriddenSet(value.base)) {
1415
1583
  return undefined;
1416
1584
  }
1417
1585
  const base = toFiniteSet(value.base).elements;
1418
- if (base.length <= MAXIMUM_ENUMERATED_SUBSET_BASE) return undefined;
1586
+ if (base.length <= MAXIMUM_BUILT_SUBSET_BASE) return undefined;
1419
1587
  const cursor = { index: -1, indices: [0] };
1420
1588
  const getSubset = (index: number) => {
1421
1589
  if (index <= cursor.index) cursor.index = -1;
@@ -1453,9 +1621,8 @@ const getSortedSubsets = (base: Value[]) => {
1453
1621
  return subsets;
1454
1622
  };
1455
1623
 
1456
- // The Enumerator of a set of records or tuples enumerates its sets in turn and stops at the first
1457
- // empty one, which leaves the product empty. Later versions of TLC decide that the set is empty
1458
- // 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.
1459
1626
  const getComponentElements = (
1460
1627
  sets: Value[],
1461
1628
  getElements: (set: Value) => Value[],
@@ -1472,7 +1639,6 @@ const getComponentElements = (
1472
1639
  return lists;
1473
1640
  };
1474
1641
 
1475
- // getElements enumerates the sets a set of functions, records, or tuples combines.
1476
1642
  const enumerateSet = (
1477
1643
  value: Value,
1478
1644
  getElements = (set: Value) => toFiniteSet(set).elements,
@@ -1490,8 +1656,7 @@ const enumerateSet = (
1490
1656
  return elements;
1491
1657
  }
1492
1658
  case "Subset": {
1493
- // SubsetValue.toSetEnum sizes the set before it enumerates it, and enumerates only the empty
1494
- // 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 {{}}.
1495
1660
  if (getCardinality(value.base) === 0) return getSortedSubsets([]);
1496
1661
  if (!isSetValue(value.base)) {
1497
1662
  throw new TlaEvaluationError(
@@ -1551,22 +1716,21 @@ const enumerateSet = (
1551
1716
  `Attempted to enumerate { x \\in S : p(x) } when S:\n${formatValue(value.base)}\nis not enumerable`,
1552
1717
  );
1553
1718
  }
1554
- 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;
1555
1724
  case "Union": {
1556
- const elements = getUnionSets(value).flatMap(
1557
- (set, index) => toFiniteSet(getUnionSet(set, index, value)).elements,
1558
- );
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
+ });
1559
1731
  return toFiniteSet(createEnumeratedSet(elements)).elements;
1560
1732
  }
1561
1733
  case "SetOperation": {
1562
- if (
1563
- value.operator === "\\cup" &&
1564
- (!isTlcEnumerable(value.left) || !isTlcEnumerable(value.right))
1565
- ) {
1566
- throw new TlaEvaluationError(
1567
- `Attempted to enumerate S \\cup T when S:\n${formatValue(value.left)}\nand T:\n${formatValue(value.right)}\nare not both enumerable`,
1568
- );
1569
- }
1570
1734
  if (
1571
1735
  value.operator === "\\cap" &&
1572
1736
  !isTlcEnumerable(value.left) &&
@@ -1582,19 +1746,23 @@ const enumerateSet = (
1582
1746
  );
1583
1747
  }
1584
1748
  if (value.operator === "\\cup") {
1585
- return computeLikeTlcOnFailure(
1586
- (union) => getSortedUnion(toFiniteSet(union.left), toFiniteSet(union.right)).elements,
1587
- (union) => sortLikeTlc(listUnionLikeTlc(union)),
1588
- value,
1589
- value,
1590
- );
1749
+ return toFiniteSet(createEnumeratedSet(listUnionLikeTlc(value))).elements;
1591
1750
  }
1592
1751
  const isLeftEnumerated = value.operator === "\\" || isTlcEnumerable(value.left);
1593
1752
  const enumerated = isLeftEnumerated ? value.left : value.right;
1594
1753
  const other = isLeftEnumerated ? value.right : value.left;
1595
- return toFiniteSet(enumerated).elements.filter(
1596
- (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
+ },
1597
1764
  );
1765
+ return toFiniteSet(createEnumeratedSet(kept)).elements;
1598
1766
  }
1599
1767
  case "InfiniteSet":
1600
1768
  case "SequenceSet":
@@ -1631,32 +1799,99 @@ export const toFiniteSet = (value: Value): SetValue => {
1631
1799
  return set;
1632
1800
  };
1633
1801
 
1634
- // SetCupValue#toSetEnum.
1635
- const listUnionLikeTlc = (union: SetOperationValue) => [
1636
- ...toFiniteSet(union.left).elements,
1637
- ...toFiniteSet(union.right).elements,
1638
- ];
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
+ };
1639
1851
 
1640
1852
  // EnumerableValue#elements(NORMALIZED) sorts a union outside its methods, so a failed comparison
1641
1853
  // isn't a fingerprint failure.
1642
- export const getNormalizedSetElements = (value: Value) =>
1643
- typeof value === "object" && value.kind === "SetOperation" && value.operator === "\\cup"
1644
- ? computeLikeTlcOnFailure(
1645
- (union) => toFiniteSet(union).elements,
1646
- (union) => sortLikeTlc(callTracedMethod(union, () => listUnionLikeTlc(union))),
1647
- value,
1648
- value,
1649
- )
1650
- : toFiniteSet(value).elements;
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
+ };
1651
1868
 
1652
- // TLC's Enumerator for a lazy set streams the sets it combines until the set caches its elements,
1653
- // so an element that two of them share comes up once for each.
1654
- export const getStreamedElements = (value: Value): Value[] => {
1655
- if (typeof value !== "object" || isCachedSet(value)) return toFiniteSet(value).elements;
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
+ }
1656
1875
  const sets = setTrace.sets;
1657
1876
  sets?.push(value);
1658
- 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
+ });
1659
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
+ });
1660
1895
  return elements;
1661
1896
  };
1662
1897
 
@@ -1669,10 +1904,9 @@ const getCombinedSets = (value: ObjectValue) =>
1669
1904
  ? [value.range]
1670
1905
  : undefined;
1671
1906
 
1672
- // Whether a value TLC builds alike at each evaluation and that enumerating, comparing or
1673
- // fingerprinting it leaves alike, so that one evaluation can stand for the next. It holds no UNION or
1674
- // \cup, which streams until TLC caches it, no lambda, which fingerprinting turns into a record, and
1675
- // 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.
1676
1910
  export const isSettledValue = (value: Value): boolean => {
1677
1911
  if (typeof value !== "object") return true;
1678
1912
  switch (value.kind) {
@@ -1701,8 +1935,7 @@ export const isSettledValue = (value: Value): boolean => {
1701
1935
  }
1702
1936
  };
1703
1937
 
1704
- // Whether a set streams its elements in another order than the normalized set, so that a set of
1705
- // 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.
1706
1939
  const isStreamedApart = (value: Value): boolean => {
1707
1940
  if (typeof value !== "object" || isCachedSet(value)) return false;
1708
1941
  if (value.kind === "Union") return true;
@@ -1715,31 +1948,36 @@ const isStreamedApart = (value: Value): boolean => {
1715
1948
  return getCombinedSets(value)?.some(isStreamedApart) ?? false;
1716
1949
  };
1717
1950
 
1718
- const streamElements = (value: ObjectValue): Value[] => {
1719
- // TLC streams the sets of a UNION it hasn't enumerated, so a set that appears twice there yields
1720
- // 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.
1721
1953
  if (value.kind === "Union") {
1722
- return getUnionSets(value, getStreamedElements).flatMap((set, index) =>
1723
- getStreamedElements(getUnionSet(set, index, value)),
1954
+ return getUnionSets(value, getStreamedElements).some((set, index) =>
1955
+ someStreamedElement(getUnionSet(set, index, value), visit),
1724
1956
  );
1725
1957
  }
1726
- if (value.kind === "FilteredSet" && !isOverriddenSet(value.base)) {
1727
- 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
+ );
1728
1963
  }
1729
1964
  const components = getCombinedSets(value);
1730
- if (components?.some(isStreamedApart)) return enumerateSet(value, getStreamedElements);
1731
- 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);
1732
1969
  if (value.operator === "\\cup") {
1733
1970
  return !isTlcEnumerable(value.left) || !isTlcEnumerable(value.right)
1734
- ? toFiniteSet(value).elements
1735
- : [...getStreamedElements(value.left), ...getStreamedElements(value.right)];
1971
+ ? toFiniteSet(value).elements.some(visit)
1972
+ : someStreamedElement(value.left, visit) || someStreamedElement(value.right, visit);
1736
1973
  }
1737
1974
  const isLeftEnumerated = value.operator === "\\" || isTlcEnumerable(value.left);
1738
1975
  const enumerated = isLeftEnumerated ? value.left : value.right;
1739
1976
  const other = isLeftEnumerated ? value.right : value.left;
1740
- if (!isTlcEnumerable(enumerated)) return toFiniteSet(value).elements;
1741
- return getStreamedElements(enumerated).filter(
1742
- (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),
1743
1981
  );
1744
1982
  };
1745
1983
 
@@ -1788,8 +2026,7 @@ const getProductCardinality = (
1788
2026
  const describeOverflow = (value: Value) =>
1789
2027
  `Overflow when computing the number of elements in:\n${formatValue(value)}`;
1790
2028
 
1791
- // TLC 1.7.4 sizes every component of a set of functions, records, or tuples without first
1792
- // 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.
1793
2030
  export const getCardinality = (value: Value, version?: TlcVersion): number => {
1794
2031
  if (typeof value !== "object") {
1795
2032
  throw new TlaEvaluationError(
@@ -1938,8 +2175,34 @@ const findSortedIndex = (sortedValues: Value[], target: Value, compare = compare
1938
2175
  return -1;
1939
2176
  };
1940
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
+
1941
2196
  export const getSequenceElements = (value: Value): Value[] | undefined => {
1942
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
+ }
1943
2206
  const functionValue = toFiniteFunction(value);
1944
2207
  return functionValue.domain.every((key, index) => key === index + 1)
1945
2208
  ? functionValue.range
@@ -1957,24 +2220,21 @@ const describeNonSetMembership = (element: Value, value: Value) => {
1957
2220
  return `${prefix} function ${formatValue(value)}`;
1958
2221
  };
1959
2222
 
1960
- // The call stack of the replay, which a failed fast path leaves frozen.
1961
2223
  interface TracedCallStack {
1962
2224
  expressions: unknown[];
1963
2225
  isFrozen: boolean;
2226
+ sources: WeakMap<ObjectValue, unknown>;
1964
2227
  fingerprint?: unknown;
1965
2228
  }
1966
2229
 
1967
- // The sets whose membership is being checked or whose elements are being enumerated, and the
1968
- // members being compared, outermost first, while TLC's CallStackTool replays a computation. A failed
1969
- // check or enumeration leaves the values it was in, each of which TLC adds to the
1970
- // 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.
1971
2232
  export const setTrace: { sets: Value[] | undefined; callStack?: TracedCallStack } = {
1972
2233
  sets: undefined,
1973
2234
  };
1974
2235
 
1975
- // Takes a fast path, and computes as TLC does where it fails. TLC never takes the fast path, so
1976
- // the failure's leftovers in the replay's trace go first. Both paths take their operands as
1977
- // 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.
1978
2238
  export const computeLikeTlcOnFailure = <Left, Right, Result>(
1979
2239
  compute: (left: Left, right: Right) => Result,
1980
2240
  computeLikeTlc: (left: Left, right: Right, error: TlaEvaluationError) => Result,
@@ -1999,6 +2259,11 @@ export const computeLikeTlcOnFailure = <Left, Right, Result>(
1999
2259
  }
2000
2260
  };
2001
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
+
2002
2267
  export const isElementOf = (element: Value, set: Value): boolean => {
2003
2268
  const sets = setTrace.sets;
2004
2269
  if (sets === undefined) return isElementOfSet(element, set);
@@ -2008,26 +2273,60 @@ export const isElementOf = (element: Value, set: Value): boolean => {
2008
2273
  return isElement;
2009
2274
  };
2010
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
+
2011
2291
  const isInSortedSet = (element: Value, set: SetValue) =>
2012
2292
  findSortedIndex(set.elements, element) !== -1;
2013
2293
 
2014
2294
  const isInSortedSetLikeTlc = (element: Value, set: SetValue) =>
2015
- normalizedSets.has(set)
2295
+ set.isNormalized
2016
2296
  ? searchLikeTlc(element, set.elements).isFound
2017
- : 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
+ };
2018
2307
 
2308
+ // The common cases stay small enough for V8 to inline.
2019
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 => {
2020
2319
  if (!isSetValue(set)) throw new TlaEvaluationError(describeNonSetMembership(element, set));
2021
2320
  switch (set.kind) {
2022
2321
  case "Set":
2023
- // SetEnumValue.member compares the element with the set's.
2322
+ // TLC compares the element with the set's.
2024
2323
  cacheSet(element);
2025
2324
  return computeLikeTlcOnFailure(isInSortedSet, isInSortedSetLikeTlc, element, set);
2026
2325
  case "MixedSet":
2027
2326
  return isElementOfLikeTlc(element, set.elements);
2028
2327
  case "Interval":
2029
2328
  if (typeof element === "number") return element >= set.low && element <= set.high;
2030
- if (set.low <= set.high && !isModelValue(element)) {
2329
+ if (set.low <= set.high && (!isModelValue(element) || element.type !== undefined)) {
2031
2330
  throw new TlaEvaluationError(
2032
2331
  `Attempted to check if the value:\n${formatValue(element)}\nis in the integer interval ${formatValue(set)}`,
2033
2332
  );
@@ -2035,19 +2334,18 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2035
2334
  return false;
2036
2335
  case "InfiniteSet": {
2037
2336
  if (set.name === "Any") return true;
2038
- if (isModelValue(element)) return false;
2337
+ if (isModelValue(element)) return isModelValueMember(element, set);
2039
2338
  const isMemberType =
2040
2339
  set.name === "STRING" ? typeof element === "string" : typeof element === "number";
2041
2340
  if (!isMemberType) {
2042
- throw new TlaEvaluationError(
2341
+ throw new TlaModuleError(
2043
2342
  `Attempted to check if the value:\n${formatValue(element)}\nis an element of ${set.name}.`,
2044
2343
  );
2045
2344
  }
2046
2345
  return set.name !== "Nat" || (typeof element === "number" && element >= 0);
2047
2346
  }
2048
2347
  case "Subset":
2049
- // SubsetValue.member fails on any value that is not Enumerable, model values and the sets a
2050
- // Java class overrides included.
2348
+ // TLC fails on a value that isn't Enumerable, model values and Java-overridden sets included.
2051
2349
  if (!isSetValue(element) || isOverriddenSet(element)) {
2052
2350
  throw new TlaEvaluationError(
2053
2351
  `Attempted to check if the non-enumerable value\n${prettyPrint(formatValue(element))}\nis element of\n${prettyPrint(formatValue(set))}`,
@@ -2056,14 +2354,14 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2056
2354
  return toFiniteSet(element).elements.every((item) => isElementOf(item, set.base));
2057
2355
  case "FunctionSet": {
2058
2356
  if (!isFunctionValue(element)) {
2059
- if (isModelValue(element)) return false;
2060
- // SetOfFcnsValue.member prints the element without Values.ppr.
2357
+ if (isModelValue(element)) return isModelValueMember(element, set);
2358
+ // TLC prints the element without Values.ppr.
2061
2359
  throw new TlaEvaluationError(
2062
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))}`,
2063
2361
  );
2064
2362
  }
2065
2363
  const functionValue = toFiniteFunction(element);
2066
- const low = getIntervalLow(functionValue.domain);
2364
+ const low = getIntervalLow(element, functionValue.domain);
2067
2365
  const isDomain =
2068
2366
  low === undefined
2069
2367
  ? isEqualLikeTlc(set.domain, createSortedSet(functionValue.domain))
@@ -2076,7 +2374,7 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2076
2374
  case "RecordSet": {
2077
2375
  const functionValue = isFunctionValue(element) ? toFiniteFunction(element) : undefined;
2078
2376
  if (!functionValue || !isRecordDomain(functionValue.domain)) {
2079
- if (isModelValue(element)) return false;
2377
+ if (isModelValue(element)) return isModelValueMember(element, set);
2080
2378
  throw new TlaEvaluationError(
2081
2379
  `Attempted to check if non-record\n${formatValue(element)}\nis in the set of records:\n${formatValue(set)}`,
2082
2380
  );
@@ -2095,7 +2393,8 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2095
2393
  const isFunction =
2096
2394
  isFunctionValue(element) &&
2097
2395
  toFiniteFunction(element).domain.every((key) => typeof key === "number");
2098
- if (isFunction || isModelValue(element)) return false;
2396
+ if (isModelValue(element)) return isModelValueMember(element, set);
2397
+ if (isFunction) return false;
2099
2398
  throw new TlaEvaluationError(
2100
2399
  `Attempted to check if non-tuple\n${formatValue(element)}\nis in the set of tuples:\n${formatValue(set)}`,
2101
2400
  );
@@ -2106,14 +2405,29 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2106
2405
  );
2107
2406
  }
2108
2407
  case "FilteredSet":
2109
- return isElementOf(element, set.base) && set.test(element);
2110
- 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": {
2111
2417
  if (!isTlcEnumerable(set.base)) {
2112
2418
  throw new TlaEvaluationError(
2113
2419
  `Attempted to check if:\n ${formatValue(element)}\nis an element of the non-enumerable set:\n ${formatUnion(set)}`,
2114
2420
  );
2115
2421
  }
2116
- 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
+ }
2117
2431
  case "SetOperation":
2118
2432
  if (set.operator === "\\cup")
2119
2433
  return isElementOf(element, set.left) || isElementOf(element, set.right);
@@ -2124,9 +2438,9 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2124
2438
  case "SequenceSet": {
2125
2439
  const elements = getSequenceElements(element);
2126
2440
  if (elements === undefined) {
2127
- if (isModelValue(element)) return false;
2128
- // Sequences.member raises TLC_MODULE_CHECK_MEMBER_OF.
2129
- throw new TlaEvaluationError(
2441
+ if (isModelValue(element)) return isModelValueMember(element, set);
2442
+ // TLC raises TLC_MODULE_CHECK_MEMBER_OF.
2443
+ throw new TlaModuleError(
2130
2444
  `Attempted to check if the value:\n${prettyPrint(formatValue(element))}\nis an element of ${prettyPrint(formatValue(set))}.`,
2131
2445
  );
2132
2446
  }
@@ -2137,8 +2451,6 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2137
2451
  }
2138
2452
  };
2139
2453
 
2140
- // A function that agrees with a member of a function set outside some entries is a member when
2141
- // those entries are.
2142
2454
  export const isUpdatedElementOf = (element: Value, member: Value, set: Value): boolean => {
2143
2455
  if (element === member) return true;
2144
2456
  if (
@@ -2161,6 +2473,9 @@ export const toFiniteFunction = (value: Value): FunctionValue => {
2161
2473
  if (typeof value === "object" && value.kind === "LazyFunction") {
2162
2474
  if (value.enumerated) return value.enumerated;
2163
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
+ }
2164
2479
  const domain = getFunctionDomain(value.domain);
2165
2480
  value.enumerated = setFunctionClass(
2166
2481
  createSortedFunction(
@@ -2232,22 +2547,29 @@ export const createNonIntegerKeyError = (argument: Value) =>
2232
2547
  `Attempted to apply function with integer domain to the non-integer argument ${prettyPrint(formatValue(argument))}`,
2233
2548
  );
2234
2549
 
2235
- // TLC's FcnRcdValue searches a domain this small linearly with equals, and a larger normalized one by
2236
- // binary search with compareTo.
2550
+ // TLC searches a domain this small linearly with equals, and a larger one with compareTo.
2237
2551
  const LINEAR_SEARCH_LIMIT = 32;
2238
2552
 
2239
- const failKeyLikeTlc = (domain: Value[], argument: Value, error: TlaEvaluationError): never => {
2240
- if (valueVersion.is174 || domain.length < LINEAR_SEARCH_LIMIT) {
2241
- 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));
2242
2565
  } else {
2243
- findSortedIndex(domain, argument, compareLikeTlc);
2566
+ findSortedIndex(keys, argument, compareLikeTlc);
2244
2567
  }
2245
2568
  throw error;
2246
2569
  };
2247
2570
 
2248
- // TLC looks a key up by the Java class of the function: a tuple or a record rejects a key of the
2249
- // wrong type, and another function rejects a non-integer for a domain it keeps as an interval, which
2250
- // 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.
2251
2573
  const findKeyIndexLikeTlc = (
2252
2574
  functionValue: FunctionValue,
2253
2575
  argument: Value,
@@ -2261,21 +2583,87 @@ const findKeyIndexLikeTlc = (
2261
2583
  if (keyType !== undefined && typeof argument !== keyType) {
2262
2584
  throw new TlaEvaluationError(describeWrongKey(functionValue, argument));
2263
2585
  }
2264
- if (keyType === undefined && !valueVersion.is174 && isIntervalDomain(domain)) {
2586
+ if (
2587
+ keyType === undefined &&
2588
+ !valueVersion.is174 &&
2589
+ typeof argument !== "number" &&
2590
+ isIntervalDomain(domain)
2591
+ ) {
2265
2592
  throw createNonIntegerKeyError(argument);
2266
2593
  }
2267
2594
  }
2268
2595
  const identical = findIdenticalKey(domain, argument);
2269
2596
  if (identical !== -1) return identical;
2270
- return computeLikeTlcOnFailure(findSortedIndex, failKeyLikeTlc, domain, argument);
2597
+ return computeLikeTlcOnFailure(findDomainIndex, failKeyLikeTlc, functionValue, argument);
2271
2598
  };
2272
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
+
2273
2653
  export const applyFunction = (
2274
2654
  functionValue: Value,
2275
2655
  argument: Value,
2276
2656
  describeMissing?: (functionValue: FunctionValue, argument: Value) => string,
2277
2657
  ): Value => {
2278
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
+ }
2279
2667
  if (!isElementOf(argument, functionValue.domain)) {
2280
2668
  throw new TlaEvaluationError(
2281
2669
  getFunctionClass(functionValue) === "lambda"
@@ -2291,6 +2679,9 @@ export const applyFunction = (
2291
2679
  );
2292
2680
  }
2293
2681
  const describe = describeMissing ?? describeMissingArgument;
2682
+ if (isOutsideLambdaDomain(functionValue, argument)) {
2683
+ throw new TlaEvaluationError(describe(functionValue, argument));
2684
+ }
2294
2685
  const position = findKeyIndexLikeTlc(functionValue, argument, describe);
2295
2686
  if (position === -1) throw new TlaEvaluationError(describe(functionValue, argument));
2296
2687
  return functionValue.range[position];
@@ -2304,8 +2695,18 @@ export const getDomainInterval = (domain: Value[]) =>
2304
2695
  export const getDomain = (functionValue: Value): Value => {
2305
2696
  if (typeof functionValue === "object" && functionValue.kind === "LazyFunction")
2306
2697
  return functionValue.domain;
2307
- const domain = toFiniteFunction(functionValue).domain;
2308
- 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;
2309
2710
  };
2310
2711
 
2311
2712
  export const updateFunction = (
@@ -2317,7 +2718,7 @@ export const updateFunction = (
2317
2718
  const isLazy =
2318
2719
  typeof functionValue === "object" &&
2319
2720
  functionValue.kind === "LazyFunction" &&
2320
- (isKeptLazy || !isEnumerable(functionValue.domain));
2721
+ (isKeptLazy || functionValue.enumerated === undefined);
2321
2722
  if (isLazy) {
2322
2723
  if (!isElementOf(argument, functionValue.domain)) return functionValue;
2323
2724
  const updated = update(functionValue.apply(argument));
@@ -2327,6 +2728,7 @@ export const updateFunction = (
2327
2728
  domain: functionValue.domain,
2328
2729
  apply: (key) => (isEqualLikeTlc(argument, key) ? updated : functionValue.apply(key)),
2329
2730
  source: functionValue.source,
2731
+ boundTupleLengths: functionValue.boundTupleLengths,
2330
2732
  },
2331
2733
  getFunctionClass(functionValue),
2332
2734
  );
@@ -2337,6 +2739,7 @@ export const updateFunction = (
2337
2739
  );
2338
2740
  }
2339
2741
  const finite = toFiniteFunction(functionValue);
2742
+ if (isOutsideLambdaDomain(finite, argument)) return finite;
2340
2743
  const position = findKeyIndexLikeTlc(finite, argument, describeExceptKey);
2341
2744
  if (position === -1) return finite;
2342
2745
  const range = [...finite.range];
@@ -2348,6 +2751,7 @@ export const updateFunction = (
2348
2751
  getFunctionClass(finite),
2349
2752
  );
2350
2753
  updated.writtenKeys = finite.writtenKeys;
2754
+ updated.lambdaDomain = finite.lambdaDomain;
2351
2755
  if (finite.hash !== 0 && finite.hash !== UNFINGERPRINTABLE_HASH) {
2352
2756
  const nextHash = getValueHash(next);
2353
2757
  if (nextHash !== UNFINGERPRINTABLE_HASH) {
@@ -2400,9 +2804,8 @@ const getElementContribution = (elementHash: number) =>
2400
2804
  const getEntryContribution = (keyHash: number, valueHash: number) =>
2401
2805
  finalizeHash((Math.imul(keyHash, 0x27d4eb2d) + valueHash) | 0);
2402
2806
 
2403
- // The hash of each value that TLC fails to fingerprint, such as Nat or a set that holds it. Calls
2404
- // with such a value as an argument still share their result, and a state that holds one fails
2405
- // 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.
2406
2809
  const UNFINGERPRINTABLE_HASH = 0x2f6b1c4d;
2407
2810
 
2408
2811
  const computeValueHash = (value: SetValue | FunctionValue) => {
@@ -2428,8 +2831,7 @@ const computeValueHash = (value: SetValue | FunctionValue) => {
2428
2831
  return hash;
2429
2832
  };
2430
2833
 
2431
- // TLC's fingerPrint enumerates each set and function a value holds, and fails on Nat, Seq(S) and
2432
- // the like, which it never enumerates.
2834
+ // TLC enumerates each set and function, and fails on Nat, Seq(S) and the like.
2433
2835
  const fingerprintValue = (value: Value): void => {
2434
2836
  if (typeof value !== "object" || value.kind === "ModelValue") return;
2435
2837
  if (value.kind === "InfiniteSet" || value.kind === "SequenceSet") {
@@ -2446,8 +2848,7 @@ const fingerprintValue = (value: Value): void => {
2446
2848
  functionValue.range.forEach(fingerprintValue);
2447
2849
  };
2448
2850
 
2449
- // The error TLC raises as it fingerprints a value: one that hashing the value raises, as for a set
2450
- // 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.
2451
2852
  export const getFingerprintError = (value: Value) => {
2452
2853
  if (typeof value !== "object" || value.kind === "ModelValue") return undefined;
2453
2854
  try {
@@ -2459,7 +2860,6 @@ export const getFingerprintError = (value: Value) => {
2459
2860
  }
2460
2861
  };
2461
2862
 
2462
- // The values a value holds, which TLC fingerprints as it fingerprints the value.
2463
2863
  export const getHeldValues = (value: ObjectValue): Value[] => {
2464
2864
  switch (value.kind) {
2465
2865
  case "Set":
@@ -2580,8 +2980,17 @@ const computeValueKey = (value: ObjectValue) => {
2580
2980
  return `(${functionValue.domain.map((key, index) => `${getValueKey(key)}:${getValueKey(functionValue.range[index])}`).join(",")})`;
2581
2981
  };
2582
2982
 
2983
+ const PRINTED_ESCAPES: Record<string, string> = {
2984
+ '"': '\\"',
2985
+ "\\": "\\\\",
2986
+ "\t": "\\t",
2987
+ "\n": "\\n",
2988
+ "\f": "\\f",
2989
+ "\r": "\\r",
2990
+ };
2991
+
2583
2992
  const formatString = (value: string) =>
2584
- `"${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])}"`;
2585
2994
 
2586
2995
  type LazySetValue =
2587
2996
  | SubsetValue
@@ -2607,23 +3016,27 @@ const expandLazySet = (value: LazySetValue) => {
2607
3016
  if (value.kind === "SetOperation" || value.kind === "FilteredSet" || value.kind === "Union") {
2608
3017
  return toFiniteSet(value);
2609
3018
  }
2610
- if (
2611
- value.kind === "FunctionSet" &&
2612
- isEnumerable(value.domain) &&
2613
- getCardinality(value.domain) === 0
2614
- ) {
2615
- 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;
2616
3024
  }
2617
- const size =
2618
- value.kind === "FunctionSet"
2619
- ? getCardinality(value.range) ** getCardinality(value.domain)
2620
- : getProductSize(value.kind === "RecordSet" ? value.sets : value.factors);
2621
- if (size === 0) return EMPTY_SET;
3025
+ const size = getProductSize(value.kind === "RecordSet" ? value.sets : value.factors);
2622
3026
  return size <= MAXIMUM_EXPANDED_PRODUCT ? toFiniteSet(value) : undefined;
2623
3027
  };
2624
3028
 
2625
3029
  const getExpandedLazySet = (value: LazySetValue, isStrict: boolean) => {
2626
- 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
+ }
2627
3040
  // TLC prints a set it can't enumerate symbolically, except in Print, PrintT, and ToString.
2628
3041
  if (!isEnumerable(value)) return undefined;
2629
3042
  try {
@@ -2658,24 +3071,78 @@ const formatLazySet = (value: LazySetValue, isStrict: boolean): string => {
2658
3071
  }
2659
3072
  };
2660
3073
 
2661
- // FcnRcdValue#isName: TLC prints a function as a record when every key consists of letters,
2662
- // 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.
2663
3075
  const isFieldName = (name: string) =>
2664
3076
  /^[\p{L}\p{Nd}_]*$/u.test(name) &&
2665
3077
  /\p{L}/u.test(name) &&
2666
3078
  (name.length < 4 || !/^[WS]F_/.test(name));
2667
3079
 
2668
- // FcnLambdaValue#toString prints a function it fails to enumerate as its parameters and body.
2669
3080
  const toPrintedFunction = (value: LazyFunctionValue) => {
2670
3081
  if (!isEnumerable(value.domain)) return undefined;
2671
3082
  try {
2672
3083
  return toFiniteFunction(value);
2673
3084
  } catch (error) {
2674
- if (error instanceof TlaEvaluationError) return undefined;
3085
+ if (error instanceof TlaEvaluationError || isStackOverflow(error)) return undefined;
2675
3086
  throw error;
2676
3087
  }
2677
3088
  };
2678
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
+
2679
3146
  export const formatValue = (value: Value, isStrict = false, isNormalized = false): string => {
2680
3147
  const format = (inner: Value) => formatValue(inner, isStrict, isNormalized);
2681
3148
  if (typeof value === "boolean") return value ? "TRUE" : "FALSE";
@@ -2699,7 +3166,7 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
2699
3166
  case "SetOperation":
2700
3167
  case "FilteredSet":
2701
3168
  case "Union": {
2702
- const expanded = getExpandedLazySet(value, isStrict);
3169
+ const expanded = printing.isExpanded ? getExpandedLazySet(value, isStrict) : undefined;
2703
3170
  return expanded ? format(expanded) : formatLazySet(value, isStrict);
2704
3171
  }
2705
3172
 
@@ -2707,7 +3174,12 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
2707
3174
  return `Seq(${format(value.base)})`;
2708
3175
  case "Function":
2709
3176
  case "LazyFunction": {
2710
- 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;
2711
3183
  if (functionValue === undefined) {
2712
3184
  const source = value.kind === "LazyFunction" ? value.source : undefined;
2713
3185
  if (!source) return "<function>";
@@ -2726,34 +3198,112 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
2726
3198
  // TLC normalizes a lambda's domain to print it, but evaluates its body afterward.
2727
3199
  const formatRange = (inner: Value) =>
2728
3200
  formatValue(inner, isStrict, isNormalized && getFunctionClass(value) !== "lambda");
3201
+ if (functionValue.domain.length === 0 && getFunctionClass(value) === "record") return "[]";
2729
3202
  if (functionValue.domain.every((key, index) => key === index + 1)) {
2730
3203
  return `<<${functionValue.range.map(formatRange).join(", ")}>>`;
2731
3204
  }
2732
- // A RecordValue prints as a record whatever its fields, and a FcnRcdValue only if each key
2733
- // 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.
2734
3209
  if (
2735
3210
  getFunctionClass(value) === "record" ||
2736
3211
  functionValue.domain.every((key) => typeof key === "string" && isFieldName(key))
2737
3212
  ) {
2738
- const isSorted =
2739
- isNormalized || functionValue.hash !== 0 || functionValue.fingerprint !== 0;
2740
- const pairs = isSorted
2741
- ? functionValue.domain.map((key, index) => [key, functionValue.range[index]])
2742
- : getWrittenPairs(functionValue);
2743
3213
  return `[${pairs.map((pair) => `${String(pair[0])} |-> ${formatRange(pair[1])}`).join(", ")}]`;
2744
3214
  }
2745
- 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(" @@ ")})`;
2746
3216
  }
2747
3217
  }
2748
3218
  };
2749
3219
 
2750
- // TLC's TLCState.toString: a line per variable, as a conjunction when there are several.
2751
- 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();
2752
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
+ }
2753
3296
  return entries
2754
- .map(
2755
- ([name, value]) =>
2756
- `${entries.length === 1 ? "" : "/\\ "}${name} = ${prettyPrint(formatValue(value))}\n`,
2757
- )
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
+ })
2758
3308
  .join("");
2759
3309
  };