tla-ts 0.0.9 → 0.0.10-dev.06b481ee0

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 (631) hide show
  1. package/README.md +30 -1
  2. package/dist/compile.cjs +23 -0
  3. package/dist/compile.js +23 -0
  4. package/dist/deciders.cjs +41 -37
  5. package/dist/deciders.js +48 -44
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +122 -12
  8. package/dist/index.d.ts +122 -12
  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 +2746 -410
  15. package/dist/prove.js +2745 -409
  16. package/dist/run.cjs +144 -31
  17. package/dist/run.js +144 -31
  18. package/dist/tlapm.cjs +2 -2
  19. package/dist/tlapm.js +2 -2
  20. package/dist/transfer.cjs +134 -104
  21. package/dist/transfer.js +134 -104
  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 +56 -60
  26. package/src/bags.ts +128 -110
  27. package/src/builtins.ts +31 -77
  28. package/src/bundled-modules.ts +1 -8
  29. package/src/check-failure.ts +118 -0
  30. package/src/check-trace.ts +320 -0
  31. package/src/check.ts +1156 -888
  32. package/src/cli/options.ts +12 -32
  33. package/src/cli/run.ts +0 -2
  34. package/src/cli/runtime-invariants.ts +100 -0
  35. package/src/cli/shared.ts +19 -12
  36. package/src/cli/tlapm.ts +433 -82
  37. package/src/cli/tlc-arguments.ts +652 -0
  38. package/src/cli/tlc-output.ts +701 -0
  39. package/src/cli/tlc-usage.ts +360 -0
  40. package/src/cli/tlc.ts +330 -659
  41. package/src/cli/typescript.ts +23 -0
  42. package/src/cli/xml-exporter.ts +27 -49
  43. package/src/cli.ts +0 -1
  44. package/src/codegen.ts +217 -82
  45. package/src/config.ts +140 -109
  46. package/src/coverage.ts +1019 -0
  47. package/src/dependencies.ts +101 -66
  48. package/src/dfid.ts +683 -0
  49. package/src/environment-config.ts +315 -0
  50. package/src/environment.ts +263 -370
  51. package/src/errors.ts +107 -57
  52. package/src/evaluate.ts +898 -369
  53. package/src/exit-codes.ts +63 -13
  54. package/src/fingerprints.ts +75 -11
  55. package/src/index.ts +3 -0
  56. package/src/instances.ts +137 -22
  57. package/src/java-hash.ts +21 -0
  58. package/src/java-overrides.ts +6 -21
  59. package/src/json-reader.ts +455 -0
  60. package/src/json.ts +252 -139
  61. package/src/levels.ts +231 -154
  62. package/src/lexer.ts +83 -101
  63. package/src/liveness-checker.ts +743 -322
  64. package/src/liveness.ts +230 -133
  65. package/src/obligations/action.ts +17 -44
  66. package/src/obligations/anonymize.ts +120 -95
  67. package/src/obligations/enabled-axioms.ts +218 -0
  68. package/src/obligations/equality.ts +1 -3
  69. package/src/obligations/expression.ts +37 -26
  70. package/src/obligations/format.ts +0 -10
  71. package/src/obligations/generate.ts +66 -64
  72. package/src/obligations/index.ts +39 -20
  73. package/src/obligations/levels.ts +27 -18
  74. package/src/obligations/module.ts +28 -55
  75. package/src/obligations/normalize.ts +31 -41
  76. package/src/obligations/operators.ts +0 -3
  77. package/src/obligations/pragma.ts +52 -24
  78. package/src/obligations/printer.ts +94 -63
  79. package/src/obligations/proof.ts +3 -6
  80. package/src/obligations/regroup.ts +0 -5
  81. package/src/obligations/simplify.ts +57 -63
  82. package/src/obligations/source.ts +121 -95
  83. package/src/obligations/subexpression.ts +49 -28
  84. package/src/obligations/substitution.ts +1 -5
  85. package/src/obligations/temporal.ts +12 -20
  86. package/src/obligations/tuples.ts +2 -10
  87. package/src/parallel-worker.ts +36 -60
  88. package/src/parallel.ts +64 -73
  89. package/src/parser.ts +1184 -531
  90. package/src/pcal/ast.ts +53 -86
  91. package/src/pcal/parse.ts +144 -219
  92. package/src/pcal/tokenize.ts +91 -131
  93. package/src/pcal/translate.ts +83 -130
  94. package/src/pcal/validate.ts +48 -68
  95. package/src/pretty-print.ts +7 -8
  96. package/src/prover/decide-pool.ts +8 -13
  97. package/src/prover/deciders.ts +12 -13
  98. package/src/prover/first-order.ts +0 -11
  99. package/src/prover/isabelle/decide.ts +3 -31
  100. package/src/prover/isabelle/encode.ts +82 -64
  101. package/src/prover/isabelle/isar/attrib.ts +250 -0
  102. package/src/prover/isabelle/isar/context.ts +335 -0
  103. package/src/prover/isabelle/isar/induct.ts +382 -0
  104. package/src/prover/isabelle/isar/inner-syntax.ts +262 -117
  105. package/src/prover/isabelle/isar/method.ts +510 -226
  106. package/src/prover/isabelle/isar/proof.ts +570 -23
  107. package/src/prover/isabelle/isar/rule-cases.ts +226 -0
  108. package/src/prover/isabelle/isar/theory.ts +488 -88
  109. package/src/prover/isabelle/isar/toplevel.ts +331 -0
  110. package/src/prover/isabelle/isar/type-check.ts +99 -38
  111. package/src/prover/isabelle/provers/blast/blast.ts +16 -105
  112. package/src/prover/isabelle/provers/blast/branch.ts +0 -33
  113. package/src/prover/isabelle/provers/blast/prove.ts +0 -36
  114. package/src/prover/isabelle/provers/blast/rules.ts +5 -45
  115. package/src/prover/isabelle/provers/blast/state.ts +1 -29
  116. package/src/prover/isabelle/provers/blast/term.ts +8 -37
  117. package/src/prover/isabelle/provers/clasimp.ts +1 -15
  118. package/src/prover/isabelle/provers/classical.ts +58 -61
  119. package/src/prover/isabelle/provers/hypsubst.ts +29 -54
  120. package/src/prover/isabelle/pure/bicompose.ts +24 -39
  121. package/src/prover/isabelle/pure/consts.ts +0 -8
  122. package/src/prover/isabelle/pure/conv.ts +2 -18
  123. package/src/prover/isabelle/pure/drule.ts +95 -45
  124. package/src/prover/isabelle/pure/envir.ts +2 -53
  125. package/src/prover/isabelle/pure/goal.ts +1 -9
  126. package/src/prover/isabelle/pure/interrupt.ts +0 -5
  127. package/src/prover/isabelle/pure/list.ts +0 -3
  128. package/src/prover/isabelle/pure/logic.ts +1 -16
  129. package/src/prover/isabelle/pure/name.ts +1 -10
  130. package/src/prover/isabelle/pure/net.ts +2 -60
  131. package/src/prover/isabelle/pure/object-logic.ts +15 -16
  132. package/src/prover/isabelle/pure/pattern.ts +1 -20
  133. package/src/prover/isabelle/pure/raw-simplifier.ts +16 -63
  134. package/src/prover/isabelle/pure/rewriter.ts +34 -77
  135. package/src/prover/isabelle/pure/search.ts +2 -11
  136. package/src/prover/isabelle/pure/seq.ts +0 -11
  137. package/src/prover/isabelle/pure/simplifier.ts +27 -16
  138. package/src/prover/isabelle/pure/table.ts +2 -33
  139. package/src/prover/isabelle/pure/tactic.ts +11 -23
  140. package/src/prover/isabelle/pure/tactical.ts +47 -48
  141. package/src/prover/isabelle/pure/term-ord.ts +1 -7
  142. package/src/prover/isabelle/pure/term.ts +4 -47
  143. package/src/prover/isabelle/pure/thm.ts +26 -48
  144. package/src/prover/isabelle/pure/type.ts +1 -16
  145. package/src/prover/isabelle/pure/unify.ts +19 -31
  146. package/src/prover/isabelle/pure/variable.ts +2 -8
  147. package/src/prover/isabelle/tla/classical-setup.ts +17 -25
  148. package/src/prover/isabelle/tla/context.ts +65 -26
  149. package/src/prover/isabelle/tla/logic-data.ts +1 -1
  150. package/src/prover/isabelle/tla/logic.ts +53 -32
  151. package/src/prover/isabelle/tla/simpdata.ts +45 -44
  152. package/src/prover/isabelle/tools/intuitionistic.ts +28 -21
  153. package/src/prover/ocaml.ts +4 -7
  154. package/src/prover/prep/action.ts +33 -66
  155. package/src/prover/prep/enabled-axioms.ts +22 -20
  156. package/src/prover/prep/fingerprint.ts +2 -21
  157. package/src/prover/prep/level-comparison.ts +8 -12
  158. package/src/prover/prep/md5.ts +26 -31
  159. package/src/prover/prep/methods.ts +189 -86
  160. package/src/prover/prep/normalize.ts +42 -37
  161. package/src/prover/prove-worker.ts +0 -2
  162. package/src/prover/prove.ts +398 -133
  163. package/src/prover/ptl/decide.ts +96 -56
  164. package/src/prover/ptl/encode.ts +15 -38
  165. package/src/prover/ptl/sat.ts +24 -32
  166. package/src/prover/ptl/tableau.ts +40 -28
  167. package/src/prover/smt/arithmetic.ts +310 -0
  168. package/src/prover/smt/axioms.ts +12 -15
  169. package/src/prover/smt/context.ts +60 -32
  170. package/src/prover/smt/data.ts +517 -401
  171. package/src/prover/smt/encode.ts +155 -85
  172. package/src/prover/smt/extensionality.ts +5 -13
  173. package/src/prover/smt/flatten.ts +7 -28
  174. package/src/prover/smt/format.ts +33 -14
  175. package/src/prover/smt/instances.ts +7 -11
  176. package/src/prover/smt/layout.ts +91 -0
  177. package/src/prover/smt/rewrite.ts +1021 -658
  178. package/src/prover/smt/simplify.ts +441 -0
  179. package/src/prover/smt/solver/ackermannize-bv-tactic.ts +61 -0
  180. package/src/prover/smt/solver/ackr-helper.ts +179 -0
  181. package/src/prover/smt/solver/ackr-model-converter.ts +105 -0
  182. package/src/prover/smt/solver/act-cache.ts +0 -16
  183. package/src/prover/smt/solver/add-bounds-tactic.ts +59 -0
  184. package/src/prover/smt/solver/aig-tactic.ts +52 -0
  185. package/src/prover/smt/solver/aig.ts +889 -0
  186. package/src/prover/smt/solver/arith-rewriter.ts +626 -56
  187. package/src/prover/smt/solver/arith-terms.ts +121 -0
  188. package/src/prover/smt/solver/array-decl-plugin.ts +175 -0
  189. package/src/prover/smt/solver/array-rewriter.ts +319 -0
  190. package/src/prover/smt/solver/array.ts +1 -3
  191. package/src/prover/smt/solver/asserted-formulas.ts +241 -99
  192. package/src/prover/smt/solver/ast-lt.ts +165 -21
  193. package/src/prover/smt/solver/ast-util.ts +160 -7
  194. package/src/prover/smt/solver/ast.ts +1480 -184
  195. package/src/prover/smt/solver/auf-solver.ts +30 -56
  196. package/src/prover/smt/solver/bit-blast-tactic.ts +608 -0
  197. package/src/prover/smt/solver/bit-blaster.ts +871 -0
  198. package/src/prover/smt/solver/blast-term-ite.ts +47 -0
  199. package/src/prover/smt/solver/bound-manager.ts +196 -0
  200. package/src/prover/smt/solver/bound-simplifier.ts +598 -0
  201. package/src/prover/smt/solver/bv-bound-chk.ts +492 -0
  202. package/src/prover/smt/solver/bv-decl-plugin.ts +341 -0
  203. package/src/prover/smt/solver/bv-divrem-bounds.ts +95 -0
  204. package/src/prover/smt/solver/bv-rewriter.ts +1901 -0
  205. package/src/prover/smt/solver/bv1-blast.ts +214 -0
  206. package/src/prover/smt/solver/bv2fpa-converter.ts +174 -0
  207. package/src/prover/smt/solver/bv2int-rewriter.ts +544 -0
  208. package/src/prover/smt/solver/bv2real-rewriter.ts +533 -0
  209. package/src/prover/smt/solver/card2bv.ts +127 -0
  210. package/src/prover/smt/solver/case-split-queue.ts +0 -10
  211. package/src/prover/smt/solver/cg-table.ts +39 -42
  212. package/src/prover/smt/solver/check-logic.ts +330 -0
  213. package/src/prover/smt/solver/clause.ts +0 -27
  214. package/src/prover/smt/solver/cofactor-elim-term-ite.ts +293 -0
  215. package/src/prover/smt/solver/conflict-resolution.ts +78 -11
  216. package/src/prover/smt/solver/context.ts +600 -187
  217. package/src/prover/smt/solver/ctx-simplify.ts +34 -52
  218. package/src/prover/smt/solver/ctx-solver-simplify.ts +122 -0
  219. package/src/prover/smt/solver/datatype-decl-plugin.ts +580 -0
  220. package/src/prover/smt/solver/datatype-rewriter.ts +82 -0
  221. package/src/prover/smt/solver/demodulator.ts +786 -0
  222. package/src/prover/smt/solver/dependent-expr-state.ts +93 -0
  223. package/src/prover/smt/solver/der.ts +39 -30
  224. package/src/prover/smt/solver/diff-neq.ts +205 -0
  225. package/src/prover/smt/solver/distribute-forall.ts +57 -0
  226. package/src/prover/smt/solver/dom-simplify.ts +511 -0
  227. package/src/prover/smt/solver/dt2bv-tactic.ts +296 -0
  228. package/src/prover/smt/solver/dyn-ack.ts +0 -11
  229. package/src/prover/smt/solver/e-matching.ts +9 -41
  230. package/src/prover/smt/solver/elim-bounds.ts +89 -0
  231. package/src/prover/smt/solver/elim-small-bv-tactic.ts +129 -0
  232. package/src/prover/smt/solver/elim-term-ite-tactic.ts +48 -0
  233. package/src/prover/smt/solver/elim-uncnstr.ts +542 -0
  234. package/src/prover/smt/solver/enode.ts +100 -23
  235. package/src/prover/smt/solver/eq2bv-tactic.ts +218 -0
  236. package/src/prover/smt/solver/euf/arith-axioms.ts +403 -0
  237. package/src/prover/smt/solver/euf/arith-internalize.ts +653 -0
  238. package/src/prover/smt/solver/euf/arith-solver.ts +889 -0
  239. package/src/prover/smt/solver/euf/array-axioms.ts +527 -0
  240. package/src/prover/smt/solver/euf/array-internalize.ts +428 -0
  241. package/src/prover/smt/solver/euf/array-solver.ts +306 -0
  242. package/src/prover/smt/solver/euf/bv-ackerman.ts +162 -0
  243. package/src/prover/smt/solver/euf/bv-internalize.ts +748 -0
  244. package/src/prover/smt/solver/euf/bv-solver.ts +449 -0
  245. package/src/prover/smt/solver/euf/dt-solver.ts +618 -0
  246. package/src/prover/smt/solver/euf/egraph.ts +901 -0
  247. package/src/prover/smt/solver/euf/euf-solver.ts +1204 -0
  248. package/src/prover/smt/solver/euf/fpa-solver.ts +317 -0
  249. package/src/prover/smt/solver/euf/mam.ts +1046 -0
  250. package/src/prover/smt/solver/euf/q-ematch.ts +829 -0
  251. package/src/prover/smt/solver/euf/q-mbi.ts +587 -0
  252. package/src/prover/smt/solver/euf/q-model-fixer.ts +296 -0
  253. package/src/prover/smt/solver/euf/q-solver.ts +361 -0
  254. package/src/prover/smt/solver/euf/th-solver.ts +328 -0
  255. package/src/prover/smt/solver/euf/th-solvers.ts +30 -0
  256. package/src/prover/smt/solver/expr-ref.ts +0 -5
  257. package/src/prover/smt/solver/expr-safe-replace.ts +26 -7
  258. package/src/prover/smt/solver/expr2polynomial.ts +271 -0
  259. package/src/prover/smt/solver/factor.ts +163 -0
  260. package/src/prover/smt/solver/fd-solver.ts +734 -0
  261. package/src/prover/smt/solver/fingerprints.ts +15 -26
  262. package/src/prover/smt/solver/fix-dl-var.ts +147 -0
  263. package/src/prover/smt/solver/flat-literals.ts +0 -9
  264. package/src/prover/smt/solver/fm-tactic.ts +884 -0
  265. package/src/prover/smt/solver/fpa-decl-plugin.ts +618 -0
  266. package/src/prover/smt/solver/fpa-rewriter.ts +639 -0
  267. package/src/prover/smt/solver/fpa2bv-converter.ts +2251 -0
  268. package/src/prover/smt/solver/fpa2bv-rewriter.ts +349 -0
  269. package/src/prover/smt/solver/fpa2bv-tactic.ts +73 -0
  270. package/src/prover/smt/solver/goal.ts +179 -28
  271. package/src/prover/smt/solver/goal2nlsat.ts +216 -0
  272. package/src/prover/smt/solver/guard-set.ts +219 -0
  273. package/src/prover/smt/solver/hash.ts +0 -9
  274. package/src/prover/smt/solver/hashtable.ts +30 -23
  275. package/src/prover/smt/solver/inf-eps.ts +63 -0
  276. package/src/prover/smt/solver/inj-axiom.ts +101 -0
  277. package/src/prover/smt/solver/internalizer.ts +113 -133
  278. package/src/prover/smt/solver/lackr.ts +381 -0
  279. package/src/prover/smt/solver/lbool.ts +0 -2
  280. package/src/prover/smt/solver/lia2card.ts +268 -0
  281. package/src/prover/smt/solver/lia2pb.ts +154 -0
  282. package/src/prover/smt/solver/literal.ts +0 -4
  283. package/src/prover/smt/solver/logic-tactics.ts +355 -0
  284. package/src/prover/smt/solver/lp/bound-propagator.ts +7 -26
  285. package/src/prover/smt/solver/lp/constraints.ts +1 -8
  286. package/src/prover/smt/solver/lp/containers.ts +18 -31
  287. package/src/prover/smt/solver/lp/core-solver.ts +35 -37
  288. package/src/prover/smt/solver/lp/cross-nested.ts +4 -21
  289. package/src/prover/smt/solver/lp/dep-intervals.ts +6 -24
  290. package/src/prover/smt/solver/lp/dependency.ts +0 -5
  291. package/src/prover/smt/solver/lp/dioph-eq.ts +8 -103
  292. package/src/prover/smt/solver/lp/explanation.ts +0 -6
  293. package/src/prover/smt/solver/lp/gomory.ts +8 -22
  294. package/src/prover/smt/solver/lp/hnf-cutter.ts +16 -23
  295. package/src/prover/smt/solver/lp/hnf.ts +10 -28
  296. package/src/prover/smt/solver/lp/int-cube.ts +17 -39
  297. package/src/prover/smt/solver/lp/int-solver.ts +3 -35
  298. package/src/prover/smt/solver/lp/lar-solver.ts +70 -83
  299. package/src/prover/smt/solver/lp/lar-term.ts +0 -5
  300. package/src/prover/smt/solver/lp/lp-settings.ts +6 -16
  301. package/src/prover/smt/solver/lp/maximize-term.ts +76 -52
  302. package/src/prover/smt/solver/lp/nex-creator.ts +7 -30
  303. package/src/prover/smt/solver/lp/nex.ts +2 -7
  304. package/src/prover/smt/solver/lp/nla-backoff.ts +0 -5
  305. package/src/prover/smt/solver/lp/nla-basics.ts +48 -30
  306. package/src/prover/smt/solver/lp/nla-core.ts +92 -136
  307. package/src/prover/smt/solver/lp/nla-divisions.ts +31 -43
  308. package/src/prover/smt/solver/lp/nla-emonics.ts +3 -21
  309. package/src/prover/smt/solver/lp/nla-factorization.ts +0 -4
  310. package/src/prover/smt/solver/lp/nla-grobner.ts +177 -149
  311. package/src/prover/smt/solver/lp/nla-horner.ts +2 -12
  312. package/src/prover/smt/solver/lp/nla-intervals.ts +1 -12
  313. package/src/prover/smt/solver/lp/nla-monomial-bounds.ts +15 -42
  314. package/src/prover/smt/solver/lp/nla-monotone.ts +1 -6
  315. package/src/prover/smt/solver/lp/nla-order.ts +0 -13
  316. package/src/prover/smt/solver/lp/nla-patcher.ts +3 -7
  317. package/src/prover/smt/solver/lp/nla-powers.ts +220 -0
  318. package/src/prover/smt/solver/lp/nla-tangents.ts +0 -10
  319. package/src/prover/smt/solver/lp/nla-throttle.ts +0 -6
  320. package/src/prover/smt/solver/lp/nla-transcendentals.ts +324 -0
  321. package/src/prover/smt/solver/lp/nla-types.ts +0 -12
  322. package/src/prover/smt/solver/lp/nla-var-eqs.ts +4 -26
  323. package/src/prover/smt/solver/lp/nra-solver.ts +164 -147
  324. package/src/prover/smt/solver/lp/numeric-pair.ts +0 -4
  325. package/src/prover/smt/solver/lp/pdd-interval.ts +6 -5
  326. package/src/prover/smt/solver/lp/pdd-simplifier.ts +61 -34
  327. package/src/prover/smt/solver/lp/pdd-solver.ts +74 -72
  328. package/src/prover/smt/solver/lp/pdd.ts +730 -358
  329. package/src/prover/smt/solver/lp/random-updater.ts +0 -9
  330. package/src/prover/smt/solver/lp/static-matrix.ts +8 -19
  331. package/src/prover/smt/solver/lp/union-find.ts +5 -5
  332. package/src/prover/smt/solver/macro-finder.ts +530 -0
  333. package/src/prover/smt/solver/mam-compiler.ts +129 -139
  334. package/src/prover/smt/solver/mam-interpreter.ts +0 -21
  335. package/src/prover/smt/solver/max-bv-sharing-tactic.ts +17 -0
  336. package/src/prover/smt/solver/max-cliques.ts +105 -0
  337. package/src/prover/smt/solver/maxcore.ts +310 -0
  338. package/src/prover/smt/solver/maximize-ac-sharing.ts +8 -21
  339. package/src/prover/smt/solver/maxlex.ts +115 -0
  340. package/src/prover/smt/solver/maxsmt-base.ts +106 -0
  341. package/src/prover/smt/solver/maxsmt.ts +92 -0
  342. package/src/prover/smt/solver/mbp/mbp-arith.ts +467 -0
  343. package/src/prover/smt/solver/mbp/mbp-basic-tg.ts +101 -0
  344. package/src/prover/smt/solver/mbp/mbp-plugin.ts +287 -0
  345. package/src/prover/smt/solver/mbp/mbp-qel.ts +48 -0
  346. package/src/prover/smt/solver/mbp/mbp-solve-plugin.ts +271 -0
  347. package/src/prover/smt/solver/mbp/mbp-term-graph.ts +606 -0
  348. package/src/prover/smt/solver/model-based-opt.ts +844 -0
  349. package/src/prover/smt/solver/model-checker.ts +20 -63
  350. package/src/prover/smt/solver/model-evaluator.ts +192 -40
  351. package/src/prover/smt/solver/model-finder.ts +14 -32
  352. package/src/prover/smt/solver/model-generator.ts +104 -46
  353. package/src/prover/smt/solver/model-macro-solver.ts +60 -114
  354. package/src/prover/smt/solver/model-printer.ts +214 -0
  355. package/src/prover/smt/solver/mpf.ts +709 -0
  356. package/src/prover/smt/solver/mus.ts +50 -0
  357. package/src/prover/smt/solver/muz/dl-context.ts +382 -0
  358. package/src/prover/smt/solver/muz/dl-mk-bit-blast.ts +97 -0
  359. package/src/prover/smt/solver/muz/dl-mk-coi-filter.ts +167 -0
  360. package/src/prover/smt/solver/muz/dl-mk-elim-term-ite.ts +125 -0
  361. package/src/prover/smt/solver/muz/dl-mk-interp-tail-simplifier.ts +299 -0
  362. package/src/prover/smt/solver/muz/dl-mk-rule-inliner.ts +455 -0
  363. package/src/prover/smt/solver/muz/dl-mk-slice.ts +340 -0
  364. package/src/prover/smt/solver/muz/dl-mk-subsumption-checker.ts +163 -0
  365. package/src/prover/smt/solver/muz/dl-rule-set.ts +273 -0
  366. package/src/prover/smt/solver/muz/dl-rule-transformer.ts +123 -0
  367. package/src/prover/smt/solver/muz/dl-rule.ts +495 -0
  368. package/src/prover/smt/solver/muz/hnf.ts +201 -0
  369. package/src/prover/smt/solver/muz/horn-subsume-model-converter.ts +176 -0
  370. package/src/prover/smt/solver/muz/horn-tactic.ts +214 -0
  371. package/src/prover/smt/solver/muz/rule-properties.ts +359 -0
  372. package/src/prover/smt/solver/muz/spacer-context.ts +1404 -0
  373. package/src/prover/smt/solver/muz/spacer-dl-interface.ts +52 -0
  374. package/src/prover/smt/solver/muz/spacer-generalizers.ts +241 -0
  375. package/src/prover/smt/solver/muz/spacer-manager.ts +127 -0
  376. package/src/prover/smt/solver/muz/spacer-pdr.ts +219 -0
  377. package/src/prover/smt/solver/muz/spacer-prop-solver.ts +333 -0
  378. package/src/prover/smt/solver/muz/spacer-util.ts +282 -0
  379. package/src/prover/smt/solver/muz/substitution.ts +203 -0
  380. package/src/prover/smt/solver/nla2bv-tactic.ts +285 -0
  381. package/src/prover/smt/solver/nlqsat.ts +484 -0
  382. package/src/prover/smt/solver/nlsat/algebraic.ts +357 -236
  383. package/src/prover/smt/solver/nlsat/atoms.ts +73 -54
  384. package/src/prover/smt/solver/nlsat/evaluator.ts +16 -22
  385. package/src/prover/smt/solver/nlsat/explain.ts +429 -275
  386. package/src/prover/smt/solver/nlsat/interval-set.ts +9 -51
  387. package/src/prover/smt/solver/nlsat/levelwise.ts +477 -344
  388. package/src/prover/smt/solver/nlsat/mpbq.ts +47 -14
  389. package/src/prover/smt/solver/nlsat/polynomial.ts +2385 -832
  390. package/src/prover/smt/solver/nlsat/solver.ts +297 -156
  391. package/src/prover/smt/solver/nlsat/transcendental-eval.ts +310 -0
  392. package/src/prover/smt/solver/nlsat/transcendentals.ts +391 -0
  393. package/src/prover/smt/solver/nlsat/types.ts +0 -9
  394. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +9 -51
  395. package/src/prover/smt/solver/nlsat/upolynomial.ts +49 -109
  396. package/src/prover/smt/solver/nlsat-tactic.ts +82 -0
  397. package/src/prover/smt/solver/nnf.ts +112 -61
  398. package/src/prover/smt/solver/normalize-bounds.ts +53 -0
  399. package/src/prover/smt/solver/occf.ts +97 -0
  400. package/src/prover/smt/solver/opt-context.ts +801 -0
  401. package/src/prover/smt/solver/opt-nlsat.ts +386 -0
  402. package/src/prover/smt/solver/opt-pareto.ts +301 -0
  403. package/src/prover/smt/solver/opt-preprocess.ts +101 -0
  404. package/src/prover/smt/solver/opt-solver.ts +312 -0
  405. package/src/prover/smt/solver/opt-value.ts +55 -0
  406. package/src/prover/smt/solver/optsmt.ts +692 -0
  407. package/src/prover/smt/solver/parallel-tactic.ts +299 -0
  408. package/src/prover/smt/solver/pattern-inference.ts +21 -26
  409. package/src/prover/smt/solver/pb-rewriter.ts +281 -0
  410. package/src/prover/smt/solver/pb2bv-tactic.ts +540 -0
  411. package/src/prover/smt/solver/poly-rewriter.ts +261 -79
  412. package/src/prover/smt/solver/probes.ts +577 -0
  413. package/src/prover/smt/solver/propagate-values.ts +37 -30
  414. package/src/prover/smt/solver/proto-model.ts +650 -66
  415. package/src/prover/smt/solver/pull-quant.ts +28 -23
  416. package/src/prover/smt/solver/purify-arith.ts +632 -0
  417. package/src/prover/smt/solver/push-app-ite.ts +37 -0
  418. package/src/prover/smt/solver/qe-arith-plugin.ts +1096 -0
  419. package/src/prover/smt/solver/qe-lite-der.ts +2 -31
  420. package/src/prover/smt/solver/qe-lite-fm.ts +4 -28
  421. package/src/prover/smt/solver/qe-lite.ts +41 -51
  422. package/src/prover/smt/solver/qe-mbp.ts +270 -0
  423. package/src/prover/smt/solver/qe.ts +1499 -0
  424. package/src/prover/smt/solver/qel.ts +25 -0
  425. package/src/prover/smt/solver/qi-queue.ts +0 -16
  426. package/src/prover/smt/solver/qsat.ts +829 -0
  427. package/src/prover/smt/solver/quant-hoist.ts +196 -0
  428. package/src/prover/smt/solver/quant-tactics.ts +17 -74
  429. package/src/prover/smt/solver/quantifier-analyzer.ts +26 -47
  430. package/src/prover/smt/solver/quantifier-manager.ts +22 -32
  431. package/src/prover/smt/solver/quasi-macros.ts +243 -0
  432. package/src/prover/smt/solver/random-gen.ts +0 -2
  433. package/src/prover/smt/solver/rational.ts +45 -8
  434. package/src/prover/smt/solver/recfun-decl-plugin.ts +262 -0
  435. package/src/prover/smt/solver/recfun-rewriter.ts +107 -0
  436. package/src/prover/smt/solver/reduce-args.ts +225 -0
  437. package/src/prover/smt/solver/reduce-bv-size.ts +119 -0
  438. package/src/prover/smt/solver/ref-vector.ts +0 -6
  439. package/src/prover/smt/solver/relevancy.ts +2 -16
  440. package/src/prover/smt/solver/rewriter-tpl.ts +59 -135
  441. package/src/prover/smt/solver/rewriter.ts +507 -144
  442. package/src/prover/smt/solver/rlimit.ts +46 -24
  443. package/src/prover/smt/solver/sat/asymm-branch.ts +325 -0
  444. package/src/prover/smt/solver/sat/big.ts +177 -0
  445. package/src/prover/smt/solver/sat/clause-use-list.ts +71 -0
  446. package/src/prover/smt/solver/sat/clause.ts +203 -0
  447. package/src/prover/smt/solver/sat/cleaner.ts +94 -0
  448. package/src/prover/smt/solver/sat/config.ts +122 -0
  449. package/src/prover/smt/solver/sat/consequences.ts +203 -0
  450. package/src/prover/smt/solver/sat/elim-eqs.ts +142 -0
  451. package/src/prover/smt/solver/sat/goal2sat.ts +579 -0
  452. package/src/prover/smt/solver/sat/inc-sat-solver.ts +464 -0
  453. package/src/prover/smt/solver/sat/model-converter.ts +136 -0
  454. package/src/prover/smt/solver/sat/pb-constraint.ts +268 -0
  455. package/src/prover/smt/solver/sat/pb-solver.ts +1596 -0
  456. package/src/prover/smt/solver/sat/probing.ts +170 -0
  457. package/src/prover/smt/solver/sat/sat-tactic.ts +53 -0
  458. package/src/prover/smt/solver/sat/sat2goal.ts +189 -0
  459. package/src/prover/smt/solver/sat/scc.ts +142 -0
  460. package/src/prover/smt/solver/sat/simplifier.ts +1618 -0
  461. package/src/prover/smt/solver/sat/solver.ts +2107 -0
  462. package/src/prover/smt/solver/sat/var-queue.ts +117 -0
  463. package/src/prover/smt/solver/sat/watch-list.ts +140 -0
  464. package/src/prover/smt/solver/search-tree.ts +284 -0
  465. package/src/prover/smt/solver/seq-axioms.ts +995 -0
  466. package/src/prover/smt/solver/seq-decl-plugin.ts +819 -0
  467. package/src/prover/smt/solver/seq-derive.ts +1298 -0
  468. package/src/prover/smt/solver/seq-eq-approx.ts +236 -0
  469. package/src/prover/smt/solver/seq-eq-solver.ts +439 -0
  470. package/src/prover/smt/solver/seq-factory.ts +89 -0
  471. package/src/prover/smt/solver/seq-monadic.ts +730 -0
  472. package/src/prover/smt/solver/seq-range-predicate.ts +235 -0
  473. package/src/prover/smt/solver/seq-re-rewriter.ts +1171 -0
  474. package/src/prover/smt/solver/seq-re-util.ts +758 -0
  475. package/src/prover/smt/solver/seq-regex-bisim.ts +144 -0
  476. package/src/prover/smt/solver/seq-regex-live.ts +200 -0
  477. package/src/prover/smt/solver/seq-rewriter.ts +2404 -0
  478. package/src/prover/smt/solver/seq-skolem.ts +294 -0
  479. package/src/prover/smt/solver/seq-subset.ts +165 -0
  480. package/src/prover/smt/solver/seq-view-witness.ts +353 -0
  481. package/src/prover/smt/solver/smt-consequences.ts +297 -0
  482. package/src/prover/smt/solver/smt-kernel.ts +124 -0
  483. package/src/prover/smt/solver/smt-logics.ts +66 -0
  484. package/src/prover/smt/solver/smt-setup.ts +589 -0
  485. package/src/prover/smt/solver/smt2-printer.ts +765 -0
  486. package/src/prover/smt/solver/smtlib-parser.ts +3546 -406
  487. package/src/prover/smt/solver/smtlib-script.ts +2134 -0
  488. package/src/prover/smt/solver/solve-eqs.ts +928 -0
  489. package/src/prover/smt/solver/solver.ts +135 -40
  490. package/src/prover/smt/solver/sort.ts +1 -5
  491. package/src/prover/smt/solver/static-features.ts +314 -0
  492. package/src/prover/smt/solver/sticky-generations.ts +0 -6
  493. package/src/prover/smt/solver/tactic.ts +2141 -0
  494. package/src/prover/smt/solver/term-enumeration.ts +205 -0
  495. package/src/prover/smt/solver/theory-array.ts +1240 -0
  496. package/src/prover/smt/solver/theory-bv.ts +1210 -0
  497. package/src/prover/smt/solver/theory-char.ts +355 -0
  498. package/src/prover/smt/solver/theory-datatype.ts +598 -0
  499. package/src/prover/smt/solver/theory-finite-set.ts +30 -0
  500. package/src/prover/smt/solver/theory-fpa.ts +389 -0
  501. package/src/prover/smt/solver/theory-lra-axioms.ts +55 -25
  502. package/src/prover/smt/solver/theory-lra-bounds.ts +31 -11
  503. package/src/prover/smt/solver/theory-lra-final-check.ts +60 -91
  504. package/src/prover/smt/solver/theory-lra-internalize.ts +96 -53
  505. package/src/prover/smt/solver/theory-lra-model.ts +23 -53
  506. package/src/prover/smt/solver/theory-lra-propagate.ts +34 -42
  507. package/src/prover/smt/solver/theory-lra-state.ts +7 -28
  508. package/src/prover/smt/solver/theory-lra.ts +189 -9
  509. package/src/prover/smt/solver/theory-pb.ts +951 -0
  510. package/src/prover/smt/solver/theory-polymorphism.ts +58 -0
  511. package/src/prover/smt/solver/theory-recfun.ts +307 -0
  512. package/src/prover/smt/solver/theory-seq-regex.ts +867 -0
  513. package/src/prover/smt/solver/theory-seq-solve.ts +1373 -0
  514. package/src/prover/smt/solver/theory-seq-state.ts +852 -0
  515. package/src/prover/smt/solver/theory-seq.ts +961 -0
  516. package/src/prover/smt/solver/theory-without-terms.ts +24 -0
  517. package/src/prover/smt/solver/theory.ts +189 -0
  518. package/src/prover/smt/solver/tseitin-cnf.ts +486 -0
  519. package/src/prover/smt/solver/var-subst.ts +37 -39
  520. package/src/prover/smt/table.ts +3 -10
  521. package/src/prover/smt/types.ts +146 -0
  522. package/src/prover/tlapm/cache.ts +74 -48
  523. package/src/prover/tlapm/ocaml-marshal.ts +19 -21
  524. package/src/prover/tlapm/tlapm.ts +21 -20
  525. package/src/prover/tlapm-library.ts +3208 -0
  526. package/src/prover/verdict.ts +9 -2
  527. package/src/prover/zenon/check/check.ts +1 -11
  528. package/src/prover/zenon/check/definitions.ts +5 -15
  529. package/src/prover/zenon/check/equality.ts +0 -8
  530. package/src/prover/zenon/check/functions.ts +0 -4
  531. package/src/prover/zenon/check/keys.ts +0 -7
  532. package/src/prover/zenon/check/propositional.ts +0 -3
  533. package/src/prover/zenon/check/records.ts +1 -6
  534. package/src/prover/zenon/check/relations.ts +2 -14
  535. package/src/prover/zenon/check/rewrites.ts +2 -21
  536. package/src/prover/zenon/check/sets.ts +40 -61
  537. package/src/prover/zenon/check/terms.ts +1 -19
  538. package/src/prover/zenon/check/tla.ts +0 -6
  539. package/src/prover/zenon/decide.ts +10 -19
  540. package/src/prover/zenon/encode.ts +0 -9
  541. package/src/prover/zenon/eqrel.ts +2 -15
  542. package/src/prover/zenon/equality-rules.ts +24 -6
  543. package/src/prover/zenon/expr.ts +29 -28
  544. package/src/prover/zenon/index-table.ts +33 -61
  545. package/src/prover/zenon/isar-case.ts +9 -21
  546. package/src/prover/zenon/isar.ts +37 -67
  547. package/src/prover/zenon/limits.ts +0 -4
  548. package/src/prover/zenon/llproof.ts +2 -22
  549. package/src/prover/zenon/mltoll.ts +66 -106
  550. package/src/prover/zenon/node.ts +20 -15
  551. package/src/prover/zenon/ocaml.ts +1 -17
  552. package/src/prover/zenon/parse.ts +9 -13
  553. package/src/prover/zenon/phrase.ts +2 -14
  554. package/src/prover/zenon/proof.ts +0 -11
  555. package/src/prover/zenon/propositional-rules.ts +0 -7
  556. package/src/prover/zenon/rules.ts +3 -8
  557. package/src/prover/zenon/search.ts +11 -35
  558. package/src/prover/zenon/tla/functions.ts +59 -33
  559. package/src/prover/zenon/tla/llproof.ts +67 -78
  560. package/src/prover/zenon/tla/records.ts +57 -35
  561. package/src/prover/zenon/tla/rewrites.ts +12 -21
  562. package/src/prover/zenon/tla/sets.ts +88 -59
  563. package/src/prover/zenon/tla/terms.ts +0 -8
  564. package/src/prover/zenon/tla/tla.ts +66 -66
  565. package/src/randomization.ts +81 -35
  566. package/src/resolve.ts +1132 -430
  567. package/src/runtime.ts +33 -23
  568. package/src/sany/builtins.ts +11 -14
  569. package/src/sany/generation.ts +383 -0
  570. package/src/sany/generator-def-entries.ts +210 -0
  571. package/src/sany/generator-definitions.ts +688 -0
  572. package/src/sany/generator-expressions.ts +1108 -0
  573. package/src/sany/generator-proofs.ts +665 -0
  574. package/src/sany/generator.ts +192 -2764
  575. package/src/sany/levels.ts +5 -35
  576. package/src/sany/lexer.ts +61 -80
  577. package/src/sany/linter.ts +0 -10
  578. package/src/sany/modules.ts +5 -7
  579. package/src/sany/nodes.ts +6 -44
  580. package/src/sany/parse-error.ts +39 -117
  581. package/src/sany/report.ts +32 -69
  582. package/src/sany/selectors.ts +60 -82
  583. package/src/sany/source.ts +1 -17
  584. package/src/sany/xml.ts +37 -120
  585. package/src/search.ts +913 -227
  586. package/src/simulate.ts +765 -0
  587. package/src/spec-description.ts +198 -104
  588. package/src/standard-definitions.ts +4 -4
  589. package/src/standard-modules.ts +302 -99
  590. package/src/state-graph.ts +52 -33
  591. package/src/subexpressions.ts +578 -166
  592. package/src/substitution-levels.ts +7 -7
  593. package/src/successors.ts +299 -108
  594. package/src/symmetry.ts +37 -28
  595. package/src/tableau.ts +29 -26
  596. package/src/tlc/fingerprint.ts +267 -79
  597. package/src/tlc/jar-data.ts +122 -6
  598. package/src/tlc/messages.ts +127 -56
  599. package/src/tlc/order.ts +53 -72
  600. package/src/tlc/random.ts +38 -49
  601. package/src/tlc/replay.ts +579 -230
  602. package/src/tlc/summary.ts +64 -60
  603. package/src/tlc/tlc-operators.ts +83 -47
  604. package/src/tlc/tlcext-operators.ts +205 -127
  605. package/src/tlc/trace-spec.ts +235 -0
  606. package/src/tlc/value-stream.ts +139 -0
  607. package/src/tlc/version.ts +1 -4
  608. package/src/trace-liveness.ts +529 -0
  609. package/src/transfer.ts +22 -25
  610. package/src/typed-tier.ts +6556 -0
  611. package/src/typescript/actions.ts +479 -0
  612. package/src/typescript/collections.ts +614 -0
  613. package/src/typescript/compile.ts +63 -0
  614. package/src/typescript/context.ts +94 -0
  615. package/src/typescript/emit.ts +121 -0
  616. package/src/typescript/expressions.ts +496 -0
  617. package/src/typescript/formula.ts +154 -0
  618. package/src/typescript/functions.ts +284 -0
  619. package/src/typescript/model.ts +162 -0
  620. package/src/typescript/names.ts +114 -0
  621. package/src/typescript/program.ts +48 -0
  622. package/src/typescript/properties.ts +139 -0
  623. package/src/typescript/scope.ts +112 -0
  624. package/src/typescript/steps.ts +167 -0
  625. package/src/typescript/types.ts +171 -0
  626. package/src/values.ts +945 -526
  627. package/src/worker.ts +7 -8
  628. package/src/prover/isabelle/isar/statement.ts +0 -57
  629. package/src/prover/smt/solver/z3-license.txt +0 -10
  630. package/src/prover/tlaps-module.ts +0 -510
  631. package/src/prover/zenon/LICENSE +0 -32
package/src/values.ts CHANGED
@@ -1,5 +1,14 @@
1
- import { TlaEvaluationError } from "./errors";
1
+ import {
2
+ isStackOverflow,
3
+ TlaAliasFormatError,
4
+ TlaEvaluationError,
5
+ TlaFeatureUnsupportedError,
6
+ TlaModuleError,
7
+ TlaSetBoundError,
8
+ } from "./errors";
9
+ import { getJavaHashCode } from "./java-hash";
2
10
  import { prettyPrint } from "./pretty-print";
11
+ import { isEvalException } from "./tlc/messages";
3
12
  import type { TlcVersion } from "./tlc/version";
4
13
 
5
14
  export interface ModelValue {
@@ -11,8 +20,6 @@ export interface ModelValue {
11
20
  fingerprint: number;
12
21
  }
13
22
 
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
23
  interface LazySet {
17
24
  enumerated?: SetValue;
18
25
  isCached?: boolean;
@@ -22,13 +29,13 @@ interface LazySet {
22
29
  export interface SetValue {
23
30
  kind: "Set";
24
31
  elements: Value[];
32
+ writtenElements: Value[] | undefined;
33
+ isNormalized: boolean;
25
34
  hash: number;
26
35
  fingerprint: number;
27
36
  isFingerprinted: boolean;
28
37
  }
29
38
 
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.
32
39
  export interface MixedSetValue extends LazySet {
33
40
  kind: "MixedSet";
34
41
  elements: Value[];
@@ -42,6 +49,7 @@ export interface FunctionValue {
42
49
  fingerprint: number;
43
50
  writtenKeys: Value[] | undefined;
44
51
  functionClass: FunctionClass | undefined;
52
+ lambdaDomain: Value | undefined;
45
53
  isFingerprinted: boolean;
46
54
  }
47
55
 
@@ -90,7 +98,6 @@ export interface SetOperationValue extends LazySet {
90
98
  right: Value;
91
99
  }
92
100
 
93
- // TLC prints a set filter as its bound names and the location of its predicate.
94
101
  interface FilteredSetSource {
95
102
  names: string;
96
103
  predicate: string;
@@ -99,11 +106,11 @@ interface FilteredSetSource {
99
106
  export interface FilteredSetValue extends LazySet {
100
107
  kind: "FilteredSet";
101
108
  base: Value;
102
- test: (element: Value) => boolean;
109
+ test: (element: Value, isMember: boolean) => boolean;
110
+ startPass?: (isMaterialized: boolean) => (element: Value) => boolean;
103
111
  source?: FilteredSetSource;
104
112
  }
105
113
 
106
- // UNION S when some element of S isn't a set enumeration. TLC enumerates it only when it has to.
107
114
  export interface UnionValue extends LazySet {
108
115
  kind: "Union";
109
116
  base: Value;
@@ -119,12 +126,11 @@ export interface LazyFunctionSource {
119
126
  body: string;
120
127
  }
121
128
 
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.
124
129
  export interface LazyFunctionValue {
125
130
  kind: "LazyFunction";
126
131
  domain: Value;
127
132
  apply: (argument: Value) => Value;
133
+ boundTupleLengths?: (number | undefined)[];
128
134
  source?: LazyFunctionSource;
129
135
  functionClass?: FunctionClass;
130
136
  enumerated?: FunctionValue;
@@ -153,7 +159,6 @@ export type Value =
153
159
 
154
160
  export type ObjectValue = Exclude<Value, boolean | number | string>;
155
161
 
156
- // The sets TLC builds lazily, which it converts and caches as it uses them.
157
162
  type ConvertibleSetValue =
158
163
  | MixedSetValue
159
164
  | SubsetValue
@@ -174,8 +179,39 @@ const isLazySet = (value: ObjectValue): value is ConvertibleSetValue =>
174
179
  value.kind !== "LazyFunction";
175
180
 
176
181
  export const MAXIMUM_INTEGER = 2147483647;
182
+
183
+ const DEFAULT_SET_BOUND = 1000000;
184
+ const VALUE_VEC_CAPACITY = 10;
185
+
186
+ let setBound = DEFAULT_SET_BOUND;
187
+
188
+ export const getSetBound = () => setBound;
189
+
190
+ export const getMaximumSetSize = () => Math.max(setBound, VALUE_VEC_CAPACITY);
191
+
192
+ export const getSetBoundMessage = () =>
193
+ `Attempted to construct a set with too many elements (>${setBound}).`;
194
+
195
+ export const addBoundedElement = (elements: Value[], element: Value) => {
196
+ if (elements.length === getMaximumSetSize()) throw new TlaSetBoundError(getSetBoundMessage());
197
+ elements.push(element);
198
+ };
199
+
200
+ export const isBeyondSetBound = (value: Value): value is IntervalValue =>
201
+ typeof value === "object" &&
202
+ value.kind === "Interval" &&
203
+ value.high - value.low >= getMaximumSetSize();
204
+
205
+ export const forEachElement = (
206
+ elements: IntervalValue | Value[],
207
+ visit: (element: Value) => void,
208
+ ) => {
209
+ if (Array.isArray(elements)) return elements.forEach(visit);
210
+ for (let element = elements.low; element <= elements.high; element++) visit(element);
211
+ };
177
212
  export const MINIMUM_INTEGER = -2147483648;
178
213
  const MAXIMUM_ENUMERATED_SUBSET_BASE = 30;
214
+ const MAXIMUM_BUILT_SUBSET_BASE = 20;
179
215
 
180
216
  export const isSetValue = (value: Value) =>
181
217
  typeof value === "object" &&
@@ -183,8 +219,6 @@ export const isSetValue = (value: Value) =>
183
219
  value.kind !== "Function" &&
184
220
  value.kind !== "LazyFunction";
185
221
 
186
- // TLC's Reducible values, SetEnumValue and IntervalValue, which combine with another set element by
187
- // element.
188
222
  export const isReducibleSet = (value: Value): value is SetValue | MixedSetValue | IntervalValue =>
189
223
  typeof value === "object" &&
190
224
  (value.kind === "Set" || value.kind === "MixedSet" || value.kind === "Interval");
@@ -198,7 +232,7 @@ export const isModelValue = (value: Value): value is ModelValue =>
198
232
  export const isEnumeratedSet = (value: Value): value is SetValue | MixedSetValue =>
199
233
  typeof value === "object" && (value.kind === "Set" || value.kind === "MixedSet");
200
234
 
201
- export const describeKind = (value: Value) => {
235
+ const describeKind = (value: Value) => {
202
236
  if (typeof value === "boolean") return "boolean";
203
237
  if (typeof value === "number") return "integer";
204
238
  if (typeof value === "string") return "string";
@@ -209,27 +243,44 @@ export const describeKind = (value: Value) => {
209
243
  export const isTlcInteger = (value: number) =>
210
244
  Number.isInteger(value) && value <= MAXIMUM_INTEGER && value >= MINIMUM_INTEGER;
211
245
 
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.
215
- const writtenOrderUse = { isUsed: false };
246
+ let isWrittenOrderUsed = false;
216
247
 
217
248
  const setWrittenOrder = (functionValue: FunctionValue, keys: Value[]) => {
218
- writtenOrderUse.isUsed = true;
249
+ isWrittenOrderUsed = true;
219
250
  functionValue.writtenKeys = keys;
220
251
  return functionValue;
221
252
  };
222
253
 
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
- };
254
+ const getWrittenKeys = (functionValue: FunctionValue) =>
255
+ (functionValue.hash !== 0 || functionValue.fingerprint !== 0
256
+ ? undefined
257
+ : functionValue.writtenKeys) ?? functionValue.domain;
258
+
259
+ export const getWrittenPairs = (functionValue: FunctionValue): [Value, Value][] =>
260
+ getWrittenKeys(functionValue).map((key) => [
261
+ key,
262
+ functionValue.range[functionValue.domain.indexOf(key)],
263
+ ]);
264
+
265
+ export const getPrintedPairs = (functionValue: FunctionValue): [Value, Value][] =>
266
+ functionValue.domain.every((key) => typeof key === "number")
267
+ ? functionValue.domain.map((key, index) => [key, functionValue.range[index]])
268
+ : getWrittenPairs(functionValue);
227
269
 
228
- export const createWrittenRecord = (names: Value[], range: Value[], writtenNames: Value[]) =>
229
- setWrittenOrder(createSortedRecord(names, range), writtenNames);
270
+ export const createWrittenRecord = (
271
+ names: Value[],
272
+ writtenIndexes: number[],
273
+ writtenRange: Value[],
274
+ writtenNames: Value[],
275
+ ) =>
276
+ setWrittenOrder(
277
+ createSortedRecord(
278
+ names,
279
+ writtenIndexes.map((index) => writtenRange[index]),
280
+ ),
281
+ writtenNames,
282
+ );
230
283
 
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.
233
284
  const forgetWrittenOrder = (value: Value): void => {
234
285
  if (typeof value !== "object" || (value.kind !== "Function" && value.kind !== "Set")) return;
235
286
  if (value.hash !== 0 || value.fingerprint !== 0) return;
@@ -238,15 +289,20 @@ const forgetWrittenOrder = (value: Value): void => {
238
289
  value.range.forEach(forgetWrittenOrder);
239
290
  };
240
291
 
292
+ // TLC's SetOfRcdsValue#member and SetOfFcnsValue#member normalize the record or function they check in place.
293
+ const forgetOwnWrittenOrder = (value: Value) => {
294
+ if (isWrittenOrderUsed && typeof value === "object" && value.kind === "Function") {
295
+ value.writtenKeys = undefined;
296
+ }
297
+ };
298
+
241
299
  const isRecordDomain = (domain: Value[]) => domain.every((key) => typeof key === "string");
242
300
 
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.
245
301
  const isRecordMismatch = (left: Value[], right: Value[]) =>
246
302
  left.length > 0 && right.length > 0 && isRecordDomain(left) !== isRecordDomain(right);
247
303
 
248
304
  const compareFunctions = (left: FunctionValue, right: FunctionValue) => {
249
- if (writtenOrderUse.isUsed) {
305
+ if (isWrittenOrderUsed) {
250
306
  left.writtenKeys = undefined;
251
307
  right.writtenKeys = undefined;
252
308
  }
@@ -302,39 +358,77 @@ const checkModelValueTypes = (left: Value, right: Value, isEquality: boolean) =>
302
358
  if (isModelValue(left) && isModelValue(right)) {
303
359
  if (leftType === undefined || rightType === undefined || leftType === rightType) return;
304
360
  throw new TlaEvaluationError(
305
- `Attempted to ${action} the differently-typed model values ${formatValue(left)} and ${formatValue(right)}`,
361
+ `Attempted to ${action} the differently-typed model values ${prettyPrint(formatValue(left))} and ${prettyPrint(formatValue(right))}`,
306
362
  );
307
363
  }
308
364
  if (leftType !== undefined) {
309
365
  throw new TlaEvaluationError(
310
- `Attempted to ${action}${isEquality ? "" : " the"} typed model value ${formatValue(left)} and non-model value\n${formatValue(right)}`,
366
+ `Attempted to ${action}${isEquality ? "" : " the"} typed model value ${prettyPrint(formatValue(left))} and non-model value\n${prettyPrint(formatValue(right))}`,
311
367
  );
312
368
  }
313
369
  throw new TlaEvaluationError(
314
- `Attempted to ${action} the typed model value ${formatValue(right)} and the non-model value\n${formatValue(left)}`,
370
+ `Attempted to ${action} the typed model value ${prettyPrint(formatValue(right))} and the non-model value\n${prettyPrint(formatValue(left))}`,
315
371
  );
316
372
  };
317
373
 
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 } = {
374
+ interface StringOrder {
375
+ ranks: Record<string, number>;
376
+ size: number;
377
+ searchRank: number | undefined;
378
+ unorderedString: string | undefined;
379
+ }
380
+
381
+ const createStringOrder = (): StringOrder => ({
321
382
  ranks: Object.create(null),
322
383
  size: 0,
323
- };
384
+ searchRank: undefined,
385
+ unorderedString: undefined,
386
+ });
387
+
388
+ const stringOrder = createStringOrder();
324
389
 
325
390
  export const setStringOrder = (texts: Iterable<string>) => {
326
- stringOrder.ranks = Object.create(null);
327
- stringOrder.size = 0;
391
+ Object.assign(stringOrder, createStringOrder());
328
392
  modelValues.clear();
329
393
  for (const text of texts) rankString(text);
330
394
  };
331
395
 
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.
334
- const valueVersion = { is174: false };
396
+ export const freezeStringOrder = () => {
397
+ stringOrder.searchRank = stringOrder.size;
398
+ };
399
+
400
+ export const getUnorderedString = () => stringOrder.unorderedString;
401
+
402
+ let isVersion174 = false;
403
+
404
+ const printing = { isExpanded: true, isViewPrinted: false };
405
+
406
+ export interface ValueOptions {
407
+ version?: TlcVersion;
408
+ maxSetSize?: number;
409
+ isLazyValueExpanded?: boolean;
410
+ isViewPrinted?: boolean;
411
+ }
412
+
413
+ export const setValueOptions = (options: ValueOptions) => {
414
+ isVersion174 = options.version === "1.7.4";
415
+ setBound = options.maxSetSize ?? DEFAULT_SET_BOUND;
416
+ printing.isExpanded = options.isLazyValueExpanded ?? true;
417
+ printing.isViewPrinted = options.isViewPrinted ?? false;
418
+ };
419
+
420
+ const viewTexts = new WeakMap<Record<string, Value>, () => string>();
421
+
422
+ export const setViewText = (state: Record<string, Value>, getText: () => string) => {
423
+ if (printing.isViewPrinted) viewTexts.set(state, getText);
424
+ return state;
425
+ };
426
+
427
+ const aliasNames = new WeakMap<Record<string, Value>, string>();
335
428
 
336
- export const setValueVersion = (version: TlcVersion | undefined) => {
337
- valueVersion.is174 = version === "1.7.4";
429
+ export const setAliasName = (state: Record<string, Value>, alias: string) => {
430
+ aliasNames.set(state, alias);
431
+ return state;
338
432
  };
339
433
 
340
434
  export const rankString = (text: string) => {
@@ -342,11 +436,6 @@ export const rankString = (text: string) => {
342
436
  return text;
343
437
  };
344
438
 
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
439
  export const getStringRank = (text: string) => stringOrder.ranks[rankString(text)];
351
440
 
352
441
  const compareStrings = (left: string, right: string) => {
@@ -354,6 +443,14 @@ const compareStrings = (left: string, right: string) => {
354
443
  const ranks = stringOrder.ranks;
355
444
  const leftRank = ranks[left];
356
445
  const rightRank = ranks[right];
446
+ const searchRank = stringOrder.searchRank;
447
+ if (
448
+ searchRank !== undefined &&
449
+ (leftRank === undefined || leftRank >= searchRank) &&
450
+ (rightRank === undefined || rightRank >= searchRank)
451
+ ) {
452
+ stringOrder.unorderedString ??= left;
453
+ }
357
454
  if (leftRank !== undefined && rightRank !== undefined) return leftRank - rightRank;
358
455
  if (leftRank !== undefined) return -1;
359
456
  if (rightRank !== undefined) return 1;
@@ -372,9 +469,13 @@ const isOverriddenComparison = (left: Value, right: Value) =>
372
469
  right.kind === "SequenceSet"
373
470
  );
374
471
 
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.
472
+ const createComparisonError = (left: Value, right: Value) =>
473
+ new TlaEvaluationError(
474
+ isOverriddenSet(left)
475
+ ? `Attempted to compare overridden value ${prettyPrint(formatValue(left, true))} with non-overridden value:\n${prettyPrint(formatValue(right))}`
476
+ : `Attempted to compare ${describeKind(left)} ${formatValue(left)} with ${describeKind(right)} ${formatValue(right)}`,
477
+ );
478
+
378
479
  const compareOverriddenSets = (
379
480
  left: Value,
380
481
  right: Value,
@@ -382,35 +483,39 @@ const compareOverriddenSets = (
382
483
  ) => {
383
484
  if (!isOverriddenSet(left)) {
384
485
  throw new TlaEvaluationError(
385
- `Attempted to ${verb} the set ${formatValue(isEnumerable(left) ? toFiniteSet(left) : left, true)} with the value:\n${formatValue(right, true)}`,
386
- );
387
- }
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)}`,
486
+ `Attempted to ${verb} the set ${prettyPrint(formatValue(isEnumerable(left) ? toFiniteSet(left) : left, true))} with the value:\n${prettyPrint(formatValue(right, true))}`,
391
487
  );
392
488
  }
489
+ if (!isOverriddenSet(right)) throw createComparisonError(left, right);
393
490
  const leftName = left.kind === "InfiniteSet" ? left.name : undefined;
394
491
  const rightName = right.kind === "InfiniteSet" ? right.name : undefined;
395
492
  if (leftName !== undefined && leftName === rightName) return 0;
396
493
  if ((leftName === "Nat" && rightName === "Int") || (leftName === "Int" && rightName === "Nat")) {
397
494
  return leftName === "Nat" ? -1 : 1;
398
495
  }
399
- throw new TlaEvaluationError(
400
- `Attempted to compare ${formatValue(left, true)} with the value\n${formatValue(right, true)}`,
496
+ throw new TlaModuleError(
497
+ `Attempted to compare ${prettyPrint(formatValue(left, true))} with the value\n${prettyPrint(formatValue(right, true))}`,
401
498
  );
402
499
  };
403
500
 
404
501
  export const ANY_SET: InfiniteSetValue = { kind: "InfiniteSet", name: "Any" };
405
502
 
406
503
  const compareAny = (other: Value): never => {
407
- throw new TlaEvaluationError(`Attempted to compare ANY with the value\n${formatValue(other)}`);
504
+ throw new TlaModuleError(
505
+ `Attempted to compare ANY with the value\n${prettyPrint(formatValue(other))}`,
506
+ );
507
+ };
508
+
509
+ const compareWithItself = (value: Value) => {
510
+ if (isWrittenOrderUsed) forgetWrittenOrder(value);
511
+ if (value === ANY_SET) compareAny(value);
512
+ if (typeof value === "object" && value.kind === "LazyFunction") toFiniteFunction(value);
408
513
  };
409
514
 
410
515
  export const compareValues = (left: Value, right: Value): number => {
411
516
  if (left === right) {
412
- if (writtenOrderUse.isUsed) forgetWrittenOrder(left);
413
- return left === ANY_SET ? compareAny(left) : 0;
517
+ compareWithItself(left);
518
+ return 0;
414
519
  }
415
520
  if (typeof left === "object" && typeof right === "object") {
416
521
  const leftKind = left.kind;
@@ -438,9 +543,15 @@ export const compareValues = (left: Value, right: Value): number => {
438
543
  }
439
544
  const isLeftSet = isSetValue(left);
440
545
  if (isLeftSet !== isSetValue(right)) {
441
- throw new TlaEvaluationError(
442
- `Attempted to compare ${describeKind(left)} ${formatValue(left)} with ${describeKind(right)} ${formatValue(right)}`,
443
- );
546
+ throw createComparisonError(left, right);
547
+ }
548
+ if (leftKind === "Interval" && rightKind === "Set") {
549
+ const difference = getCardinality(left) - right.elements.length;
550
+ if (difference !== 0) return difference;
551
+ }
552
+ if (leftKind === "Set" && rightKind === "Interval") {
553
+ const difference = left.elements.length - getCardinality(right);
554
+ if (difference !== 0) return difference;
444
555
  }
445
556
  if (isLeftSet) return compareSets(toFiniteSet(left), toFiniteSet(right));
446
557
  return compareFunctions(toFiniteFunction(left), toFiniteFunction(right));
@@ -451,17 +562,21 @@ export const compareValues = (left: Value, right: Value): number => {
451
562
  checkModelValueTypes(left, right, false);
452
563
  if (isModelValue(left)) return -1;
453
564
  if (isModelValue(right)) return 1;
454
- throw new TlaEvaluationError(
455
- `Attempted to compare ${describeKind(left)} ${formatValue(left)} with ${describeKind(right)} ${formatValue(right)}`,
456
- );
565
+ throw createComparisonError(left, right);
457
566
  };
458
567
 
459
568
  const modelValues = new Map<string, ModelValue>();
460
569
 
461
- // setStringOrder clears the model values, so each check ranks and creates its own.
570
+ const MAXIMUM_MODEL_VALUES = 32768;
571
+
462
572
  export const createModelValue = (name: string): ModelValue => {
463
573
  const known = modelValues.get(name);
464
574
  if (known) return known;
575
+ if (modelValues.size === MAXIMUM_MODEL_VALUES) {
576
+ throw new TlaFeatureUnsupportedError(
577
+ `TLC supports at most ${MAXIMUM_MODEL_VALUES} model values, but model value ${name} exceeds this limit.`,
578
+ );
579
+ }
465
580
  const value: ModelValue = {
466
581
  kind: "ModelValue",
467
582
  name,
@@ -474,14 +589,24 @@ export const createModelValue = (name: string): ModelValue => {
474
589
  return value;
475
590
  };
476
591
 
592
+ export const getModelValues = () => [...modelValues.values()];
593
+
477
594
  export const createSortedSet = (elements: Value[]): SetValue => ({
478
595
  kind: "Set",
479
596
  elements,
597
+ writtenElements: undefined,
598
+ isNormalized: false,
480
599
  hash: 0,
481
600
  fingerprint: 0,
482
601
  isFingerprinted: false,
483
602
  });
484
603
 
604
+ export const createNormalizedSet = (elements: Value[]): SetValue => {
605
+ const set = createSortedSet(elements);
606
+ set.isNormalized = true;
607
+ return set;
608
+ };
609
+
485
610
  export const createSortedFunction = (domain: Value[], range: Value[]): FunctionValue => ({
486
611
  kind: "Function",
487
612
  domain,
@@ -490,22 +615,19 @@ export const createSortedFunction = (domain: Value[], range: Value[]): FunctionV
490
615
  fingerprint: 0,
491
616
  writtenKeys: undefined,
492
617
  functionClass: undefined,
618
+ lambdaDomain: undefined,
493
619
  isFingerprinted: false,
494
620
  });
495
621
 
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.
499
622
  export type FunctionClass = "lambda" | "tuple" | "record";
500
623
 
501
- // Whether a lambda exists for markFingerprinted to find, so that a spec without one skips the walk.
502
- const lambdaPresence = { isPresent: false };
624
+ let hasLambda = false;
503
625
 
504
626
  export const setFunctionClass = <FunctionLike extends FunctionValue | LazyFunctionValue>(
505
627
  functionValue: FunctionLike,
506
628
  functionClass: FunctionClass | undefined,
507
629
  ) => {
508
- if (functionClass === "lambda") lambdaPresence.isPresent = true;
630
+ if (functionClass === "lambda") hasLambda = true;
509
631
  if (functionClass !== undefined) functionValue.functionClass = functionClass;
510
632
  return functionValue;
511
633
  };
@@ -519,22 +641,17 @@ export const markLambdaFunction = <FunctionLike extends FunctionValue | LazyFunc
519
641
  functionValue: FunctionLike,
520
642
  ) => setFunctionClass(functionValue, "lambda");
521
643
 
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.
524
644
  const isCachedSet = (value: ObjectValue) => isLazySet(value) && value.isCached === true;
525
645
 
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.
528
- const streamedSetPresence = { isPresent: false };
646
+ let hasStreamedSet = false;
529
647
 
530
648
  export const markStreamedSet = <Streamed extends UnionValue | SetOperationValue>(
531
649
  value: Streamed,
532
650
  ) => {
533
- streamedSetPresence.isPresent = true;
651
+ hasStreamedSet = true;
534
652
  return value;
535
653
  };
536
654
 
537
- // The sets that stream their elements apart from the normalized set until TLC caches them.
538
655
  const STREAMING_KINDS = new Set<ObjectValue["kind"]>([
539
656
  "Union",
540
657
  "SetOperation",
@@ -546,7 +663,7 @@ const STREAMING_KINDS = new Set<ObjectValue["kind"]>([
546
663
 
547
664
  const cacheSet = (value: Value) => {
548
665
  if (
549
- streamedSetPresence.isPresent &&
666
+ hasStreamedSet &&
550
667
  typeof value === "object" &&
551
668
  isLazySet(value) &&
552
669
  STREAMING_KINDS.has(value.kind)
@@ -555,12 +672,8 @@ const cacheSet = (value: Value) => {
555
672
  }
556
673
  };
557
674
 
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.
560
675
  export const markFingerprinted = (value: Value): void => {
561
- if ((!lambdaPresence.isPresent && !streamedSetPresence.isPresent) || typeof value !== "object") {
562
- return;
563
- }
676
+ if ((!hasLambda && !hasStreamedSet) || typeof value !== "object") return;
564
677
  if (value.kind === "ModelValue" || value.kind === "Interval" || value.kind === "InfiniteSet") {
565
678
  return;
566
679
  }
@@ -581,8 +694,8 @@ export const markFingerprinted = (value: Value): void => {
581
694
  export const valuesEqual = (left: Value, right: Value): boolean => {
582
695
  cacheSet(left);
583
696
  if (left === right) {
584
- if (writtenOrderUse.isUsed) forgetWrittenOrder(left);
585
- return left !== ANY_SET || compareAny(left);
697
+ compareWithItself(left);
698
+ return true;
586
699
  }
587
700
  if (typeof left !== "object" || typeof right !== "object") {
588
701
  if (typeof left === typeof right) return false;
@@ -591,16 +704,17 @@ export const valuesEqual = (left: Value, right: Value): boolean => {
591
704
  }
592
705
  return compareValues(left, right) === 0;
593
706
  }
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
707
  if (left.kind === "Function" && right.kind === "Function")
601
708
  return compareFunctions(left, right) === 0;
602
709
  if (left.kind === "Set" && right.kind === "Set") return compareSets(left, right) === 0;
710
+ if (left.kind === "Interval" && right.kind === "Set") {
711
+ if (getCardinality(left) !== right.elements.length) return false;
712
+ }
713
+ if (left.kind === "Set" && right.kind === "Interval") {
714
+ if (left.elements.length !== getCardinality(right)) return false;
715
+ }
603
716
  if (isModelValue(left) || isModelValue(right)) {
717
+ if (left.kind === "LazyFunction") toFiniteFunction(left);
604
718
  checkModelValueTypes(left, right, true);
605
719
  return isModelValue(left) && isModelValue(right) && left.name === right.name;
606
720
  }
@@ -653,8 +767,6 @@ export const valuesEqual = (left: Value, right: Value): boolean => {
653
767
  return compareValues(left, right) === 0;
654
768
  };
655
769
 
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.
658
770
  const createSameValueCheck = (isClassSensitive: boolean) => {
659
771
  const areSameValues = (left: Value[], right: Value[]) => {
660
772
  if (left === right) return true;
@@ -694,8 +806,6 @@ const canonicalizeElements = (elements: Value[], canonicalize: (value: Value) =>
694
806
  }
695
807
  };
696
808
 
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.
699
809
  export const createCanonicalizer = () => {
700
810
  const canonicalValues = new Map<number, Value | Value[]>();
701
811
  const canonicalize = (value: Value): Value => {
@@ -729,21 +839,14 @@ export const createCanonicalizer = () => {
729
839
  };
730
840
  };
731
841
 
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.
735
842
  interface TlcFunction {
736
843
  domain: Value[];
737
844
  range: Value[];
738
845
  low: number | undefined;
739
846
  }
740
847
 
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
- };
848
+ const getIntervalLow = (value: Value, domain: Value[]) =>
849
+ domain.length === 0 || getFunctionClass(value) === "tuple" ? 1 : getDomainInterval(domain)?.low;
747
850
 
748
851
  const toTlcFunction = (value: Value) => {
749
852
  if (!isFunctionValue(value)) return undefined;
@@ -751,37 +854,21 @@ const toTlcFunction = (value: Value) => {
751
854
  return {
752
855
  domain: functionValue.domain,
753
856
  range: functionValue.range,
754
- low: getIntervalLow(functionValue.domain),
857
+ low: getIntervalLow(value, functionValue.domain),
755
858
  };
756
859
  };
757
860
 
758
861
  const toTlcRecord = (value: Value) => {
759
862
  if (!isFunctionValue(value)) return undefined;
760
863
  const functionValue = toFiniteFunction(value);
761
- return functionValue.domain.every((key) => typeof key === "string") ? functionValue : undefined;
864
+ return isRecordDomain(functionValue.domain) ? functionValue : undefined;
762
865
  };
763
866
 
764
- // A model value compared with a value of another kind. The other value is never a model value.
765
- const compareModelValueWith = (modelValue: ModelValue, other: Value) => {
766
- checkModelValueTypes(other, modelValue, false);
867
+ const compareModelValueWith = (modelValue: ModelValue, other: Value, isEquality: boolean) => {
868
+ checkModelValueTypes(other, modelValue, isEquality);
767
869
  return 1;
768
870
  };
769
871
 
770
- const equalsModelValueWith = (modelValue: ModelValue, other: Value) => {
771
- checkModelValueTypes(other, modelValue, true);
772
- return false;
773
- };
774
-
775
- const compareModelValue = (left: ModelValue, right: Value) => {
776
- if (left.type !== undefined) checkModelValueTypes(left, right, false);
777
- return isModelValue(right) ? left.rank - right.rank : -1;
778
- };
779
-
780
- const equalsModelValue = (left: ModelValue, right: Value) => {
781
- if (left.type !== undefined) checkModelValueTypes(left, right, true);
782
- return isModelValue(right) && left.name === right.name;
783
- };
784
-
785
872
  const SCALAR_KINDS = {
786
873
  number: { name: "integer", other: "non-integer", equality: "check equality of" },
787
874
  string: { name: "string", other: "non-string", equality: "check equality of" },
@@ -797,34 +884,43 @@ const describeScalarMismatch = (
797
884
  SCALAR_KINDS[
798
885
  typeof left === "number" ? "number" : typeof left === "string" ? "string" : "boolean"
799
886
  ];
800
- return `Attempted to ${isEquality ? kind.equality : "compare"} ${kind.name} ${formatValue(left)} with ${kind.other}:\n${formatValue(right)}`;
887
+ return `Attempted to ${isEquality ? kind.equality : "compare"} ${kind.name} ${prettyPrint(formatValue(left))} with ${kind.other}:\n${prettyPrint(formatValue(right))}`;
801
888
  };
802
889
 
803
- const compareTlcFunctions = (functionValue: TlcFunction, left: Value, right: Value) => {
890
+ const getComparisonVerb = (isEquality: boolean) => (isEquality ? "check equality of" : "compare");
891
+
892
+ const compareTlcFunctions = (
893
+ functionValue: TlcFunction,
894
+ left: Value,
895
+ right: Value,
896
+ isEquality: boolean,
897
+ ) => {
804
898
  const other = toTlcFunction(right);
805
899
  if (!other) {
806
- if (isModelValue(right)) return compareModelValueWith(right, left);
900
+ if (isModelValue(right)) return compareModelValueWith(right, left, isEquality);
807
901
  throw new TlaEvaluationError(
808
- `Attempted to compare the function ${formatValue(left)} with the value:\n${formatValue(right)}`,
902
+ `Attempted to ${getComparisonVerb(isEquality)} the function ${prettyPrint(formatValue(left))} with the value:\n${prettyPrint(formatValue(right))}`,
809
903
  );
810
904
  }
811
905
  if (functionValue.range.length !== other.range.length)
812
906
  return functionValue.range.length - other.range.length;
813
- const compareRanges = () => compareElementsLikeTlc(functionValue.range, other.range);
907
+ const compareRanges = () => compareElementsLikeTlc(functionValue.range, other.range, isEquality);
814
908
  if (functionValue.low !== undefined && functionValue.range.length === 0) return 0;
815
909
  if (functionValue.low !== undefined && other.low !== undefined) {
816
910
  return functionValue.low === other.low ? compareRanges() : functionValue.low - other.low;
817
911
  }
818
912
  const intervalLow = functionValue.low ?? other.low;
819
913
  if (intervalLow === undefined) {
820
- return compareElementsLikeTlc(functionValue.domain, other.domain) || compareRanges();
914
+ return (
915
+ compareElementsLikeTlc(functionValue.domain, other.domain, isEquality) || compareRanges()
916
+ );
821
917
  }
822
918
  const keys = functionValue.low === undefined ? functionValue.domain : other.domain;
823
919
  for (let index = 0; index < keys.length; index++) {
824
920
  const key = keys[index];
825
921
  if (typeof key !== "number") {
826
922
  throw new TlaEvaluationError(
827
- `Attempted to compare integer with non-integer${functionValue.low === undefined ? "" : ":"}\n${formatValue(key)}.`,
923
+ `Attempted to compare ${isEquality ? "an " : ""}integer with non-integer${isEquality || functionValue.low !== undefined ? ":" : ""}\n${prettyPrint(formatValue(key))}.`,
828
924
  );
829
925
  }
830
926
  const difference =
@@ -834,48 +930,50 @@ const compareTlcFunctions = (functionValue: TlcFunction, left: Value, right: Val
834
930
  return compareRanges();
835
931
  };
836
932
 
837
- const compareElementsLikeTlc = (left: Value[], right: Value[]) => {
933
+ const compareElementsLikeTlc = (left: Value[], right: Value[], isEquality: boolean) => {
838
934
  for (let index = 0; index < left.length; index++) {
839
- const comparison = compareLikeTlc(left[index], right[index]);
935
+ const comparison = compareOrEqualLikeTlc(left[index], right[index], isEquality);
840
936
  if (comparison !== 0) return comparison;
841
937
  }
842
938
  return 0;
843
939
  };
844
940
 
845
- const compareFunctionLikeTlc = (left: FunctionValue | LazyFunctionValue, right: Value) => {
941
+ const compareFunctionLikeTlc = (
942
+ left: FunctionValue | LazyFunctionValue,
943
+ right: Value,
944
+ isEquality: boolean,
945
+ ) => {
846
946
  const functionValue = toFiniteFunction(left);
847
- const isTuple = left.kind === "Function" && getSequenceElements(functionValue) !== undefined;
848
- if (isTuple) {
947
+ if (getFunctionClass(left) === "tuple") {
849
948
  const tuple = isFunctionValue(right) ? getSequenceElements(right) : undefined;
850
- if (!tuple) return compareTlcFunctions({ ...functionValue, low: 1 }, left, right);
949
+ if (!tuple) return compareTlcFunctions({ ...functionValue, low: 1 }, left, right, isEquality);
851
950
  return (
852
951
  functionValue.range.length - tuple.length ||
853
- compareElementsLikeTlc(functionValue.range, tuple)
952
+ compareElementsLikeTlc(functionValue.range, tuple, isEquality)
854
953
  );
855
954
  }
856
955
  if (getFunctionClass(left) === "record") {
857
956
  const record = toTlcRecord(right);
858
957
  if (!record) {
859
- if (isModelValue(right)) return compareModelValueWith(right, left);
958
+ if (isModelValue(right)) return compareModelValueWith(right, left, isEquality);
860
959
  throw new TlaEvaluationError(
861
- `Attempted to compare record:\n${formatValue(left)}\nwith non-record\n${formatValue(right)}`,
960
+ `Attempted to ${getComparisonVerb(isEquality)} record:\n${prettyPrint(formatValue(left))}\nwith non-record\n${prettyPrint(formatValue(right))}`,
862
961
  );
863
962
  }
864
963
  return (
865
964
  functionValue.domain.length - record.domain.length ||
866
- compareElementsLikeTlc(functionValue.domain, record.domain) ||
867
- compareElementsLikeTlc(functionValue.range, record.range)
965
+ compareElementsLikeTlc(functionValue.domain, record.domain, isEquality) ||
966
+ compareElementsLikeTlc(functionValue.range, record.range, isEquality)
868
967
  );
869
968
  }
870
969
  return compareTlcFunctions(
871
- { ...functionValue, low: getIntervalLow(functionValue.domain) },
970
+ { ...functionValue, low: getIntervalLow(left, functionValue.domain) },
872
971
  left,
873
972
  right,
973
+ isEquality,
874
974
  );
875
975
  };
876
976
 
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.
879
977
  const isComparedByClass = (left: ObjectValue, right: Value) =>
880
978
  isOverriddenSet(left) ||
881
979
  isOverriddenSet(right) ||
@@ -892,131 +990,48 @@ const getSetElementsLikeTlc = (left: SetValue | MixedSetValue, right: Value) =>
892
990
  return { elements: toFiniteSet(left).elements, otherElements: toFiniteSet(other).elements };
893
991
  };
894
992
 
895
- const compareSetLikeTlc = (left: ObjectValue, right: Value): number => {
896
- if (isComparedByClass(left, right)) return compareValues(left, right);
897
- if (!isEnumeratedSet(left)) return compareSetLikeTlc(toFiniteSet(left), right);
993
+ const compareSetLikeTlc = (left: ObjectValue, right: Value, isEquality: boolean): number => {
994
+ if (isComparedByClass(left, right)) {
995
+ if (!isEquality) return compareValues(left, right);
996
+ return valuesEqual(left, right) ? 0 : 1;
997
+ }
998
+ if (!isEnumeratedSet(left)) return compareSetLikeTlc(toFiniteSet(left), right, isEquality);
898
999
  if (!isSetValue(right)) {
899
- if (isModelValue(right)) return compareModelValueWith(right, left);
1000
+ if (isModelValue(right)) return compareModelValueWith(right, left, isEquality);
900
1001
  throw new TlaEvaluationError(
901
- `Attempted to compare the set ${formatValue(left)} with the value:\n${formatValue(right)}`,
1002
+ `Attempted to ${getComparisonVerb(isEquality)} the set ${prettyPrint(formatValue(left))} with the value:\n${prettyPrint(formatValue(right))}`,
902
1003
  );
903
1004
  }
904
1005
  const sets = getSetElementsLikeTlc(left, right);
905
1006
  return (
906
1007
  sets.elements.length - sets.otherElements.length ||
907
- compareElementsLikeTlc(sets.elements, sets.otherElements)
1008
+ compareElementsLikeTlc(sets.elements, sets.otherElements, isEquality)
908
1009
  );
909
1010
  };
910
1011
 
911
- const compareLikeTlc = (left: Value, right: Value): number => {
1012
+ const compareOrEqualLikeTlc = (left: Value, right: Value, isEquality: boolean): number => {
912
1013
  if (typeof left !== "object") {
913
- if (typeof right === typeof left) return compareValues(left, right);
914
- if (isModelValue(right)) return compareModelValueWith(right, left);
915
- throw new TlaEvaluationError(describeScalarMismatch(left, right, false));
916
- }
917
- if (left.kind === "ModelValue") return compareModelValue(left, right);
918
- if (isFunctionValue(left)) return compareFunctionLikeTlc(left, right);
919
- return compareSetLikeTlc(left, right);
920
- };
921
-
922
- const equalsElementsLikeTlc = (left: Value[], right: Value[]) =>
923
- left.every((element, index) => equalsLikeTlc(element, right[index]));
924
-
925
- const equalsTlcFunctions = (functionValue: TlcFunction, left: Value, right: Value) => {
926
- const other = toTlcFunction(right);
927
- if (!other) {
928
- if (isModelValue(right)) return equalsModelValueWith(right, left);
929
- throw new TlaEvaluationError(
930
- `Attempted to check equality of the function ${formatValue(left)} with the value:\n${formatValue(right)}`,
931
- );
932
- }
933
- if (functionValue.range.length !== other.range.length) return false;
934
- if (functionValue.low !== undefined && other.low !== undefined) {
935
- return (
936
- (functionValue.range.length === 0 || functionValue.low === other.low) &&
937
- equalsElementsLikeTlc(functionValue.range, other.range)
938
- );
939
- }
940
- const intervalLow = functionValue.low ?? other.low;
941
- if (intervalLow === undefined) {
942
- return (
943
- equalsElementsLikeTlc(functionValue.domain, other.domain) &&
944
- equalsElementsLikeTlc(functionValue.range, other.range)
945
- );
946
- }
947
- const keys = functionValue.low === undefined ? functionValue.domain : other.domain;
948
- return (
949
- keys.every((key, index) => {
950
- if (typeof key !== "number") {
951
- throw new TlaEvaluationError(
952
- `Attempted to compare an integer with non-integer:\n${formatValue(key)}.`,
953
- );
954
- }
955
- return key === intervalLow + index;
956
- }) && equalsElementsLikeTlc(functionValue.range, other.range)
957
- );
958
- };
959
-
960
- const equalsFunctionLikeTlc = (left: FunctionValue | LazyFunctionValue, right: Value) => {
961
- const functionValue = toFiniteFunction(left);
962
- const isTuple = left.kind === "Function" && getSequenceElements(functionValue) !== undefined;
963
- if (isTuple) {
964
- const tuple = isFunctionValue(right) ? getSequenceElements(right) : undefined;
965
- if (!tuple) return equalsTlcFunctions({ ...functionValue, low: 1 }, left, right);
966
- return (
967
- functionValue.range.length === tuple.length &&
968
- equalsElementsLikeTlc(functionValue.range, tuple)
969
- );
970
- }
971
- if (getFunctionClass(left) === "record") {
972
- const record = toTlcRecord(right);
973
- if (!record) {
974
- if (isModelValue(right)) return equalsModelValueWith(right, left);
975
- throw new TlaEvaluationError(
976
- `Attempted to check equality of record:\n${formatValue(left)}\nwith non-record\n${formatValue(right)}`,
977
- );
1014
+ if (typeof right === typeof left) {
1015
+ if (!isEquality) return compareValues(left, right);
1016
+ return left === right ? 0 : 1;
978
1017
  }
979
- return (
980
- functionValue.domain.length === record.domain.length &&
981
- equalsElementsLikeTlc(functionValue.domain, record.domain) &&
982
- equalsElementsLikeTlc(functionValue.range, record.range)
983
- );
1018
+ if (isModelValue(right)) return compareModelValueWith(right, left, isEquality);
1019
+ throw new TlaEvaluationError(describeScalarMismatch(left, right, isEquality));
984
1020
  }
985
- return equalsTlcFunctions(
986
- { ...functionValue, low: getIntervalLow(functionValue.domain) },
987
- left,
988
- right,
989
- );
990
- };
991
-
992
- const equalsSetLikeTlc = (left: ObjectValue, right: Value): boolean => {
993
- if (isComparedByClass(left, right)) return valuesEqual(left, right);
994
- if (!isEnumeratedSet(left)) return equalsSetLikeTlc(toFiniteSet(left), right);
995
- if (!isSetValue(right)) {
996
- if (isModelValue(right)) return equalsModelValueWith(right, left);
997
- throw new TlaEvaluationError(
998
- `Attempted to check equality of the set ${formatValue(left)} with the value:\n${formatValue(right)}`,
999
- );
1021
+ if (left.kind === "ModelValue") {
1022
+ if (left.type !== undefined) checkModelValueTypes(left, right, isEquality);
1023
+ if (!isModelValue(right)) return -1;
1024
+ if (!isEquality) return left.rank - right.rank;
1025
+ return left.name === right.name ? 0 : 1;
1000
1026
  }
1001
- const sets = getSetElementsLikeTlc(left, right);
1002
- return (
1003
- sets.elements.length === sets.otherElements.length &&
1004
- equalsElementsLikeTlc(sets.elements, sets.otherElements)
1005
- );
1027
+ if (isFunctionValue(left)) return compareFunctionLikeTlc(left, right, isEquality);
1028
+ return compareSetLikeTlc(left, right, isEquality);
1006
1029
  };
1007
1030
 
1008
- const equalsLikeTlc = (left: Value, right: Value): boolean => {
1009
- if (typeof left !== "object") {
1010
- if (typeof right === typeof left) return left === right;
1011
- if (isModelValue(right)) return equalsModelValueWith(right, left);
1012
- throw new TlaEvaluationError(describeScalarMismatch(left, right, true));
1013
- }
1014
- if (left.kind === "ModelValue") return equalsModelValue(left, right);
1015
- if (isFunctionValue(left)) return equalsFunctionLikeTlc(left, right);
1016
- return equalsSetLikeTlc(left, right);
1017
- };
1031
+ const compareLikeTlc = (left: Value, right: Value) => compareOrEqualLikeTlc(left, right, false);
1032
+
1033
+ const equalsLikeTlc = (left: Value, right: Value) => compareOrEqualLikeTlc(left, right, true) === 0;
1018
1034
 
1019
- // TLC's ValueVec.sort, which inserts each element into the sorted prefix by binary search.
1020
1035
  const sortLikeTlc = (elements: Value[]) => {
1021
1036
  const sorted: Value[] = [];
1022
1037
  for (const element of elements) {
@@ -1026,7 +1041,6 @@ const sortLikeTlc = (elements: Value[]) => {
1026
1041
  return sorted;
1027
1042
  };
1028
1043
 
1029
- // Calls a method of a value as TLC does, whose failure the value heads when it has a source.
1030
1044
  const callTracedMethod = <Result>(receiver: Value, method: () => Result) => {
1031
1045
  const sets = setTrace.sets;
1032
1046
  if (sets === undefined) return method();
@@ -1036,43 +1050,66 @@ const callTracedMethod = <Result>(receiver: Value, method: () => Result) => {
1036
1050
  return result;
1037
1051
  };
1038
1052
 
1039
- // ValueVec.search on sorted elements: a binary search with compareTo, which ends where the element
1040
- // is or would go.
1041
1053
  const searchLikeTlc = (element: Value, sorted: Value[]) => {
1042
- const bounds = { low: 0, high: sorted.length };
1043
- while (bounds.low < bounds.high) {
1044
- const middle = bounds.low + ((bounds.high - bounds.low) >> 1);
1054
+ let low = 0;
1055
+ let high = sorted.length;
1056
+ while (low < high) {
1057
+ const middle = low + ((high - low) >> 1);
1045
1058
  const comparison = callTracedMethod(element, () => compareLikeTlc(element, sorted[middle]));
1046
1059
  if (comparison === 0) return { index: middle, isFound: true };
1047
- if (comparison < 0) bounds.high = middle;
1048
- else bounds.low = middle + 1;
1060
+ if (comparison < 0) high = middle;
1061
+ else low = middle + 1;
1049
1062
  }
1050
- return { index: bounds.low, isFound: false };
1063
+ return { index: low, isFound: false };
1051
1064
  };
1052
1065
 
1053
- // TLC checks membership in a set enumeration it hasn't sorted element by element, with the equals
1054
- // method of each member.
1055
1066
  const isElementOfLikeTlc = (element: Value, elements: Value[]) =>
1056
1067
  elements.some((member) => callTracedMethod(member, () => equalsLikeTlc(member, element)));
1057
1068
 
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>();
1069
+ export const getWrittenElements = (set: SetValue | MixedSetValue) =>
1070
+ set.kind === "MixedSet" || set.isNormalized
1071
+ ? set.elements
1072
+ : (set.writtenElements ?? set.elements);
1061
1073
 
1062
- // IValue.deepNormalize, which TLC applies to the constants of the config and the constant
1063
- // definitions it computes as it starts.
1064
1074
  export const markNormalized = (value: Value): void => {
1065
1075
  if (typeof value !== "object") return;
1066
1076
  if (value.kind === "Set") {
1067
- normalizedSets.add(value);
1077
+ value.isNormalized = true;
1068
1078
  value.elements.forEach(markNormalized);
1069
1079
  }
1070
1080
  if (value.kind === "Function") {
1081
+ value.writtenKeys = undefined;
1071
1082
  value.domain.forEach(markNormalized);
1072
1083
  value.range.forEach(markNormalized);
1073
1084
  }
1074
1085
  };
1075
1086
 
1087
+ export const normalizeShallowly = (value: Value): void => {
1088
+ if (typeof value !== "object" || isCachedSet(value)) return;
1089
+ switch (value.kind) {
1090
+ case "Set":
1091
+ value.isNormalized = true;
1092
+ return;
1093
+ case "MixedSet":
1094
+ toFiniteSet(value);
1095
+ return;
1096
+ case "FilteredSet":
1097
+ case "Subset":
1098
+ return normalizeShallowly(value.base);
1099
+ case "SetOperation":
1100
+ if (value.operator === "\\cup") return;
1101
+ normalizeShallowly(value.left);
1102
+ return normalizeShallowly(value.right);
1103
+ case "FunctionSet":
1104
+ normalizeShallowly(value.domain);
1105
+ return normalizeShallowly(value.range);
1106
+ case "RecordSet":
1107
+ return value.sets.forEach(normalizeShallowly);
1108
+ case "ProductSet":
1109
+ return value.factors.forEach(normalizeShallowly);
1110
+ }
1111
+ };
1112
+
1076
1113
  export const isEqualLikeTlc = (left: Value, right: Value) =>
1077
1114
  computeLikeTlcOnFailure(valuesEqual, equalsLikeTlc, left, right);
1078
1115
 
@@ -1083,8 +1120,18 @@ const isStrictlySorted = (elements: Value[]) => {
1083
1120
  return true;
1084
1121
  };
1085
1122
 
1123
+ const isAscendingIntegers = (elements: Value[]) => {
1124
+ for (let index = 0; index < elements.length; index++) {
1125
+ const element = elements[index];
1126
+ const previous = index > 0 ? elements[index - 1] : undefined;
1127
+ if (typeof element !== "number" || (typeof previous === "number" && previous >= element)) {
1128
+ return false;
1129
+ }
1130
+ }
1131
+ return true;
1132
+ };
1133
+
1086
1134
  export const createSet = (elements: Value[]): SetValue => {
1087
- // ValueVec.sort compares each element after the first with those before it.
1088
1135
  for (let index = 1; index < elements.length; index++) cacheSet(elements[index]);
1089
1136
  if (elements.length < 2 || isStrictlySorted(elements)) return createSortedSet(elements);
1090
1137
  const sorted = [...elements].sort(compareValues);
@@ -1095,15 +1142,17 @@ export const createSet = (elements: Value[]): SetValue => {
1095
1142
  return createSortedSet(unique);
1096
1143
  };
1097
1144
 
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>(
1145
+ export const createEnumeratedSet = (elements: Value[]): SetValue | MixedSetValue => {
1146
+ if (isAscendingIntegers(elements)) return createSortedSet(elements);
1147
+ const set = computeLikeTlcOnFailure<Value[], undefined, SetValue | MixedSetValue>(
1102
1148
  createSet,
1103
1149
  (mixed) => ({ kind: "MixedSet", elements: mixed }),
1104
1150
  elements,
1105
1151
  undefined,
1106
1152
  );
1153
+ if (set.kind === "Set" && set.elements !== elements) set.writtenElements = elements;
1154
+ return set;
1155
+ };
1107
1156
 
1108
1157
  export const EMPTY_SET = createSortedSet([]);
1109
1158
 
@@ -1219,7 +1268,6 @@ export const createWrittenFunction = (pairs: [Value, Value][]) => {
1219
1268
  const functionValue = createFunction(pairs);
1220
1269
  const isWrittenSorted =
1221
1270
  functionValue.domain.length !== pairs.length ||
1222
- pairs.some((pair) => typeof pair[0] !== "string") ||
1223
1271
  pairs.every((pair, index) => pair[0] === functionValue.domain[index]);
1224
1272
  return isWrittenSorted
1225
1273
  ? functionValue
@@ -1229,23 +1277,21 @@ export const createWrittenFunction = (pairs: [Value, Value][]) => {
1229
1277
  );
1230
1278
  };
1231
1279
 
1280
+ const MAX_SHARED_INTERVAL_LENGTH = 1024;
1232
1281
  const intervalDomains: Value[][] = [];
1282
+ const longIntervalDomains = new Map<number, WeakRef<Value[]>>();
1233
1283
  const intervalValues: IntervalValue[] = [];
1234
1284
  const intervalArrays = new WeakMap<Value[], IntervalValue>();
1235
1285
 
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.
1239
1286
  const getIntervalDomain = (length: number): Value[] => {
1240
- const cached = intervalDomains[length];
1287
+ const cached = intervalDomains[length] ?? longIntervalDomains.get(length)?.deref();
1241
1288
  if (cached) return cached;
1242
- const domain = Array.from({ length }, (_, index) => index + 1);
1243
- intervalDomains[length] = domain;
1289
+ const domain = Array.from({ length }, (_value, index) => index + 1);
1290
+ if (length > MAX_SHARED_INTERVAL_LENGTH) longIntervalDomains.set(length, new WeakRef(domain));
1291
+ else intervalDomains[length] = domain;
1244
1292
  return domain;
1245
1293
  };
1246
1294
 
1247
- // The elements of an interval for a caller that only iterates them, so they need not record
1248
- // the interval for DOMAIN.
1249
1295
  export const getIntervalElements = (value: IntervalValue): Value[] => {
1250
1296
  getCardinality(value);
1251
1297
  if (value.low === 1 && value.high >= 1) return getIntervalDomain(value.high);
@@ -1255,10 +1301,11 @@ export const getIntervalElements = (value: IntervalValue): Value[] => {
1255
1301
  };
1256
1302
 
1257
1303
  const isIntervalDomain = (domain: Value[]) =>
1258
- domain.length > 0 && (domain === intervalDomains[domain.length] || intervalArrays.has(domain));
1304
+ (domain.length > 0 &&
1305
+ (domain === intervalDomains[domain.length] ||
1306
+ domain === longIntervalDomains.get(domain.length)?.deref())) ||
1307
+ intervalArrays.has(domain);
1259
1308
 
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.
1262
1309
  export const getFunctionDomain = (set: Value): Value[] => {
1263
1310
  const elements = toFiniteSet(set).elements;
1264
1311
  return isIntervalDomain(elements) && !(typeof set === "object" && set.kind === "Interval")
@@ -1283,7 +1330,6 @@ export const createRecord = (fields: [string, Value][]): FunctionValue =>
1283
1330
  export const createSortedRecord = (names: Value[], range: Value[]) =>
1284
1331
  setFunctionClass(createSortedFunction(names, range), "record");
1285
1332
 
1286
- // TLC's Enumerable classes: every set except the ones it implements in Java.
1287
1333
  export const isTlcEnumerable = (value: Value) => isSetValue(value) && !isOverriddenSet(value);
1288
1334
 
1289
1335
  const formatUnion = (value: UnionValue, isStrict = false) =>
@@ -1306,7 +1352,7 @@ const getUnionSet = (set: Value, index: number, union: UnionValue) => {
1306
1352
  throw new TlaEvaluationError(
1307
1353
  index === 0
1308
1354
  ? "Attempted to enumerate UNION(s), but some element of s is nonenumerable."
1309
- : `Attempted to enumerate the nonenumerable set:\n${formatValue(set)}\nwhen enumerating:\n${formatUnion(union)}`,
1355
+ : `Attempted to enumerate the nonenumerable set:\n${prettyPrint(formatValue(set))}\nwhen enumerating:\n${prettyPrint(formatUnion(union))}`,
1310
1356
  );
1311
1357
  };
1312
1358
 
@@ -1334,7 +1380,13 @@ export const isEnumerable = (value: Value): boolean => {
1334
1380
  case "ProductSet":
1335
1381
  return value.factors.every(isEnumerable) || getEmptiness(value) === true;
1336
1382
  case "Union":
1337
- return isEnumerable(value.base) && getStreamedElements(value.base).every(isEnumerable);
1383
+ return (
1384
+ isEnumerable(value.base) &&
1385
+ (isEnumeratedSet(value.base)
1386
+ ? getWrittenElements(value.base)
1387
+ : getStreamedElements(value.base)
1388
+ ).every(isEnumerable)
1389
+ );
1338
1390
  case "SetOperation":
1339
1391
  if (value.operator === "\\cup") return isEnumerable(value.left) && isEnumerable(value.right);
1340
1392
  if (value.operator === "\\cap") return isEnumerable(value.left) || isEnumerable(value.right);
@@ -1407,26 +1459,24 @@ const advanceCombination = (indices: number[], length: number) => {
1407
1459
  return false;
1408
1460
  };
1409
1461
 
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.
1413
1462
  export const getLazySubsets = (value: Value): Value[] | undefined => {
1414
1463
  if (typeof value !== "object" || value.kind !== "Subset" || isOverriddenSet(value.base)) {
1415
1464
  return undefined;
1416
1465
  }
1417
1466
  const base = toFiniteSet(value.base).elements;
1418
- if (base.length <= MAXIMUM_ENUMERATED_SUBSET_BASE) return undefined;
1419
- const cursor = { index: -1, indices: [0] };
1467
+ if (base.length <= MAXIMUM_BUILT_SUBSET_BASE) return undefined;
1468
+ let cursorIndex = -1;
1469
+ let indices = [0];
1420
1470
  const getSubset = (index: number) => {
1421
- if (index <= cursor.index) cursor.index = -1;
1422
- while (cursor.index < index) {
1423
- if (cursor.index === -1) cursor.indices = [];
1424
- else if (!advanceCombination(cursor.indices, base.length)) {
1425
- cursor.indices = Array.from({ length: cursor.indices.length + 1 }, (_, item) => item);
1471
+ if (index <= cursorIndex) cursorIndex = -1;
1472
+ while (cursorIndex < index) {
1473
+ if (cursorIndex === -1) indices = [];
1474
+ else if (!advanceCombination(indices, base.length)) {
1475
+ indices = Array.from({ length: indices.length + 1 }, (_value, position) => position);
1426
1476
  }
1427
- cursor.index++;
1477
+ cursorIndex++;
1428
1478
  }
1429
- return createSortedSet(cursor.indices.map((item) => base[item]));
1479
+ return createSortedSet(indices.map((baseIndex) => base[baseIndex]));
1430
1480
  };
1431
1481
  const length = 2 ** base.length;
1432
1482
  const isIndex = (property: string | symbol) =>
@@ -1445,7 +1495,7 @@ export const getLazySubsets = (value: Value): Value[] | undefined => {
1445
1495
  const getSortedSubsets = (base: Value[]) => {
1446
1496
  const subsets: Value[] = [];
1447
1497
  for (let size = 0; size <= base.length; size++) {
1448
- const indices = Array.from({ length: size }, (_, index) => index);
1498
+ const indices = Array.from({ length: size }, (_value, index) => index);
1449
1499
  do {
1450
1500
  subsets.push(createSortedSet(indices.map((index) => base[index])));
1451
1501
  } while (advanceCombination(indices, base.length));
@@ -1453,9 +1503,6 @@ const getSortedSubsets = (base: Value[]) => {
1453
1503
  return subsets;
1454
1504
  };
1455
1505
 
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.
1459
1506
  const getComponentElements = (
1460
1507
  sets: Value[],
1461
1508
  getElements: (set: Value) => Value[],
@@ -1472,7 +1519,6 @@ const getComponentElements = (
1472
1519
  return lists;
1473
1520
  };
1474
1521
 
1475
- // getElements enumerates the sets a set of functions, records, or tuples combines.
1476
1522
  const enumerateSet = (
1477
1523
  value: Value,
1478
1524
  getElements = (set: Value) => toFiniteSet(set).elements,
@@ -1490,8 +1536,6 @@ const enumerateSet = (
1490
1536
  return elements;
1491
1537
  }
1492
1538
  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.
1495
1539
  if (getCardinality(value.base) === 0) return getSortedSubsets([]);
1496
1540
  if (!isSetValue(value.base)) {
1497
1541
  throw new TlaEvaluationError(
@@ -1505,17 +1549,16 @@ const enumerateSet = (
1505
1549
  return getSortedSubsets(base);
1506
1550
  }
1507
1551
  case "FunctionSet": {
1508
- if (!valueVersion.is174 && isEmptySet(value)) return [];
1552
+ if (!isVersion174 && isEmptySet(value)) return [];
1509
1553
  if (isOverriddenSet(value.domain)) {
1510
1554
  throw new TlaEvaluationError(
1511
- `Attempted to enumerate a set of the form [D -> R],but the domain D:\n${formatValue(value.domain)}\ncannot be enumerated.`,
1555
+ `Attempted to enumerate a set of the form [D -> R],but the domain D:\n${prettyPrint(formatValue(value.domain))}\ncannot be enumerated.`,
1512
1556
  );
1513
1557
  }
1514
1558
  const domain = getFunctionDomain(value.domain);
1515
- // TLC 1.7.4 requires an enumerable range even of an empty domain.
1516
- if ((domain.length > 0 || valueVersion.is174) && isOverriddenSet(value.range)) {
1559
+ if ((domain.length > 0 || isVersion174) && isOverriddenSet(value.range)) {
1517
1560
  throw new TlaEvaluationError(
1518
- `Attempted to enumerate a set of the form [D -> R],but the range R:\n${formatValue(value.range)}\ncannot be enumerated.`,
1561
+ `Attempted to enumerate a set of the form [D -> R],but the range R:\n${prettyPrint(formatValue(value.range))}\ncannot be enumerated.`,
1519
1562
  );
1520
1563
  }
1521
1564
  const range = domain.length === 0 ? [] : getElements(value.range);
@@ -1524,77 +1567,82 @@ const enumerateSet = (
1524
1567
  );
1525
1568
  }
1526
1569
  case "RecordSet": {
1527
- if (!valueVersion.is174 && isEmptySet(value)) return [];
1570
+ if (!isVersion174 && isEmptySet(value)) return [];
1528
1571
  const fields = getComponentElements(
1529
1572
  value.sets,
1530
1573
  getElements,
1531
1574
  (set, index) =>
1532
- `Attempted to enumerate a set of the form [l1 : v1, ..., ln : vn],\nbut can't enumerate the value of the \`${value.names[index]}' field:\n${formatValue(set)}`,
1575
+ `Attempted to enumerate a set of the form [l1 : v1, ..., ln : vn],\nbut can't enumerate the value of the \`${value.names[index]}' field:\n${prettyPrint(formatValue(set))}`,
1533
1576
  );
1534
1577
  return getCartesianProduct(fields).map((combination) =>
1535
1578
  createRecord(value.names.map((name, index): [string, Value] => [name, combination[index]])),
1536
1579
  );
1537
1580
  }
1538
1581
  case "ProductSet": {
1539
- if (!valueVersion.is174 && isEmptySet(value)) return [];
1582
+ if (!isVersion174 && isEmptySet(value)) return [];
1540
1583
  const factors = getComponentElements(
1541
1584
  value.factors,
1542
1585
  getElements,
1543
1586
  (factor, index) =>
1544
- `Attempted to enumerate a set of the form s1 \\X s2 ... \\X sn,\nbut can't enumerate s${index}:\n${formatValue(factor)}`,
1587
+ `Attempted to enumerate a set of the form s1 \\X s2 ... \\X sn,\nbut can't enumerate s${index}:\n${prettyPrint(formatValue(factor))}`,
1545
1588
  );
1546
1589
  return getCartesianProduct(factors).map(createTuple);
1547
1590
  }
1548
1591
  case "FilteredSet":
1549
1592
  if (!isSetValue(value.base) || isOverriddenSet(value.base)) {
1550
1593
  throw new TlaEvaluationError(
1551
- `Attempted to enumerate { x \\in S : p(x) } when S:\n${formatValue(value.base)}\nis not enumerable`,
1594
+ `Attempted to enumerate { x \\in S : p(x) } when S:\n${prettyPrint(formatValue(value.base))}\nis not enumerable`,
1552
1595
  );
1553
1596
  }
1554
- return toFiniteSet(value.base).elements.filter(value.test);
1597
+ return toFiniteSet(
1598
+ createEnumeratedSet(
1599
+ getStreamedElements(value.base).filter(
1600
+ value.startPass?.(true) ?? ((element) => value.test(element, false)),
1601
+ ),
1602
+ ),
1603
+ ).elements;
1555
1604
  case "Union": {
1556
- const elements = getUnionSets(value).flatMap(
1557
- (set, index) => toFiniteSet(getUnionSet(set, index, value)).elements,
1558
- );
1605
+ const elements: Value[] = [];
1606
+ getUnionSets(value).forEach((set, index) => {
1607
+ const unionSet = getUnionSet(set, index, value);
1608
+ if (isBeyondSetBound(unionSet)) throw new TlaSetBoundError(getSetBoundMessage());
1609
+ getStreamedElements(unionSet).forEach((element) => addBoundedElement(elements, element));
1610
+ });
1559
1611
  return toFiniteSet(createEnumeratedSet(elements)).elements;
1560
1612
  }
1561
1613
  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
1614
  if (
1571
1615
  value.operator === "\\cap" &&
1572
1616
  !isTlcEnumerable(value.left) &&
1573
1617
  !isTlcEnumerable(value.right)
1574
1618
  ) {
1575
1619
  throw new TlaEvaluationError(
1576
- `Attempted to enumerate S \\cap T when neither S:\n${formatValue(value.left)}\nnor T:\n${formatValue(value.right)}\nis enumerable`,
1620
+ `Attempted to enumerate S \\cap T when neither S:\n${prettyPrint(formatValue(value.left))}\nnor T:\n${prettyPrint(formatValue(value.right))}\nis enumerable`,
1577
1621
  );
1578
1622
  }
1579
1623
  if (value.operator === "\\" && !isTlcEnumerable(value.left)) {
1580
1624
  throw new TlaEvaluationError(
1581
- `Attempted to enumerate S \\ T when S:\n${formatValue(value.left)}\nis not enumerable.`,
1625
+ `Attempted to enumerate S \\ T when S:\n${prettyPrint(formatValue(value.left))}\nis not enumerable.`,
1582
1626
  );
1583
1627
  }
1584
1628
  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
- );
1629
+ return toFiniteSet(createEnumeratedSet(listUnionLikeTlc(value))).elements;
1591
1630
  }
1592
1631
  const isLeftEnumerated = value.operator === "\\" || isTlcEnumerable(value.left);
1593
1632
  const enumerated = isLeftEnumerated ? value.left : value.right;
1594
1633
  const other = isLeftEnumerated ? value.right : value.left;
1595
- return toFiniteSet(enumerated).elements.filter(
1596
- (element) => isElementOf(element, other) === (value.operator === "\\cap"),
1634
+ const kept: Value[] = [];
1635
+ forEachElement(
1636
+ typeof enumerated === "object" && enumerated.kind === "Interval"
1637
+ ? enumerated
1638
+ : getStreamedElements(enumerated),
1639
+ (element) => {
1640
+ if (isElementOf(element, other) === (value.operator === "\\cap")) {
1641
+ addBoundedElement(kept, element);
1642
+ }
1643
+ },
1597
1644
  );
1645
+ return toFiniteSet(createEnumeratedSet(kept)).elements;
1598
1646
  }
1599
1647
  case "InfiniteSet":
1600
1648
  case "SequenceSet":
@@ -1631,32 +1679,92 @@ export const toFiniteSet = (value: Value): SetValue => {
1631
1679
  return set;
1632
1680
  };
1633
1681
 
1634
- // SetCupValue#toSetEnum.
1635
- const listUnionLikeTlc = (union: SetOperationValue) => [
1636
- ...toFiniteSet(union.left).elements,
1637
- ...toFiniteSet(union.right).elements,
1638
- ];
1639
-
1640
- // EnumerableValue#elements(NORMALIZED) sorts a union outside its methods, so a failed comparison
1641
- // 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;
1682
+ const openStream = (value: Value): void => {
1683
+ if (typeof value !== "object" || isCachedSet(value)) return;
1684
+ switch (value.kind) {
1685
+ case "MixedSet":
1686
+ toFiniteSet(value);
1687
+ return;
1688
+ case "FilteredSet":
1689
+ if (!isTlcEnumerable(value.base)) toFiniteSet(value);
1690
+ return openStream(value.base);
1691
+ case "Union":
1692
+ if (!isEnumeratedSet(value.base) && isTlcEnumerable(value.base)) {
1693
+ return openStream(value.base);
1694
+ }
1695
+ getUnionSets(value)
1696
+ .slice(0, 1)
1697
+ .forEach((set) => openStream(getUnionSet(set, 0, value)));
1698
+ return;
1699
+ case "SetOperation":
1700
+ if (value.operator === "\\" && !isTlcEnumerable(value.left)) toFiniteSet(value);
1701
+ if (
1702
+ value.operator === "\\cup" &&
1703
+ (!isTlcEnumerable(value.left) || !isTlcEnumerable(value.right))
1704
+ ) {
1705
+ toFiniteSet(value);
1706
+ }
1707
+ if (value.operator !== "\\cap" || isTlcEnumerable(value.left)) openStream(value.left);
1708
+ else openStream(value.right);
1709
+ if (value.operator === "\\cup") openStream(value.right);
1710
+ }
1711
+ };
1712
+
1713
+ const listUnionLikeTlc = (union: SetOperationValue) => {
1714
+ if (!isTlcEnumerable(union.left) || !isTlcEnumerable(union.right)) {
1715
+ throw new TlaEvaluationError(
1716
+ `Attempted to enumerate S \\cup T when S:\n${prettyPrint(formatValue(union.left))}\nand T:\n${prettyPrint(formatValue(union.right))}\nare not both enumerable`,
1717
+ );
1718
+ }
1719
+ openStream(union.left);
1720
+ openStream(union.right);
1721
+ if (isBeyondSetBound(union.left)) throw new TlaSetBoundError(getSetBoundMessage());
1722
+ const left = getStreamedElements(union.left);
1723
+ const right = isBeyondSetBound(union.right) ? undefined : getStreamedElements(union.right);
1724
+ if (!right || left.length + right.length > getMaximumSetSize()) {
1725
+ throw new TlaSetBoundError(getSetBoundMessage());
1726
+ }
1727
+ return [...left, ...right];
1728
+ };
1729
+
1730
+ export const getNormalizedSetElements = (value: Value) => {
1731
+ if (
1732
+ typeof value !== "object" ||
1733
+ value.kind !== "SetOperation" ||
1734
+ value.operator !== "\\cup" ||
1735
+ value.enumerated
1736
+ ) {
1737
+ return toFiniteSet(value).elements;
1738
+ }
1739
+ const listed = callTracedMethod(value, () => listUnionLikeTlc(value));
1740
+ const elements = toFiniteSet(createEnumeratedSet(listed)).elements;
1741
+ value.enumerated = createSortedSet(elements);
1742
+ return elements;
1743
+ };
1651
1744
 
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;
1745
+ export const someStreamedElement = (value: Value, visit: (element: Value) => boolean): boolean => {
1746
+ if (typeof value !== "object" || isCachedSet(value)) {
1747
+ return toFiniteSet(value).elements.some(visit);
1748
+ }
1656
1749
  const sets = setTrace.sets;
1657
1750
  sets?.push(value);
1658
- const elements = streamElements(value);
1751
+ openStream(value);
1752
+ const isFound = someElementOfStream(value, (element) => {
1753
+ sets?.pop();
1754
+ const isAccepted = visit(element);
1755
+ sets?.push(value);
1756
+ return isAccepted;
1757
+ });
1659
1758
  sets?.pop();
1759
+ return isFound;
1760
+ };
1761
+
1762
+ export const getStreamedElements = (value: Value) => {
1763
+ const elements: Value[] = [];
1764
+ someStreamedElement(value, (element) => {
1765
+ elements.push(element);
1766
+ return false;
1767
+ });
1660
1768
  return elements;
1661
1769
  };
1662
1770
 
@@ -1669,10 +1777,6 @@ const getCombinedSets = (value: ObjectValue) =>
1669
1777
  ? [value.range]
1670
1778
  : undefined;
1671
1779
 
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.
1676
1780
  export const isSettledValue = (value: Value): boolean => {
1677
1781
  if (typeof value !== "object") return true;
1678
1782
  switch (value.kind) {
@@ -1701,8 +1805,6 @@ export const isSettledValue = (value: Value): boolean => {
1701
1805
  }
1702
1806
  };
1703
1807
 
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.
1706
1808
  const isStreamedApart = (value: Value): boolean => {
1707
1809
  if (typeof value !== "object" || isCachedSet(value)) return false;
1708
1810
  if (value.kind === "Union") return true;
@@ -1715,36 +1817,43 @@ const isStreamedApart = (value: Value): boolean => {
1715
1817
  return getCombinedSets(value)?.some(isStreamedApart) ?? false;
1716
1818
  };
1717
1819
 
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.
1820
+ const someElementOfStream = (value: ObjectValue, visit: (element: Value) => boolean): boolean => {
1721
1821
  if (value.kind === "Union") {
1722
- return getUnionSets(value, getStreamedElements).flatMap((set, index) =>
1723
- getStreamedElements(getUnionSet(set, index, value)),
1822
+ return getUnionSets(value, getStreamedElements).some((set, index) =>
1823
+ someStreamedElement(getUnionSet(set, index, value), visit),
1724
1824
  );
1725
1825
  }
1726
- if (value.kind === "FilteredSet" && !isOverriddenSet(value.base)) {
1727
- return getStreamedElements(value.base).filter(value.test);
1826
+ if (value.kind === "FilteredSet" && isTlcEnumerable(value.base)) {
1827
+ const test = value.startPass?.(false);
1828
+ if (test) return someStreamedElement(value.base, (element) => test(element) && visit(element));
1829
+ return someStreamedElement(
1830
+ value.base,
1831
+ (element) => value.test(element, false) && visit(element),
1832
+ );
1728
1833
  }
1729
1834
  const components = getCombinedSets(value);
1730
- if (components?.some(isStreamedApart)) return enumerateSet(value, getStreamedElements);
1731
- if (value.kind !== "SetOperation") return toFiniteSet(value).elements;
1835
+ if (components?.some(isStreamedApart)) {
1836
+ return enumerateSet(value, getStreamedElements).some(visit);
1837
+ }
1838
+ if (value.kind !== "SetOperation") return toFiniteSet(value).elements.some(visit);
1732
1839
  if (value.operator === "\\cup") {
1733
1840
  return !isTlcEnumerable(value.left) || !isTlcEnumerable(value.right)
1734
- ? toFiniteSet(value).elements
1735
- : [...getStreamedElements(value.left), ...getStreamedElements(value.right)];
1841
+ ? toFiniteSet(value).elements.some(visit)
1842
+ : someStreamedElement(value.left, visit) || someStreamedElement(value.right, visit);
1736
1843
  }
1737
1844
  const isLeftEnumerated = value.operator === "\\" || isTlcEnumerable(value.left);
1738
1845
  const enumerated = isLeftEnumerated ? value.left : value.right;
1739
1846
  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"),
1847
+ if (!isTlcEnumerable(enumerated)) return toFiniteSet(value).elements.some(visit);
1848
+ return someStreamedElement(
1849
+ enumerated,
1850
+ (element) => isElementOf(element, other) === (value.operator === "\\cap") && visit(element),
1743
1851
  );
1744
1852
  };
1745
1853
 
1746
1854
  export const isEmptySet = (value: Value): boolean => {
1747
1855
  if (typeof value !== "object" || !isSetValue(value)) {
1856
+ setTrace.sets?.push(value);
1748
1857
  throw new TlaEvaluationError(`Shouldn't call isEmpty() on value ${formatValue(value)}`);
1749
1858
  }
1750
1859
  switch (value.kind) {
@@ -1786,20 +1895,18 @@ const getProductCardinality = (
1786
1895
  }, 1);
1787
1896
 
1788
1897
  const describeOverflow = (value: Value) =>
1789
- `Overflow when computing the number of elements in:\n${formatValue(value)}`;
1898
+ `Overflow when computing the number of elements in:\n${prettyPrint(formatValue(value))}`;
1790
1899
 
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.
1793
1900
  export const getCardinality = (value: Value, version?: TlcVersion): number => {
1794
1901
  if (typeof value !== "object") {
1795
1902
  throw new TlaEvaluationError(
1796
- `Attempted to compute the number of elements in the ${describeKind(value)} ${formatValue(value)}.`,
1903
+ `Attempted to compute the number of elements in the ${describeKind(value)} ${prettyPrint(formatValue(value))}.`,
1797
1904
  );
1798
1905
  }
1799
1906
  switch (value.kind) {
1800
1907
  case "ModelValue":
1801
1908
  throw new TlaEvaluationError(
1802
- `Attempted to compute the number of elements in the model value ${formatValue(value)}.`,
1909
+ `Attempted to compute the number of elements in the model value ${prettyPrint(formatValue(value))}.`,
1803
1910
  );
1804
1911
  case "Function":
1805
1912
  return value.domain.length;
@@ -1817,7 +1924,7 @@ export const getCardinality = (value: Value, version?: TlcVersion): number => {
1817
1924
  case "InfiniteSet":
1818
1925
  case "SequenceSet":
1819
1926
  throw new TlaEvaluationError(
1820
- `Attempted to compute the number of elements in the overridden value ${formatValue(value)}.`,
1927
+ `Attempted to compute the number of elements in the overridden value ${prettyPrint(formatValue(value))}.`,
1821
1928
  );
1822
1929
  case "Subset": {
1823
1930
  const size = getCardinality(value.base, version);
@@ -1833,12 +1940,12 @@ export const getCardinality = (value: Value, version?: TlcVersion): number => {
1833
1940
  const domainSize = getCardinality(value.domain, version);
1834
1941
  const rangeSize = getCardinality(value.range, version);
1835
1942
  if (rangeSize <= 1) return domainSize === 0 ? 1 : rangeSize;
1836
- const size = { value: 1 };
1943
+ let size = 1;
1837
1944
  for (let index = 0; index < domainSize; index++) {
1838
- size.value *= rangeSize;
1839
- if (size.value > MAXIMUM_INTEGER) throw new TlaEvaluationError(describeOverflow(value));
1945
+ size *= rangeSize;
1946
+ if (size > MAXIMUM_INTEGER) throw new TlaEvaluationError(describeOverflow(value));
1840
1947
  }
1841
- return size.value;
1948
+ return size;
1842
1949
  }
1843
1950
  case "RecordSet":
1844
1951
  if (version !== "1.7.4" && isEmptySet(value)) return 0;
@@ -1848,7 +1955,8 @@ export const getCardinality = (value: Value, version?: TlcVersion): number => {
1848
1955
  return getProductCardinality(
1849
1956
  value.factors,
1850
1957
  version,
1851
- () => `Overflow when computing the number of elements in ${formatValue(value)}`,
1958
+ () =>
1959
+ `Overflow when computing the number of elements in ${prettyPrint(formatValue(value))}`,
1852
1960
  );
1853
1961
  default:
1854
1962
  cacheSet(value);
@@ -1857,12 +1965,12 @@ export const getCardinality = (value: Value, version?: TlcVersion): number => {
1857
1965
  };
1858
1966
 
1859
1967
  const describeInfiniteCheck = (value: Value) =>
1860
- `Attempted to check if the set ${formatValue(value)}is finite.`;
1968
+ `Attempted to check if the set ${prettyPrint(formatValue(value))}is finite.`;
1861
1969
 
1862
1970
  export const isFiniteSet = (value: Value): boolean => {
1863
1971
  if (typeof value !== "object" || value.kind === "ModelValue") {
1864
1972
  throw new TlaEvaluationError(
1865
- `Attempted to check if the ${describeKind(value)} ${formatValue(value)} is a finite set.`,
1973
+ `Attempted to check if the ${describeKind(value)} ${prettyPrint(formatValue(value))} is a finite set.`,
1866
1974
  );
1867
1975
  }
1868
1976
  switch (value.kind) {
@@ -1873,7 +1981,7 @@ export const isFiniteSet = (value: Value): boolean => {
1873
1981
  return true;
1874
1982
  case "LazyFunction":
1875
1983
  throw new TlaEvaluationError(
1876
- `Attempted to check if the function:\n${formatValue(value)}\nis a finite set.`,
1984
+ `Attempted to check if the function:\n${prettyPrint(formatValue(value))}\nis a finite set.`,
1877
1985
  );
1878
1986
  case "InfiniteSet":
1879
1987
  return false;
@@ -1891,12 +1999,12 @@ export const isFiniteSet = (value: Value): boolean => {
1891
1999
  case "RecordSet":
1892
2000
  case "ProductSet": {
1893
2001
  const parts = value.kind === "RecordSet" ? value.sets : value.factors;
1894
- const finiteness = { isAllFinite: true };
2002
+ let isAllFinite = true;
1895
2003
  for (const part of parts) {
1896
- if (!isFiniteSet(part)) finiteness.isAllFinite = false;
2004
+ if (!isFiniteSet(part)) isAllFinite = false;
1897
2005
  else if (isEmptySet(part)) return true;
1898
2006
  }
1899
- return finiteness.isAllFinite;
2007
+ return isAllFinite;
1900
2008
  }
1901
2009
  case "Union":
1902
2010
  if (!isTlcEnumerable(value.base)) {
@@ -1919,7 +2027,7 @@ export const isFiniteSet = (value: Value): boolean => {
1919
2027
  case "FilteredSet":
1920
2028
  if (!isFiniteSet(value.base)) {
1921
2029
  throw new TlaEvaluationError(
1922
- `Attempted to check if expression of form {x \\in S : p(x)} is a finite set, but cannot check if S:\n${formatValue(value.base)}\nis finite.`,
2030
+ `Attempted to check if expression of form {x \\in S : p(x)} is a finite set, but cannot check if S:\n${prettyPrint(formatValue(value.base))}\nis finite.`,
1923
2031
  );
1924
2032
  }
1925
2033
  return true;
@@ -1927,19 +2035,45 @@ export const isFiniteSet = (value: Value): boolean => {
1927
2035
  };
1928
2036
 
1929
2037
  const findSortedIndex = (sortedValues: Value[], target: Value, compare = compareValues) => {
1930
- const bounds = { low: 0, high: sortedValues.length - 1 };
1931
- while (bounds.low <= bounds.high) {
1932
- const middle = (bounds.low + bounds.high) >> 1;
2038
+ let low = 0;
2039
+ let high = sortedValues.length - 1;
2040
+ while (low <= high) {
2041
+ const middle = (low + high) >> 1;
1933
2042
  const comparison = compare(sortedValues[middle], target);
1934
2043
  if (comparison === 0) return middle;
1935
- if (comparison < 0) bounds.low = middle + 1;
1936
- else bounds.high = middle - 1;
2044
+ if (comparison < 0) low = middle + 1;
2045
+ else high = middle - 1;
1937
2046
  }
1938
2047
  return -1;
1939
2048
  };
1940
2049
 
2050
+ export const createUnsortedCopy = (set: SetValue, added: Value[]): SetValue => {
2051
+ const elements = set.elements;
2052
+ if (elements.length > getMaximumSetSize()) throw new TlaSetBoundError(getSetBoundMessage());
2053
+ const isAdded = Array.from({ length: elements.length }, () => false);
2054
+ const written = added.filter((element) => {
2055
+ const index = findSortedIndex(elements, element);
2056
+ if (isAdded[index]) return false;
2057
+ isAdded[index] = true;
2058
+ return true;
2059
+ });
2060
+ const copy = createSortedSet(elements);
2061
+ if (written.some((element, index) => element !== elements[index])) {
2062
+ copy.writtenElements = written;
2063
+ }
2064
+ return copy;
2065
+ };
2066
+
1941
2067
  export const getSequenceElements = (value: Value): Value[] | undefined => {
1942
2068
  if (typeof value !== "object" || !isFunctionValue(value)) return undefined;
2069
+ if (
2070
+ value.kind === "LazyFunction" &&
2071
+ (!isSetValue(value.domain) || isOverriddenSet(value.domain))
2072
+ ) {
2073
+ throw new TlaEvaluationError(
2074
+ "To convert a function of form [x \\in S |-> f(x)] to a tuple, the set S must be enumerable.",
2075
+ );
2076
+ }
1943
2077
  const functionValue = toFiniteFunction(value);
1944
2078
  return functionValue.domain.every((key, index) => key === index + 1)
1945
2079
  ? functionValue.range
@@ -1947,34 +2081,28 @@ export const getSequenceElements = (value: Value): Value[] | undefined => {
1947
2081
  };
1948
2082
 
1949
2083
  const describeNonSetMembership = (element: Value, value: Value) => {
1950
- const prefix = `Attempted to check if the value:\n${formatValue(element)}\nis an element of the`;
1951
- if (!isFunctionValue(value)) return `${prefix} ${describeKind(value)} ${formatValue(value)}`;
2084
+ const prefix = `Attempted to check if the value:\n${prettyPrint(formatValue(element))}\nis an element of the`;
2085
+ if (!isFunctionValue(value))
2086
+ return `${prefix} ${describeKind(value)} ${prettyPrint(formatValue(value))}`;
1952
2087
  const functionClass = getFunctionClass(value);
1953
2088
  if (functionClass === "record") {
1954
- return `Attempted to check if element:\n${formatValue(element)}\nis in the record:\n${formatValue(value)}`;
2089
+ return `Attempted to check if element:\n${prettyPrint(formatValue(element))}\nis in the record:\n${prettyPrint(formatValue(value))}`;
1955
2090
  }
1956
2091
  if (functionClass === "tuple") return "Attempted to check set membership in a tuple value.";
1957
- return `${prefix} function ${formatValue(value)}`;
2092
+ return `${prefix} function ${prettyPrint(formatValue(value))}`;
1958
2093
  };
1959
2094
 
1960
- // The call stack of the replay, which a failed fast path leaves frozen.
1961
2095
  interface TracedCallStack {
1962
2096
  expressions: unknown[];
1963
2097
  isFrozen: boolean;
2098
+ sources: WeakMap<ObjectValue, unknown>;
1964
2099
  fingerprint?: unknown;
1965
2100
  }
1966
2101
 
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.
1971
2102
  export const setTrace: { sets: Value[] | undefined; callStack?: TracedCallStack } = {
1972
2103
  sets: undefined,
1973
2104
  };
1974
2105
 
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.
1978
2106
  export const computeLikeTlcOnFailure = <Left, Right, Result>(
1979
2107
  compute: (left: Left, right: Right) => Result,
1980
2108
  computeLikeTlc: (left: Left, right: Right, error: TlaEvaluationError) => Result,
@@ -1999,6 +2127,11 @@ export const computeLikeTlcOnFailure = <Left, Right, Result>(
1999
2127
  }
2000
2128
  };
2001
2129
 
2130
+ export const isFingerprintedSince = (depth: number) =>
2131
+ (setTrace.sets ?? [])
2132
+ .slice(depth)
2133
+ .some((set) => typeof set === "object" && setTrace.callStack?.sources.has(set) === true);
2134
+
2002
2135
  export const isElementOf = (element: Value, set: Value): boolean => {
2003
2136
  const sets = setTrace.sets;
2004
2137
  if (sets === undefined) return isElementOfSet(element, set);
@@ -2008,46 +2141,77 @@ export const isElementOf = (element: Value, set: Value): boolean => {
2008
2141
  return isElement;
2009
2142
  };
2010
2143
 
2144
+ const isIntegerInSortedSet = (element: number, set: SetValue) => {
2145
+ const elements = set.elements;
2146
+ let low = 0;
2147
+ let high = elements.length - 1;
2148
+ while (low <= high) {
2149
+ const middle = (low + high) >> 1;
2150
+ const probe = elements[middle];
2151
+ if (typeof probe !== "number") return undefined;
2152
+ if (probe === element) return true;
2153
+ if (probe < element) low = middle + 1;
2154
+ else high = middle - 1;
2155
+ }
2156
+ return false;
2157
+ };
2158
+
2011
2159
  const isInSortedSet = (element: Value, set: SetValue) =>
2012
2160
  findSortedIndex(set.elements, element) !== -1;
2013
2161
 
2014
2162
  const isInSortedSetLikeTlc = (element: Value, set: SetValue) =>
2015
- normalizedSets.has(set)
2163
+ set.isNormalized
2016
2164
  ? searchLikeTlc(element, set.elements).isFound
2017
- : isElementOfLikeTlc(element, set.elements);
2165
+ : isElementOfLikeTlc(element, getWrittenElements(set));
2166
+
2167
+ const isModelValueMember = (modelValue: ModelValue, set: Value) => {
2168
+ if (modelValue.type !== undefined) {
2169
+ throw new TlaEvaluationError(
2170
+ `Attempted to check if the typed model value ${prettyPrint(formatValue(modelValue))} is an element of\n${prettyPrint(formatValue(set))}`,
2171
+ );
2172
+ }
2173
+ return false;
2174
+ };
2018
2175
 
2176
+ // The common cases stay small enough for V8 to inline.
2019
2177
  const isElementOfSet = (element: Value, set: Value): boolean => {
2178
+ if (typeof element === "number" && typeof set === "object") {
2179
+ if (set.kind === "Set")
2180
+ return isIntegerInSortedSet(element, set) ?? isElementOfAnySet(element, set);
2181
+ if (set.kind === "Interval") return element >= set.low && element <= set.high;
2182
+ }
2183
+ return isElementOfAnySet(element, set);
2184
+ };
2185
+
2186
+ const isElementOfAnySet = (element: Value, set: Value): boolean => {
2020
2187
  if (!isSetValue(set)) throw new TlaEvaluationError(describeNonSetMembership(element, set));
2021
2188
  switch (set.kind) {
2022
2189
  case "Set":
2023
- // SetEnumValue.member compares the element with the set's.
2024
2190
  cacheSet(element);
2025
2191
  return computeLikeTlcOnFailure(isInSortedSet, isInSortedSetLikeTlc, element, set);
2026
2192
  case "MixedSet":
2027
2193
  return isElementOfLikeTlc(element, set.elements);
2028
2194
  case "Interval":
2029
2195
  if (typeof element === "number") return element >= set.low && element <= set.high;
2030
- if (set.low <= set.high && !isModelValue(element)) {
2196
+ if (set.low <= set.high && (!isModelValue(element) || element.type !== undefined)) {
2031
2197
  throw new TlaEvaluationError(
2032
- `Attempted to check if the value:\n${formatValue(element)}\nis in the integer interval ${formatValue(set)}`,
2198
+ `Attempted to check if the value:\n${prettyPrint(formatValue(element))}\nis in the integer interval ${prettyPrint(formatValue(set))}`,
2033
2199
  );
2034
2200
  }
2035
2201
  return false;
2036
2202
  case "InfiniteSet": {
2037
2203
  if (set.name === "Any") return true;
2038
- if (isModelValue(element)) return false;
2204
+ if (isModelValue(element)) return isModelValueMember(element, set);
2039
2205
  const isMemberType =
2040
2206
  set.name === "STRING" ? typeof element === "string" : typeof element === "number";
2041
2207
  if (!isMemberType) {
2042
- throw new TlaEvaluationError(
2043
- `Attempted to check if the value:\n${formatValue(element)}\nis an element of ${set.name}.`,
2208
+ throw new TlaModuleError(
2209
+ `Attempted to check if the value:\n${prettyPrint(formatValue(element))}\nis an element of ${set.name}.`,
2044
2210
  );
2045
2211
  }
2046
2212
  return set.name !== "Nat" || (typeof element === "number" && element >= 0);
2047
2213
  }
2048
2214
  case "Subset":
2049
- // SubsetValue.member fails on any value that is not Enumerable, model values and the sets a
2050
- // Java class overrides included.
2051
2215
  if (!isSetValue(element) || isOverriddenSet(element)) {
2052
2216
  throw new TlaEvaluationError(
2053
2217
  `Attempted to check if the non-enumerable value\n${prettyPrint(formatValue(element))}\nis element of\n${prettyPrint(formatValue(set))}`,
@@ -2056,14 +2220,14 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2056
2220
  return toFiniteSet(element).elements.every((item) => isElementOf(item, set.base));
2057
2221
  case "FunctionSet": {
2058
2222
  if (!isFunctionValue(element)) {
2059
- if (isModelValue(element)) return false;
2060
- // SetOfFcnsValue.member prints the element without Values.ppr.
2223
+ if (isModelValue(element)) return isModelValueMember(element, set);
2061
2224
  throw new TlaEvaluationError(
2062
2225
  `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
2226
  );
2064
2227
  }
2228
+ forgetOwnWrittenOrder(element);
2065
2229
  const functionValue = toFiniteFunction(element);
2066
- const low = getIntervalLow(functionValue.domain);
2230
+ const low = getIntervalLow(element, functionValue.domain);
2067
2231
  const isDomain =
2068
2232
  low === undefined
2069
2233
  ? isEqualLikeTlc(set.domain, createSortedSet(functionValue.domain))
@@ -2074,11 +2238,12 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2074
2238
  return isDomain && functionValue.range.every((item) => isElementOf(item, set.range));
2075
2239
  }
2076
2240
  case "RecordSet": {
2241
+ forgetOwnWrittenOrder(element);
2077
2242
  const functionValue = isFunctionValue(element) ? toFiniteFunction(element) : undefined;
2078
2243
  if (!functionValue || !isRecordDomain(functionValue.domain)) {
2079
- if (isModelValue(element)) return false;
2244
+ if (isModelValue(element)) return isModelValueMember(element, set);
2080
2245
  throw new TlaEvaluationError(
2081
- `Attempted to check if non-record\n${formatValue(element)}\nis in the set of records:\n${formatValue(set)}`,
2246
+ `Attempted to check if non-record\n${formatValue(element)}\nis in the set of records:\n${prettyPrint(formatValue(set))}`,
2082
2247
  );
2083
2248
  }
2084
2249
  return (
@@ -2095,9 +2260,10 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2095
2260
  const isFunction =
2096
2261
  isFunctionValue(element) &&
2097
2262
  toFiniteFunction(element).domain.every((key) => typeof key === "number");
2098
- if (isFunction || isModelValue(element)) return false;
2263
+ if (isModelValue(element)) return isModelValueMember(element, set);
2264
+ if (isFunction) return false;
2099
2265
  throw new TlaEvaluationError(
2100
- `Attempted to check if non-tuple\n${formatValue(element)}\nis in the set of tuples:\n${formatValue(set)}`,
2266
+ `Attempted to check if non-tuple\n${prettyPrint(formatValue(element))}\nis in the set of tuples:\n${prettyPrint(formatValue(set))}`,
2101
2267
  );
2102
2268
  }
2103
2269
  return (
@@ -2106,14 +2272,28 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2106
2272
  );
2107
2273
  }
2108
2274
  case "FilteredSet":
2109
- return isElementOf(element, set.base) && set.test(element);
2110
- case "Union":
2275
+ try {
2276
+ return isElementOf(element, set.base) && set.test(element, true);
2277
+ } catch (error) {
2278
+ if (!(error instanceof TlaEvaluationError) || !isEvalException(error)) throw error;
2279
+ throw new TlaEvaluationError(
2280
+ `Cannot decide if element:\n${prettyPrint(formatValue(element))}\n is element of:\n${prettyPrint(formatValue(set.base))}\nand satisfies the predicate ${set.source?.predicate}`,
2281
+ );
2282
+ }
2283
+ case "Union": {
2111
2284
  if (!isTlcEnumerable(set.base)) {
2112
2285
  throw new TlaEvaluationError(
2113
- `Attempted to check if:\n ${formatValue(element)}\nis an element of the non-enumerable set:\n ${formatUnion(set)}`,
2286
+ `Attempted to check if:\n ${prettyPrint(formatValue(element))}\nis an element of the non-enumerable set:\n ${prettyPrint(formatUnion(set))}`,
2114
2287
  );
2115
2288
  }
2116
- return toFiniteSet(set.base).elements.some((inner) => isElementOf(element, inner));
2289
+ const sets = toFiniteSet(set.base).elements;
2290
+ if (sets.length > 1) {
2291
+ sets.forEach((inner) => {
2292
+ if (typeof inner === "object" && inner.kind === "Set") inner.isNormalized = true;
2293
+ });
2294
+ }
2295
+ return sets.some((inner) => isElementOf(element, inner));
2296
+ }
2117
2297
  case "SetOperation":
2118
2298
  if (set.operator === "\\cup")
2119
2299
  return isElementOf(element, set.left) || isElementOf(element, set.right);
@@ -2124,9 +2304,8 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2124
2304
  case "SequenceSet": {
2125
2305
  const elements = getSequenceElements(element);
2126
2306
  if (elements === undefined) {
2127
- if (isModelValue(element)) return false;
2128
- // Sequences.member raises TLC_MODULE_CHECK_MEMBER_OF.
2129
- throw new TlaEvaluationError(
2307
+ if (isModelValue(element)) return isModelValueMember(element, set);
2308
+ throw new TlaModuleError(
2130
2309
  `Attempted to check if the value:\n${prettyPrint(formatValue(element))}\nis an element of ${prettyPrint(formatValue(set))}.`,
2131
2310
  );
2132
2311
  }
@@ -2137,8 +2316,6 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2137
2316
  }
2138
2317
  };
2139
2318
 
2140
- // A function that agrees with a member of a function set outside some entries is a member when
2141
- // those entries are.
2142
2319
  export const isUpdatedElementOf = (element: Value, member: Value, set: Value): boolean => {
2143
2320
  if (element === member) return true;
2144
2321
  if (
@@ -2161,13 +2338,13 @@ export const toFiniteFunction = (value: Value): FunctionValue => {
2161
2338
  if (typeof value === "object" && value.kind === "LazyFunction") {
2162
2339
  if (value.enumerated) return value.enumerated;
2163
2340
  if (!isEnumerable(value.domain)) getCardinality(value.domain);
2341
+ if (!isSetValue(value.domain)) {
2342
+ throw new TlaEvaluationError("The domains of formal parameters must be enumerable.");
2343
+ }
2164
2344
  const domain = getFunctionDomain(value.domain);
2165
- value.enumerated = setFunctionClass(
2166
- createSortedFunction(
2167
- domain,
2168
- domain.map((key) => value.apply(key)),
2169
- ),
2170
- getFunctionClass(value),
2345
+ value.enumerated = createSortedFunction(
2346
+ domain,
2347
+ domain.map((key) => value.apply(key)),
2171
2348
  );
2172
2349
  return value.enumerated;
2173
2350
  }
@@ -2208,16 +2385,14 @@ export const describeMissingArgument = (
2208
2385
  }
2209
2386
  };
2210
2387
 
2211
- // TLC 1.7.4 words a key of the wrong type in an EXCEPT, which selects rather than applies, apart.
2212
2388
  const describeExceptKey = (functionValue: FunctionValue, argument: Value) => {
2213
- if (!valueVersion.is174) return describeMissingArgument(functionValue, argument);
2389
+ if (!isVersion174) return describeMissingArgument(functionValue, argument);
2214
2390
  const shown = prettyPrint(formatValue(argument));
2215
2391
  return getFunctionClass(functionValue) === "tuple"
2216
2392
  ? `Attempted to apply tuple to a non-integer argument ${shown}.`
2217
2393
  : `Attempted to apply record to a non-string argument ${shown}.`;
2218
2394
  };
2219
2395
 
2220
- // A key the domain holds itself, which TLC finds without a comparison that can fail.
2221
2396
  const findIdenticalKey = (domain: Value[], argument: Value) => {
2222
2397
  const first = domain[0];
2223
2398
  if (typeof argument === "number" && typeof first === "number") {
@@ -2232,22 +2407,25 @@ export const createNonIntegerKeyError = (argument: Value) =>
2232
2407
  `Attempted to apply function with integer domain to the non-integer argument ${prettyPrint(formatValue(argument))}`,
2233
2408
  );
2234
2409
 
2235
- // TLC's FcnRcdValue searches a domain this small linearly with equals, and a larger normalized one by
2236
- // binary search with compareTo.
2237
2410
  const LINEAR_SEARCH_LIMIT = 32;
2238
2411
 
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));
2412
+ const findDomainIndex = (functionValue: FunctionValue, argument: Value) =>
2413
+ findSortedIndex(functionValue.domain, argument);
2414
+
2415
+ const failKeyLikeTlc = (
2416
+ functionValue: FunctionValue,
2417
+ argument: Value,
2418
+ error: TlaEvaluationError,
2419
+ ): never => {
2420
+ const keys = getWrittenKeys(functionValue);
2421
+ if (isVersion174 || keys !== functionValue.domain || keys.length < LINEAR_SEARCH_LIMIT) {
2422
+ keys.forEach((key) => equalsLikeTlc(key, argument));
2242
2423
  } else {
2243
- findSortedIndex(domain, argument, compareLikeTlc);
2424
+ findSortedIndex(keys, argument, compareLikeTlc);
2244
2425
  }
2245
2426
  throw error;
2246
2427
  };
2247
2428
 
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.
2251
2429
  const findKeyIndexLikeTlc = (
2252
2430
  functionValue: FunctionValue,
2253
2431
  argument: Value,
@@ -2261,21 +2439,104 @@ const findKeyIndexLikeTlc = (
2261
2439
  if (keyType !== undefined && typeof argument !== keyType) {
2262
2440
  throw new TlaEvaluationError(describeWrongKey(functionValue, argument));
2263
2441
  }
2264
- if (keyType === undefined && !valueVersion.is174 && isIntervalDomain(domain)) {
2442
+ if (
2443
+ keyType === undefined &&
2444
+ !isVersion174 &&
2445
+ typeof argument !== "number" &&
2446
+ isIntervalDomain(domain)
2447
+ ) {
2265
2448
  throw createNonIntegerKeyError(argument);
2266
2449
  }
2267
2450
  }
2268
2451
  const identical = findIdenticalKey(domain, argument);
2269
2452
  if (identical !== -1) return identical;
2270
- return computeLikeTlcOnFailure(findSortedIndex, failKeyLikeTlc, domain, argument);
2453
+ return computeLikeTlcOnFailure(findDomainIndex, failKeyLikeTlc, functionValue, argument);
2454
+ };
2455
+
2456
+ const describeBoundArgument = (
2457
+ functionValue: LazyFunctionValue,
2458
+ position: string,
2459
+ shown: Value,
2460
+ problem: string,
2461
+ ) =>
2462
+ `In applying the function\n${prettyPrint(formatValue(functionValue))},\nthe ${position} is:\n${prettyPrint(formatValue(shown))}\nwhich ${problem}.\n`;
2463
+
2464
+ const createArgumentListError = (functionValue: LazyFunctionValue, argument: Value) =>
2465
+ new TlaEvaluationError(
2466
+ describeBoundArgument(
2467
+ functionValue,
2468
+ "argument list",
2469
+ argument,
2470
+ "does not match its formal parameter",
2471
+ ),
2472
+ );
2473
+
2474
+ // Deviation from TLC: FcnLambdaValue#apply indexes past an argument tuple shorter than the bounds and ignores a longer one, where this rejects the list.
2475
+ const checkBoundArguments = (
2476
+ functionValue: LazyFunctionValue,
2477
+ tupleLengths: (number | undefined)[],
2478
+ argument: Value,
2479
+ ) => {
2480
+ const domain = functionValue.domain;
2481
+ const elements = getSequenceElements(argument);
2482
+ if (elements === undefined) throw createArgumentListError(functionValue, argument);
2483
+ if (typeof domain !== "object" || domain.kind !== "ProductSet") {
2484
+ throw new TlaEvaluationError(
2485
+ `Attempted to apply a function to ${formatValue(argument)}, which is not in its domain`,
2486
+ );
2487
+ }
2488
+ tupleLengths.forEach((tupleLength, index) => {
2489
+ if (index >= elements.length) throw createArgumentListError(functionValue, argument);
2490
+ const element = elements[index];
2491
+ const position = `argument number ${index + 1}`;
2492
+ if (!isElementOf(element, domain.factors[index])) {
2493
+ throw new TlaEvaluationError(
2494
+ describeBoundArgument(
2495
+ functionValue,
2496
+ position,
2497
+ element,
2498
+ tupleLength === undefined
2499
+ ? `is not in the function's domain ${formatValue(domain)}`
2500
+ : "is not in its domain",
2501
+ ),
2502
+ );
2503
+ }
2504
+ if (tupleLength !== undefined && getSequenceElements(element)?.length !== tupleLength) {
2505
+ throw new TlaEvaluationError(
2506
+ describeBoundArgument(
2507
+ functionValue,
2508
+ position,
2509
+ element,
2510
+ "does not match its formal parameter",
2511
+ ),
2512
+ );
2513
+ }
2514
+ });
2515
+ if (elements.length > tupleLengths.length) {
2516
+ throw createArgumentListError(functionValue, argument);
2517
+ }
2271
2518
  };
2272
2519
 
2520
+ const isOutsideLambdaDomain = (functionValue: FunctionValue, argument: Value) =>
2521
+ functionValue.lambdaDomain !== undefined &&
2522
+ functionValue.hash === 0 &&
2523
+ functionValue.fingerprint === 0 &&
2524
+ !isElementOf(argument, functionValue.lambdaDomain);
2525
+
2273
2526
  export const applyFunction = (
2274
2527
  functionValue: Value,
2275
2528
  argument: Value,
2276
2529
  describeMissing?: (functionValue: FunctionValue, argument: Value) => string,
2277
2530
  ): Value => {
2278
2531
  if (typeof functionValue === "object" && functionValue.kind === "LazyFunction") {
2532
+ if (functionValue.enumerated) {
2533
+ return applyFunction(functionValue.enumerated, argument, describeMissing);
2534
+ }
2535
+ const tupleLengths = functionValue.boundTupleLengths;
2536
+ if (tupleLengths !== undefined) {
2537
+ checkBoundArguments(functionValue, tupleLengths, argument);
2538
+ return functionValue.apply(argument);
2539
+ }
2279
2540
  if (!isElementOf(argument, functionValue.domain)) {
2280
2541
  throw new TlaEvaluationError(
2281
2542
  getFunctionClass(functionValue) === "lambda"
@@ -2291,6 +2552,9 @@ export const applyFunction = (
2291
2552
  );
2292
2553
  }
2293
2554
  const describe = describeMissing ?? describeMissingArgument;
2555
+ if (isOutsideLambdaDomain(functionValue, argument)) {
2556
+ throw new TlaEvaluationError(describe(functionValue, argument));
2557
+ }
2294
2558
  const position = findKeyIndexLikeTlc(functionValue, argument, describe);
2295
2559
  if (position === -1) throw new TlaEvaluationError(describe(functionValue, argument));
2296
2560
  return functionValue.range[position];
@@ -2304,8 +2568,17 @@ export const getDomainInterval = (domain: Value[]) =>
2304
2568
  export const getDomain = (functionValue: Value): Value => {
2305
2569
  if (typeof functionValue === "object" && functionValue.kind === "LazyFunction")
2306
2570
  return functionValue.domain;
2307
- const domain = toFiniteFunction(functionValue).domain;
2308
- return getDomainInterval(domain) ?? createSortedSet(domain);
2571
+ const finite = toFiniteFunction(functionValue);
2572
+ if (finite.functionClass === "lambda" && finite.lambdaDomain) return finite.lambdaDomain;
2573
+ const interval = getDomainInterval(finite.domain);
2574
+ if (interval) return interval;
2575
+ const set = createSortedSet(finite.domain);
2576
+ if (finite.functionClass === "record") {
2577
+ if (finite.writtenKeys) set.writtenElements = finite.writtenKeys;
2578
+ return set;
2579
+ }
2580
+ set.isNormalized = true;
2581
+ return set;
2309
2582
  };
2310
2583
 
2311
2584
  export const updateFunction = (
@@ -2317,8 +2590,14 @@ export const updateFunction = (
2317
2590
  const isLazy =
2318
2591
  typeof functionValue === "object" &&
2319
2592
  functionValue.kind === "LazyFunction" &&
2320
- (isKeptLazy || !isEnumerable(functionValue.domain));
2593
+ (isKeptLazy || functionValue.enumerated === undefined);
2321
2594
  if (isLazy) {
2595
+ if (
2596
+ functionValue.boundTupleLengths !== undefined &&
2597
+ getSequenceElements(argument) === undefined
2598
+ ) {
2599
+ throw createArgumentListError(functionValue, argument);
2600
+ }
2322
2601
  if (!isElementOf(argument, functionValue.domain)) return functionValue;
2323
2602
  const updated = update(functionValue.apply(argument));
2324
2603
  return setFunctionClass<LazyFunctionValue>(
@@ -2327,6 +2606,7 @@ export const updateFunction = (
2327
2606
  domain: functionValue.domain,
2328
2607
  apply: (key) => (isEqualLikeTlc(argument, key) ? updated : functionValue.apply(key)),
2329
2608
  source: functionValue.source,
2609
+ boundTupleLengths: functionValue.boundTupleLengths,
2330
2610
  },
2331
2611
  getFunctionClass(functionValue),
2332
2612
  );
@@ -2337,6 +2617,7 @@ export const updateFunction = (
2337
2617
  );
2338
2618
  }
2339
2619
  const finite = toFiniteFunction(functionValue);
2620
+ if (isOutsideLambdaDomain(finite, argument)) return finite;
2340
2621
  const position = findKeyIndexLikeTlc(finite, argument, describeExceptKey);
2341
2622
  if (position === -1) return finite;
2342
2623
  const range = [...finite.range];
@@ -2348,6 +2629,7 @@ export const updateFunction = (
2348
2629
  getFunctionClass(finite),
2349
2630
  );
2350
2631
  updated.writtenKeys = finite.writtenKeys;
2632
+ updated.lambdaDomain = finite.lambdaDomain;
2351
2633
  if (finite.hash !== 0 && finite.hash !== UNFINGERPRINTABLE_HASH) {
2352
2634
  const nextHash = getValueHash(next);
2353
2635
  if (nextHash !== UNFINGERPRINTABLE_HASH) {
@@ -2400,9 +2682,6 @@ const getElementContribution = (elementHash: number) =>
2400
2682
  const getEntryContribution = (keyHash: number, valueHash: number) =>
2401
2683
  finalizeHash((Math.imul(keyHash, 0x27d4eb2d) + valueHash) | 0);
2402
2684
 
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.
2406
2685
  const UNFINGERPRINTABLE_HASH = 0x2f6b1c4d;
2407
2686
 
2408
2687
  const computeValueHash = (value: SetValue | FunctionValue) => {
@@ -2428,13 +2707,11 @@ const computeValueHash = (value: SetValue | FunctionValue) => {
2428
2707
  return hash;
2429
2708
  };
2430
2709
 
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.
2433
2710
  const fingerprintValue = (value: Value): void => {
2434
2711
  if (typeof value !== "object" || value.kind === "ModelValue") return;
2435
2712
  if (value.kind === "InfiniteSet" || value.kind === "SequenceSet") {
2436
2713
  throw new TlaEvaluationError(
2437
- `TLC has found a state in which the value of a variable contains ${formatValue(value)}`,
2714
+ `TLC has found a state in which the value of a variable contains ${prettyPrint(formatValue(value))}`,
2438
2715
  );
2439
2716
  }
2440
2717
  if (isSetValue(value)) {
@@ -2446,8 +2723,6 @@ const fingerprintValue = (value: Value): void => {
2446
2723
  functionValue.range.forEach(fingerprintValue);
2447
2724
  };
2448
2725
 
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.
2451
2726
  export const getFingerprintError = (value: Value) => {
2452
2727
  if (typeof value !== "object" || value.kind === "ModelValue") return undefined;
2453
2728
  try {
@@ -2459,7 +2734,6 @@ export const getFingerprintError = (value: Value) => {
2459
2734
  }
2460
2735
  };
2461
2736
 
2462
- // The values a value holds, which TLC fingerprints as it fingerprints the value.
2463
2737
  export const getHeldValues = (value: ObjectValue): Value[] => {
2464
2738
  switch (value.kind) {
2465
2739
  case "Set":
@@ -2580,17 +2854,19 @@ const computeValueKey = (value: ObjectValue) => {
2580
2854
  return `(${functionValue.domain.map((key, index) => `${getValueKey(key)}:${getValueKey(functionValue.range[index])}`).join(",")})`;
2581
2855
  };
2582
2856
 
2857
+ const PRINTED_ESCAPES: Record<string, string> = {
2858
+ '"': '\\"',
2859
+ "\\": "\\\\",
2860
+ "\t": "\\t",
2861
+ "\n": "\\n",
2862
+ "\f": "\\f",
2863
+ "\r": "\\r",
2864
+ };
2865
+
2583
2866
  const formatString = (value: string) =>
2584
- `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\t/g, "\\t")}"`;
2867
+ `"${value.replace(/["\\\t\n\f\r]/g, (character) => PRINTED_ESCAPES[character])}"`;
2585
2868
 
2586
- type LazySetValue =
2587
- | SubsetValue
2588
- | FunctionSetValue
2589
- | RecordSetValue
2590
- | ProductSetValue
2591
- | SetOperationValue
2592
- | FilteredSetValue
2593
- | UnionValue;
2869
+ type LazySetValue = Exclude<ConvertibleSetValue, MixedSetValue | SequenceSetValue>;
2594
2870
 
2595
2871
  const MAXIMUM_EXPANDED_SUBSET_BASE = 6;
2596
2872
  const MAXIMUM_EXPANDED_PRODUCT = 1999;
@@ -2607,24 +2883,24 @@ const expandLazySet = (value: LazySetValue) => {
2607
2883
  if (value.kind === "SetOperation" || value.kind === "FilteredSet" || value.kind === "Union") {
2608
2884
  return toFiniteSet(value);
2609
2885
  }
2610
- if (
2611
- value.kind === "FunctionSet" &&
2612
- isEnumerable(value.domain) &&
2613
- getCardinality(value.domain) === 0
2614
- ) {
2615
- return createSortedSet([createSortedFunction([], [])]);
2886
+ if (value.kind === "FunctionSet") {
2887
+ const domainSize = isEmptySet(value.domain) ? 0 : getCardinality(value.domain);
2888
+ const size = domainSize === 0 ? 1 : getCardinality(value.range) ** domainSize;
2889
+ return size <= MAXIMUM_EXPANDED_PRODUCT ? toFiniteSet(value) : undefined;
2616
2890
  }
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;
2891
+ const size = getProductSize(value.kind === "RecordSet" ? value.sets : value.factors);
2622
2892
  return size <= MAXIMUM_EXPANDED_PRODUCT ? toFiniteSet(value) : undefined;
2623
2893
  };
2624
2894
 
2625
2895
  const getExpandedLazySet = (value: LazySetValue, isStrict: boolean) => {
2626
- if (isStrict) return expandLazySet(value);
2627
- // TLC prints a set it can't enumerate symbolically, except in Print, PrintT, and ToString.
2896
+ if (isStrict || value.kind === "Union") return expandLazySet(value);
2897
+ if (
2898
+ value.kind === "Subset" &&
2899
+ isFunctionValue(value.base) &&
2900
+ (value.base.kind === "Function" || isEnumerable(value.base.domain))
2901
+ ) {
2902
+ return expandLazySet(value);
2903
+ }
2628
2904
  if (!isEnumerable(value)) return undefined;
2629
2905
  try {
2630
2906
  return expandLazySet(value);
@@ -2658,24 +2934,93 @@ const formatLazySet = (value: LazySetValue, isStrict: boolean): string => {
2658
2934
  }
2659
2935
  };
2660
2936
 
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.
2663
2937
  const isFieldName = (name: string) =>
2664
2938
  /^[\p{L}\p{Nd}_]*$/u.test(name) &&
2665
2939
  /\p{L}/u.test(name) &&
2666
2940
  (name.length < 4 || !/^[WS]F_/.test(name));
2667
2941
 
2668
- // FcnLambdaValue#toString prints a function it fails to enumerate as its parameters and body.
2669
2942
  const toPrintedFunction = (value: LazyFunctionValue) => {
2670
2943
  if (!isEnumerable(value.domain)) return undefined;
2671
2944
  try {
2672
2945
  return toFiniteFunction(value);
2673
2946
  } catch (error) {
2674
- if (error instanceof TlaEvaluationError) return undefined;
2947
+ if (error instanceof TlaEvaluationError || isStackOverflow(error)) return undefined;
2675
2948
  throw error;
2676
2949
  }
2677
2950
  };
2678
2951
 
2952
+ export const formatNormalizedCopies = (values: Value[]) => {
2953
+ const markedSets: SetValue[] = [];
2954
+ const writtenFunctions: [FunctionValue, Value[]][] = [];
2955
+ const copiedFunctions: LazyFunctionValue[] = [];
2956
+ // TLC prints a deep copy, which copies functions but shares sets, so it caches only the functions inside a set.
2957
+ const normalize = (value: Value, isWrittenOrderKept: boolean, isCopied: boolean): void => {
2958
+ if (typeof value !== "object") return;
2959
+ const normalizeInner = (inner: Value) => normalize(inner, isWrittenOrderKept, false);
2960
+ switch (value.kind) {
2961
+ case "Set":
2962
+ value.elements.forEach(normalizeInner);
2963
+ if (value.isNormalized) return;
2964
+ value.isNormalized = true;
2965
+ markedSets.push(value);
2966
+ return;
2967
+ case "MixedSet":
2968
+ value.elements.forEach(normalizeInner);
2969
+ toFiniteSet(value);
2970
+ return;
2971
+ case "Function": {
2972
+ const isRangeWrittenOrderKept = isWrittenOrderKept || getFunctionClass(value) === "lambda";
2973
+ value.range.forEach((inner) => normalize(inner, isRangeWrittenOrderKept, isCopied));
2974
+ if (isWrittenOrderKept || value.writtenKeys === undefined) return;
2975
+ writtenFunctions.push([value, value.writtenKeys]);
2976
+ value.writtenKeys = undefined;
2977
+ return;
2978
+ }
2979
+ case "LazyFunction":
2980
+ if (value.enumerated) return normalize(value.enumerated, true, isCopied);
2981
+ if (isCopied) copiedFunctions.push(value);
2982
+ normalizeInner(value.domain);
2983
+ return;
2984
+ case "SetOperation":
2985
+ normalizeInner(value.left);
2986
+ normalizeInner(value.right);
2987
+ return;
2988
+ case "FunctionSet":
2989
+ normalizeInner(value.domain);
2990
+ normalizeInner(value.range);
2991
+ return;
2992
+ case "RecordSet":
2993
+ value.sets.forEach(normalizeInner);
2994
+ return;
2995
+ case "ProductSet":
2996
+ value.factors.forEach(normalizeInner);
2997
+ return;
2998
+ case "Subset":
2999
+ case "Union":
3000
+ case "FilteredSet":
3001
+ case "SequenceSet":
3002
+ normalizeInner(value.base);
3003
+ return;
3004
+ default:
3005
+ return;
3006
+ }
3007
+ };
3008
+ try {
3009
+ values.forEach((value) => normalize(value, false, true));
3010
+ return values.map((value) => formatValue(value, true, true));
3011
+ } finally {
3012
+ markedSets.forEach((set) => {
3013
+ set.isNormalized = false;
3014
+ });
3015
+ copiedFunctions.forEach((copied) => {
3016
+ copied.enumerated = undefined;
3017
+ });
3018
+ writtenFunctions.forEach((entry) => {
3019
+ entry[0].writtenKeys = entry[1];
3020
+ });
3021
+ }
3022
+ };
3023
+
2679
3024
  export const formatValue = (value: Value, isStrict = false, isNormalized = false): string => {
2680
3025
  const format = (inner: Value) => formatValue(inner, isStrict, isNormalized);
2681
3026
  if (typeof value === "boolean") return value ? "TRUE" : "FALSE";
@@ -2699,7 +3044,7 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
2699
3044
  case "SetOperation":
2700
3045
  case "FilteredSet":
2701
3046
  case "Union": {
2702
- const expanded = getExpandedLazySet(value, isStrict);
3047
+ const expanded = printing.isExpanded ? getExpandedLazySet(value, isStrict) : undefined;
2703
3048
  return expanded ? format(expanded) : formatLazySet(value, isStrict);
2704
3049
  }
2705
3050
 
@@ -2707,7 +3052,12 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
2707
3052
  return `Seq(${format(value.base)})`;
2708
3053
  case "Function":
2709
3054
  case "LazyFunction": {
2710
- const functionValue = value.kind === "LazyFunction" ? toPrintedFunction(value) : value;
3055
+ const functionValue =
3056
+ value.kind !== "LazyFunction"
3057
+ ? value
3058
+ : printing.isExpanded || !value.source
3059
+ ? toPrintedFunction(value)
3060
+ : undefined;
2711
3061
  if (functionValue === undefined) {
2712
3062
  const source = value.kind === "LazyFunction" ? value.source : undefined;
2713
3063
  if (!source) return "<function>";
@@ -2718,42 +3068,111 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
2718
3068
  }
2719
3069
  if (
2720
3070
  functionValue.domain.length === 0 &&
2721
- valueVersion.is174 &&
3071
+ isVersion174 &&
2722
3072
  getFunctionClass(value) !== "tuple"
2723
3073
  ) {
2724
3074
  return "<< >>";
2725
3075
  }
2726
- // TLC normalizes a lambda's domain to print it, but evaluates its body afterward.
2727
3076
  const formatRange = (inner: Value) =>
2728
3077
  formatValue(inner, isStrict, isNormalized && getFunctionClass(value) !== "lambda");
3078
+ if (functionValue.domain.length === 0 && getFunctionClass(value) === "record") return "[]";
2729
3079
  if (functionValue.domain.every((key, index) => key === index + 1)) {
2730
3080
  return `<<${functionValue.range.map(formatRange).join(", ")}>>`;
2731
3081
  }
2732
- // A RecordValue prints as a record whatever its fields, and a FcnRcdValue only if each key
2733
- // is a name.
3082
+ const pairs = isNormalized
3083
+ ? functionValue.domain.map((key, index) => [key, functionValue.range[index]])
3084
+ : getPrintedPairs(functionValue);
2734
3085
  if (
2735
3086
  getFunctionClass(value) === "record" ||
2736
3087
  functionValue.domain.every((key) => typeof key === "string" && isFieldName(key))
2737
3088
  ) {
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
3089
  return `[${pairs.map((pair) => `${String(pair[0])} |-> ${formatRange(pair[1])}`).join(", ")}]`;
2744
3090
  }
2745
- return `(${functionValue.domain.map((key, index) => `${format(key)} :> ${formatRange(functionValue.range[index])}`).join(" @@ ")})`;
3091
+ return `(${pairs.map((pair) => `${format(pair[0])} :> ${formatRange(pair[1])}`).join(" @@ ")})`;
2746
3092
  }
2747
3093
  }
2748
3094
  };
2749
3095
 
2750
- // TLC's TLCState.toString: a line per variable, as a conjunction when there are several.
2751
- export const formatState = (state: Record<string, Value>) => {
3096
+ const isUnchanged = (previous: Value | undefined, value: Value) => {
3097
+ if (previous === undefined) return false;
3098
+ try {
3099
+ return valuesEqual(previous, value);
3100
+ } catch (error) {
3101
+ if (error instanceof TlaEvaluationError) return false;
3102
+ throw error;
3103
+ }
3104
+ };
3105
+
3106
+ const JAVA_FORMAT_SPECIFIER = /%(\d+\$)?([-#+ 0,(<]*)(\d+)?(\.\d+)?(.?)/gs;
3107
+
3108
+ const formatJava = (format: string, args: string[]) => {
3109
+ let nextIndex = 0;
3110
+ let lastIndex = -1;
3111
+ let isFitting = true;
3112
+ const text = format.replace(
3113
+ JAVA_FORMAT_SPECIFIER,
3114
+ (match, explicit?: string, flags = "", width?: string, precision?: string, conversion = "") => {
3115
+ const pad = (value: string) =>
3116
+ flags.includes("-") ? value.padEnd(Number(width)) : value.padStart(Number(width ?? 0));
3117
+ const isRelative = flags.includes("<");
3118
+ const otherFlags = flags.replace("<", "");
3119
+ if (conversion === "n" && match === "%n") return "\n";
3120
+ if (conversion === "%" && precision === undefined && /^-?$/.test(otherFlags)) {
3121
+ if (otherFlags === "-" && width === undefined) isFitting = false;
3122
+ return pad("%");
3123
+ }
3124
+ const index = isRelative
3125
+ ? lastIndex
3126
+ : explicit === undefined
3127
+ ? nextIndex++
3128
+ : Number(explicit.slice(0, -1)) - 1;
3129
+ lastIndex = index;
3130
+ const arg = args[index];
3131
+ if (
3132
+ !"sSbBhH".includes(conversion) ||
3133
+ conversion === "" ||
3134
+ !/^-?$/.test(otherFlags) ||
3135
+ (otherFlags === "-" && width === undefined) ||
3136
+ arg === undefined
3137
+ ) {
3138
+ isFitting = false;
3139
+ return match;
3140
+ }
3141
+ const lower = conversion.toLowerCase();
3142
+ const value =
3143
+ lower === "s" ? arg : lower === "b" ? "true" : (getJavaHashCode(arg) >>> 0).toString(16);
3144
+ const shown = pad(
3145
+ precision === undefined ? value : value.slice(0, Number(precision.slice(1))),
3146
+ );
3147
+ return conversion === lower ? shown : shown.toUpperCase();
3148
+ },
3149
+ );
3150
+ return isFitting ? text : undefined;
3151
+ };
3152
+
3153
+ export const formatState = (state: Record<string, Value>, previous?: Record<string, Value>) => {
3154
+ const getViewText = previous ? undefined : viewTexts.get(state);
3155
+ if (getViewText) return getViewText();
2752
3156
  const entries = Object.entries(state);
3157
+ const alias = aliasNames.get(state);
3158
+ const isFormatted = alias !== undefined && "_format" in state;
3159
+ const format = isFormatted ? state._format : entries.length === 1 ? "%s = %s\n" : "/\\ %s = %s\n";
3160
+ if (typeof format !== "string") {
3161
+ throw new TlaAliasFormatError(
3162
+ `The _format field of the ALIAS ${alias} is ${formatValue(format)}, but it must be a string.`,
3163
+ );
3164
+ }
2753
3165
  return entries
2754
- .map(
2755
- ([name, value]) =>
2756
- `${entries.length === 1 ? "" : "/\\ "}${name} = ${prettyPrint(formatValue(value))}\n`,
2757
- )
3166
+ .filter((entry) => !(isFormatted && entry[0] === "_format"))
3167
+ .filter((entry) => !previous || !isUnchanged(previous[entry[0]], entry[1]))
3168
+ .map((entry) => {
3169
+ const text = formatJava(format, [entry[0], prettyPrint(formatValue(entry[1]))]);
3170
+ if (text === undefined) {
3171
+ throw new TlaAliasFormatError(
3172
+ `The _format field of the ALIAS ${alias} is ${formatValue(format)}, but it must format two strings, the name and the value of a field.`,
3173
+ );
3174
+ }
3175
+ return text;
3176
+ })
2758
3177
  .join("");
2759
3178
  };