tla-ts 0.0.9-dev.8298a52 → 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 +8 -0
  2. package/dist/compile.cjs +6 -6
  3. package/dist/compile.js +10 -10
  4. package/dist/deciders.cjs +41 -37
  5. package/dist/deciders.js +57 -53
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +121 -12
  8. package/dist/index.d.ts +121 -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 +1 -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 +1155 -900
  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 +318 -656
  41. package/src/cli/typescript.ts +0 -3
  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 +260 -371
  51. package/src/errors.ts +93 -58
  52. package/src/evaluate.ts +848 -374
  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 +97 -43
  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 -325
  64. package/src/liveness.ts +224 -131
  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 +34 -57
  88. package/src/parallel.ts +62 -72
  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 +129 -38
  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 +296 -105
  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 +10 -25
  612. package/src/typescript/collections.ts +34 -35
  613. package/src/typescript/compile.ts +1 -8
  614. package/src/typescript/context.ts +0 -12
  615. package/src/typescript/emit.ts +0 -1
  616. package/src/typescript/expressions.ts +0 -12
  617. package/src/typescript/formula.ts +9 -15
  618. package/src/typescript/functions.ts +6 -17
  619. package/src/typescript/model.ts +14 -16
  620. package/src/typescript/names.ts +0 -2
  621. package/src/typescript/program.ts +0 -3
  622. package/src/typescript/properties.ts +6 -8
  623. package/src/typescript/scope.ts +0 -5
  624. package/src/typescript/steps.ts +20 -28
  625. package/src/typescript/types.ts +3 -10
  626. package/src/values.ts +917 -522
  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,42 +358,37 @@ 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
374
  interface StringOrder {
319
375
  ranks: Record<string, number>;
320
376
  size: number;
321
- // A parallel search's workers rank the strings they create in different orders, so the search
322
- // notes the first string it orders against another string ranked from this rank on.
323
377
  searchRank: number | undefined;
324
378
  unorderedString: string | undefined;
325
379
  }
326
380
 
327
- // TLC orders strings and model value names by when it first interned the text, so every
328
- // check sets the order of its spec's strings before it builds any value.
329
- const stringOrder: StringOrder = {
381
+ const createStringOrder = (): StringOrder => ({
330
382
  ranks: Object.create(null),
331
383
  size: 0,
332
384
  searchRank: undefined,
333
385
  unorderedString: undefined,
334
- };
386
+ });
387
+
388
+ const stringOrder = createStringOrder();
335
389
 
336
390
  export const setStringOrder = (texts: Iterable<string>) => {
337
- stringOrder.ranks = Object.create(null);
338
- stringOrder.size = 0;
339
- stringOrder.searchRank = undefined;
340
- stringOrder.unorderedString = undefined;
391
+ Object.assign(stringOrder, createStringOrder());
341
392
  modelValues.clear();
342
393
  for (const text of texts) rankString(text);
343
394
  };
@@ -348,12 +399,36 @@ export const freezeStringOrder = () => {
348
399
 
349
400
  export const getUnorderedString = () => stringOrder.unorderedString;
350
401
 
351
- // TLC 1.7.4 prints an empty function that isn't a tuple with a space between its brackets, and
352
- // looks a key up in a function differently, so every check also sets the version its values follow.
353
- const valueVersion = { is174: false };
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
+ }
354
412
 
355
- export const setValueVersion = (version: TlcVersion | undefined) => {
356
- valueVersion.is174 = version === "1.7.4";
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>();
428
+
429
+ export const setAliasName = (state: Record<string, Value>, alias: string) => {
430
+ aliasNames.set(state, alias);
431
+ return state;
357
432
  };
358
433
 
359
434
  export const rankString = (text: string) => {
@@ -394,9 +469,13 @@ const isOverriddenComparison = (left: Value, right: Value) =>
394
469
  right.kind === "SequenceSet"
395
470
  );
396
471
 
397
- // TLC implements Nat, Int, STRING, Seq(S), and Any in Java classes that compare only with each
398
- // other and with model values. Comparing one with any other set is an error, worded by the class of
399
- // 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
+
400
479
  const compareOverriddenSets = (
401
480
  left: Value,
402
481
  right: Value,
@@ -404,35 +483,39 @@ const compareOverriddenSets = (
404
483
  ) => {
405
484
  if (!isOverriddenSet(left)) {
406
485
  throw new TlaEvaluationError(
407
- `Attempted to ${verb} the set ${formatValue(isEnumerable(left) ? toFiniteSet(left) : left, true)} with the value:\n${formatValue(right, true)}`,
408
- );
409
- }
410
- if (!isOverriddenSet(right)) {
411
- throw new TlaEvaluationError(
412
- `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))}`,
413
487
  );
414
488
  }
489
+ if (!isOverriddenSet(right)) throw createComparisonError(left, right);
415
490
  const leftName = left.kind === "InfiniteSet" ? left.name : undefined;
416
491
  const rightName = right.kind === "InfiniteSet" ? right.name : undefined;
417
492
  if (leftName !== undefined && leftName === rightName) return 0;
418
493
  if ((leftName === "Nat" && rightName === "Int") || (leftName === "Int" && rightName === "Nat")) {
419
494
  return leftName === "Nat" ? -1 : 1;
420
495
  }
421
- throw new TlaEvaluationError(
422
- `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))}`,
423
498
  );
424
499
  };
425
500
 
426
501
  export const ANY_SET: InfiniteSetValue = { kind: "InfiniteSet", name: "Any" };
427
502
 
428
503
  const compareAny = (other: Value): never => {
429
- 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);
430
513
  };
431
514
 
432
515
  export const compareValues = (left: Value, right: Value): number => {
433
516
  if (left === right) {
434
- if (writtenOrderUse.isUsed) forgetWrittenOrder(left);
435
- return left === ANY_SET ? compareAny(left) : 0;
517
+ compareWithItself(left);
518
+ return 0;
436
519
  }
437
520
  if (typeof left === "object" && typeof right === "object") {
438
521
  const leftKind = left.kind;
@@ -460,9 +543,15 @@ export const compareValues = (left: Value, right: Value): number => {
460
543
  }
461
544
  const isLeftSet = isSetValue(left);
462
545
  if (isLeftSet !== isSetValue(right)) {
463
- throw new TlaEvaluationError(
464
- `Attempted to compare ${describeKind(left)} ${formatValue(left)} with ${describeKind(right)} ${formatValue(right)}`,
465
- );
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;
466
555
  }
467
556
  if (isLeftSet) return compareSets(toFiniteSet(left), toFiniteSet(right));
468
557
  return compareFunctions(toFiniteFunction(left), toFiniteFunction(right));
@@ -473,17 +562,21 @@ export const compareValues = (left: Value, right: Value): number => {
473
562
  checkModelValueTypes(left, right, false);
474
563
  if (isModelValue(left)) return -1;
475
564
  if (isModelValue(right)) return 1;
476
- throw new TlaEvaluationError(
477
- `Attempted to compare ${describeKind(left)} ${formatValue(left)} with ${describeKind(right)} ${formatValue(right)}`,
478
- );
565
+ throw createComparisonError(left, right);
479
566
  };
480
567
 
481
568
  const modelValues = new Map<string, ModelValue>();
482
569
 
483
- // setStringOrder clears the model values, so each check ranks and creates its own.
570
+ const MAXIMUM_MODEL_VALUES = 32768;
571
+
484
572
  export const createModelValue = (name: string): ModelValue => {
485
573
  const known = modelValues.get(name);
486
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
+ }
487
580
  const value: ModelValue = {
488
581
  kind: "ModelValue",
489
582
  name,
@@ -496,14 +589,24 @@ export const createModelValue = (name: string): ModelValue => {
496
589
  return value;
497
590
  };
498
591
 
592
+ export const getModelValues = () => [...modelValues.values()];
593
+
499
594
  export const createSortedSet = (elements: Value[]): SetValue => ({
500
595
  kind: "Set",
501
596
  elements,
597
+ writtenElements: undefined,
598
+ isNormalized: false,
502
599
  hash: 0,
503
600
  fingerprint: 0,
504
601
  isFingerprinted: false,
505
602
  });
506
603
 
604
+ export const createNormalizedSet = (elements: Value[]): SetValue => {
605
+ const set = createSortedSet(elements);
606
+ set.isNormalized = true;
607
+ return set;
608
+ };
609
+
507
610
  export const createSortedFunction = (domain: Value[], range: Value[]): FunctionValue => ({
508
611
  kind: "Function",
509
612
  domain,
@@ -512,22 +615,19 @@ export const createSortedFunction = (domain: Value[], range: Value[]): FunctionV
512
615
  fingerprint: 0,
513
616
  writtenKeys: undefined,
514
617
  functionClass: undefined,
618
+ lambdaDomain: undefined,
515
619
  isFingerprinted: false,
516
620
  });
517
621
 
518
- // TLC words a failed function application by the Java class of the function: FcnLambdaValue for
519
- // [x \in S |-> e], TupleValue for <<...>> and what the sequence operators build, RecordValue for
520
- // [a |-> e], and FcnRcdValue for any other function.
521
622
  export type FunctionClass = "lambda" | "tuple" | "record";
522
623
 
523
- // Whether a lambda exists for markFingerprinted to find, so that a spec without one skips the walk.
524
- const lambdaPresence = { isPresent: false };
624
+ let hasLambda = false;
525
625
 
526
626
  export const setFunctionClass = <FunctionLike extends FunctionValue | LazyFunctionValue>(
527
627
  functionValue: FunctionLike,
528
628
  functionClass: FunctionClass | undefined,
529
629
  ) => {
530
- if (functionClass === "lambda") lambdaPresence.isPresent = true;
630
+ if (functionClass === "lambda") hasLambda = true;
531
631
  if (functionClass !== undefined) functionValue.functionClass = functionClass;
532
632
  return functionValue;
533
633
  };
@@ -541,22 +641,17 @@ export const markLambdaFunction = <FunctionLike extends FunctionValue | LazyFunc
541
641
  functionValue: FunctionLike,
542
642
  ) => setFunctionClass(functionValue, "lambda");
543
643
 
544
- // TLC caches a lazy set as the receiver of compareTo, equals, size, and fingerPrint, not as their
545
- // argument, and enumerates the sets an uncached one combines, duplicates and all.
546
644
  const isCachedSet = (value: ObjectValue) => isLazySet(value) && value.isCached === true;
547
645
 
548
- // Whether the spec has built a UNION or \cup set, the sets that stream duplicates, so that a spec
549
- // without one skips tracking what TLC caches.
550
- const streamedSetPresence = { isPresent: false };
646
+ let hasStreamedSet = false;
551
647
 
552
648
  export const markStreamedSet = <Streamed extends UnionValue | SetOperationValue>(
553
649
  value: Streamed,
554
650
  ) => {
555
- streamedSetPresence.isPresent = true;
651
+ hasStreamedSet = true;
556
652
  return value;
557
653
  };
558
654
 
559
- // The sets that stream their elements apart from the normalized set until TLC caches them.
560
655
  const STREAMING_KINDS = new Set<ObjectValue["kind"]>([
561
656
  "Union",
562
657
  "SetOperation",
@@ -568,7 +663,7 @@ const STREAMING_KINDS = new Set<ObjectValue["kind"]>([
568
663
 
569
664
  const cacheSet = (value: Value) => {
570
665
  if (
571
- streamedSetPresence.isPresent &&
666
+ hasStreamedSet &&
572
667
  typeof value === "object" &&
573
668
  isLazySet(value) &&
574
669
  STREAMING_KINDS.has(value.kind)
@@ -577,12 +672,8 @@ const cacheSet = (value: Value) => {
577
672
  }
578
673
  };
579
674
 
580
- // FcnLambdaValue#fingerPrint caches the FcnRcdValue the function enumerates to, which applies it
581
- // from then on, so a function TLC has fingerprinted is no longer a lambda.
582
675
  export const markFingerprinted = (value: Value): void => {
583
- if ((!lambdaPresence.isPresent && !streamedSetPresence.isPresent) || typeof value !== "object") {
584
- return;
585
- }
676
+ if ((!hasLambda && !hasStreamedSet) || typeof value !== "object") return;
586
677
  if (value.kind === "ModelValue" || value.kind === "Interval" || value.kind === "InfiniteSet") {
587
678
  return;
588
679
  }
@@ -603,8 +694,8 @@ export const markFingerprinted = (value: Value): void => {
603
694
  export const valuesEqual = (left: Value, right: Value): boolean => {
604
695
  cacheSet(left);
605
696
  if (left === right) {
606
- if (writtenOrderUse.isUsed) forgetWrittenOrder(left);
607
- return left !== ANY_SET || compareAny(left);
697
+ compareWithItself(left);
698
+ return true;
608
699
  }
609
700
  if (typeof left !== "object" || typeof right !== "object") {
610
701
  if (typeof left === typeof right) return false;
@@ -616,7 +707,14 @@ export const valuesEqual = (left: Value, right: Value): boolean => {
616
707
  if (left.kind === "Function" && right.kind === "Function")
617
708
  return compareFunctions(left, right) === 0;
618
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
+ }
619
716
  if (isModelValue(left) || isModelValue(right)) {
717
+ if (left.kind === "LazyFunction") toFiniteFunction(left);
620
718
  checkModelValueTypes(left, right, true);
621
719
  return isModelValue(left) && isModelValue(right) && left.name === right.name;
622
720
  }
@@ -669,8 +767,6 @@ export const valuesEqual = (left: Value, right: Value): boolean => {
669
767
  return compareValues(left, right) === 0;
670
768
  };
671
769
 
672
- // TLC prints and words errors about an equal function by its Java class, so a value can stand for
673
- // another in a state only if each function in it has the same class.
674
770
  const createSameValueCheck = (isClassSensitive: boolean) => {
675
771
  const areSameValues = (left: Value[], right: Value[]) => {
676
772
  if (left === right) return true;
@@ -710,8 +806,6 @@ const canonicalizeElements = (elements: Value[], canonicalize: (value: Value) =>
710
806
  }
711
807
  };
712
808
 
713
- // Replaces each set and function in a state with the first interchangeable one it has seen, so that
714
- // the states it keeps share their values.
715
809
  export const createCanonicalizer = () => {
716
810
  const canonicalValues = new Map<number, Value | Value[]>();
717
811
  const canonicalize = (value: Value): Value => {
@@ -745,21 +839,14 @@ export const createCanonicalizer = () => {
745
839
  };
746
840
  };
747
841
 
748
- // The comparisons above fail with their own messages. These follow the compareTo and equals
749
- // methods of TLC's Java value classes, which word a failure by the class of the left operand, so a
750
- // failed comparison runs again through them to fail as TLC does.
751
842
  interface TlcFunction {
752
843
  domain: Value[];
753
844
  range: Value[];
754
845
  low: number | undefined;
755
846
  }
756
847
 
757
- const getIntervalLow = (domain: Value[]) => {
758
- const first = domain.length === 0 ? 1 : domain[0];
759
- return typeof first === "number" && domain.every((key, index) => key === first + index)
760
- ? first
761
- : undefined;
762
- };
848
+ const getIntervalLow = (value: Value, domain: Value[]) =>
849
+ domain.length === 0 || getFunctionClass(value) === "tuple" ? 1 : getDomainInterval(domain)?.low;
763
850
 
764
851
  const toTlcFunction = (value: Value) => {
765
852
  if (!isFunctionValue(value)) return undefined;
@@ -767,37 +854,21 @@ const toTlcFunction = (value: Value) => {
767
854
  return {
768
855
  domain: functionValue.domain,
769
856
  range: functionValue.range,
770
- low: getIntervalLow(functionValue.domain),
857
+ low: getIntervalLow(value, functionValue.domain),
771
858
  };
772
859
  };
773
860
 
774
861
  const toTlcRecord = (value: Value) => {
775
862
  if (!isFunctionValue(value)) return undefined;
776
863
  const functionValue = toFiniteFunction(value);
777
- return functionValue.domain.every((key) => typeof key === "string") ? functionValue : undefined;
864
+ return isRecordDomain(functionValue.domain) ? functionValue : undefined;
778
865
  };
779
866
 
780
- // A model value compared with a value of another kind. The other value is never a model value.
781
- const compareModelValueWith = (modelValue: ModelValue, other: Value) => {
782
- checkModelValueTypes(other, modelValue, false);
867
+ const compareModelValueWith = (modelValue: ModelValue, other: Value, isEquality: boolean) => {
868
+ checkModelValueTypes(other, modelValue, isEquality);
783
869
  return 1;
784
870
  };
785
871
 
786
- const equalsModelValueWith = (modelValue: ModelValue, other: Value) => {
787
- checkModelValueTypes(other, modelValue, true);
788
- return false;
789
- };
790
-
791
- const compareModelValue = (left: ModelValue, right: Value) => {
792
- if (left.type !== undefined) checkModelValueTypes(left, right, false);
793
- return isModelValue(right) ? left.rank - right.rank : -1;
794
- };
795
-
796
- const equalsModelValue = (left: ModelValue, right: Value) => {
797
- if (left.type !== undefined) checkModelValueTypes(left, right, true);
798
- return isModelValue(right) && left.name === right.name;
799
- };
800
-
801
872
  const SCALAR_KINDS = {
802
873
  number: { name: "integer", other: "non-integer", equality: "check equality of" },
803
874
  string: { name: "string", other: "non-string", equality: "check equality of" },
@@ -813,34 +884,43 @@ const describeScalarMismatch = (
813
884
  SCALAR_KINDS[
814
885
  typeof left === "number" ? "number" : typeof left === "string" ? "string" : "boolean"
815
886
  ];
816
- 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))}`;
817
888
  };
818
889
 
819
- 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
+ ) => {
820
898
  const other = toTlcFunction(right);
821
899
  if (!other) {
822
- if (isModelValue(right)) return compareModelValueWith(right, left);
900
+ if (isModelValue(right)) return compareModelValueWith(right, left, isEquality);
823
901
  throw new TlaEvaluationError(
824
- `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))}`,
825
903
  );
826
904
  }
827
905
  if (functionValue.range.length !== other.range.length)
828
906
  return functionValue.range.length - other.range.length;
829
- const compareRanges = () => compareElementsLikeTlc(functionValue.range, other.range);
907
+ const compareRanges = () => compareElementsLikeTlc(functionValue.range, other.range, isEquality);
830
908
  if (functionValue.low !== undefined && functionValue.range.length === 0) return 0;
831
909
  if (functionValue.low !== undefined && other.low !== undefined) {
832
910
  return functionValue.low === other.low ? compareRanges() : functionValue.low - other.low;
833
911
  }
834
912
  const intervalLow = functionValue.low ?? other.low;
835
913
  if (intervalLow === undefined) {
836
- return compareElementsLikeTlc(functionValue.domain, other.domain) || compareRanges();
914
+ return (
915
+ compareElementsLikeTlc(functionValue.domain, other.domain, isEquality) || compareRanges()
916
+ );
837
917
  }
838
918
  const keys = functionValue.low === undefined ? functionValue.domain : other.domain;
839
919
  for (let index = 0; index < keys.length; index++) {
840
920
  const key = keys[index];
841
921
  if (typeof key !== "number") {
842
922
  throw new TlaEvaluationError(
843
- `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))}.`,
844
924
  );
845
925
  }
846
926
  const difference =
@@ -850,48 +930,50 @@ const compareTlcFunctions = (functionValue: TlcFunction, left: Value, right: Val
850
930
  return compareRanges();
851
931
  };
852
932
 
853
- const compareElementsLikeTlc = (left: Value[], right: Value[]) => {
933
+ const compareElementsLikeTlc = (left: Value[], right: Value[], isEquality: boolean) => {
854
934
  for (let index = 0; index < left.length; index++) {
855
- const comparison = compareLikeTlc(left[index], right[index]);
935
+ const comparison = compareOrEqualLikeTlc(left[index], right[index], isEquality);
856
936
  if (comparison !== 0) return comparison;
857
937
  }
858
938
  return 0;
859
939
  };
860
940
 
861
- const compareFunctionLikeTlc = (left: FunctionValue | LazyFunctionValue, right: Value) => {
941
+ const compareFunctionLikeTlc = (
942
+ left: FunctionValue | LazyFunctionValue,
943
+ right: Value,
944
+ isEquality: boolean,
945
+ ) => {
862
946
  const functionValue = toFiniteFunction(left);
863
- const isTuple = left.kind === "Function" && getSequenceElements(functionValue) !== undefined;
864
- if (isTuple) {
947
+ if (getFunctionClass(left) === "tuple") {
865
948
  const tuple = isFunctionValue(right) ? getSequenceElements(right) : undefined;
866
- if (!tuple) return compareTlcFunctions({ ...functionValue, low: 1 }, left, right);
949
+ if (!tuple) return compareTlcFunctions({ ...functionValue, low: 1 }, left, right, isEquality);
867
950
  return (
868
951
  functionValue.range.length - tuple.length ||
869
- compareElementsLikeTlc(functionValue.range, tuple)
952
+ compareElementsLikeTlc(functionValue.range, tuple, isEquality)
870
953
  );
871
954
  }
872
955
  if (getFunctionClass(left) === "record") {
873
956
  const record = toTlcRecord(right);
874
957
  if (!record) {
875
- if (isModelValue(right)) return compareModelValueWith(right, left);
958
+ if (isModelValue(right)) return compareModelValueWith(right, left, isEquality);
876
959
  throw new TlaEvaluationError(
877
- `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))}`,
878
961
  );
879
962
  }
880
963
  return (
881
964
  functionValue.domain.length - record.domain.length ||
882
- compareElementsLikeTlc(functionValue.domain, record.domain) ||
883
- compareElementsLikeTlc(functionValue.range, record.range)
965
+ compareElementsLikeTlc(functionValue.domain, record.domain, isEquality) ||
966
+ compareElementsLikeTlc(functionValue.range, record.range, isEquality)
884
967
  );
885
968
  }
886
969
  return compareTlcFunctions(
887
- { ...functionValue, low: getIntervalLow(functionValue.domain) },
970
+ { ...functionValue, low: getIntervalLow(left, functionValue.domain) },
888
971
  left,
889
972
  right,
973
+ isEquality,
890
974
  );
891
975
  };
892
976
 
893
- // TLC compares a lazy set, or a set it overrides in Java, through its own class before it compares
894
- // elements. The comparisons above already fail as those classes do.
895
977
  const isComparedByClass = (left: ObjectValue, right: Value) =>
896
978
  isOverriddenSet(left) ||
897
979
  isOverriddenSet(right) ||
@@ -908,131 +990,48 @@ const getSetElementsLikeTlc = (left: SetValue | MixedSetValue, right: Value) =>
908
990
  return { elements: toFiniteSet(left).elements, otherElements: toFiniteSet(other).elements };
909
991
  };
910
992
 
911
- const compareSetLikeTlc = (left: ObjectValue, right: Value): number => {
912
- if (isComparedByClass(left, right)) return compareValues(left, right);
913
- 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);
914
999
  if (!isSetValue(right)) {
915
- if (isModelValue(right)) return compareModelValueWith(right, left);
1000
+ if (isModelValue(right)) return compareModelValueWith(right, left, isEquality);
916
1001
  throw new TlaEvaluationError(
917
- `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))}`,
918
1003
  );
919
1004
  }
920
1005
  const sets = getSetElementsLikeTlc(left, right);
921
1006
  return (
922
1007
  sets.elements.length - sets.otherElements.length ||
923
- compareElementsLikeTlc(sets.elements, sets.otherElements)
1008
+ compareElementsLikeTlc(sets.elements, sets.otherElements, isEquality)
924
1009
  );
925
1010
  };
926
1011
 
927
- const compareLikeTlc = (left: Value, right: Value): number => {
1012
+ const compareOrEqualLikeTlc = (left: Value, right: Value, isEquality: boolean): number => {
928
1013
  if (typeof left !== "object") {
929
- if (typeof right === typeof left) return compareValues(left, right);
930
- if (isModelValue(right)) return compareModelValueWith(right, left);
931
- throw new TlaEvaluationError(describeScalarMismatch(left, right, false));
932
- }
933
- if (left.kind === "ModelValue") return compareModelValue(left, right);
934
- if (isFunctionValue(left)) return compareFunctionLikeTlc(left, right);
935
- return compareSetLikeTlc(left, right);
936
- };
937
-
938
- const equalsElementsLikeTlc = (left: Value[], right: Value[]) =>
939
- left.every((element, index) => equalsLikeTlc(element, right[index]));
940
-
941
- const equalsTlcFunctions = (functionValue: TlcFunction, left: Value, right: Value) => {
942
- const other = toTlcFunction(right);
943
- if (!other) {
944
- if (isModelValue(right)) return equalsModelValueWith(right, left);
945
- throw new TlaEvaluationError(
946
- `Attempted to check equality of the function ${formatValue(left)} with the value:\n${formatValue(right)}`,
947
- );
948
- }
949
- if (functionValue.range.length !== other.range.length) return false;
950
- if (functionValue.low !== undefined && other.low !== undefined) {
951
- return (
952
- (functionValue.range.length === 0 || functionValue.low === other.low) &&
953
- equalsElementsLikeTlc(functionValue.range, other.range)
954
- );
955
- }
956
- const intervalLow = functionValue.low ?? other.low;
957
- if (intervalLow === undefined) {
958
- return (
959
- equalsElementsLikeTlc(functionValue.domain, other.domain) &&
960
- equalsElementsLikeTlc(functionValue.range, other.range)
961
- );
962
- }
963
- const keys = functionValue.low === undefined ? functionValue.domain : other.domain;
964
- return (
965
- keys.every((key, index) => {
966
- if (typeof key !== "number") {
967
- throw new TlaEvaluationError(
968
- `Attempted to compare an integer with non-integer:\n${formatValue(key)}.`,
969
- );
970
- }
971
- return key === intervalLow + index;
972
- }) && equalsElementsLikeTlc(functionValue.range, other.range)
973
- );
974
- };
975
-
976
- const equalsFunctionLikeTlc = (left: FunctionValue | LazyFunctionValue, right: Value) => {
977
- const functionValue = toFiniteFunction(left);
978
- const isTuple = left.kind === "Function" && getSequenceElements(functionValue) !== undefined;
979
- if (isTuple) {
980
- const tuple = isFunctionValue(right) ? getSequenceElements(right) : undefined;
981
- if (!tuple) return equalsTlcFunctions({ ...functionValue, low: 1 }, left, right);
982
- return (
983
- functionValue.range.length === tuple.length &&
984
- equalsElementsLikeTlc(functionValue.range, tuple)
985
- );
986
- }
987
- if (getFunctionClass(left) === "record") {
988
- const record = toTlcRecord(right);
989
- if (!record) {
990
- if (isModelValue(right)) return equalsModelValueWith(right, left);
991
- throw new TlaEvaluationError(
992
- `Attempted to check equality of record:\n${formatValue(left)}\nwith non-record\n${formatValue(right)}`,
993
- );
1014
+ if (typeof right === typeof left) {
1015
+ if (!isEquality) return compareValues(left, right);
1016
+ return left === right ? 0 : 1;
994
1017
  }
995
- return (
996
- functionValue.domain.length === record.domain.length &&
997
- equalsElementsLikeTlc(functionValue.domain, record.domain) &&
998
- equalsElementsLikeTlc(functionValue.range, record.range)
999
- );
1018
+ if (isModelValue(right)) return compareModelValueWith(right, left, isEquality);
1019
+ throw new TlaEvaluationError(describeScalarMismatch(left, right, isEquality));
1000
1020
  }
1001
- return equalsTlcFunctions(
1002
- { ...functionValue, low: getIntervalLow(functionValue.domain) },
1003
- left,
1004
- right,
1005
- );
1006
- };
1007
-
1008
- const equalsSetLikeTlc = (left: ObjectValue, right: Value): boolean => {
1009
- if (isComparedByClass(left, right)) return valuesEqual(left, right);
1010
- if (!isEnumeratedSet(left)) return equalsSetLikeTlc(toFiniteSet(left), right);
1011
- if (!isSetValue(right)) {
1012
- if (isModelValue(right)) return equalsModelValueWith(right, left);
1013
- throw new TlaEvaluationError(
1014
- `Attempted to check equality of the set ${formatValue(left)} with the value:\n${formatValue(right)}`,
1015
- );
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;
1016
1026
  }
1017
- const sets = getSetElementsLikeTlc(left, right);
1018
- return (
1019
- sets.elements.length === sets.otherElements.length &&
1020
- equalsElementsLikeTlc(sets.elements, sets.otherElements)
1021
- );
1027
+ if (isFunctionValue(left)) return compareFunctionLikeTlc(left, right, isEquality);
1028
+ return compareSetLikeTlc(left, right, isEquality);
1022
1029
  };
1023
1030
 
1024
- const equalsLikeTlc = (left: Value, right: Value): boolean => {
1025
- if (typeof left !== "object") {
1026
- if (typeof right === typeof left) return left === right;
1027
- if (isModelValue(right)) return equalsModelValueWith(right, left);
1028
- throw new TlaEvaluationError(describeScalarMismatch(left, right, true));
1029
- }
1030
- if (left.kind === "ModelValue") return equalsModelValue(left, right);
1031
- if (isFunctionValue(left)) return equalsFunctionLikeTlc(left, right);
1032
- return equalsSetLikeTlc(left, right);
1033
- };
1031
+ const compareLikeTlc = (left: Value, right: Value) => compareOrEqualLikeTlc(left, right, false);
1032
+
1033
+ const equalsLikeTlc = (left: Value, right: Value) => compareOrEqualLikeTlc(left, right, true) === 0;
1034
1034
 
1035
- // TLC's ValueVec.sort, which inserts each element into the sorted prefix by binary search.
1036
1035
  const sortLikeTlc = (elements: Value[]) => {
1037
1036
  const sorted: Value[] = [];
1038
1037
  for (const element of elements) {
@@ -1042,7 +1041,6 @@ const sortLikeTlc = (elements: Value[]) => {
1042
1041
  return sorted;
1043
1042
  };
1044
1043
 
1045
- // Calls a method of a value as TLC does, whose failure the value heads when it has a source.
1046
1044
  const callTracedMethod = <Result>(receiver: Value, method: () => Result) => {
1047
1045
  const sets = setTrace.sets;
1048
1046
  if (sets === undefined) return method();
@@ -1052,43 +1050,66 @@ const callTracedMethod = <Result>(receiver: Value, method: () => Result) => {
1052
1050
  return result;
1053
1051
  };
1054
1052
 
1055
- // ValueVec.search on sorted elements: a binary search with compareTo, which ends where the element
1056
- // is or would go.
1057
1053
  const searchLikeTlc = (element: Value, sorted: Value[]) => {
1058
- const bounds = { low: 0, high: sorted.length };
1059
- while (bounds.low < bounds.high) {
1060
- 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);
1061
1058
  const comparison = callTracedMethod(element, () => compareLikeTlc(element, sorted[middle]));
1062
1059
  if (comparison === 0) return { index: middle, isFound: true };
1063
- if (comparison < 0) bounds.high = middle;
1064
- else bounds.low = middle + 1;
1060
+ if (comparison < 0) high = middle;
1061
+ else low = middle + 1;
1065
1062
  }
1066
- return { index: bounds.low, isFound: false };
1063
+ return { index: low, isFound: false };
1067
1064
  };
1068
1065
 
1069
- // TLC checks membership in a set enumeration it hasn't sorted element by element, with the equals
1070
- // method of each member.
1071
1066
  const isElementOfLikeTlc = (element: Value, elements: Value[]) =>
1072
1067
  elements.some((member) => callTracedMethod(member, () => equalsLikeTlc(member, element)));
1073
1068
 
1074
- // The sets TLC has normalized, whose membership ValueVec.search checks by binary search with
1075
- // compareTo instead of element by element.
1076
- 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);
1077
1073
 
1078
- // IValue.deepNormalize, which TLC applies to the constants of the config and the constant
1079
- // definitions it computes as it starts.
1080
1074
  export const markNormalized = (value: Value): void => {
1081
1075
  if (typeof value !== "object") return;
1082
1076
  if (value.kind === "Set") {
1083
- normalizedSets.add(value);
1077
+ value.isNormalized = true;
1084
1078
  value.elements.forEach(markNormalized);
1085
1079
  }
1086
1080
  if (value.kind === "Function") {
1081
+ value.writtenKeys = undefined;
1087
1082
  value.domain.forEach(markNormalized);
1088
1083
  value.range.forEach(markNormalized);
1089
1084
  }
1090
1085
  };
1091
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
+
1092
1113
  export const isEqualLikeTlc = (left: Value, right: Value) =>
1093
1114
  computeLikeTlcOnFailure(valuesEqual, equalsLikeTlc, left, right);
1094
1115
 
@@ -1099,8 +1120,18 @@ const isStrictlySorted = (elements: Value[]) => {
1099
1120
  return true;
1100
1121
  };
1101
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
+
1102
1134
  export const createSet = (elements: Value[]): SetValue => {
1103
- // ValueVec.sort compares each element after the first with those before it.
1104
1135
  for (let index = 1; index < elements.length; index++) cacheSet(elements[index]);
1105
1136
  if (elements.length < 2 || isStrictlySorted(elements)) return createSortedSet(elements);
1106
1137
  const sorted = [...elements].sort(compareValues);
@@ -1111,15 +1142,17 @@ export const createSet = (elements: Value[]): SetValue => {
1111
1142
  return createSortedSet(unique);
1112
1143
  };
1113
1144
 
1114
- // TLC builds a set enumeration without sorting it, so one whose elements it can't compare still
1115
- // evaluates.
1116
- export const createEnumeratedSet = (elements: Value[]): SetValue | MixedSetValue =>
1117
- 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>(
1118
1148
  createSet,
1119
1149
  (mixed) => ({ kind: "MixedSet", elements: mixed }),
1120
1150
  elements,
1121
1151
  undefined,
1122
1152
  );
1153
+ if (set.kind === "Set" && set.elements !== elements) set.writtenElements = elements;
1154
+ return set;
1155
+ };
1123
1156
 
1124
1157
  export const EMPTY_SET = createSortedSet([]);
1125
1158
 
@@ -1235,7 +1268,6 @@ export const createWrittenFunction = (pairs: [Value, Value][]) => {
1235
1268
  const functionValue = createFunction(pairs);
1236
1269
  const isWrittenSorted =
1237
1270
  functionValue.domain.length !== pairs.length ||
1238
- pairs.some((pair) => typeof pair[0] !== "string") ||
1239
1271
  pairs.every((pair, index) => pair[0] === functionValue.domain[index]);
1240
1272
  return isWrittenSorted
1241
1273
  ? functionValue
@@ -1251,22 +1283,15 @@ const longIntervalDomains = new Map<number, WeakRef<Value[]>>();
1251
1283
  const intervalValues: IntervalValue[] = [];
1252
1284
  const intervalArrays = new WeakMap<Value[], IntervalValue>();
1253
1285
 
1254
- // TLC keeps the domain of a tuple, or of a function built over an interval, as an interval. Every
1255
- // function over 1..n shares one domain array per length, and the elements of any other interval
1256
- // map to it, so the array's identity records it. Callers must not mutate the returned array.
1257
- // Longer domains are held weakly: a sequence that grows one element at a time would otherwise keep
1258
- // an array of every length it passed through, n * n / 2 numbers in all.
1259
1286
  const getIntervalDomain = (length: number): Value[] => {
1260
1287
  const cached = intervalDomains[length] ?? longIntervalDomains.get(length)?.deref();
1261
1288
  if (cached) return cached;
1262
- const domain = Array.from({ length }, (_, index) => index + 1);
1289
+ const domain = Array.from({ length }, (_value, index) => index + 1);
1263
1290
  if (length > MAX_SHARED_INTERVAL_LENGTH) longIntervalDomains.set(length, new WeakRef(domain));
1264
1291
  else intervalDomains[length] = domain;
1265
1292
  return domain;
1266
1293
  };
1267
1294
 
1268
- // The elements of an interval for a caller that only iterates them, so they need not record
1269
- // the interval for DOMAIN.
1270
1295
  export const getIntervalElements = (value: IntervalValue): Value[] => {
1271
1296
  getCardinality(value);
1272
1297
  if (value.low === 1 && value.high >= 1) return getIntervalDomain(value.high);
@@ -1276,13 +1301,11 @@ export const getIntervalElements = (value: IntervalValue): Value[] => {
1276
1301
  };
1277
1302
 
1278
1303
  const isIntervalDomain = (domain: Value[]) =>
1279
- domain.length > 0 &&
1280
- (domain === intervalDomains[domain.length] ||
1281
- domain === longIntervalDomains.get(domain.length)?.deref() ||
1282
- intervalArrays.has(domain));
1304
+ (domain.length > 0 &&
1305
+ (domain === intervalDomains[domain.length] ||
1306
+ domain === longIntervalDomains.get(domain.length)?.deref())) ||
1307
+ intervalArrays.has(domain);
1283
1308
 
1284
- // TLC keeps an interval domain only for a function built over an interval itself, so a set
1285
- // such as (1..2) \cap S, whose elements are the shared array, gets a copy.
1286
1309
  export const getFunctionDomain = (set: Value): Value[] => {
1287
1310
  const elements = toFiniteSet(set).elements;
1288
1311
  return isIntervalDomain(elements) && !(typeof set === "object" && set.kind === "Interval")
@@ -1307,7 +1330,6 @@ export const createRecord = (fields: [string, Value][]): FunctionValue =>
1307
1330
  export const createSortedRecord = (names: Value[], range: Value[]) =>
1308
1331
  setFunctionClass(createSortedFunction(names, range), "record");
1309
1332
 
1310
- // TLC's Enumerable classes: every set except the ones it implements in Java.
1311
1333
  export const isTlcEnumerable = (value: Value) => isSetValue(value) && !isOverriddenSet(value);
1312
1334
 
1313
1335
  const formatUnion = (value: UnionValue, isStrict = false) =>
@@ -1330,7 +1352,7 @@ const getUnionSet = (set: Value, index: number, union: UnionValue) => {
1330
1352
  throw new TlaEvaluationError(
1331
1353
  index === 0
1332
1354
  ? "Attempted to enumerate UNION(s), but some element of s is nonenumerable."
1333
- : `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))}`,
1334
1356
  );
1335
1357
  };
1336
1358
 
@@ -1358,7 +1380,13 @@ export const isEnumerable = (value: Value): boolean => {
1358
1380
  case "ProductSet":
1359
1381
  return value.factors.every(isEnumerable) || getEmptiness(value) === true;
1360
1382
  case "Union":
1361
- 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
+ );
1362
1390
  case "SetOperation":
1363
1391
  if (value.operator === "\\cup") return isEnumerable(value.left) && isEnumerable(value.right);
1364
1392
  if (value.operator === "\\cap") return isEnumerable(value.left) || isEnumerable(value.right);
@@ -1431,26 +1459,24 @@ const advanceCombination = (indices: number[], length: number) => {
1431
1459
  return false;
1432
1460
  };
1433
1461
 
1434
- // TLC enumerates SUBSET S lazily, by size and then in the order of S, so a quantifier that finds
1435
- // its witness early never builds the rest. For a power set too large to build, the elements are
1436
- // computed in that order as a loop reads them.
1437
1462
  export const getLazySubsets = (value: Value): Value[] | undefined => {
1438
1463
  if (typeof value !== "object" || value.kind !== "Subset" || isOverriddenSet(value.base)) {
1439
1464
  return undefined;
1440
1465
  }
1441
1466
  const base = toFiniteSet(value.base).elements;
1442
- if (base.length <= MAXIMUM_ENUMERATED_SUBSET_BASE) return undefined;
1443
- const cursor = { index: -1, indices: [0] };
1467
+ if (base.length <= MAXIMUM_BUILT_SUBSET_BASE) return undefined;
1468
+ let cursorIndex = -1;
1469
+ let indices = [0];
1444
1470
  const getSubset = (index: number) => {
1445
- if (index <= cursor.index) cursor.index = -1;
1446
- while (cursor.index < index) {
1447
- if (cursor.index === -1) cursor.indices = [];
1448
- else if (!advanceCombination(cursor.indices, base.length)) {
1449
- 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);
1450
1476
  }
1451
- cursor.index++;
1477
+ cursorIndex++;
1452
1478
  }
1453
- return createSortedSet(cursor.indices.map((item) => base[item]));
1479
+ return createSortedSet(indices.map((baseIndex) => base[baseIndex]));
1454
1480
  };
1455
1481
  const length = 2 ** base.length;
1456
1482
  const isIndex = (property: string | symbol) =>
@@ -1469,7 +1495,7 @@ export const getLazySubsets = (value: Value): Value[] | undefined => {
1469
1495
  const getSortedSubsets = (base: Value[]) => {
1470
1496
  const subsets: Value[] = [];
1471
1497
  for (let size = 0; size <= base.length; size++) {
1472
- const indices = Array.from({ length: size }, (_, index) => index);
1498
+ const indices = Array.from({ length: size }, (_value, index) => index);
1473
1499
  do {
1474
1500
  subsets.push(createSortedSet(indices.map((index) => base[index])));
1475
1501
  } while (advanceCombination(indices, base.length));
@@ -1477,9 +1503,6 @@ const getSortedSubsets = (base: Value[]) => {
1477
1503
  return subsets;
1478
1504
  };
1479
1505
 
1480
- // The Enumerator of a set of records or tuples enumerates its sets in turn and stops at the first
1481
- // empty one, which leaves the product empty. Later versions of TLC decide that the set is empty
1482
- // before they enumerate it.
1483
1506
  const getComponentElements = (
1484
1507
  sets: Value[],
1485
1508
  getElements: (set: Value) => Value[],
@@ -1496,7 +1519,6 @@ const getComponentElements = (
1496
1519
  return lists;
1497
1520
  };
1498
1521
 
1499
- // getElements enumerates the sets a set of functions, records, or tuples combines.
1500
1522
  const enumerateSet = (
1501
1523
  value: Value,
1502
1524
  getElements = (set: Value) => toFiniteSet(set).elements,
@@ -1514,8 +1536,6 @@ const enumerateSet = (
1514
1536
  return elements;
1515
1537
  }
1516
1538
  case "Subset": {
1517
- // SubsetValue.toSetEnum sizes the set before it enumerates it, and enumerates only the empty
1518
- // set of a value of size 0, a function with an empty domain among them.
1519
1539
  if (getCardinality(value.base) === 0) return getSortedSubsets([]);
1520
1540
  if (!isSetValue(value.base)) {
1521
1541
  throw new TlaEvaluationError(
@@ -1529,17 +1549,16 @@ const enumerateSet = (
1529
1549
  return getSortedSubsets(base);
1530
1550
  }
1531
1551
  case "FunctionSet": {
1532
- if (!valueVersion.is174 && isEmptySet(value)) return [];
1552
+ if (!isVersion174 && isEmptySet(value)) return [];
1533
1553
  if (isOverriddenSet(value.domain)) {
1534
1554
  throw new TlaEvaluationError(
1535
- `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.`,
1536
1556
  );
1537
1557
  }
1538
1558
  const domain = getFunctionDomain(value.domain);
1539
- // TLC 1.7.4 requires an enumerable range even of an empty domain.
1540
- if ((domain.length > 0 || valueVersion.is174) && isOverriddenSet(value.range)) {
1559
+ if ((domain.length > 0 || isVersion174) && isOverriddenSet(value.range)) {
1541
1560
  throw new TlaEvaluationError(
1542
- `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.`,
1543
1562
  );
1544
1563
  }
1545
1564
  const range = domain.length === 0 ? [] : getElements(value.range);
@@ -1548,77 +1567,82 @@ const enumerateSet = (
1548
1567
  );
1549
1568
  }
1550
1569
  case "RecordSet": {
1551
- if (!valueVersion.is174 && isEmptySet(value)) return [];
1570
+ if (!isVersion174 && isEmptySet(value)) return [];
1552
1571
  const fields = getComponentElements(
1553
1572
  value.sets,
1554
1573
  getElements,
1555
1574
  (set, index) =>
1556
- `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))}`,
1557
1576
  );
1558
1577
  return getCartesianProduct(fields).map((combination) =>
1559
1578
  createRecord(value.names.map((name, index): [string, Value] => [name, combination[index]])),
1560
1579
  );
1561
1580
  }
1562
1581
  case "ProductSet": {
1563
- if (!valueVersion.is174 && isEmptySet(value)) return [];
1582
+ if (!isVersion174 && isEmptySet(value)) return [];
1564
1583
  const factors = getComponentElements(
1565
1584
  value.factors,
1566
1585
  getElements,
1567
1586
  (factor, index) =>
1568
- `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))}`,
1569
1588
  );
1570
1589
  return getCartesianProduct(factors).map(createTuple);
1571
1590
  }
1572
1591
  case "FilteredSet":
1573
1592
  if (!isSetValue(value.base) || isOverriddenSet(value.base)) {
1574
1593
  throw new TlaEvaluationError(
1575
- `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`,
1576
1595
  );
1577
1596
  }
1578
- 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;
1579
1604
  case "Union": {
1580
- const elements = getUnionSets(value).flatMap(
1581
- (set, index) => toFiniteSet(getUnionSet(set, index, value)).elements,
1582
- );
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
+ });
1583
1611
  return toFiniteSet(createEnumeratedSet(elements)).elements;
1584
1612
  }
1585
1613
  case "SetOperation": {
1586
- if (
1587
- value.operator === "\\cup" &&
1588
- (!isTlcEnumerable(value.left) || !isTlcEnumerable(value.right))
1589
- ) {
1590
- throw new TlaEvaluationError(
1591
- `Attempted to enumerate S \\cup T when S:\n${formatValue(value.left)}\nand T:\n${formatValue(value.right)}\nare not both enumerable`,
1592
- );
1593
- }
1594
1614
  if (
1595
1615
  value.operator === "\\cap" &&
1596
1616
  !isTlcEnumerable(value.left) &&
1597
1617
  !isTlcEnumerable(value.right)
1598
1618
  ) {
1599
1619
  throw new TlaEvaluationError(
1600
- `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`,
1601
1621
  );
1602
1622
  }
1603
1623
  if (value.operator === "\\" && !isTlcEnumerable(value.left)) {
1604
1624
  throw new TlaEvaluationError(
1605
- `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.`,
1606
1626
  );
1607
1627
  }
1608
1628
  if (value.operator === "\\cup") {
1609
- return computeLikeTlcOnFailure(
1610
- (union) => getSortedUnion(toFiniteSet(union.left), toFiniteSet(union.right)).elements,
1611
- (union) => sortLikeTlc(listUnionLikeTlc(union)),
1612
- value,
1613
- value,
1614
- );
1629
+ return toFiniteSet(createEnumeratedSet(listUnionLikeTlc(value))).elements;
1615
1630
  }
1616
1631
  const isLeftEnumerated = value.operator === "\\" || isTlcEnumerable(value.left);
1617
1632
  const enumerated = isLeftEnumerated ? value.left : value.right;
1618
1633
  const other = isLeftEnumerated ? value.right : value.left;
1619
- return toFiniteSet(enumerated).elements.filter(
1620
- (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
+ },
1621
1644
  );
1645
+ return toFiniteSet(createEnumeratedSet(kept)).elements;
1622
1646
  }
1623
1647
  case "InfiniteSet":
1624
1648
  case "SequenceSet":
@@ -1655,32 +1679,92 @@ export const toFiniteSet = (value: Value): SetValue => {
1655
1679
  return set;
1656
1680
  };
1657
1681
 
1658
- // SetCupValue#toSetEnum.
1659
- const listUnionLikeTlc = (union: SetOperationValue) => [
1660
- ...toFiniteSet(union.left).elements,
1661
- ...toFiniteSet(union.right).elements,
1662
- ];
1663
-
1664
- // EnumerableValue#elements(NORMALIZED) sorts a union outside its methods, so a failed comparison
1665
- // isn't a fingerprint failure.
1666
- export const getNormalizedSetElements = (value: Value) =>
1667
- typeof value === "object" && value.kind === "SetOperation" && value.operator === "\\cup"
1668
- ? computeLikeTlcOnFailure(
1669
- (union) => toFiniteSet(union).elements,
1670
- (union) => sortLikeTlc(callTracedMethod(union, () => listUnionLikeTlc(union))),
1671
- value,
1672
- value,
1673
- )
1674
- : 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
+ };
1675
1729
 
1676
- // TLC's Enumerator for a lazy set streams the sets it combines until the set caches its elements,
1677
- // so an element that two of them share comes up once for each.
1678
- export const getStreamedElements = (value: Value): Value[] => {
1679
- if (typeof value !== "object" || isCachedSet(value)) return toFiniteSet(value).elements;
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
+ };
1744
+
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
+ }
1680
1749
  const sets = setTrace.sets;
1681
1750
  sets?.push(value);
1682
- 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
+ });
1683
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
+ });
1684
1768
  return elements;
1685
1769
  };
1686
1770
 
@@ -1693,10 +1777,6 @@ const getCombinedSets = (value: ObjectValue) =>
1693
1777
  ? [value.range]
1694
1778
  : undefined;
1695
1779
 
1696
- // Whether a value TLC builds alike at each evaluation and that enumerating, comparing or
1697
- // fingerprinting it leaves alike, so that one evaluation can stand for the next. It holds no UNION or
1698
- // \cup, which streams until TLC caches it, no lambda, which fingerprinting turns into a record, and
1699
- // no record a comparison reorders.
1700
1780
  export const isSettledValue = (value: Value): boolean => {
1701
1781
  if (typeof value !== "object") return true;
1702
1782
  switch (value.kind) {
@@ -1725,8 +1805,6 @@ export const isSettledValue = (value: Value): boolean => {
1725
1805
  }
1726
1806
  };
1727
1807
 
1728
- // Whether a set streams its elements in another order than the normalized set, so that a set of
1729
- // tuples, records, or functions it is a component of has to stream too.
1730
1808
  const isStreamedApart = (value: Value): boolean => {
1731
1809
  if (typeof value !== "object" || isCachedSet(value)) return false;
1732
1810
  if (value.kind === "Union") return true;
@@ -1739,36 +1817,43 @@ const isStreamedApart = (value: Value): boolean => {
1739
1817
  return getCombinedSets(value)?.some(isStreamedApart) ?? false;
1740
1818
  };
1741
1819
 
1742
- const streamElements = (value: ObjectValue): Value[] => {
1743
- // TLC streams the sets of a UNION it hasn't enumerated, so a set that appears twice there yields
1744
- // its elements twice.
1820
+ const someElementOfStream = (value: ObjectValue, visit: (element: Value) => boolean): boolean => {
1745
1821
  if (value.kind === "Union") {
1746
- return getUnionSets(value, getStreamedElements).flatMap((set, index) =>
1747
- getStreamedElements(getUnionSet(set, index, value)),
1822
+ return getUnionSets(value, getStreamedElements).some((set, index) =>
1823
+ someStreamedElement(getUnionSet(set, index, value), visit),
1748
1824
  );
1749
1825
  }
1750
- if (value.kind === "FilteredSet" && !isOverriddenSet(value.base)) {
1751
- 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
+ );
1752
1833
  }
1753
1834
  const components = getCombinedSets(value);
1754
- if (components?.some(isStreamedApart)) return enumerateSet(value, getStreamedElements);
1755
- 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);
1756
1839
  if (value.operator === "\\cup") {
1757
1840
  return !isTlcEnumerable(value.left) || !isTlcEnumerable(value.right)
1758
- ? toFiniteSet(value).elements
1759
- : [...getStreamedElements(value.left), ...getStreamedElements(value.right)];
1841
+ ? toFiniteSet(value).elements.some(visit)
1842
+ : someStreamedElement(value.left, visit) || someStreamedElement(value.right, visit);
1760
1843
  }
1761
1844
  const isLeftEnumerated = value.operator === "\\" || isTlcEnumerable(value.left);
1762
1845
  const enumerated = isLeftEnumerated ? value.left : value.right;
1763
1846
  const other = isLeftEnumerated ? value.right : value.left;
1764
- if (!isTlcEnumerable(enumerated)) return toFiniteSet(value).elements;
1765
- return getStreamedElements(enumerated).filter(
1766
- (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),
1767
1851
  );
1768
1852
  };
1769
1853
 
1770
1854
  export const isEmptySet = (value: Value): boolean => {
1771
1855
  if (typeof value !== "object" || !isSetValue(value)) {
1856
+ setTrace.sets?.push(value);
1772
1857
  throw new TlaEvaluationError(`Shouldn't call isEmpty() on value ${formatValue(value)}`);
1773
1858
  }
1774
1859
  switch (value.kind) {
@@ -1810,20 +1895,18 @@ const getProductCardinality = (
1810
1895
  }, 1);
1811
1896
 
1812
1897
  const describeOverflow = (value: Value) =>
1813
- `Overflow when computing the number of elements in:\n${formatValue(value)}`;
1898
+ `Overflow when computing the number of elements in:\n${prettyPrint(formatValue(value))}`;
1814
1899
 
1815
- // TLC 1.7.4 sizes every component of a set of functions, records, or tuples without first
1816
- // checking whether one is empty, so an infinite component fails even beside an empty one.
1817
1900
  export const getCardinality = (value: Value, version?: TlcVersion): number => {
1818
1901
  if (typeof value !== "object") {
1819
1902
  throw new TlaEvaluationError(
1820
- `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))}.`,
1821
1904
  );
1822
1905
  }
1823
1906
  switch (value.kind) {
1824
1907
  case "ModelValue":
1825
1908
  throw new TlaEvaluationError(
1826
- `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))}.`,
1827
1910
  );
1828
1911
  case "Function":
1829
1912
  return value.domain.length;
@@ -1841,7 +1924,7 @@ export const getCardinality = (value: Value, version?: TlcVersion): number => {
1841
1924
  case "InfiniteSet":
1842
1925
  case "SequenceSet":
1843
1926
  throw new TlaEvaluationError(
1844
- `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))}.`,
1845
1928
  );
1846
1929
  case "Subset": {
1847
1930
  const size = getCardinality(value.base, version);
@@ -1857,12 +1940,12 @@ export const getCardinality = (value: Value, version?: TlcVersion): number => {
1857
1940
  const domainSize = getCardinality(value.domain, version);
1858
1941
  const rangeSize = getCardinality(value.range, version);
1859
1942
  if (rangeSize <= 1) return domainSize === 0 ? 1 : rangeSize;
1860
- const size = { value: 1 };
1943
+ let size = 1;
1861
1944
  for (let index = 0; index < domainSize; index++) {
1862
- size.value *= rangeSize;
1863
- if (size.value > MAXIMUM_INTEGER) throw new TlaEvaluationError(describeOverflow(value));
1945
+ size *= rangeSize;
1946
+ if (size > MAXIMUM_INTEGER) throw new TlaEvaluationError(describeOverflow(value));
1864
1947
  }
1865
- return size.value;
1948
+ return size;
1866
1949
  }
1867
1950
  case "RecordSet":
1868
1951
  if (version !== "1.7.4" && isEmptySet(value)) return 0;
@@ -1872,7 +1955,8 @@ export const getCardinality = (value: Value, version?: TlcVersion): number => {
1872
1955
  return getProductCardinality(
1873
1956
  value.factors,
1874
1957
  version,
1875
- () => `Overflow when computing the number of elements in ${formatValue(value)}`,
1958
+ () =>
1959
+ `Overflow when computing the number of elements in ${prettyPrint(formatValue(value))}`,
1876
1960
  );
1877
1961
  default:
1878
1962
  cacheSet(value);
@@ -1881,12 +1965,12 @@ export const getCardinality = (value: Value, version?: TlcVersion): number => {
1881
1965
  };
1882
1966
 
1883
1967
  const describeInfiniteCheck = (value: Value) =>
1884
- `Attempted to check if the set ${formatValue(value)}is finite.`;
1968
+ `Attempted to check if the set ${prettyPrint(formatValue(value))}is finite.`;
1885
1969
 
1886
1970
  export const isFiniteSet = (value: Value): boolean => {
1887
1971
  if (typeof value !== "object" || value.kind === "ModelValue") {
1888
1972
  throw new TlaEvaluationError(
1889
- `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.`,
1890
1974
  );
1891
1975
  }
1892
1976
  switch (value.kind) {
@@ -1897,7 +1981,7 @@ export const isFiniteSet = (value: Value): boolean => {
1897
1981
  return true;
1898
1982
  case "LazyFunction":
1899
1983
  throw new TlaEvaluationError(
1900
- `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.`,
1901
1985
  );
1902
1986
  case "InfiniteSet":
1903
1987
  return false;
@@ -1915,12 +1999,12 @@ export const isFiniteSet = (value: Value): boolean => {
1915
1999
  case "RecordSet":
1916
2000
  case "ProductSet": {
1917
2001
  const parts = value.kind === "RecordSet" ? value.sets : value.factors;
1918
- const finiteness = { isAllFinite: true };
2002
+ let isAllFinite = true;
1919
2003
  for (const part of parts) {
1920
- if (!isFiniteSet(part)) finiteness.isAllFinite = false;
2004
+ if (!isFiniteSet(part)) isAllFinite = false;
1921
2005
  else if (isEmptySet(part)) return true;
1922
2006
  }
1923
- return finiteness.isAllFinite;
2007
+ return isAllFinite;
1924
2008
  }
1925
2009
  case "Union":
1926
2010
  if (!isTlcEnumerable(value.base)) {
@@ -1943,7 +2027,7 @@ export const isFiniteSet = (value: Value): boolean => {
1943
2027
  case "FilteredSet":
1944
2028
  if (!isFiniteSet(value.base)) {
1945
2029
  throw new TlaEvaluationError(
1946
- `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.`,
1947
2031
  );
1948
2032
  }
1949
2033
  return true;
@@ -1951,19 +2035,45 @@ export const isFiniteSet = (value: Value): boolean => {
1951
2035
  };
1952
2036
 
1953
2037
  const findSortedIndex = (sortedValues: Value[], target: Value, compare = compareValues) => {
1954
- const bounds = { low: 0, high: sortedValues.length - 1 };
1955
- while (bounds.low <= bounds.high) {
1956
- 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;
1957
2042
  const comparison = compare(sortedValues[middle], target);
1958
2043
  if (comparison === 0) return middle;
1959
- if (comparison < 0) bounds.low = middle + 1;
1960
- else bounds.high = middle - 1;
2044
+ if (comparison < 0) low = middle + 1;
2045
+ else high = middle - 1;
1961
2046
  }
1962
2047
  return -1;
1963
2048
  };
1964
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
+
1965
2067
  export const getSequenceElements = (value: Value): Value[] | undefined => {
1966
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
+ }
1967
2077
  const functionValue = toFiniteFunction(value);
1968
2078
  return functionValue.domain.every((key, index) => key === index + 1)
1969
2079
  ? functionValue.range
@@ -1971,34 +2081,28 @@ export const getSequenceElements = (value: Value): Value[] | undefined => {
1971
2081
  };
1972
2082
 
1973
2083
  const describeNonSetMembership = (element: Value, value: Value) => {
1974
- const prefix = `Attempted to check if the value:\n${formatValue(element)}\nis an element of the`;
1975
- 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))}`;
1976
2087
  const functionClass = getFunctionClass(value);
1977
2088
  if (functionClass === "record") {
1978
- 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))}`;
1979
2090
  }
1980
2091
  if (functionClass === "tuple") return "Attempted to check set membership in a tuple value.";
1981
- return `${prefix} function ${formatValue(value)}`;
2092
+ return `${prefix} function ${prettyPrint(formatValue(value))}`;
1982
2093
  };
1983
2094
 
1984
- // The call stack of the replay, which a failed fast path leaves frozen.
1985
2095
  interface TracedCallStack {
1986
2096
  expressions: unknown[];
1987
2097
  isFrozen: boolean;
2098
+ sources: WeakMap<ObjectValue, unknown>;
1988
2099
  fingerprint?: unknown;
1989
2100
  }
1990
2101
 
1991
- // The sets whose membership is being checked or whose elements are being enumerated, and the
1992
- // members being compared, outermost first, while TLC's CallStackTool replays a computation. A failed
1993
- // check or enumeration leaves the values it was in, each of which TLC adds to the
1994
- // FingerprintException when it has a source.
1995
2102
  export const setTrace: { sets: Value[] | undefined; callStack?: TracedCallStack } = {
1996
2103
  sets: undefined,
1997
2104
  };
1998
2105
 
1999
- // Takes a fast path, and computes as TLC does where it fails. TLC never takes the fast path, so
2000
- // the failure's leftovers in the replay's trace go first. Both paths take their operands as
2001
- // arguments, so a hot caller passes functions it doesn't allocate.
2002
2106
  export const computeLikeTlcOnFailure = <Left, Right, Result>(
2003
2107
  compute: (left: Left, right: Right) => Result,
2004
2108
  computeLikeTlc: (left: Left, right: Right, error: TlaEvaluationError) => Result,
@@ -2023,6 +2127,11 @@ export const computeLikeTlcOnFailure = <Left, Right, Result>(
2023
2127
  }
2024
2128
  };
2025
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
+
2026
2135
  export const isElementOf = (element: Value, set: Value): boolean => {
2027
2136
  const sets = setTrace.sets;
2028
2137
  if (sets === undefined) return isElementOfSet(element, set);
@@ -2032,46 +2141,77 @@ export const isElementOf = (element: Value, set: Value): boolean => {
2032
2141
  return isElement;
2033
2142
  };
2034
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
+
2035
2159
  const isInSortedSet = (element: Value, set: SetValue) =>
2036
2160
  findSortedIndex(set.elements, element) !== -1;
2037
2161
 
2038
2162
  const isInSortedSetLikeTlc = (element: Value, set: SetValue) =>
2039
- normalizedSets.has(set)
2163
+ set.isNormalized
2040
2164
  ? searchLikeTlc(element, set.elements).isFound
2041
- : isElementOfLikeTlc(element, set.elements);
2165
+ : isElementOfLikeTlc(element, getWrittenElements(set));
2042
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
+ };
2175
+
2176
+ // The common cases stay small enough for V8 to inline.
2043
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 => {
2044
2187
  if (!isSetValue(set)) throw new TlaEvaluationError(describeNonSetMembership(element, set));
2045
2188
  switch (set.kind) {
2046
2189
  case "Set":
2047
- // SetEnumValue.member compares the element with the set's.
2048
2190
  cacheSet(element);
2049
2191
  return computeLikeTlcOnFailure(isInSortedSet, isInSortedSetLikeTlc, element, set);
2050
2192
  case "MixedSet":
2051
2193
  return isElementOfLikeTlc(element, set.elements);
2052
2194
  case "Interval":
2053
2195
  if (typeof element === "number") return element >= set.low && element <= set.high;
2054
- if (set.low <= set.high && !isModelValue(element)) {
2196
+ if (set.low <= set.high && (!isModelValue(element) || element.type !== undefined)) {
2055
2197
  throw new TlaEvaluationError(
2056
- `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))}`,
2057
2199
  );
2058
2200
  }
2059
2201
  return false;
2060
2202
  case "InfiniteSet": {
2061
2203
  if (set.name === "Any") return true;
2062
- if (isModelValue(element)) return false;
2204
+ if (isModelValue(element)) return isModelValueMember(element, set);
2063
2205
  const isMemberType =
2064
2206
  set.name === "STRING" ? typeof element === "string" : typeof element === "number";
2065
2207
  if (!isMemberType) {
2066
- throw new TlaEvaluationError(
2067
- `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}.`,
2068
2210
  );
2069
2211
  }
2070
2212
  return set.name !== "Nat" || (typeof element === "number" && element >= 0);
2071
2213
  }
2072
2214
  case "Subset":
2073
- // SubsetValue.member fails on any value that is not Enumerable, model values and the sets a
2074
- // Java class overrides included.
2075
2215
  if (!isSetValue(element) || isOverriddenSet(element)) {
2076
2216
  throw new TlaEvaluationError(
2077
2217
  `Attempted to check if the non-enumerable value\n${prettyPrint(formatValue(element))}\nis element of\n${prettyPrint(formatValue(set))}`,
@@ -2080,14 +2220,14 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2080
2220
  return toFiniteSet(element).elements.every((item) => isElementOf(item, set.base));
2081
2221
  case "FunctionSet": {
2082
2222
  if (!isFunctionValue(element)) {
2083
- if (isModelValue(element)) return false;
2084
- // SetOfFcnsValue.member prints the element without Values.ppr.
2223
+ if (isModelValue(element)) return isModelValueMember(element, set);
2085
2224
  throw new TlaEvaluationError(
2086
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))}`,
2087
2226
  );
2088
2227
  }
2228
+ forgetOwnWrittenOrder(element);
2089
2229
  const functionValue = toFiniteFunction(element);
2090
- const low = getIntervalLow(functionValue.domain);
2230
+ const low = getIntervalLow(element, functionValue.domain);
2091
2231
  const isDomain =
2092
2232
  low === undefined
2093
2233
  ? isEqualLikeTlc(set.domain, createSortedSet(functionValue.domain))
@@ -2098,11 +2238,12 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2098
2238
  return isDomain && functionValue.range.every((item) => isElementOf(item, set.range));
2099
2239
  }
2100
2240
  case "RecordSet": {
2241
+ forgetOwnWrittenOrder(element);
2101
2242
  const functionValue = isFunctionValue(element) ? toFiniteFunction(element) : undefined;
2102
2243
  if (!functionValue || !isRecordDomain(functionValue.domain)) {
2103
- if (isModelValue(element)) return false;
2244
+ if (isModelValue(element)) return isModelValueMember(element, set);
2104
2245
  throw new TlaEvaluationError(
2105
- `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))}`,
2106
2247
  );
2107
2248
  }
2108
2249
  return (
@@ -2119,9 +2260,10 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2119
2260
  const isFunction =
2120
2261
  isFunctionValue(element) &&
2121
2262
  toFiniteFunction(element).domain.every((key) => typeof key === "number");
2122
- if (isFunction || isModelValue(element)) return false;
2263
+ if (isModelValue(element)) return isModelValueMember(element, set);
2264
+ if (isFunction) return false;
2123
2265
  throw new TlaEvaluationError(
2124
- `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))}`,
2125
2267
  );
2126
2268
  }
2127
2269
  return (
@@ -2130,14 +2272,28 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2130
2272
  );
2131
2273
  }
2132
2274
  case "FilteredSet":
2133
- return isElementOf(element, set.base) && set.test(element);
2134
- 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": {
2135
2284
  if (!isTlcEnumerable(set.base)) {
2136
2285
  throw new TlaEvaluationError(
2137
- `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))}`,
2138
2287
  );
2139
2288
  }
2140
- 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
+ }
2141
2297
  case "SetOperation":
2142
2298
  if (set.operator === "\\cup")
2143
2299
  return isElementOf(element, set.left) || isElementOf(element, set.right);
@@ -2148,9 +2304,8 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2148
2304
  case "SequenceSet": {
2149
2305
  const elements = getSequenceElements(element);
2150
2306
  if (elements === undefined) {
2151
- if (isModelValue(element)) return false;
2152
- // Sequences.member raises TLC_MODULE_CHECK_MEMBER_OF.
2153
- throw new TlaEvaluationError(
2307
+ if (isModelValue(element)) return isModelValueMember(element, set);
2308
+ throw new TlaModuleError(
2154
2309
  `Attempted to check if the value:\n${prettyPrint(formatValue(element))}\nis an element of ${prettyPrint(formatValue(set))}.`,
2155
2310
  );
2156
2311
  }
@@ -2161,8 +2316,6 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2161
2316
  }
2162
2317
  };
2163
2318
 
2164
- // A function that agrees with a member of a function set outside some entries is a member when
2165
- // those entries are.
2166
2319
  export const isUpdatedElementOf = (element: Value, member: Value, set: Value): boolean => {
2167
2320
  if (element === member) return true;
2168
2321
  if (
@@ -2185,13 +2338,13 @@ export const toFiniteFunction = (value: Value): FunctionValue => {
2185
2338
  if (typeof value === "object" && value.kind === "LazyFunction") {
2186
2339
  if (value.enumerated) return value.enumerated;
2187
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
+ }
2188
2344
  const domain = getFunctionDomain(value.domain);
2189
- value.enumerated = setFunctionClass(
2190
- createSortedFunction(
2191
- domain,
2192
- domain.map((key) => value.apply(key)),
2193
- ),
2194
- getFunctionClass(value),
2345
+ value.enumerated = createSortedFunction(
2346
+ domain,
2347
+ domain.map((key) => value.apply(key)),
2195
2348
  );
2196
2349
  return value.enumerated;
2197
2350
  }
@@ -2232,16 +2385,14 @@ export const describeMissingArgument = (
2232
2385
  }
2233
2386
  };
2234
2387
 
2235
- // TLC 1.7.4 words a key of the wrong type in an EXCEPT, which selects rather than applies, apart.
2236
2388
  const describeExceptKey = (functionValue: FunctionValue, argument: Value) => {
2237
- if (!valueVersion.is174) return describeMissingArgument(functionValue, argument);
2389
+ if (!isVersion174) return describeMissingArgument(functionValue, argument);
2238
2390
  const shown = prettyPrint(formatValue(argument));
2239
2391
  return getFunctionClass(functionValue) === "tuple"
2240
2392
  ? `Attempted to apply tuple to a non-integer argument ${shown}.`
2241
2393
  : `Attempted to apply record to a non-string argument ${shown}.`;
2242
2394
  };
2243
2395
 
2244
- // A key the domain holds itself, which TLC finds without a comparison that can fail.
2245
2396
  const findIdenticalKey = (domain: Value[], argument: Value) => {
2246
2397
  const first = domain[0];
2247
2398
  if (typeof argument === "number" && typeof first === "number") {
@@ -2256,22 +2407,25 @@ export const createNonIntegerKeyError = (argument: Value) =>
2256
2407
  `Attempted to apply function with integer domain to the non-integer argument ${prettyPrint(formatValue(argument))}`,
2257
2408
  );
2258
2409
 
2259
- // TLC's FcnRcdValue searches a domain this small linearly with equals, and a larger normalized one by
2260
- // binary search with compareTo.
2261
2410
  const LINEAR_SEARCH_LIMIT = 32;
2262
2411
 
2263
- const failKeyLikeTlc = (domain: Value[], argument: Value, error: TlaEvaluationError): never => {
2264
- if (valueVersion.is174 || domain.length < LINEAR_SEARCH_LIMIT) {
2265
- 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));
2266
2423
  } else {
2267
- findSortedIndex(domain, argument, compareLikeTlc);
2424
+ findSortedIndex(keys, argument, compareLikeTlc);
2268
2425
  }
2269
2426
  throw error;
2270
2427
  };
2271
2428
 
2272
- // TLC looks a key up by the Java class of the function: a tuple or a record rejects a key of the
2273
- // wrong type, and another function rejects a non-integer for a domain it keeps as an interval, which
2274
- // TLC 1.7.4 doesn't. A key of another type than the domain's keys otherwise fails TLC's comparison.
2275
2429
  const findKeyIndexLikeTlc = (
2276
2430
  functionValue: FunctionValue,
2277
2431
  argument: Value,
@@ -2285,21 +2439,104 @@ const findKeyIndexLikeTlc = (
2285
2439
  if (keyType !== undefined && typeof argument !== keyType) {
2286
2440
  throw new TlaEvaluationError(describeWrongKey(functionValue, argument));
2287
2441
  }
2288
- if (keyType === undefined && !valueVersion.is174 && isIntervalDomain(domain)) {
2442
+ if (
2443
+ keyType === undefined &&
2444
+ !isVersion174 &&
2445
+ typeof argument !== "number" &&
2446
+ isIntervalDomain(domain)
2447
+ ) {
2289
2448
  throw createNonIntegerKeyError(argument);
2290
2449
  }
2291
2450
  }
2292
2451
  const identical = findIdenticalKey(domain, argument);
2293
2452
  if (identical !== -1) return identical;
2294
- return computeLikeTlcOnFailure(findSortedIndex, failKeyLikeTlc, domain, argument);
2453
+ return computeLikeTlcOnFailure(findDomainIndex, failKeyLikeTlc, functionValue, argument);
2295
2454
  };
2296
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
+ }
2518
+ };
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
+
2297
2526
  export const applyFunction = (
2298
2527
  functionValue: Value,
2299
2528
  argument: Value,
2300
2529
  describeMissing?: (functionValue: FunctionValue, argument: Value) => string,
2301
2530
  ): Value => {
2302
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
+ }
2303
2540
  if (!isElementOf(argument, functionValue.domain)) {
2304
2541
  throw new TlaEvaluationError(
2305
2542
  getFunctionClass(functionValue) === "lambda"
@@ -2315,6 +2552,9 @@ export const applyFunction = (
2315
2552
  );
2316
2553
  }
2317
2554
  const describe = describeMissing ?? describeMissingArgument;
2555
+ if (isOutsideLambdaDomain(functionValue, argument)) {
2556
+ throw new TlaEvaluationError(describe(functionValue, argument));
2557
+ }
2318
2558
  const position = findKeyIndexLikeTlc(functionValue, argument, describe);
2319
2559
  if (position === -1) throw new TlaEvaluationError(describe(functionValue, argument));
2320
2560
  return functionValue.range[position];
@@ -2328,8 +2568,17 @@ export const getDomainInterval = (domain: Value[]) =>
2328
2568
  export const getDomain = (functionValue: Value): Value => {
2329
2569
  if (typeof functionValue === "object" && functionValue.kind === "LazyFunction")
2330
2570
  return functionValue.domain;
2331
- const domain = toFiniteFunction(functionValue).domain;
2332
- 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;
2333
2582
  };
2334
2583
 
2335
2584
  export const updateFunction = (
@@ -2341,8 +2590,14 @@ export const updateFunction = (
2341
2590
  const isLazy =
2342
2591
  typeof functionValue === "object" &&
2343
2592
  functionValue.kind === "LazyFunction" &&
2344
- (isKeptLazy || !isEnumerable(functionValue.domain));
2593
+ (isKeptLazy || functionValue.enumerated === undefined);
2345
2594
  if (isLazy) {
2595
+ if (
2596
+ functionValue.boundTupleLengths !== undefined &&
2597
+ getSequenceElements(argument) === undefined
2598
+ ) {
2599
+ throw createArgumentListError(functionValue, argument);
2600
+ }
2346
2601
  if (!isElementOf(argument, functionValue.domain)) return functionValue;
2347
2602
  const updated = update(functionValue.apply(argument));
2348
2603
  return setFunctionClass<LazyFunctionValue>(
@@ -2351,6 +2606,7 @@ export const updateFunction = (
2351
2606
  domain: functionValue.domain,
2352
2607
  apply: (key) => (isEqualLikeTlc(argument, key) ? updated : functionValue.apply(key)),
2353
2608
  source: functionValue.source,
2609
+ boundTupleLengths: functionValue.boundTupleLengths,
2354
2610
  },
2355
2611
  getFunctionClass(functionValue),
2356
2612
  );
@@ -2361,6 +2617,7 @@ export const updateFunction = (
2361
2617
  );
2362
2618
  }
2363
2619
  const finite = toFiniteFunction(functionValue);
2620
+ if (isOutsideLambdaDomain(finite, argument)) return finite;
2364
2621
  const position = findKeyIndexLikeTlc(finite, argument, describeExceptKey);
2365
2622
  if (position === -1) return finite;
2366
2623
  const range = [...finite.range];
@@ -2372,6 +2629,7 @@ export const updateFunction = (
2372
2629
  getFunctionClass(finite),
2373
2630
  );
2374
2631
  updated.writtenKeys = finite.writtenKeys;
2632
+ updated.lambdaDomain = finite.lambdaDomain;
2375
2633
  if (finite.hash !== 0 && finite.hash !== UNFINGERPRINTABLE_HASH) {
2376
2634
  const nextHash = getValueHash(next);
2377
2635
  if (nextHash !== UNFINGERPRINTABLE_HASH) {
@@ -2424,9 +2682,6 @@ const getElementContribution = (elementHash: number) =>
2424
2682
  const getEntryContribution = (keyHash: number, valueHash: number) =>
2425
2683
  finalizeHash((Math.imul(keyHash, 0x27d4eb2d) + valueHash) | 0);
2426
2684
 
2427
- // The hash of each value that TLC fails to fingerprint, such as Nat or a set that holds it. Calls
2428
- // with such a value as an argument still share their result, and a state that holds one fails
2429
- // when TLC fingerprints it.
2430
2685
  const UNFINGERPRINTABLE_HASH = 0x2f6b1c4d;
2431
2686
 
2432
2687
  const computeValueHash = (value: SetValue | FunctionValue) => {
@@ -2452,13 +2707,11 @@ const computeValueHash = (value: SetValue | FunctionValue) => {
2452
2707
  return hash;
2453
2708
  };
2454
2709
 
2455
- // TLC's fingerPrint enumerates each set and function a value holds, and fails on Nat, Seq(S) and
2456
- // the like, which it never enumerates.
2457
2710
  const fingerprintValue = (value: Value): void => {
2458
2711
  if (typeof value !== "object" || value.kind === "ModelValue") return;
2459
2712
  if (value.kind === "InfiniteSet" || value.kind === "SequenceSet") {
2460
2713
  throw new TlaEvaluationError(
2461
- `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))}`,
2462
2715
  );
2463
2716
  }
2464
2717
  if (isSetValue(value)) {
@@ -2470,8 +2723,6 @@ const fingerprintValue = (value: Value): void => {
2470
2723
  functionValue.range.forEach(fingerprintValue);
2471
2724
  };
2472
2725
 
2473
- // The error TLC raises as it fingerprints a value: one that hashing the value raises, as for a set
2474
- // too large to enumerate, or one of a value with the hash of the values TLC fails on.
2475
2726
  export const getFingerprintError = (value: Value) => {
2476
2727
  if (typeof value !== "object" || value.kind === "ModelValue") return undefined;
2477
2728
  try {
@@ -2483,7 +2734,6 @@ export const getFingerprintError = (value: Value) => {
2483
2734
  }
2484
2735
  };
2485
2736
 
2486
- // The values a value holds, which TLC fingerprints as it fingerprints the value.
2487
2737
  export const getHeldValues = (value: ObjectValue): Value[] => {
2488
2738
  switch (value.kind) {
2489
2739
  case "Set":
@@ -2604,17 +2854,19 @@ const computeValueKey = (value: ObjectValue) => {
2604
2854
  return `(${functionValue.domain.map((key, index) => `${getValueKey(key)}:${getValueKey(functionValue.range[index])}`).join(",")})`;
2605
2855
  };
2606
2856
 
2857
+ const PRINTED_ESCAPES: Record<string, string> = {
2858
+ '"': '\\"',
2859
+ "\\": "\\\\",
2860
+ "\t": "\\t",
2861
+ "\n": "\\n",
2862
+ "\f": "\\f",
2863
+ "\r": "\\r",
2864
+ };
2865
+
2607
2866
  const formatString = (value: string) =>
2608
- `"${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])}"`;
2609
2868
 
2610
- type LazySetValue =
2611
- | SubsetValue
2612
- | FunctionSetValue
2613
- | RecordSetValue
2614
- | ProductSetValue
2615
- | SetOperationValue
2616
- | FilteredSetValue
2617
- | UnionValue;
2869
+ type LazySetValue = Exclude<ConvertibleSetValue, MixedSetValue | SequenceSetValue>;
2618
2870
 
2619
2871
  const MAXIMUM_EXPANDED_SUBSET_BASE = 6;
2620
2872
  const MAXIMUM_EXPANDED_PRODUCT = 1999;
@@ -2631,24 +2883,24 @@ const expandLazySet = (value: LazySetValue) => {
2631
2883
  if (value.kind === "SetOperation" || value.kind === "FilteredSet" || value.kind === "Union") {
2632
2884
  return toFiniteSet(value);
2633
2885
  }
2634
- if (
2635
- value.kind === "FunctionSet" &&
2636
- isEnumerable(value.domain) &&
2637
- getCardinality(value.domain) === 0
2638
- ) {
2639
- 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;
2640
2890
  }
2641
- const size =
2642
- value.kind === "FunctionSet"
2643
- ? getCardinality(value.range) ** getCardinality(value.domain)
2644
- : getProductSize(value.kind === "RecordSet" ? value.sets : value.factors);
2645
- if (size === 0) return EMPTY_SET;
2891
+ const size = getProductSize(value.kind === "RecordSet" ? value.sets : value.factors);
2646
2892
  return size <= MAXIMUM_EXPANDED_PRODUCT ? toFiniteSet(value) : undefined;
2647
2893
  };
2648
2894
 
2649
2895
  const getExpandedLazySet = (value: LazySetValue, isStrict: boolean) => {
2650
- if (isStrict) return expandLazySet(value);
2651
- // 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
+ }
2652
2904
  if (!isEnumerable(value)) return undefined;
2653
2905
  try {
2654
2906
  return expandLazySet(value);
@@ -2682,24 +2934,93 @@ const formatLazySet = (value: LazySetValue, isStrict: boolean): string => {
2682
2934
  }
2683
2935
  };
2684
2936
 
2685
- // FcnRcdValue#isName: TLC prints a function as a record when every key consists of letters,
2686
- // decimal digits, and underscores, with at least one letter.
2687
2937
  const isFieldName = (name: string) =>
2688
2938
  /^[\p{L}\p{Nd}_]*$/u.test(name) &&
2689
2939
  /\p{L}/u.test(name) &&
2690
2940
  (name.length < 4 || !/^[WS]F_/.test(name));
2691
2941
 
2692
- // FcnLambdaValue#toString prints a function it fails to enumerate as its parameters and body.
2693
2942
  const toPrintedFunction = (value: LazyFunctionValue) => {
2694
2943
  if (!isEnumerable(value.domain)) return undefined;
2695
2944
  try {
2696
2945
  return toFiniteFunction(value);
2697
2946
  } catch (error) {
2698
- if (error instanceof TlaEvaluationError) return undefined;
2947
+ if (error instanceof TlaEvaluationError || isStackOverflow(error)) return undefined;
2699
2948
  throw error;
2700
2949
  }
2701
2950
  };
2702
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
+
2703
3024
  export const formatValue = (value: Value, isStrict = false, isNormalized = false): string => {
2704
3025
  const format = (inner: Value) => formatValue(inner, isStrict, isNormalized);
2705
3026
  if (typeof value === "boolean") return value ? "TRUE" : "FALSE";
@@ -2723,7 +3044,7 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
2723
3044
  case "SetOperation":
2724
3045
  case "FilteredSet":
2725
3046
  case "Union": {
2726
- const expanded = getExpandedLazySet(value, isStrict);
3047
+ const expanded = printing.isExpanded ? getExpandedLazySet(value, isStrict) : undefined;
2727
3048
  return expanded ? format(expanded) : formatLazySet(value, isStrict);
2728
3049
  }
2729
3050
 
@@ -2731,7 +3052,12 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
2731
3052
  return `Seq(${format(value.base)})`;
2732
3053
  case "Function":
2733
3054
  case "LazyFunction": {
2734
- 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;
2735
3061
  if (functionValue === undefined) {
2736
3062
  const source = value.kind === "LazyFunction" ? value.source : undefined;
2737
3063
  if (!source) return "<function>";
@@ -2742,42 +3068,111 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
2742
3068
  }
2743
3069
  if (
2744
3070
  functionValue.domain.length === 0 &&
2745
- valueVersion.is174 &&
3071
+ isVersion174 &&
2746
3072
  getFunctionClass(value) !== "tuple"
2747
3073
  ) {
2748
3074
  return "<< >>";
2749
3075
  }
2750
- // TLC normalizes a lambda's domain to print it, but evaluates its body afterward.
2751
3076
  const formatRange = (inner: Value) =>
2752
3077
  formatValue(inner, isStrict, isNormalized && getFunctionClass(value) !== "lambda");
3078
+ if (functionValue.domain.length === 0 && getFunctionClass(value) === "record") return "[]";
2753
3079
  if (functionValue.domain.every((key, index) => key === index + 1)) {
2754
3080
  return `<<${functionValue.range.map(formatRange).join(", ")}>>`;
2755
3081
  }
2756
- // A RecordValue prints as a record whatever its fields, and a FcnRcdValue only if each key
2757
- // is a name.
3082
+ const pairs = isNormalized
3083
+ ? functionValue.domain.map((key, index) => [key, functionValue.range[index]])
3084
+ : getPrintedPairs(functionValue);
2758
3085
  if (
2759
3086
  getFunctionClass(value) === "record" ||
2760
3087
  functionValue.domain.every((key) => typeof key === "string" && isFieldName(key))
2761
3088
  ) {
2762
- const isSorted =
2763
- isNormalized || functionValue.hash !== 0 || functionValue.fingerprint !== 0;
2764
- const pairs = isSorted
2765
- ? functionValue.domain.map((key, index) => [key, functionValue.range[index]])
2766
- : getWrittenPairs(functionValue);
2767
3089
  return `[${pairs.map((pair) => `${String(pair[0])} |-> ${formatRange(pair[1])}`).join(", ")}]`;
2768
3090
  }
2769
- 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(" @@ ")})`;
2770
3092
  }
2771
3093
  }
2772
3094
  };
2773
3095
 
2774
- // TLC's TLCState.toString: a line per variable, as a conjunction when there are several.
2775
- 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();
2776
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
+ }
2777
3165
  return entries
2778
- .map(
2779
- ([name, value]) =>
2780
- `${entries.length === 1 ? "" : "/\\ "}${name} = ${prettyPrint(formatValue(value))}\n`,
2781
- )
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
+ })
2782
3177
  .join("");
2783
3178
  };