tla-ts 0.0.9-dev.8298a52 → 0.0.10-dev.28c823e4b

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (390) hide show
  1. package/README.md +7 -0
  2. package/dist/compile.cjs +3 -3
  3. package/dist/compile.js +3 -3
  4. package/dist/deciders.cjs +28 -28
  5. package/dist/deciders.js +52 -52
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +105 -10
  8. package/dist/index.d.ts +105 -10
  9. package/dist/index.js +1 -1
  10. package/dist/parallel-worker.cjs +1 -1
  11. package/dist/parallel-worker.js +1 -1
  12. package/dist/prove-worker.cjs +1 -1
  13. package/dist/prove-worker.js +1 -1
  14. package/dist/prove.cjs +116 -36
  15. package/dist/prove.js +116 -36
  16. package/dist/run.cjs +143 -31
  17. package/dist/run.js +143 -31
  18. package/dist/tlapm.cjs +1 -1
  19. package/dist/tlapm.js +2 -2
  20. package/dist/transfer.cjs +129 -104
  21. package/dist/transfer.js +129 -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 +4 -23
  26. package/src/bags.ts +99 -102
  27. package/src/builtins.ts +40 -78
  28. package/src/bundled-modules.ts +1 -8
  29. package/src/check.ts +564 -366
  30. package/src/cli/options.ts +10 -5
  31. package/src/cli/run.ts +0 -2
  32. package/src/cli/runtime-invariants.ts +136 -0
  33. package/src/cli/shared.ts +18 -11
  34. package/src/cli/tlapm.ts +0 -12
  35. package/src/cli/tlc-arguments.ts +640 -0
  36. package/src/cli/tlc-usage.ts +361 -0
  37. package/src/cli/tlc.ts +525 -216
  38. package/src/cli/typescript.ts +0 -3
  39. package/src/cli/xml-exporter.ts +4 -16
  40. package/src/cli.ts +0 -1
  41. package/src/codegen.ts +191 -64
  42. package/src/config.ts +140 -109
  43. package/src/coverage.ts +837 -0
  44. package/src/dependencies.ts +6 -40
  45. package/src/dfid.ts +618 -0
  46. package/src/environment.ts +237 -119
  47. package/src/errors.ts +56 -56
  48. package/src/evaluate.ts +543 -341
  49. package/src/exit-codes.ts +37 -3
  50. package/src/fingerprints.ts +10 -10
  51. package/src/index.ts +3 -0
  52. package/src/instances.ts +38 -31
  53. package/src/java-overrides.ts +4 -19
  54. package/src/json-reader.ts +455 -0
  55. package/src/json.ts +255 -139
  56. package/src/levels.ts +8 -17
  57. package/src/lexer.ts +80 -100
  58. package/src/liveness-checker.ts +77 -117
  59. package/src/liveness.ts +106 -62
  60. package/src/obligations/action.ts +4 -28
  61. package/src/obligations/anonymize.ts +84 -80
  62. package/src/obligations/equality.ts +1 -1
  63. package/src/obligations/expression.ts +2 -19
  64. package/src/obligations/format.ts +1 -9
  65. package/src/obligations/generate.ts +1 -11
  66. package/src/obligations/index.ts +0 -11
  67. package/src/obligations/levels.ts +4 -8
  68. package/src/obligations/module.ts +1 -15
  69. package/src/obligations/normalize.ts +5 -24
  70. package/src/obligations/operators.ts +1 -2
  71. package/src/obligations/pragma.ts +1 -10
  72. package/src/obligations/printer.ts +47 -46
  73. package/src/obligations/proof.ts +1 -5
  74. package/src/obligations/regroup.ts +1 -4
  75. package/src/obligations/simplify.ts +3 -14
  76. package/src/obligations/source.ts +1 -21
  77. package/src/obligations/subexpression.ts +5 -11
  78. package/src/obligations/substitution.ts +1 -3
  79. package/src/obligations/temporal.ts +8 -14
  80. package/src/obligations/tuples.ts +3 -9
  81. package/src/parallel-worker.ts +24 -33
  82. package/src/parallel.ts +48 -40
  83. package/src/parser.ts +565 -282
  84. package/src/pcal/ast.ts +53 -86
  85. package/src/pcal/parse.ts +144 -219
  86. package/src/pcal/tokenize.ts +91 -131
  87. package/src/pcal/translate.ts +83 -130
  88. package/src/pcal/validate.ts +48 -68
  89. package/src/pretty-print.ts +7 -8
  90. package/src/prover/decide-pool.ts +5 -10
  91. package/src/prover/deciders.ts +0 -4
  92. package/src/prover/first-order.ts +0 -11
  93. package/src/prover/isabelle/decide.ts +0 -6
  94. package/src/prover/isabelle/encode.ts +11 -23
  95. package/src/prover/isabelle/isar/inner-syntax.ts +108 -114
  96. package/src/prover/isabelle/isar/method.ts +25 -38
  97. package/src/prover/isabelle/isar/proof.ts +1 -10
  98. package/src/prover/isabelle/isar/statement.ts +1 -6
  99. package/src/prover/isabelle/isar/theory.ts +15 -26
  100. package/src/prover/isabelle/isar/type-check.ts +11 -25
  101. package/src/prover/isabelle/provers/blast/blast.ts +10 -41
  102. package/src/prover/isabelle/provers/blast/branch.ts +1 -32
  103. package/src/prover/isabelle/provers/blast/prove.ts +1 -35
  104. package/src/prover/isabelle/provers/blast/rules.ts +6 -44
  105. package/src/prover/isabelle/provers/blast/state.ts +2 -28
  106. package/src/prover/isabelle/provers/blast/term.ts +9 -36
  107. package/src/prover/isabelle/provers/clasimp.ts +1 -13
  108. package/src/prover/isabelle/provers/classical.ts +14 -42
  109. package/src/prover/isabelle/provers/hypsubst.ts +11 -25
  110. package/src/prover/isabelle/pure/bicompose.ts +16 -13
  111. package/src/prover/isabelle/pure/consts.ts +1 -7
  112. package/src/prover/isabelle/pure/conv.ts +1 -9
  113. package/src/prover/isabelle/pure/drule.ts +24 -40
  114. package/src/prover/isabelle/pure/envir.ts +3 -52
  115. package/src/prover/isabelle/pure/goal.ts +1 -7
  116. package/src/prover/isabelle/pure/interrupt.ts +0 -5
  117. package/src/prover/isabelle/pure/list.ts +0 -3
  118. package/src/prover/isabelle/pure/logic.ts +1 -14
  119. package/src/prover/isabelle/pure/name.ts +2 -9
  120. package/src/prover/isabelle/pure/net.ts +3 -59
  121. package/src/prover/isabelle/pure/object-logic.ts +3 -10
  122. package/src/prover/isabelle/pure/pattern.ts +2 -19
  123. package/src/prover/isabelle/pure/raw-simplifier.ts +13 -49
  124. package/src/prover/isabelle/pure/rewriter.ts +26 -58
  125. package/src/prover/isabelle/pure/search.ts +3 -10
  126. package/src/prover/isabelle/pure/seq.ts +1 -10
  127. package/src/prover/isabelle/pure/simplifier.ts +4 -12
  128. package/src/prover/isabelle/pure/table.ts +1 -31
  129. package/src/prover/isabelle/pure/tactic.ts +12 -22
  130. package/src/prover/isabelle/pure/tactical.ts +6 -12
  131. package/src/prover/isabelle/pure/term-ord.ts +2 -6
  132. package/src/prover/isabelle/pure/term.ts +2 -43
  133. package/src/prover/isabelle/pure/thm.ts +13 -36
  134. package/src/prover/isabelle/pure/type.ts +2 -15
  135. package/src/prover/isabelle/pure/unify.ts +20 -30
  136. package/src/prover/isabelle/pure/variable.ts +3 -7
  137. package/src/prover/isabelle/tla/classical-setup.ts +9 -19
  138. package/src/prover/isabelle/tla/context.ts +8 -16
  139. package/src/prover/isabelle/tla/logic.ts +4 -11
  140. package/src/prover/isabelle/tla/simpdata.ts +46 -34
  141. package/src/prover/isabelle/tools/intuitionistic.ts +1 -10
  142. package/src/prover/ocaml.ts +0 -6
  143. package/src/prover/prep/action.ts +4 -36
  144. package/src/prover/prep/enabled-axioms.ts +12 -19
  145. package/src/prover/prep/fingerprint.ts +0 -16
  146. package/src/prover/prep/level-comparison.ts +8 -12
  147. package/src/prover/prep/md5.ts +0 -2
  148. package/src/prover/prep/methods.ts +9 -36
  149. package/src/prover/prep/normalize.ts +4 -28
  150. package/src/prover/prove-worker.ts +0 -2
  151. package/src/prover/prove.ts +0 -36
  152. package/src/prover/ptl/decide.ts +7 -12
  153. package/src/prover/ptl/encode.ts +14 -36
  154. package/src/prover/ptl/sat.ts +24 -32
  155. package/src/prover/ptl/tableau.ts +12 -26
  156. package/src/prover/smt/axioms.ts +0 -7
  157. package/src/prover/smt/context.ts +19 -26
  158. package/src/prover/smt/data.ts +51 -54
  159. package/src/prover/smt/encode.ts +14 -35
  160. package/src/prover/smt/extensionality.ts +0 -10
  161. package/src/prover/smt/flatten.ts +3 -22
  162. package/src/prover/smt/format.ts +5 -10
  163. package/src/prover/smt/instances.ts +0 -10
  164. package/src/prover/smt/rewrite.ts +66 -101
  165. package/src/prover/smt/solver/act-cache.ts +0 -15
  166. package/src/prover/smt/solver/arith-rewriter.ts +3 -48
  167. package/src/prover/smt/solver/array.ts +1 -3
  168. package/src/prover/smt/solver/asserted-formulas.ts +1 -43
  169. package/src/prover/smt/solver/ast-lt.ts +1 -11
  170. package/src/prover/smt/solver/ast-util.ts +1 -6
  171. package/src/prover/smt/solver/ast.ts +1 -143
  172. package/src/prover/smt/solver/auf-solver.ts +6 -39
  173. package/src/prover/smt/solver/case-split-queue.ts +1 -9
  174. package/src/prover/smt/solver/cg-table.ts +1 -18
  175. package/src/prover/smt/solver/clause.ts +1 -27
  176. package/src/prover/smt/solver/conflict-resolution.ts +0 -9
  177. package/src/prover/smt/solver/context.ts +4 -61
  178. package/src/prover/smt/solver/ctx-simplify.ts +14 -41
  179. package/src/prover/smt/solver/der.ts +2 -21
  180. package/src/prover/smt/solver/dyn-ack.ts +1 -11
  181. package/src/prover/smt/solver/e-matching.ts +3 -34
  182. package/src/prover/smt/solver/enode.ts +1 -21
  183. package/src/prover/smt/solver/expr-ref.ts +1 -5
  184. package/src/prover/smt/solver/expr-safe-replace.ts +0 -5
  185. package/src/prover/smt/solver/fingerprints.ts +1 -12
  186. package/src/prover/smt/solver/flat-literals.ts +1 -9
  187. package/src/prover/smt/solver/goal.ts +2 -14
  188. package/src/prover/smt/solver/hash.ts +0 -8
  189. package/src/prover/smt/solver/hashtable.ts +1 -12
  190. package/src/prover/smt/solver/internalizer.ts +6 -98
  191. package/src/prover/smt/solver/lbool.ts +1 -2
  192. package/src/prover/smt/solver/literal.ts +0 -3
  193. package/src/prover/smt/solver/lp/bound-propagator.ts +8 -26
  194. package/src/prover/smt/solver/lp/constraints.ts +2 -8
  195. package/src/prover/smt/solver/lp/containers.ts +12 -30
  196. package/src/prover/smt/solver/lp/core-solver.ts +10 -31
  197. package/src/prover/smt/solver/lp/cross-nested.ts +6 -20
  198. package/src/prover/smt/solver/lp/dep-intervals.ts +7 -22
  199. package/src/prover/smt/solver/lp/dependency.ts +1 -4
  200. package/src/prover/smt/solver/lp/dioph-eq.ts +12 -98
  201. package/src/prover/smt/solver/lp/explanation.ts +1 -6
  202. package/src/prover/smt/solver/lp/gomory.ts +9 -22
  203. package/src/prover/smt/solver/lp/hnf-cutter.ts +17 -23
  204. package/src/prover/smt/solver/lp/hnf.ts +11 -26
  205. package/src/prover/smt/solver/lp/int-cube.ts +15 -36
  206. package/src/prover/smt/solver/lp/int-solver.ts +4 -34
  207. package/src/prover/smt/solver/lp/lar-solver.ts +32 -81
  208. package/src/prover/smt/solver/lp/lar-term.ts +1 -5
  209. package/src/prover/smt/solver/lp/lp-settings.ts +1 -14
  210. package/src/prover/smt/solver/lp/maximize-term.ts +20 -45
  211. package/src/prover/smt/solver/lp/nex-creator.ts +5 -28
  212. package/src/prover/smt/solver/lp/nex.ts +1 -6
  213. package/src/prover/smt/solver/lp/nla-backoff.ts +1 -4
  214. package/src/prover/smt/solver/lp/nla-basics.ts +5 -30
  215. package/src/prover/smt/solver/lp/nla-core.ts +35 -130
  216. package/src/prover/smt/solver/lp/nla-divisions.ts +32 -42
  217. package/src/prover/smt/solver/lp/nla-emonics.ts +4 -21
  218. package/src/prover/smt/solver/lp/nla-factorization.ts +1 -4
  219. package/src/prover/smt/solver/lp/nla-grobner.ts +15 -69
  220. package/src/prover/smt/solver/lp/nla-horner.ts +3 -11
  221. package/src/prover/smt/solver/lp/nla-intervals.ts +2 -12
  222. package/src/prover/smt/solver/lp/nla-monomial-bounds.ts +16 -41
  223. package/src/prover/smt/solver/lp/nla-monotone.ts +2 -6
  224. package/src/prover/smt/solver/lp/nla-order.ts +2 -13
  225. package/src/prover/smt/solver/lp/nla-patcher.ts +4 -7
  226. package/src/prover/smt/solver/lp/nla-tangents.ts +1 -9
  227. package/src/prover/smt/solver/lp/nla-throttle.ts +1 -6
  228. package/src/prover/smt/solver/lp/nla-types.ts +1 -11
  229. package/src/prover/smt/solver/lp/nla-var-eqs.ts +4 -25
  230. package/src/prover/smt/solver/lp/nra-solver.ts +5 -52
  231. package/src/prover/smt/solver/lp/numeric-pair.ts +1 -4
  232. package/src/prover/smt/solver/lp/pdd-interval.ts +1 -3
  233. package/src/prover/smt/solver/lp/pdd-simplifier.ts +2 -14
  234. package/src/prover/smt/solver/lp/pdd-solver.ts +4 -33
  235. package/src/prover/smt/solver/lp/pdd.ts +7 -70
  236. package/src/prover/smt/solver/lp/random-updater.ts +1 -8
  237. package/src/prover/smt/solver/lp/static-matrix.ts +9 -19
  238. package/src/prover/smt/solver/lp/union-find.ts +1 -6
  239. package/src/prover/smt/solver/mam-compiler.ts +14 -56
  240. package/src/prover/smt/solver/mam-interpreter.ts +1 -21
  241. package/src/prover/smt/solver/maximize-ac-sharing.ts +2 -17
  242. package/src/prover/smt/solver/model-checker.ts +2 -36
  243. package/src/prover/smt/solver/model-evaluator.ts +3 -29
  244. package/src/prover/smt/solver/model-finder.ts +3 -15
  245. package/src/prover/smt/solver/model-generator.ts +1 -12
  246. package/src/prover/smt/solver/model-macro-solver.ts +12 -69
  247. package/src/prover/smt/solver/nlsat/algebraic.ts +55 -151
  248. package/src/prover/smt/solver/nlsat/atoms.ts +5 -19
  249. package/src/prover/smt/solver/nlsat/evaluator.ts +17 -22
  250. package/src/prover/smt/solver/nlsat/explain.ts +3 -47
  251. package/src/prover/smt/solver/nlsat/interval-set.ts +9 -50
  252. package/src/prover/smt/solver/nlsat/levelwise.ts +48 -129
  253. package/src/prover/smt/solver/nlsat/mpbq.ts +3 -14
  254. package/src/prover/smt/solver/nlsat/polynomial.ts +17 -156
  255. package/src/prover/smt/solver/nlsat/solver.ts +7 -67
  256. package/src/prover/smt/solver/nlsat/types.ts +1 -8
  257. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +1 -44
  258. package/src/prover/smt/solver/nlsat/upolynomial.ts +11 -92
  259. package/src/prover/smt/solver/nnf.ts +3 -38
  260. package/src/prover/smt/solver/pattern-inference.ts +2 -15
  261. package/src/prover/smt/solver/poly-rewriter.ts +3 -23
  262. package/src/prover/smt/solver/propagate-values.ts +1 -10
  263. package/src/prover/smt/solver/proto-model.ts +3 -48
  264. package/src/prover/smt/solver/pull-quant.ts +1 -12
  265. package/src/prover/smt/solver/qe-lite-der.ts +1 -29
  266. package/src/prover/smt/solver/qe-lite-fm.ts +2 -25
  267. package/src/prover/smt/solver/qe-lite.ts +3 -33
  268. package/src/prover/smt/solver/qi-queue.ts +1 -16
  269. package/src/prover/smt/solver/quant-tactics.ts +5 -22
  270. package/src/prover/smt/solver/quantifier-analyzer.ts +17 -37
  271. package/src/prover/smt/solver/quantifier-manager.ts +1 -8
  272. package/src/prover/smt/solver/random-gen.ts +1 -2
  273. package/src/prover/smt/solver/rational.ts +1 -8
  274. package/src/prover/smt/solver/ref-vector.ts +1 -6
  275. package/src/prover/smt/solver/relevancy.ts +2 -15
  276. package/src/prover/smt/solver/rewriter-tpl.ts +3 -147
  277. package/src/prover/smt/solver/rewriter.ts +3 -85
  278. package/src/prover/smt/solver/rlimit.ts +2 -20
  279. package/src/prover/smt/solver/smtlib-parser.ts +2 -37
  280. package/src/prover/smt/solver/solver.ts +1 -16
  281. package/src/prover/smt/solver/sort.ts +1 -5
  282. package/src/prover/smt/solver/sticky-generations.ts +0 -5
  283. package/src/prover/smt/solver/theory-lra-axioms.ts +3 -24
  284. package/src/prover/smt/solver/theory-lra-bounds.ts +0 -5
  285. package/src/prover/smt/solver/theory-lra-final-check.ts +4 -22
  286. package/src/prover/smt/solver/theory-lra-internalize.ts +1 -27
  287. package/src/prover/smt/solver/theory-lra-model.ts +4 -19
  288. package/src/prover/smt/solver/theory-lra-propagate.ts +1 -15
  289. package/src/prover/smt/solver/theory-lra-state.ts +3 -8
  290. package/src/prover/smt/solver/theory-lra.ts +1 -8
  291. package/src/prover/smt/solver/var-subst.ts +2 -26
  292. package/src/prover/smt/table.ts +0 -8
  293. package/src/prover/tlapm/cache.ts +20 -25
  294. package/src/prover/tlapm/ocaml-marshal.ts +19 -21
  295. package/src/prover/tlapm/tlapm.ts +12 -17
  296. package/src/prover/verdict.ts +0 -2
  297. package/src/prover/zenon/check/check.ts +0 -9
  298. package/src/prover/zenon/check/definitions.ts +5 -15
  299. package/src/prover/zenon/check/equality.ts +0 -8
  300. package/src/prover/zenon/check/functions.ts +0 -4
  301. package/src/prover/zenon/check/keys.ts +0 -7
  302. package/src/prover/zenon/check/propositional.ts +0 -3
  303. package/src/prover/zenon/check/records.ts +0 -5
  304. package/src/prover/zenon/check/relations.ts +0 -13
  305. package/src/prover/zenon/check/rewrites.ts +0 -6
  306. package/src/prover/zenon/check/sets.ts +0 -3
  307. package/src/prover/zenon/check/terms.ts +0 -17
  308. package/src/prover/zenon/check/tla.ts +0 -6
  309. package/src/prover/zenon/decide.ts +0 -12
  310. package/src/prover/zenon/encode.ts +1 -8
  311. package/src/prover/zenon/eqrel.ts +0 -13
  312. package/src/prover/zenon/equality-rules.ts +0 -4
  313. package/src/prover/zenon/expr.ts +1 -26
  314. package/src/prover/zenon/index-table.ts +17 -38
  315. package/src/prover/zenon/isar-case.ts +9 -19
  316. package/src/prover/zenon/isar.ts +1 -29
  317. package/src/prover/zenon/limits.ts +0 -4
  318. package/src/prover/zenon/llproof.ts +0 -9
  319. package/src/prover/zenon/mltoll.ts +54 -76
  320. package/src/prover/zenon/node.ts +1 -11
  321. package/src/prover/zenon/ocaml.ts +1 -17
  322. package/src/prover/zenon/parse.ts +2 -7
  323. package/src/prover/zenon/phrase.ts +1 -11
  324. package/src/prover/zenon/proof.ts +0 -9
  325. package/src/prover/zenon/propositional-rules.ts +0 -5
  326. package/src/prover/zenon/rules.ts +2 -6
  327. package/src/prover/zenon/search.ts +1 -17
  328. package/src/prover/zenon/tla/functions.ts +57 -29
  329. package/src/prover/zenon/tla/llproof.ts +63 -70
  330. package/src/prover/zenon/tla/records.ts +56 -27
  331. package/src/prover/zenon/tla/rewrites.ts +12 -19
  332. package/src/prover/zenon/tla/sets.ts +68 -39
  333. package/src/prover/zenon/tla/terms.ts +0 -6
  334. package/src/prover/zenon/tla/tla.ts +59 -58
  335. package/src/randomization.ts +81 -35
  336. package/src/resolve.ts +12 -112
  337. package/src/runtime.ts +22 -22
  338. package/src/sany/builtins.ts +2 -5
  339. package/src/sany/generator.ts +149 -252
  340. package/src/sany/levels.ts +6 -34
  341. package/src/sany/lexer.ts +41 -61
  342. package/src/sany/linter.ts +1 -9
  343. package/src/sany/modules.ts +1 -5
  344. package/src/sany/nodes.ts +0 -31
  345. package/src/sany/parse-error.ts +39 -117
  346. package/src/sany/report.ts +29 -63
  347. package/src/sany/selectors.ts +15 -39
  348. package/src/sany/source.ts +1 -17
  349. package/src/sany/xml.ts +13 -63
  350. package/src/search.ts +495 -155
  351. package/src/simulate.ts +685 -0
  352. package/src/spec-description.ts +176 -69
  353. package/src/standard-definitions.ts +0 -4
  354. package/src/standard-modules.ts +254 -69
  355. package/src/state-graph.ts +50 -24
  356. package/src/subexpressions.ts +69 -52
  357. package/src/substitution-levels.ts +2 -3
  358. package/src/successors.ts +260 -91
  359. package/src/symmetry.ts +33 -25
  360. package/src/tableau.ts +27 -24
  361. package/src/tlc/fingerprint.ts +183 -67
  362. package/src/tlc/jar-data.ts +112 -6
  363. package/src/tlc/messages.ts +110 -44
  364. package/src/tlc/order.ts +37 -60
  365. package/src/tlc/random.ts +33 -45
  366. package/src/tlc/replay.ts +549 -217
  367. package/src/tlc/summary.ts +36 -47
  368. package/src/tlc/tlc-operators.ts +76 -41
  369. package/src/tlc/tlcext-operators.ts +139 -122
  370. package/src/tlc/trace-spec.ts +269 -0
  371. package/src/tlc/value-stream.ts +139 -0
  372. package/src/tlc/version.ts +1 -4
  373. package/src/transfer.ts +22 -25
  374. package/src/typescript/actions.ts +8 -21
  375. package/src/typescript/collections.ts +0 -15
  376. package/src/typescript/compile.ts +0 -5
  377. package/src/typescript/context.ts +0 -12
  378. package/src/typescript/emit.ts +0 -1
  379. package/src/typescript/expressions.ts +0 -12
  380. package/src/typescript/formula.ts +4 -12
  381. package/src/typescript/functions.ts +6 -17
  382. package/src/typescript/model.ts +10 -11
  383. package/src/typescript/names.ts +0 -2
  384. package/src/typescript/program.ts +0 -3
  385. package/src/typescript/properties.ts +6 -8
  386. package/src/typescript/scope.ts +0 -5
  387. package/src/typescript/steps.ts +0 -10
  388. package/src/typescript/types.ts +1 -8
  389. package/src/values.ts +749 -330
  390. package/src/worker.ts +7 -8
package/src/values.ts CHANGED
@@ -1,5 +1,13 @@
1
- import { TlaEvaluationError } from "./errors";
1
+ import {
2
+ isStackOverflow,
3
+ TlaAliasFormatError,
4
+ TlaEvaluationError,
5
+ TlaFeatureUnsupportedError,
6
+ TlaModuleError,
7
+ TlaSetBoundError,
8
+ } from "./errors";
2
9
  import { prettyPrint } from "./pretty-print";
10
+ import { isEvalException } from "./tlc/messages";
3
11
  import type { TlcVersion } from "./tlc/version";
4
12
 
5
13
  export interface ModelValue {
@@ -11,8 +19,6 @@ export interface ModelValue {
11
19
  fingerprint: number;
12
20
  }
13
21
 
14
- // What TLC keeps on a set it builds lazily: the enumeration it converted to and cached, as
15
- // SetPredValue#convertAndCache does, whether it has cached it, and whether it has fingerprinted it.
16
22
  interface LazySet {
17
23
  enumerated?: SetValue;
18
24
  isCached?: boolean;
@@ -22,13 +28,13 @@ interface LazySet {
22
28
  export interface SetValue {
23
29
  kind: "Set";
24
30
  elements: Value[];
31
+ writtenElements: Value[] | undefined;
32
+ isNormalized: boolean;
25
33
  hash: number;
26
34
  fingerprint: number;
27
35
  isFingerprinted: boolean;
28
36
  }
29
37
 
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
38
  export interface MixedSetValue extends LazySet {
33
39
  kind: "MixedSet";
34
40
  elements: Value[];
@@ -42,6 +48,7 @@ export interface FunctionValue {
42
48
  fingerprint: number;
43
49
  writtenKeys: Value[] | undefined;
44
50
  functionClass: FunctionClass | undefined;
51
+ lambdaDomain: Value | undefined;
45
52
  isFingerprinted: boolean;
46
53
  }
47
54
 
@@ -90,7 +97,6 @@ export interface SetOperationValue extends LazySet {
90
97
  right: Value;
91
98
  }
92
99
 
93
- // TLC prints a set filter as its bound names and the location of its predicate.
94
100
  interface FilteredSetSource {
95
101
  names: string;
96
102
  predicate: string;
@@ -99,11 +105,10 @@ interface FilteredSetSource {
99
105
  export interface FilteredSetValue extends LazySet {
100
106
  kind: "FilteredSet";
101
107
  base: Value;
102
- test: (element: Value) => boolean;
108
+ test: (element: Value, isMember: boolean) => boolean;
103
109
  source?: FilteredSetSource;
104
110
  }
105
111
 
106
- // UNION S when some element of S isn't a set enumeration. TLC enumerates it only when it has to.
107
112
  export interface UnionValue extends LazySet {
108
113
  kind: "Union";
109
114
  base: Value;
@@ -119,12 +124,11 @@ export interface LazyFunctionSource {
119
124
  body: string;
120
125
  }
121
126
 
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
127
  export interface LazyFunctionValue {
125
128
  kind: "LazyFunction";
126
129
  domain: Value;
127
130
  apply: (argument: Value) => Value;
131
+ boundTupleLengths?: (number | undefined)[];
128
132
  source?: LazyFunctionSource;
129
133
  functionClass?: FunctionClass;
130
134
  enumerated?: FunctionValue;
@@ -153,7 +157,6 @@ export type Value =
153
157
 
154
158
  export type ObjectValue = Exclude<Value, boolean | number | string>;
155
159
 
156
- // The sets TLC builds lazily, which it converts and caches as it uses them.
157
160
  type ConvertibleSetValue =
158
161
  | MixedSetValue
159
162
  | SubsetValue
@@ -174,8 +177,39 @@ const isLazySet = (value: ObjectValue): value is ConvertibleSetValue =>
174
177
  value.kind !== "LazyFunction";
175
178
 
176
179
  export const MAXIMUM_INTEGER = 2147483647;
180
+
181
+ const DEFAULT_SET_BOUND = 1000000;
182
+ const VALUE_VEC_CAPACITY = 10;
183
+
184
+ let setBound = DEFAULT_SET_BOUND;
185
+
186
+ export const getSetBound = () => setBound;
187
+
188
+ export const getMaximumSetSize = () => Math.max(setBound, VALUE_VEC_CAPACITY);
189
+
190
+ export const getSetBoundMessage = () =>
191
+ `Attempted to construct a set with too many elements (>${setBound}).`;
192
+
193
+ export const addBoundedElement = (elements: Value[], element: Value) => {
194
+ if (elements.length === getMaximumSetSize()) throw new TlaSetBoundError(getSetBoundMessage());
195
+ elements.push(element);
196
+ };
197
+
198
+ export const isBeyondSetBound = (value: Value): value is IntervalValue =>
199
+ typeof value === "object" &&
200
+ value.kind === "Interval" &&
201
+ value.high - value.low >= getMaximumSetSize();
202
+
203
+ export const forEachElement = (
204
+ elements: IntervalValue | Value[],
205
+ visit: (element: Value) => void,
206
+ ) => {
207
+ if (Array.isArray(elements)) return elements.forEach(visit);
208
+ for (let element = elements.low; element <= elements.high; element++) visit(element);
209
+ };
177
210
  export const MINIMUM_INTEGER = -2147483648;
178
211
  const MAXIMUM_ENUMERATED_SUBSET_BASE = 30;
212
+ const MAXIMUM_BUILT_SUBSET_BASE = 20;
179
213
 
180
214
  export const isSetValue = (value: Value) =>
181
215
  typeof value === "object" &&
@@ -183,8 +217,6 @@ export const isSetValue = (value: Value) =>
183
217
  value.kind !== "Function" &&
184
218
  value.kind !== "LazyFunction";
185
219
 
186
- // TLC's Reducible values, SetEnumValue and IntervalValue, which combine with another set element by
187
- // element.
188
220
  export const isReducibleSet = (value: Value): value is SetValue | MixedSetValue | IntervalValue =>
189
221
  typeof value === "object" &&
190
222
  (value.kind === "Set" || value.kind === "MixedSet" || value.kind === "Interval");
@@ -209,27 +241,33 @@ export const describeKind = (value: Value) => {
209
241
  export const isTlcInteger = (value: number) =>
210
242
  Number.isInteger(value) && value <= MAXIMUM_INTEGER && value >= MINIMUM_INTEGER;
211
243
 
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 };
244
+ let isWrittenOrderUsed = false;
216
245
 
217
246
  const setWrittenOrder = (functionValue: FunctionValue, keys: Value[]) => {
218
- writtenOrderUse.isUsed = true;
247
+ isWrittenOrderUsed = true;
219
248
  functionValue.writtenKeys = keys;
220
249
  return functionValue;
221
250
  };
222
251
 
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
- };
252
+ const getWrittenKeys = (functionValue: FunctionValue) =>
253
+ (functionValue.hash !== 0 || functionValue.fingerprint !== 0
254
+ ? undefined
255
+ : functionValue.writtenKeys) ?? functionValue.domain;
256
+
257
+ export const getWrittenPairs = (functionValue: FunctionValue): [Value, Value][] =>
258
+ getWrittenKeys(functionValue).map((key) => [
259
+ key,
260
+ functionValue.range[functionValue.domain.indexOf(key)],
261
+ ]);
262
+
263
+ export const getPrintedPairs = (functionValue: FunctionValue): [Value, Value][] =>
264
+ functionValue.domain.every((key) => typeof key === "number")
265
+ ? functionValue.domain.map((key, index) => [key, functionValue.range[index]])
266
+ : getWrittenPairs(functionValue);
227
267
 
228
268
  export const createWrittenRecord = (names: Value[], range: Value[], writtenNames: Value[]) =>
229
269
  setWrittenOrder(createSortedRecord(names, range), writtenNames);
230
270
 
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
271
  const forgetWrittenOrder = (value: Value): void => {
234
272
  if (typeof value !== "object" || (value.kind !== "Function" && value.kind !== "Set")) return;
235
273
  if (value.hash !== 0 || value.fingerprint !== 0) return;
@@ -240,13 +278,11 @@ const forgetWrittenOrder = (value: Value): void => {
240
278
 
241
279
  const isRecordDomain = (domain: Value[]) => domain.every((key) => typeof key === "string");
242
280
 
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
281
  const isRecordMismatch = (left: Value[], right: Value[]) =>
246
282
  left.length > 0 && right.length > 0 && isRecordDomain(left) !== isRecordDomain(right);
247
283
 
248
284
  const compareFunctions = (left: FunctionValue, right: FunctionValue) => {
249
- if (writtenOrderUse.isUsed) {
285
+ if (isWrittenOrderUsed) {
250
286
  left.writtenKeys = undefined;
251
287
  right.writtenKeys = undefined;
252
288
  }
@@ -318,14 +354,10 @@ const checkModelValueTypes = (left: Value, right: Value, isEquality: boolean) =>
318
354
  interface StringOrder {
319
355
  ranks: Record<string, number>;
320
356
  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
357
  searchRank: number | undefined;
324
358
  unorderedString: string | undefined;
325
359
  }
326
360
 
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
361
  const stringOrder: StringOrder = {
330
362
  ranks: Object.create(null),
331
363
  size: 0,
@@ -348,12 +380,36 @@ export const freezeStringOrder = () => {
348
380
 
349
381
  export const getUnorderedString = () => stringOrder.unorderedString;
350
382
 
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 };
383
+ let isVersion174 = false;
384
+
385
+ const printing = { isExpanded: true, isViewPrinted: false };
386
+
387
+ export interface ValueOptions {
388
+ version?: TlcVersion;
389
+ maxSetSize?: number;
390
+ isLazyValueExpanded?: boolean;
391
+ isViewPrinted?: boolean;
392
+ }
393
+
394
+ export const setValueOptions = (options: ValueOptions) => {
395
+ isVersion174 = options.version === "1.7.4";
396
+ setBound = options.maxSetSize ?? DEFAULT_SET_BOUND;
397
+ printing.isExpanded = options.isLazyValueExpanded ?? true;
398
+ printing.isViewPrinted = options.isViewPrinted ?? false;
399
+ };
400
+
401
+ const viewTexts = new WeakMap<Record<string, Value>, () => string>();
354
402
 
355
- export const setValueVersion = (version: TlcVersion | undefined) => {
356
- valueVersion.is174 = version === "1.7.4";
403
+ export const setViewText = (state: Record<string, Value>, getText: () => string) => {
404
+ if (printing.isViewPrinted) viewTexts.set(state, getText);
405
+ return state;
406
+ };
407
+
408
+ const aliasNames = new WeakMap<Record<string, Value>, string>();
409
+
410
+ export const setAliasName = (state: Record<string, Value>, alias: string) => {
411
+ aliasNames.set(state, alias);
412
+ return state;
357
413
  };
358
414
 
359
415
  export const rankString = (text: string) => {
@@ -394,9 +450,13 @@ const isOverriddenComparison = (left: Value, right: Value) =>
394
450
  right.kind === "SequenceSet"
395
451
  );
396
452
 
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.
453
+ const createComparisonError = (left: Value, right: Value) =>
454
+ new TlaEvaluationError(
455
+ isOverriddenSet(left)
456
+ ? `Attempted to compare overridden value ${formatValue(left, true)} with non-overridden value:\n${formatValue(right)}`
457
+ : `Attempted to compare ${describeKind(left)} ${formatValue(left)} with ${describeKind(right)} ${formatValue(right)}`,
458
+ );
459
+
400
460
  const compareOverriddenSets = (
401
461
  left: Value,
402
462
  right: Value,
@@ -407,18 +467,14 @@ const compareOverriddenSets = (
407
467
  `Attempted to ${verb} the set ${formatValue(isEnumerable(left) ? toFiniteSet(left) : left, true)} with the value:\n${formatValue(right, true)}`,
408
468
  );
409
469
  }
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)}`,
413
- );
414
- }
470
+ if (!isOverriddenSet(right)) throw createComparisonError(left, right);
415
471
  const leftName = left.kind === "InfiniteSet" ? left.name : undefined;
416
472
  const rightName = right.kind === "InfiniteSet" ? right.name : undefined;
417
473
  if (leftName !== undefined && leftName === rightName) return 0;
418
474
  if ((leftName === "Nat" && rightName === "Int") || (leftName === "Int" && rightName === "Nat")) {
419
475
  return leftName === "Nat" ? -1 : 1;
420
476
  }
421
- throw new TlaEvaluationError(
477
+ throw new TlaModuleError(
422
478
  `Attempted to compare ${formatValue(left, true)} with the value\n${formatValue(right, true)}`,
423
479
  );
424
480
  };
@@ -426,13 +482,19 @@ const compareOverriddenSets = (
426
482
  export const ANY_SET: InfiniteSetValue = { kind: "InfiniteSet", name: "Any" };
427
483
 
428
484
  const compareAny = (other: Value): never => {
429
- throw new TlaEvaluationError(`Attempted to compare ANY with the value\n${formatValue(other)}`);
485
+ throw new TlaModuleError(`Attempted to compare ANY with the value\n${formatValue(other)}`);
486
+ };
487
+
488
+ const compareWithItself = (value: Value) => {
489
+ if (isWrittenOrderUsed) forgetWrittenOrder(value);
490
+ if (value === ANY_SET) compareAny(value);
491
+ if (typeof value === "object" && value.kind === "LazyFunction") toFiniteFunction(value);
430
492
  };
431
493
 
432
494
  export const compareValues = (left: Value, right: Value): number => {
433
495
  if (left === right) {
434
- if (writtenOrderUse.isUsed) forgetWrittenOrder(left);
435
- return left === ANY_SET ? compareAny(left) : 0;
496
+ compareWithItself(left);
497
+ return 0;
436
498
  }
437
499
  if (typeof left === "object" && typeof right === "object") {
438
500
  const leftKind = left.kind;
@@ -460,9 +522,15 @@ export const compareValues = (left: Value, right: Value): number => {
460
522
  }
461
523
  const isLeftSet = isSetValue(left);
462
524
  if (isLeftSet !== isSetValue(right)) {
463
- throw new TlaEvaluationError(
464
- `Attempted to compare ${describeKind(left)} ${formatValue(left)} with ${describeKind(right)} ${formatValue(right)}`,
465
- );
525
+ throw createComparisonError(left, right);
526
+ }
527
+ if (leftKind === "Interval" && rightKind === "Set") {
528
+ const difference = getCardinality(left) - right.elements.length;
529
+ if (difference !== 0) return difference;
530
+ }
531
+ if (leftKind === "Set" && rightKind === "Interval") {
532
+ const difference = left.elements.length - getCardinality(right);
533
+ if (difference !== 0) return difference;
466
534
  }
467
535
  if (isLeftSet) return compareSets(toFiniteSet(left), toFiniteSet(right));
468
536
  return compareFunctions(toFiniteFunction(left), toFiniteFunction(right));
@@ -473,17 +541,21 @@ export const compareValues = (left: Value, right: Value): number => {
473
541
  checkModelValueTypes(left, right, false);
474
542
  if (isModelValue(left)) return -1;
475
543
  if (isModelValue(right)) return 1;
476
- throw new TlaEvaluationError(
477
- `Attempted to compare ${describeKind(left)} ${formatValue(left)} with ${describeKind(right)} ${formatValue(right)}`,
478
- );
544
+ throw createComparisonError(left, right);
479
545
  };
480
546
 
481
547
  const modelValues = new Map<string, ModelValue>();
482
548
 
483
- // setStringOrder clears the model values, so each check ranks and creates its own.
549
+ const MAXIMUM_MODEL_VALUES = 32768;
550
+
484
551
  export const createModelValue = (name: string): ModelValue => {
485
552
  const known = modelValues.get(name);
486
553
  if (known) return known;
554
+ if (modelValues.size === MAXIMUM_MODEL_VALUES) {
555
+ throw new TlaFeatureUnsupportedError(
556
+ `TLC supports at most ${MAXIMUM_MODEL_VALUES} model values, but model value ${name} exceeds this limit.`,
557
+ );
558
+ }
487
559
  const value: ModelValue = {
488
560
  kind: "ModelValue",
489
561
  name,
@@ -496,14 +568,24 @@ export const createModelValue = (name: string): ModelValue => {
496
568
  return value;
497
569
  };
498
570
 
571
+ export const getModelValues = () => [...modelValues.values()];
572
+
499
573
  export const createSortedSet = (elements: Value[]): SetValue => ({
500
574
  kind: "Set",
501
575
  elements,
576
+ writtenElements: undefined,
577
+ isNormalized: false,
502
578
  hash: 0,
503
579
  fingerprint: 0,
504
580
  isFingerprinted: false,
505
581
  });
506
582
 
583
+ export const createNormalizedSet = (elements: Value[]): SetValue => {
584
+ const set = createSortedSet(elements);
585
+ set.isNormalized = true;
586
+ return set;
587
+ };
588
+
507
589
  export const createSortedFunction = (domain: Value[], range: Value[]): FunctionValue => ({
508
590
  kind: "Function",
509
591
  domain,
@@ -512,22 +594,19 @@ export const createSortedFunction = (domain: Value[], range: Value[]): FunctionV
512
594
  fingerprint: 0,
513
595
  writtenKeys: undefined,
514
596
  functionClass: undefined,
597
+ lambdaDomain: undefined,
515
598
  isFingerprinted: false,
516
599
  });
517
600
 
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
601
  export type FunctionClass = "lambda" | "tuple" | "record";
522
602
 
523
- // Whether a lambda exists for markFingerprinted to find, so that a spec without one skips the walk.
524
- const lambdaPresence = { isPresent: false };
603
+ let hasLambda = false;
525
604
 
526
605
  export const setFunctionClass = <FunctionLike extends FunctionValue | LazyFunctionValue>(
527
606
  functionValue: FunctionLike,
528
607
  functionClass: FunctionClass | undefined,
529
608
  ) => {
530
- if (functionClass === "lambda") lambdaPresence.isPresent = true;
609
+ if (functionClass === "lambda") hasLambda = true;
531
610
  if (functionClass !== undefined) functionValue.functionClass = functionClass;
532
611
  return functionValue;
533
612
  };
@@ -541,22 +620,17 @@ export const markLambdaFunction = <FunctionLike extends FunctionValue | LazyFunc
541
620
  functionValue: FunctionLike,
542
621
  ) => setFunctionClass(functionValue, "lambda");
543
622
 
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
623
  const isCachedSet = (value: ObjectValue) => isLazySet(value) && value.isCached === true;
547
624
 
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 };
625
+ let hasStreamedSet = false;
551
626
 
552
627
  export const markStreamedSet = <Streamed extends UnionValue | SetOperationValue>(
553
628
  value: Streamed,
554
629
  ) => {
555
- streamedSetPresence.isPresent = true;
630
+ hasStreamedSet = true;
556
631
  return value;
557
632
  };
558
633
 
559
- // The sets that stream their elements apart from the normalized set until TLC caches them.
560
634
  const STREAMING_KINDS = new Set<ObjectValue["kind"]>([
561
635
  "Union",
562
636
  "SetOperation",
@@ -568,7 +642,7 @@ const STREAMING_KINDS = new Set<ObjectValue["kind"]>([
568
642
 
569
643
  const cacheSet = (value: Value) => {
570
644
  if (
571
- streamedSetPresence.isPresent &&
645
+ hasStreamedSet &&
572
646
  typeof value === "object" &&
573
647
  isLazySet(value) &&
574
648
  STREAMING_KINDS.has(value.kind)
@@ -577,12 +651,8 @@ const cacheSet = (value: Value) => {
577
651
  }
578
652
  };
579
653
 
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
654
  export const markFingerprinted = (value: Value): void => {
583
- if ((!lambdaPresence.isPresent && !streamedSetPresence.isPresent) || typeof value !== "object") {
584
- return;
585
- }
655
+ if ((!hasLambda && !hasStreamedSet) || typeof value !== "object") return;
586
656
  if (value.kind === "ModelValue" || value.kind === "Interval" || value.kind === "InfiniteSet") {
587
657
  return;
588
658
  }
@@ -603,8 +673,8 @@ export const markFingerprinted = (value: Value): void => {
603
673
  export const valuesEqual = (left: Value, right: Value): boolean => {
604
674
  cacheSet(left);
605
675
  if (left === right) {
606
- if (writtenOrderUse.isUsed) forgetWrittenOrder(left);
607
- return left !== ANY_SET || compareAny(left);
676
+ compareWithItself(left);
677
+ return true;
608
678
  }
609
679
  if (typeof left !== "object" || typeof right !== "object") {
610
680
  if (typeof left === typeof right) return false;
@@ -616,7 +686,14 @@ export const valuesEqual = (left: Value, right: Value): boolean => {
616
686
  if (left.kind === "Function" && right.kind === "Function")
617
687
  return compareFunctions(left, right) === 0;
618
688
  if (left.kind === "Set" && right.kind === "Set") return compareSets(left, right) === 0;
689
+ if (left.kind === "Interval" && right.kind === "Set") {
690
+ if (getCardinality(left) !== right.elements.length) return false;
691
+ }
692
+ if (left.kind === "Set" && right.kind === "Interval") {
693
+ if (left.elements.length !== getCardinality(right)) return false;
694
+ }
619
695
  if (isModelValue(left) || isModelValue(right)) {
696
+ if (left.kind === "LazyFunction") toFiniteFunction(left);
620
697
  checkModelValueTypes(left, right, true);
621
698
  return isModelValue(left) && isModelValue(right) && left.name === right.name;
622
699
  }
@@ -669,8 +746,6 @@ export const valuesEqual = (left: Value, right: Value): boolean => {
669
746
  return compareValues(left, right) === 0;
670
747
  };
671
748
 
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
749
  const createSameValueCheck = (isClassSensitive: boolean) => {
675
750
  const areSameValues = (left: Value[], right: Value[]) => {
676
751
  if (left === right) return true;
@@ -710,8 +785,6 @@ const canonicalizeElements = (elements: Value[], canonicalize: (value: Value) =>
710
785
  }
711
786
  };
712
787
 
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
788
  export const createCanonicalizer = () => {
716
789
  const canonicalValues = new Map<number, Value | Value[]>();
717
790
  const canonicalize = (value: Value): Value => {
@@ -745,21 +818,14 @@ export const createCanonicalizer = () => {
745
818
  };
746
819
  };
747
820
 
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
821
  interface TlcFunction {
752
822
  domain: Value[];
753
823
  range: Value[];
754
824
  low: number | undefined;
755
825
  }
756
826
 
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
- };
827
+ const getIntervalLow = (value: Value, domain: Value[]) =>
828
+ domain.length === 0 || getFunctionClass(value) === "tuple" ? 1 : getDomainInterval(domain)?.low;
763
829
 
764
830
  const toTlcFunction = (value: Value) => {
765
831
  if (!isFunctionValue(value)) return undefined;
@@ -767,17 +833,16 @@ const toTlcFunction = (value: Value) => {
767
833
  return {
768
834
  domain: functionValue.domain,
769
835
  range: functionValue.range,
770
- low: getIntervalLow(functionValue.domain),
836
+ low: getIntervalLow(value, functionValue.domain),
771
837
  };
772
838
  };
773
839
 
774
840
  const toTlcRecord = (value: Value) => {
775
841
  if (!isFunctionValue(value)) return undefined;
776
842
  const functionValue = toFiniteFunction(value);
777
- return functionValue.domain.every((key) => typeof key === "string") ? functionValue : undefined;
843
+ return isRecordDomain(functionValue.domain) ? functionValue : undefined;
778
844
  };
779
845
 
780
- // A model value compared with a value of another kind. The other value is never a model value.
781
846
  const compareModelValueWith = (modelValue: ModelValue, other: Value) => {
782
847
  checkModelValueTypes(other, modelValue, false);
783
848
  return 1;
@@ -860,8 +925,7 @@ const compareElementsLikeTlc = (left: Value[], right: Value[]) => {
860
925
 
861
926
  const compareFunctionLikeTlc = (left: FunctionValue | LazyFunctionValue, right: Value) => {
862
927
  const functionValue = toFiniteFunction(left);
863
- const isTuple = left.kind === "Function" && getSequenceElements(functionValue) !== undefined;
864
- if (isTuple) {
928
+ if (getFunctionClass(left) === "tuple") {
865
929
  const tuple = isFunctionValue(right) ? getSequenceElements(right) : undefined;
866
930
  if (!tuple) return compareTlcFunctions({ ...functionValue, low: 1 }, left, right);
867
931
  return (
@@ -884,14 +948,12 @@ const compareFunctionLikeTlc = (left: FunctionValue | LazyFunctionValue, right:
884
948
  );
885
949
  }
886
950
  return compareTlcFunctions(
887
- { ...functionValue, low: getIntervalLow(functionValue.domain) },
951
+ { ...functionValue, low: getIntervalLow(left, functionValue.domain) },
888
952
  left,
889
953
  right,
890
954
  );
891
955
  };
892
956
 
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
957
  const isComparedByClass = (left: ObjectValue, right: Value) =>
896
958
  isOverriddenSet(left) ||
897
959
  isOverriddenSet(right) ||
@@ -975,8 +1037,7 @@ const equalsTlcFunctions = (functionValue: TlcFunction, left: Value, right: Valu
975
1037
 
976
1038
  const equalsFunctionLikeTlc = (left: FunctionValue | LazyFunctionValue, right: Value) => {
977
1039
  const functionValue = toFiniteFunction(left);
978
- const isTuple = left.kind === "Function" && getSequenceElements(functionValue) !== undefined;
979
- if (isTuple) {
1040
+ if (getFunctionClass(left) === "tuple") {
980
1041
  const tuple = isFunctionValue(right) ? getSequenceElements(right) : undefined;
981
1042
  if (!tuple) return equalsTlcFunctions({ ...functionValue, low: 1 }, left, right);
982
1043
  return (
@@ -999,7 +1060,7 @@ const equalsFunctionLikeTlc = (left: FunctionValue | LazyFunctionValue, right: V
999
1060
  );
1000
1061
  }
1001
1062
  return equalsTlcFunctions(
1002
- { ...functionValue, low: getIntervalLow(functionValue.domain) },
1063
+ { ...functionValue, low: getIntervalLow(left, functionValue.domain) },
1003
1064
  left,
1004
1065
  right,
1005
1066
  );
@@ -1032,7 +1093,6 @@ const equalsLikeTlc = (left: Value, right: Value): boolean => {
1032
1093
  return equalsSetLikeTlc(left, right);
1033
1094
  };
1034
1095
 
1035
- // TLC's ValueVec.sort, which inserts each element into the sorted prefix by binary search.
1036
1096
  const sortLikeTlc = (elements: Value[]) => {
1037
1097
  const sorted: Value[] = [];
1038
1098
  for (const element of elements) {
@@ -1042,7 +1102,6 @@ const sortLikeTlc = (elements: Value[]) => {
1042
1102
  return sorted;
1043
1103
  };
1044
1104
 
1045
- // Calls a method of a value as TLC does, whose failure the value heads when it has a source.
1046
1105
  const callTracedMethod = <Result>(receiver: Value, method: () => Result) => {
1047
1106
  const sets = setTrace.sets;
1048
1107
  if (sets === undefined) return method();
@@ -1052,35 +1111,31 @@ const callTracedMethod = <Result>(receiver: Value, method: () => Result) => {
1052
1111
  return result;
1053
1112
  };
1054
1113
 
1055
- // ValueVec.search on sorted elements: a binary search with compareTo, which ends where the element
1056
- // is or would go.
1057
1114
  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);
1115
+ let low = 0;
1116
+ let high = sorted.length;
1117
+ while (low < high) {
1118
+ const middle = low + ((high - low) >> 1);
1061
1119
  const comparison = callTracedMethod(element, () => compareLikeTlc(element, sorted[middle]));
1062
1120
  if (comparison === 0) return { index: middle, isFound: true };
1063
- if (comparison < 0) bounds.high = middle;
1064
- else bounds.low = middle + 1;
1121
+ if (comparison < 0) high = middle;
1122
+ else low = middle + 1;
1065
1123
  }
1066
- return { index: bounds.low, isFound: false };
1124
+ return { index: low, isFound: false };
1067
1125
  };
1068
1126
 
1069
- // TLC checks membership in a set enumeration it hasn't sorted element by element, with the equals
1070
- // method of each member.
1071
1127
  const isElementOfLikeTlc = (element: Value, elements: Value[]) =>
1072
1128
  elements.some((member) => callTracedMethod(member, () => equalsLikeTlc(member, element)));
1073
1129
 
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>();
1130
+ export const getWrittenElements = (set: SetValue | MixedSetValue) =>
1131
+ set.kind === "MixedSet" || set.isNormalized
1132
+ ? set.elements
1133
+ : (set.writtenElements ?? set.elements);
1077
1134
 
1078
- // IValue.deepNormalize, which TLC applies to the constants of the config and the constant
1079
- // definitions it computes as it starts.
1080
1135
  export const markNormalized = (value: Value): void => {
1081
1136
  if (typeof value !== "object") return;
1082
1137
  if (value.kind === "Set") {
1083
- normalizedSets.add(value);
1138
+ value.isNormalized = true;
1084
1139
  value.elements.forEach(markNormalized);
1085
1140
  }
1086
1141
  if (value.kind === "Function") {
@@ -1089,6 +1144,32 @@ export const markNormalized = (value: Value): void => {
1089
1144
  }
1090
1145
  };
1091
1146
 
1147
+ export const normalizeShallowly = (value: Value): void => {
1148
+ if (typeof value !== "object" || isCachedSet(value)) return;
1149
+ switch (value.kind) {
1150
+ case "Set":
1151
+ value.isNormalized = true;
1152
+ return;
1153
+ case "MixedSet":
1154
+ toFiniteSet(value);
1155
+ return;
1156
+ case "FilteredSet":
1157
+ case "Subset":
1158
+ return normalizeShallowly(value.base);
1159
+ case "SetOperation":
1160
+ if (value.operator === "\\cup") return;
1161
+ normalizeShallowly(value.left);
1162
+ return normalizeShallowly(value.right);
1163
+ case "FunctionSet":
1164
+ normalizeShallowly(value.domain);
1165
+ return normalizeShallowly(value.range);
1166
+ case "RecordSet":
1167
+ return value.sets.forEach(normalizeShallowly);
1168
+ case "ProductSet":
1169
+ return value.factors.forEach(normalizeShallowly);
1170
+ }
1171
+ };
1172
+
1092
1173
  export const isEqualLikeTlc = (left: Value, right: Value) =>
1093
1174
  computeLikeTlcOnFailure(valuesEqual, equalsLikeTlc, left, right);
1094
1175
 
@@ -1099,8 +1180,18 @@ const isStrictlySorted = (elements: Value[]) => {
1099
1180
  return true;
1100
1181
  };
1101
1182
 
1183
+ const isAscendingIntegers = (elements: Value[]) => {
1184
+ for (let index = 0; index < elements.length; index++) {
1185
+ const element = elements[index];
1186
+ const previous = index > 0 ? elements[index - 1] : undefined;
1187
+ if (typeof element !== "number" || (typeof previous === "number" && previous >= element)) {
1188
+ return false;
1189
+ }
1190
+ }
1191
+ return true;
1192
+ };
1193
+
1102
1194
  export const createSet = (elements: Value[]): SetValue => {
1103
- // ValueVec.sort compares each element after the first with those before it.
1104
1195
  for (let index = 1; index < elements.length; index++) cacheSet(elements[index]);
1105
1196
  if (elements.length < 2 || isStrictlySorted(elements)) return createSortedSet(elements);
1106
1197
  const sorted = [...elements].sort(compareValues);
@@ -1111,15 +1202,17 @@ export const createSet = (elements: Value[]): SetValue => {
1111
1202
  return createSortedSet(unique);
1112
1203
  };
1113
1204
 
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>(
1205
+ export const createEnumeratedSet = (elements: Value[]): SetValue | MixedSetValue => {
1206
+ if (isAscendingIntegers(elements)) return createSortedSet(elements);
1207
+ const set = computeLikeTlcOnFailure<Value[], undefined, SetValue | MixedSetValue>(
1118
1208
  createSet,
1119
1209
  (mixed) => ({ kind: "MixedSet", elements: mixed }),
1120
1210
  elements,
1121
1211
  undefined,
1122
1212
  );
1213
+ if (set.kind === "Set" && set.elements !== elements) set.writtenElements = elements;
1214
+ return set;
1215
+ };
1123
1216
 
1124
1217
  export const EMPTY_SET = createSortedSet([]);
1125
1218
 
@@ -1235,7 +1328,6 @@ export const createWrittenFunction = (pairs: [Value, Value][]) => {
1235
1328
  const functionValue = createFunction(pairs);
1236
1329
  const isWrittenSorted =
1237
1330
  functionValue.domain.length !== pairs.length ||
1238
- pairs.some((pair) => typeof pair[0] !== "string") ||
1239
1331
  pairs.every((pair, index) => pair[0] === functionValue.domain[index]);
1240
1332
  return isWrittenSorted
1241
1333
  ? functionValue
@@ -1251,22 +1343,15 @@ const longIntervalDomains = new Map<number, WeakRef<Value[]>>();
1251
1343
  const intervalValues: IntervalValue[] = [];
1252
1344
  const intervalArrays = new WeakMap<Value[], IntervalValue>();
1253
1345
 
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
1346
  const getIntervalDomain = (length: number): Value[] => {
1260
1347
  const cached = intervalDomains[length] ?? longIntervalDomains.get(length)?.deref();
1261
1348
  if (cached) return cached;
1262
- const domain = Array.from({ length }, (_, index) => index + 1);
1349
+ const domain = Array.from({ length }, (_value, index) => index + 1);
1263
1350
  if (length > MAX_SHARED_INTERVAL_LENGTH) longIntervalDomains.set(length, new WeakRef(domain));
1264
1351
  else intervalDomains[length] = domain;
1265
1352
  return domain;
1266
1353
  };
1267
1354
 
1268
- // The elements of an interval for a caller that only iterates them, so they need not record
1269
- // the interval for DOMAIN.
1270
1355
  export const getIntervalElements = (value: IntervalValue): Value[] => {
1271
1356
  getCardinality(value);
1272
1357
  if (value.low === 1 && value.high >= 1) return getIntervalDomain(value.high);
@@ -1276,13 +1361,11 @@ export const getIntervalElements = (value: IntervalValue): Value[] => {
1276
1361
  };
1277
1362
 
1278
1363
  const isIntervalDomain = (domain: Value[]) =>
1279
- domain.length > 0 &&
1280
- (domain === intervalDomains[domain.length] ||
1281
- domain === longIntervalDomains.get(domain.length)?.deref() ||
1282
- intervalArrays.has(domain));
1364
+ (domain.length > 0 &&
1365
+ (domain === intervalDomains[domain.length] ||
1366
+ domain === longIntervalDomains.get(domain.length)?.deref())) ||
1367
+ intervalArrays.has(domain);
1283
1368
 
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
1369
  export const getFunctionDomain = (set: Value): Value[] => {
1287
1370
  const elements = toFiniteSet(set).elements;
1288
1371
  return isIntervalDomain(elements) && !(typeof set === "object" && set.kind === "Interval")
@@ -1307,7 +1390,6 @@ export const createRecord = (fields: [string, Value][]): FunctionValue =>
1307
1390
  export const createSortedRecord = (names: Value[], range: Value[]) =>
1308
1391
  setFunctionClass(createSortedFunction(names, range), "record");
1309
1392
 
1310
- // TLC's Enumerable classes: every set except the ones it implements in Java.
1311
1393
  export const isTlcEnumerable = (value: Value) => isSetValue(value) && !isOverriddenSet(value);
1312
1394
 
1313
1395
  const formatUnion = (value: UnionValue, isStrict = false) =>
@@ -1358,7 +1440,13 @@ export const isEnumerable = (value: Value): boolean => {
1358
1440
  case "ProductSet":
1359
1441
  return value.factors.every(isEnumerable) || getEmptiness(value) === true;
1360
1442
  case "Union":
1361
- return isEnumerable(value.base) && getStreamedElements(value.base).every(isEnumerable);
1443
+ return (
1444
+ isEnumerable(value.base) &&
1445
+ (isEnumeratedSet(value.base)
1446
+ ? getWrittenElements(value.base)
1447
+ : getStreamedElements(value.base)
1448
+ ).every(isEnumerable)
1449
+ );
1362
1450
  case "SetOperation":
1363
1451
  if (value.operator === "\\cup") return isEnumerable(value.left) && isEnumerable(value.right);
1364
1452
  if (value.operator === "\\cap") return isEnumerable(value.left) || isEnumerable(value.right);
@@ -1431,26 +1519,24 @@ const advanceCombination = (indices: number[], length: number) => {
1431
1519
  return false;
1432
1520
  };
1433
1521
 
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
1522
  export const getLazySubsets = (value: Value): Value[] | undefined => {
1438
1523
  if (typeof value !== "object" || value.kind !== "Subset" || isOverriddenSet(value.base)) {
1439
1524
  return undefined;
1440
1525
  }
1441
1526
  const base = toFiniteSet(value.base).elements;
1442
- if (base.length <= MAXIMUM_ENUMERATED_SUBSET_BASE) return undefined;
1443
- const cursor = { index: -1, indices: [0] };
1527
+ if (base.length <= MAXIMUM_BUILT_SUBSET_BASE) return undefined;
1528
+ let cursorIndex = -1;
1529
+ let indices = [0];
1444
1530
  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);
1531
+ if (index <= cursorIndex) cursorIndex = -1;
1532
+ while (cursorIndex < index) {
1533
+ if (cursorIndex === -1) indices = [];
1534
+ else if (!advanceCombination(indices, base.length)) {
1535
+ indices = Array.from({ length: indices.length + 1 }, (_value, position) => position);
1450
1536
  }
1451
- cursor.index++;
1537
+ cursorIndex++;
1452
1538
  }
1453
- return createSortedSet(cursor.indices.map((item) => base[item]));
1539
+ return createSortedSet(indices.map((baseIndex) => base[baseIndex]));
1454
1540
  };
1455
1541
  const length = 2 ** base.length;
1456
1542
  const isIndex = (property: string | symbol) =>
@@ -1469,7 +1555,7 @@ export const getLazySubsets = (value: Value): Value[] | undefined => {
1469
1555
  const getSortedSubsets = (base: Value[]) => {
1470
1556
  const subsets: Value[] = [];
1471
1557
  for (let size = 0; size <= base.length; size++) {
1472
- const indices = Array.from({ length: size }, (_, index) => index);
1558
+ const indices = Array.from({ length: size }, (_value, index) => index);
1473
1559
  do {
1474
1560
  subsets.push(createSortedSet(indices.map((index) => base[index])));
1475
1561
  } while (advanceCombination(indices, base.length));
@@ -1477,9 +1563,6 @@ const getSortedSubsets = (base: Value[]) => {
1477
1563
  return subsets;
1478
1564
  };
1479
1565
 
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
1566
  const getComponentElements = (
1484
1567
  sets: Value[],
1485
1568
  getElements: (set: Value) => Value[],
@@ -1496,7 +1579,6 @@ const getComponentElements = (
1496
1579
  return lists;
1497
1580
  };
1498
1581
 
1499
- // getElements enumerates the sets a set of functions, records, or tuples combines.
1500
1582
  const enumerateSet = (
1501
1583
  value: Value,
1502
1584
  getElements = (set: Value) => toFiniteSet(set).elements,
@@ -1514,8 +1596,6 @@ const enumerateSet = (
1514
1596
  return elements;
1515
1597
  }
1516
1598
  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
1599
  if (getCardinality(value.base) === 0) return getSortedSubsets([]);
1520
1600
  if (!isSetValue(value.base)) {
1521
1601
  throw new TlaEvaluationError(
@@ -1529,15 +1609,14 @@ const enumerateSet = (
1529
1609
  return getSortedSubsets(base);
1530
1610
  }
1531
1611
  case "FunctionSet": {
1532
- if (!valueVersion.is174 && isEmptySet(value)) return [];
1612
+ if (!isVersion174 && isEmptySet(value)) return [];
1533
1613
  if (isOverriddenSet(value.domain)) {
1534
1614
  throw new TlaEvaluationError(
1535
1615
  `Attempted to enumerate a set of the form [D -> R],but the domain D:\n${formatValue(value.domain)}\ncannot be enumerated.`,
1536
1616
  );
1537
1617
  }
1538
1618
  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)) {
1619
+ if ((domain.length > 0 || isVersion174) && isOverriddenSet(value.range)) {
1541
1620
  throw new TlaEvaluationError(
1542
1621
  `Attempted to enumerate a set of the form [D -> R],but the range R:\n${formatValue(value.range)}\ncannot be enumerated.`,
1543
1622
  );
@@ -1548,7 +1627,7 @@ const enumerateSet = (
1548
1627
  );
1549
1628
  }
1550
1629
  case "RecordSet": {
1551
- if (!valueVersion.is174 && isEmptySet(value)) return [];
1630
+ if (!isVersion174 && isEmptySet(value)) return [];
1552
1631
  const fields = getComponentElements(
1553
1632
  value.sets,
1554
1633
  getElements,
@@ -1560,7 +1639,7 @@ const enumerateSet = (
1560
1639
  );
1561
1640
  }
1562
1641
  case "ProductSet": {
1563
- if (!valueVersion.is174 && isEmptySet(value)) return [];
1642
+ if (!isVersion174 && isEmptySet(value)) return [];
1564
1643
  const factors = getComponentElements(
1565
1644
  value.factors,
1566
1645
  getElements,
@@ -1575,22 +1654,21 @@ const enumerateSet = (
1575
1654
  `Attempted to enumerate { x \\in S : p(x) } when S:\n${formatValue(value.base)}\nis not enumerable`,
1576
1655
  );
1577
1656
  }
1578
- return toFiniteSet(value.base).elements.filter(value.test);
1657
+ return toFiniteSet(
1658
+ createEnumeratedSet(
1659
+ getStreamedElements(value.base).filter((element) => value.test(element, false)),
1660
+ ),
1661
+ ).elements;
1579
1662
  case "Union": {
1580
- const elements = getUnionSets(value).flatMap(
1581
- (set, index) => toFiniteSet(getUnionSet(set, index, value)).elements,
1582
- );
1663
+ const elements: Value[] = [];
1664
+ getUnionSets(value).forEach((set, index) => {
1665
+ const unionSet = getUnionSet(set, index, value);
1666
+ if (isBeyondSetBound(unionSet)) throw new TlaSetBoundError(getSetBoundMessage());
1667
+ getStreamedElements(unionSet).forEach((element) => addBoundedElement(elements, element));
1668
+ });
1583
1669
  return toFiniteSet(createEnumeratedSet(elements)).elements;
1584
1670
  }
1585
1671
  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
1672
  if (
1595
1673
  value.operator === "\\cap" &&
1596
1674
  !isTlcEnumerable(value.left) &&
@@ -1606,19 +1684,23 @@ const enumerateSet = (
1606
1684
  );
1607
1685
  }
1608
1686
  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
- );
1687
+ return toFiniteSet(createEnumeratedSet(listUnionLikeTlc(value))).elements;
1615
1688
  }
1616
1689
  const isLeftEnumerated = value.operator === "\\" || isTlcEnumerable(value.left);
1617
1690
  const enumerated = isLeftEnumerated ? value.left : value.right;
1618
1691
  const other = isLeftEnumerated ? value.right : value.left;
1619
- return toFiniteSet(enumerated).elements.filter(
1620
- (element) => isElementOf(element, other) === (value.operator === "\\cap"),
1692
+ const kept: Value[] = [];
1693
+ forEachElement(
1694
+ typeof enumerated === "object" && enumerated.kind === "Interval"
1695
+ ? enumerated
1696
+ : getStreamedElements(enumerated),
1697
+ (element) => {
1698
+ if (isElementOf(element, other) === (value.operator === "\\cap")) {
1699
+ addBoundedElement(kept, element);
1700
+ }
1701
+ },
1621
1702
  );
1703
+ return toFiniteSet(createEnumeratedSet(kept)).elements;
1622
1704
  }
1623
1705
  case "InfiniteSet":
1624
1706
  case "SequenceSet":
@@ -1655,32 +1737,92 @@ export const toFiniteSet = (value: Value): SetValue => {
1655
1737
  return set;
1656
1738
  };
1657
1739
 
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;
1740
+ const openStream = (value: Value): void => {
1741
+ if (typeof value !== "object" || isCachedSet(value)) return;
1742
+ switch (value.kind) {
1743
+ case "MixedSet":
1744
+ toFiniteSet(value);
1745
+ return;
1746
+ case "FilteredSet":
1747
+ if (!isTlcEnumerable(value.base)) toFiniteSet(value);
1748
+ return openStream(value.base);
1749
+ case "Union":
1750
+ if (!isEnumeratedSet(value.base) && isTlcEnumerable(value.base)) {
1751
+ return openStream(value.base);
1752
+ }
1753
+ getUnionSets(value)
1754
+ .slice(0, 1)
1755
+ .forEach((set) => openStream(getUnionSet(set, 0, value)));
1756
+ return;
1757
+ case "SetOperation":
1758
+ if (value.operator === "\\" && !isTlcEnumerable(value.left)) toFiniteSet(value);
1759
+ if (
1760
+ value.operator === "\\cup" &&
1761
+ (!isTlcEnumerable(value.left) || !isTlcEnumerable(value.right))
1762
+ ) {
1763
+ toFiniteSet(value);
1764
+ }
1765
+ if (value.operator !== "\\cap" || isTlcEnumerable(value.left)) openStream(value.left);
1766
+ else openStream(value.right);
1767
+ if (value.operator === "\\cup") openStream(value.right);
1768
+ }
1769
+ };
1675
1770
 
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;
1771
+ const listUnionLikeTlc = (union: SetOperationValue) => {
1772
+ if (!isTlcEnumerable(union.left) || !isTlcEnumerable(union.right)) {
1773
+ throw new TlaEvaluationError(
1774
+ `Attempted to enumerate S \\cup T when S:\n${formatValue(union.left)}\nand T:\n${formatValue(union.right)}\nare not both enumerable`,
1775
+ );
1776
+ }
1777
+ openStream(union.left);
1778
+ openStream(union.right);
1779
+ if (isBeyondSetBound(union.left)) throw new TlaSetBoundError(getSetBoundMessage());
1780
+ const left = getStreamedElements(union.left);
1781
+ const right = isBeyondSetBound(union.right) ? undefined : getStreamedElements(union.right);
1782
+ if (!right || left.length + right.length > getMaximumSetSize()) {
1783
+ throw new TlaSetBoundError(getSetBoundMessage());
1784
+ }
1785
+ return [...left, ...right];
1786
+ };
1787
+
1788
+ export const getNormalizedSetElements = (value: Value) => {
1789
+ if (
1790
+ typeof value !== "object" ||
1791
+ value.kind !== "SetOperation" ||
1792
+ value.operator !== "\\cup" ||
1793
+ value.enumerated
1794
+ ) {
1795
+ return toFiniteSet(value).elements;
1796
+ }
1797
+ const listed = callTracedMethod(value, () => listUnionLikeTlc(value));
1798
+ const elements = toFiniteSet(createEnumeratedSet(listed)).elements;
1799
+ value.enumerated = createSortedSet(elements);
1800
+ return elements;
1801
+ };
1802
+
1803
+ export const someStreamedElement = (value: Value, visit: (element: Value) => boolean): boolean => {
1804
+ if (typeof value !== "object" || isCachedSet(value)) {
1805
+ return toFiniteSet(value).elements.some(visit);
1806
+ }
1680
1807
  const sets = setTrace.sets;
1681
1808
  sets?.push(value);
1682
- const elements = streamElements(value);
1809
+ openStream(value);
1810
+ const isFound = someElementOfStream(value, (element) => {
1811
+ sets?.pop();
1812
+ const isAccepted = visit(element);
1813
+ sets?.push(value);
1814
+ return isAccepted;
1815
+ });
1683
1816
  sets?.pop();
1817
+ return isFound;
1818
+ };
1819
+
1820
+ export const getStreamedElements = (value: Value) => {
1821
+ const elements: Value[] = [];
1822
+ someStreamedElement(value, (element) => {
1823
+ elements.push(element);
1824
+ return false;
1825
+ });
1684
1826
  return elements;
1685
1827
  };
1686
1828
 
@@ -1693,10 +1835,6 @@ const getCombinedSets = (value: ObjectValue) =>
1693
1835
  ? [value.range]
1694
1836
  : undefined;
1695
1837
 
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
1838
  export const isSettledValue = (value: Value): boolean => {
1701
1839
  if (typeof value !== "object") return true;
1702
1840
  switch (value.kind) {
@@ -1725,8 +1863,6 @@ export const isSettledValue = (value: Value): boolean => {
1725
1863
  }
1726
1864
  };
1727
1865
 
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
1866
  const isStreamedApart = (value: Value): boolean => {
1731
1867
  if (typeof value !== "object" || isCachedSet(value)) return false;
1732
1868
  if (value.kind === "Union") return true;
@@ -1739,31 +1875,35 @@ const isStreamedApart = (value: Value): boolean => {
1739
1875
  return getCombinedSets(value)?.some(isStreamedApart) ?? false;
1740
1876
  };
1741
1877
 
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.
1878
+ const someElementOfStream = (value: ObjectValue, visit: (element: Value) => boolean): boolean => {
1745
1879
  if (value.kind === "Union") {
1746
- return getUnionSets(value, getStreamedElements).flatMap((set, index) =>
1747
- getStreamedElements(getUnionSet(set, index, value)),
1880
+ return getUnionSets(value, getStreamedElements).some((set, index) =>
1881
+ someStreamedElement(getUnionSet(set, index, value), visit),
1748
1882
  );
1749
1883
  }
1750
- if (value.kind === "FilteredSet" && !isOverriddenSet(value.base)) {
1751
- return getStreamedElements(value.base).filter(value.test);
1884
+ if (value.kind === "FilteredSet" && isTlcEnumerable(value.base)) {
1885
+ return someStreamedElement(
1886
+ value.base,
1887
+ (element) => value.test(element, false) && visit(element),
1888
+ );
1752
1889
  }
1753
1890
  const components = getCombinedSets(value);
1754
- if (components?.some(isStreamedApart)) return enumerateSet(value, getStreamedElements);
1755
- if (value.kind !== "SetOperation") return toFiniteSet(value).elements;
1891
+ if (components?.some(isStreamedApart)) {
1892
+ return enumerateSet(value, getStreamedElements).some(visit);
1893
+ }
1894
+ if (value.kind !== "SetOperation") return toFiniteSet(value).elements.some(visit);
1756
1895
  if (value.operator === "\\cup") {
1757
1896
  return !isTlcEnumerable(value.left) || !isTlcEnumerable(value.right)
1758
- ? toFiniteSet(value).elements
1759
- : [...getStreamedElements(value.left), ...getStreamedElements(value.right)];
1897
+ ? toFiniteSet(value).elements.some(visit)
1898
+ : someStreamedElement(value.left, visit) || someStreamedElement(value.right, visit);
1760
1899
  }
1761
1900
  const isLeftEnumerated = value.operator === "\\" || isTlcEnumerable(value.left);
1762
1901
  const enumerated = isLeftEnumerated ? value.left : value.right;
1763
1902
  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"),
1903
+ if (!isTlcEnumerable(enumerated)) return toFiniteSet(value).elements.some(visit);
1904
+ return someStreamedElement(
1905
+ enumerated,
1906
+ (element) => isElementOf(element, other) === (value.operator === "\\cap") && visit(element),
1767
1907
  );
1768
1908
  };
1769
1909
 
@@ -1812,8 +1952,6 @@ const getProductCardinality = (
1812
1952
  const describeOverflow = (value: Value) =>
1813
1953
  `Overflow when computing the number of elements in:\n${formatValue(value)}`;
1814
1954
 
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
1955
  export const getCardinality = (value: Value, version?: TlcVersion): number => {
1818
1956
  if (typeof value !== "object") {
1819
1957
  throw new TlaEvaluationError(
@@ -1857,12 +1995,12 @@ export const getCardinality = (value: Value, version?: TlcVersion): number => {
1857
1995
  const domainSize = getCardinality(value.domain, version);
1858
1996
  const rangeSize = getCardinality(value.range, version);
1859
1997
  if (rangeSize <= 1) return domainSize === 0 ? 1 : rangeSize;
1860
- const size = { value: 1 };
1998
+ let size = 1;
1861
1999
  for (let index = 0; index < domainSize; index++) {
1862
- size.value *= rangeSize;
1863
- if (size.value > MAXIMUM_INTEGER) throw new TlaEvaluationError(describeOverflow(value));
2000
+ size *= rangeSize;
2001
+ if (size > MAXIMUM_INTEGER) throw new TlaEvaluationError(describeOverflow(value));
1864
2002
  }
1865
- return size.value;
2003
+ return size;
1866
2004
  }
1867
2005
  case "RecordSet":
1868
2006
  if (version !== "1.7.4" && isEmptySet(value)) return 0;
@@ -1915,12 +2053,12 @@ export const isFiniteSet = (value: Value): boolean => {
1915
2053
  case "RecordSet":
1916
2054
  case "ProductSet": {
1917
2055
  const parts = value.kind === "RecordSet" ? value.sets : value.factors;
1918
- const finiteness = { isAllFinite: true };
2056
+ let isAllFinite = true;
1919
2057
  for (const part of parts) {
1920
- if (!isFiniteSet(part)) finiteness.isAllFinite = false;
2058
+ if (!isFiniteSet(part)) isAllFinite = false;
1921
2059
  else if (isEmptySet(part)) return true;
1922
2060
  }
1923
- return finiteness.isAllFinite;
2061
+ return isAllFinite;
1924
2062
  }
1925
2063
  case "Union":
1926
2064
  if (!isTlcEnumerable(value.base)) {
@@ -1951,19 +2089,45 @@ export const isFiniteSet = (value: Value): boolean => {
1951
2089
  };
1952
2090
 
1953
2091
  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;
2092
+ let low = 0;
2093
+ let high = sortedValues.length - 1;
2094
+ while (low <= high) {
2095
+ const middle = (low + high) >> 1;
1957
2096
  const comparison = compare(sortedValues[middle], target);
1958
2097
  if (comparison === 0) return middle;
1959
- if (comparison < 0) bounds.low = middle + 1;
1960
- else bounds.high = middle - 1;
2098
+ if (comparison < 0) low = middle + 1;
2099
+ else high = middle - 1;
1961
2100
  }
1962
2101
  return -1;
1963
2102
  };
1964
2103
 
2104
+ export const createUnsortedCopy = (set: SetValue, added: Value[]): SetValue => {
2105
+ const elements = set.elements;
2106
+ if (elements.length > getMaximumSetSize()) throw new TlaSetBoundError(getSetBoundMessage());
2107
+ const isAdded = Array.from({ length: elements.length }, () => false);
2108
+ const written = added.filter((element) => {
2109
+ const index = findSortedIndex(elements, element);
2110
+ if (isAdded[index]) return false;
2111
+ isAdded[index] = true;
2112
+ return true;
2113
+ });
2114
+ const copy = createSortedSet(elements);
2115
+ if (written.some((element, index) => element !== elements[index])) {
2116
+ copy.writtenElements = written;
2117
+ }
2118
+ return copy;
2119
+ };
2120
+
1965
2121
  export const getSequenceElements = (value: Value): Value[] | undefined => {
1966
2122
  if (typeof value !== "object" || !isFunctionValue(value)) return undefined;
2123
+ if (
2124
+ value.kind === "LazyFunction" &&
2125
+ (!isSetValue(value.domain) || isOverriddenSet(value.domain))
2126
+ ) {
2127
+ throw new TlaEvaluationError(
2128
+ "To convert a function of form [x \\in S |-> f(x)] to a tuple, the set S must be enumerable.",
2129
+ );
2130
+ }
1967
2131
  const functionValue = toFiniteFunction(value);
1968
2132
  return functionValue.domain.every((key, index) => key === index + 1)
1969
2133
  ? functionValue.range
@@ -1981,24 +2145,17 @@ const describeNonSetMembership = (element: Value, value: Value) => {
1981
2145
  return `${prefix} function ${formatValue(value)}`;
1982
2146
  };
1983
2147
 
1984
- // The call stack of the replay, which a failed fast path leaves frozen.
1985
2148
  interface TracedCallStack {
1986
2149
  expressions: unknown[];
1987
2150
  isFrozen: boolean;
2151
+ sources: WeakMap<ObjectValue, unknown>;
1988
2152
  fingerprint?: unknown;
1989
2153
  }
1990
2154
 
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
2155
  export const setTrace: { sets: Value[] | undefined; callStack?: TracedCallStack } = {
1996
2156
  sets: undefined,
1997
2157
  };
1998
2158
 
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
2159
  export const computeLikeTlcOnFailure = <Left, Right, Result>(
2003
2160
  compute: (left: Left, right: Right) => Result,
2004
2161
  computeLikeTlc: (left: Left, right: Right, error: TlaEvaluationError) => Result,
@@ -2023,6 +2180,11 @@ export const computeLikeTlcOnFailure = <Left, Right, Result>(
2023
2180
  }
2024
2181
  };
2025
2182
 
2183
+ export const isFingerprintedSince = (depth: number) =>
2184
+ (setTrace.sets ?? [])
2185
+ .slice(depth)
2186
+ .some((set) => typeof set === "object" && setTrace.callStack?.sources.has(set) === true);
2187
+
2026
2188
  export const isElementOf = (element: Value, set: Value): boolean => {
2027
2189
  const sets = setTrace.sets;
2028
2190
  if (sets === undefined) return isElementOfSet(element, set);
@@ -2032,26 +2194,59 @@ export const isElementOf = (element: Value, set: Value): boolean => {
2032
2194
  return isElement;
2033
2195
  };
2034
2196
 
2197
+ const isIntegerInSortedSet = (element: number, set: SetValue) => {
2198
+ const elements = set.elements;
2199
+ let low = 0;
2200
+ let high = elements.length - 1;
2201
+ while (low <= high) {
2202
+ const middle = (low + high) >> 1;
2203
+ const probe = elements[middle];
2204
+ if (typeof probe !== "number") return undefined;
2205
+ if (probe === element) return true;
2206
+ if (probe < element) low = middle + 1;
2207
+ else high = middle - 1;
2208
+ }
2209
+ return false;
2210
+ };
2211
+
2035
2212
  const isInSortedSet = (element: Value, set: SetValue) =>
2036
2213
  findSortedIndex(set.elements, element) !== -1;
2037
2214
 
2038
2215
  const isInSortedSetLikeTlc = (element: Value, set: SetValue) =>
2039
- normalizedSets.has(set)
2216
+ set.isNormalized
2040
2217
  ? searchLikeTlc(element, set.elements).isFound
2041
- : isElementOfLikeTlc(element, set.elements);
2218
+ : isElementOfLikeTlc(element, getWrittenElements(set));
2219
+
2220
+ const isModelValueMember = (modelValue: ModelValue, set: Value) => {
2221
+ if (modelValue.type !== undefined) {
2222
+ throw new TlaEvaluationError(
2223
+ `Attempted to check if the typed model value ${prettyPrint(formatValue(modelValue))} is an element of\n${prettyPrint(formatValue(set))}`,
2224
+ );
2225
+ }
2226
+ return false;
2227
+ };
2042
2228
 
2229
+ // The common cases stay small enough for V8 to inline.
2043
2230
  const isElementOfSet = (element: Value, set: Value): boolean => {
2231
+ if (typeof element === "number" && typeof set === "object") {
2232
+ if (set.kind === "Set")
2233
+ return isIntegerInSortedSet(element, set) ?? isElementOfAnySet(element, set);
2234
+ if (set.kind === "Interval") return element >= set.low && element <= set.high;
2235
+ }
2236
+ return isElementOfAnySet(element, set);
2237
+ };
2238
+
2239
+ const isElementOfAnySet = (element: Value, set: Value): boolean => {
2044
2240
  if (!isSetValue(set)) throw new TlaEvaluationError(describeNonSetMembership(element, set));
2045
2241
  switch (set.kind) {
2046
2242
  case "Set":
2047
- // SetEnumValue.member compares the element with the set's.
2048
2243
  cacheSet(element);
2049
2244
  return computeLikeTlcOnFailure(isInSortedSet, isInSortedSetLikeTlc, element, set);
2050
2245
  case "MixedSet":
2051
2246
  return isElementOfLikeTlc(element, set.elements);
2052
2247
  case "Interval":
2053
2248
  if (typeof element === "number") return element >= set.low && element <= set.high;
2054
- if (set.low <= set.high && !isModelValue(element)) {
2249
+ if (set.low <= set.high && (!isModelValue(element) || element.type !== undefined)) {
2055
2250
  throw new TlaEvaluationError(
2056
2251
  `Attempted to check if the value:\n${formatValue(element)}\nis in the integer interval ${formatValue(set)}`,
2057
2252
  );
@@ -2059,19 +2254,17 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2059
2254
  return false;
2060
2255
  case "InfiniteSet": {
2061
2256
  if (set.name === "Any") return true;
2062
- if (isModelValue(element)) return false;
2257
+ if (isModelValue(element)) return isModelValueMember(element, set);
2063
2258
  const isMemberType =
2064
2259
  set.name === "STRING" ? typeof element === "string" : typeof element === "number";
2065
2260
  if (!isMemberType) {
2066
- throw new TlaEvaluationError(
2261
+ throw new TlaModuleError(
2067
2262
  `Attempted to check if the value:\n${formatValue(element)}\nis an element of ${set.name}.`,
2068
2263
  );
2069
2264
  }
2070
2265
  return set.name !== "Nat" || (typeof element === "number" && element >= 0);
2071
2266
  }
2072
2267
  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
2268
  if (!isSetValue(element) || isOverriddenSet(element)) {
2076
2269
  throw new TlaEvaluationError(
2077
2270
  `Attempted to check if the non-enumerable value\n${prettyPrint(formatValue(element))}\nis element of\n${prettyPrint(formatValue(set))}`,
@@ -2080,14 +2273,13 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2080
2273
  return toFiniteSet(element).elements.every((item) => isElementOf(item, set.base));
2081
2274
  case "FunctionSet": {
2082
2275
  if (!isFunctionValue(element)) {
2083
- if (isModelValue(element)) return false;
2084
- // SetOfFcnsValue.member prints the element without Values.ppr.
2276
+ if (isModelValue(element)) return isModelValueMember(element, set);
2085
2277
  throw new TlaEvaluationError(
2086
2278
  `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
2279
  );
2088
2280
  }
2089
2281
  const functionValue = toFiniteFunction(element);
2090
- const low = getIntervalLow(functionValue.domain);
2282
+ const low = getIntervalLow(element, functionValue.domain);
2091
2283
  const isDomain =
2092
2284
  low === undefined
2093
2285
  ? isEqualLikeTlc(set.domain, createSortedSet(functionValue.domain))
@@ -2100,7 +2292,7 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2100
2292
  case "RecordSet": {
2101
2293
  const functionValue = isFunctionValue(element) ? toFiniteFunction(element) : undefined;
2102
2294
  if (!functionValue || !isRecordDomain(functionValue.domain)) {
2103
- if (isModelValue(element)) return false;
2295
+ if (isModelValue(element)) return isModelValueMember(element, set);
2104
2296
  throw new TlaEvaluationError(
2105
2297
  `Attempted to check if non-record\n${formatValue(element)}\nis in the set of records:\n${formatValue(set)}`,
2106
2298
  );
@@ -2119,7 +2311,8 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2119
2311
  const isFunction =
2120
2312
  isFunctionValue(element) &&
2121
2313
  toFiniteFunction(element).domain.every((key) => typeof key === "number");
2122
- if (isFunction || isModelValue(element)) return false;
2314
+ if (isModelValue(element)) return isModelValueMember(element, set);
2315
+ if (isFunction) return false;
2123
2316
  throw new TlaEvaluationError(
2124
2317
  `Attempted to check if non-tuple\n${formatValue(element)}\nis in the set of tuples:\n${formatValue(set)}`,
2125
2318
  );
@@ -2130,14 +2323,28 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2130
2323
  );
2131
2324
  }
2132
2325
  case "FilteredSet":
2133
- return isElementOf(element, set.base) && set.test(element);
2134
- case "Union":
2326
+ try {
2327
+ return isElementOf(element, set.base) && set.test(element, true);
2328
+ } catch (error) {
2329
+ if (!(error instanceof TlaEvaluationError) || !isEvalException(error)) throw error;
2330
+ throw new TlaEvaluationError(
2331
+ `Cannot decide if element:\n${prettyPrint(formatValue(element))}\n is element of:\n${prettyPrint(formatValue(set.base))}\nand satisfies the predicate ${set.source?.predicate}`,
2332
+ );
2333
+ }
2334
+ case "Union": {
2135
2335
  if (!isTlcEnumerable(set.base)) {
2136
2336
  throw new TlaEvaluationError(
2137
2337
  `Attempted to check if:\n ${formatValue(element)}\nis an element of the non-enumerable set:\n ${formatUnion(set)}`,
2138
2338
  );
2139
2339
  }
2140
- return toFiniteSet(set.base).elements.some((inner) => isElementOf(element, inner));
2340
+ const sets = toFiniteSet(set.base).elements;
2341
+ if (sets.length > 1) {
2342
+ sets.forEach((inner) => {
2343
+ if (typeof inner === "object" && inner.kind === "Set") inner.isNormalized = true;
2344
+ });
2345
+ }
2346
+ return sets.some((inner) => isElementOf(element, inner));
2347
+ }
2141
2348
  case "SetOperation":
2142
2349
  if (set.operator === "\\cup")
2143
2350
  return isElementOf(element, set.left) || isElementOf(element, set.right);
@@ -2148,9 +2355,8 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2148
2355
  case "SequenceSet": {
2149
2356
  const elements = getSequenceElements(element);
2150
2357
  if (elements === undefined) {
2151
- if (isModelValue(element)) return false;
2152
- // Sequences.member raises TLC_MODULE_CHECK_MEMBER_OF.
2153
- throw new TlaEvaluationError(
2358
+ if (isModelValue(element)) return isModelValueMember(element, set);
2359
+ throw new TlaModuleError(
2154
2360
  `Attempted to check if the value:\n${prettyPrint(formatValue(element))}\nis an element of ${prettyPrint(formatValue(set))}.`,
2155
2361
  );
2156
2362
  }
@@ -2161,8 +2367,6 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2161
2367
  }
2162
2368
  };
2163
2369
 
2164
- // A function that agrees with a member of a function set outside some entries is a member when
2165
- // those entries are.
2166
2370
  export const isUpdatedElementOf = (element: Value, member: Value, set: Value): boolean => {
2167
2371
  if (element === member) return true;
2168
2372
  if (
@@ -2185,6 +2389,9 @@ export const toFiniteFunction = (value: Value): FunctionValue => {
2185
2389
  if (typeof value === "object" && value.kind === "LazyFunction") {
2186
2390
  if (value.enumerated) return value.enumerated;
2187
2391
  if (!isEnumerable(value.domain)) getCardinality(value.domain);
2392
+ if (!isSetValue(value.domain)) {
2393
+ throw new TlaEvaluationError("The domains of formal parameters must be enumerable.");
2394
+ }
2188
2395
  const domain = getFunctionDomain(value.domain);
2189
2396
  value.enumerated = setFunctionClass(
2190
2397
  createSortedFunction(
@@ -2232,16 +2439,14 @@ export const describeMissingArgument = (
2232
2439
  }
2233
2440
  };
2234
2441
 
2235
- // TLC 1.7.4 words a key of the wrong type in an EXCEPT, which selects rather than applies, apart.
2236
2442
  const describeExceptKey = (functionValue: FunctionValue, argument: Value) => {
2237
- if (!valueVersion.is174) return describeMissingArgument(functionValue, argument);
2443
+ if (!isVersion174) return describeMissingArgument(functionValue, argument);
2238
2444
  const shown = prettyPrint(formatValue(argument));
2239
2445
  return getFunctionClass(functionValue) === "tuple"
2240
2446
  ? `Attempted to apply tuple to a non-integer argument ${shown}.`
2241
2447
  : `Attempted to apply record to a non-string argument ${shown}.`;
2242
2448
  };
2243
2449
 
2244
- // A key the domain holds itself, which TLC finds without a comparison that can fail.
2245
2450
  const findIdenticalKey = (domain: Value[], argument: Value) => {
2246
2451
  const first = domain[0];
2247
2452
  if (typeof argument === "number" && typeof first === "number") {
@@ -2256,22 +2461,25 @@ export const createNonIntegerKeyError = (argument: Value) =>
2256
2461
  `Attempted to apply function with integer domain to the non-integer argument ${prettyPrint(formatValue(argument))}`,
2257
2462
  );
2258
2463
 
2259
- // TLC's FcnRcdValue searches a domain this small linearly with equals, and a larger normalized one by
2260
- // binary search with compareTo.
2261
2464
  const LINEAR_SEARCH_LIMIT = 32;
2262
2465
 
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));
2466
+ const findDomainIndex = (functionValue: FunctionValue, argument: Value) =>
2467
+ findSortedIndex(functionValue.domain, argument);
2468
+
2469
+ const failKeyLikeTlc = (
2470
+ functionValue: FunctionValue,
2471
+ argument: Value,
2472
+ error: TlaEvaluationError,
2473
+ ): never => {
2474
+ const keys = getWrittenKeys(functionValue);
2475
+ if (isVersion174 || keys !== functionValue.domain || keys.length < LINEAR_SEARCH_LIMIT) {
2476
+ keys.forEach((key) => equalsLikeTlc(key, argument));
2266
2477
  } else {
2267
- findSortedIndex(domain, argument, compareLikeTlc);
2478
+ findSortedIndex(keys, argument, compareLikeTlc);
2268
2479
  }
2269
2480
  throw error;
2270
2481
  };
2271
2482
 
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
2483
  const findKeyIndexLikeTlc = (
2276
2484
  functionValue: FunctionValue,
2277
2485
  argument: Value,
@@ -2285,21 +2493,84 @@ const findKeyIndexLikeTlc = (
2285
2493
  if (keyType !== undefined && typeof argument !== keyType) {
2286
2494
  throw new TlaEvaluationError(describeWrongKey(functionValue, argument));
2287
2495
  }
2288
- if (keyType === undefined && !valueVersion.is174 && isIntervalDomain(domain)) {
2496
+ if (
2497
+ keyType === undefined &&
2498
+ !isVersion174 &&
2499
+ typeof argument !== "number" &&
2500
+ isIntervalDomain(domain)
2501
+ ) {
2289
2502
  throw createNonIntegerKeyError(argument);
2290
2503
  }
2291
2504
  }
2292
2505
  const identical = findIdenticalKey(domain, argument);
2293
2506
  if (identical !== -1) return identical;
2294
- return computeLikeTlcOnFailure(findSortedIndex, failKeyLikeTlc, domain, argument);
2507
+ return computeLikeTlcOnFailure(findDomainIndex, failKeyLikeTlc, functionValue, argument);
2508
+ };
2509
+
2510
+ // Deviation from TLC: FcnLambdaValue#apply indexes past an argument tuple shorter than the bounds and ignores a longer one, where this rejects the list.
2511
+ const checkBoundArguments = (
2512
+ functionValue: LazyFunctionValue,
2513
+ tupleLengths: (number | undefined)[],
2514
+ argument: Value,
2515
+ ) => {
2516
+ const domain = functionValue.domain;
2517
+ const elements = getSequenceElements(argument);
2518
+ const describe = (position: string, shown: Value, problem: string) =>
2519
+ `In applying the function\n${prettyPrint(formatValue(functionValue))},\nthe ${position} is:\n${prettyPrint(formatValue(shown))}\nwhich ${problem}.\n`;
2520
+ const createListError = () =>
2521
+ new TlaEvaluationError(
2522
+ describe("argument list", argument, "does not match its formal parameter"),
2523
+ );
2524
+ if (elements === undefined) throw createListError();
2525
+ if (typeof domain !== "object" || domain.kind !== "ProductSet") {
2526
+ throw new TlaEvaluationError(
2527
+ `Attempted to apply a function to ${formatValue(argument)}, which is not in its domain`,
2528
+ );
2529
+ }
2530
+ tupleLengths.forEach((tupleLength, index) => {
2531
+ if (index >= elements.length) throw createListError();
2532
+ const element = elements[index];
2533
+ const position = `argument number ${index + 1}`;
2534
+ if (!isElementOf(element, domain.factors[index])) {
2535
+ throw new TlaEvaluationError(
2536
+ describe(
2537
+ position,
2538
+ element,
2539
+ tupleLength === undefined
2540
+ ? `is not in the function's domain ${formatValue(domain)}`
2541
+ : "is not in its domain",
2542
+ ),
2543
+ );
2544
+ }
2545
+ if (tupleLength !== undefined && getSequenceElements(element)?.length !== tupleLength) {
2546
+ throw new TlaEvaluationError(
2547
+ describe(position, element, "does not match its formal parameter"),
2548
+ );
2549
+ }
2550
+ });
2551
+ if (elements.length > tupleLengths.length) throw createListError();
2295
2552
  };
2296
2553
 
2554
+ const isOutsideLambdaDomain = (functionValue: FunctionValue, argument: Value) =>
2555
+ functionValue.lambdaDomain !== undefined &&
2556
+ functionValue.hash === 0 &&
2557
+ functionValue.fingerprint === 0 &&
2558
+ !isElementOf(argument, functionValue.lambdaDomain);
2559
+
2297
2560
  export const applyFunction = (
2298
2561
  functionValue: Value,
2299
2562
  argument: Value,
2300
2563
  describeMissing?: (functionValue: FunctionValue, argument: Value) => string,
2301
2564
  ): Value => {
2302
2565
  if (typeof functionValue === "object" && functionValue.kind === "LazyFunction") {
2566
+ if (functionValue.enumerated) {
2567
+ return applyFunction(functionValue.enumerated, argument, describeMissing);
2568
+ }
2569
+ const tupleLengths = functionValue.boundTupleLengths;
2570
+ if (tupleLengths !== undefined) {
2571
+ checkBoundArguments(functionValue, tupleLengths, argument);
2572
+ return functionValue.apply(argument);
2573
+ }
2303
2574
  if (!isElementOf(argument, functionValue.domain)) {
2304
2575
  throw new TlaEvaluationError(
2305
2576
  getFunctionClass(functionValue) === "lambda"
@@ -2315,6 +2586,9 @@ export const applyFunction = (
2315
2586
  );
2316
2587
  }
2317
2588
  const describe = describeMissing ?? describeMissingArgument;
2589
+ if (isOutsideLambdaDomain(functionValue, argument)) {
2590
+ throw new TlaEvaluationError(describe(functionValue, argument));
2591
+ }
2318
2592
  const position = findKeyIndexLikeTlc(functionValue, argument, describe);
2319
2593
  if (position === -1) throw new TlaEvaluationError(describe(functionValue, argument));
2320
2594
  return functionValue.range[position];
@@ -2328,8 +2602,17 @@ export const getDomainInterval = (domain: Value[]) =>
2328
2602
  export const getDomain = (functionValue: Value): Value => {
2329
2603
  if (typeof functionValue === "object" && functionValue.kind === "LazyFunction")
2330
2604
  return functionValue.domain;
2331
- const domain = toFiniteFunction(functionValue).domain;
2332
- return getDomainInterval(domain) ?? createSortedSet(domain);
2605
+ const finite = toFiniteFunction(functionValue);
2606
+ if (finite.functionClass === "lambda" && finite.lambdaDomain) return finite.lambdaDomain;
2607
+ const interval = getDomainInterval(finite.domain);
2608
+ if (interval) return interval;
2609
+ const set = createSortedSet(finite.domain);
2610
+ if (finite.functionClass === "record") {
2611
+ if (finite.writtenKeys) set.writtenElements = finite.writtenKeys;
2612
+ return set;
2613
+ }
2614
+ set.isNormalized = true;
2615
+ return set;
2333
2616
  };
2334
2617
 
2335
2618
  export const updateFunction = (
@@ -2341,7 +2624,7 @@ export const updateFunction = (
2341
2624
  const isLazy =
2342
2625
  typeof functionValue === "object" &&
2343
2626
  functionValue.kind === "LazyFunction" &&
2344
- (isKeptLazy || !isEnumerable(functionValue.domain));
2627
+ (isKeptLazy || functionValue.enumerated === undefined);
2345
2628
  if (isLazy) {
2346
2629
  if (!isElementOf(argument, functionValue.domain)) return functionValue;
2347
2630
  const updated = update(functionValue.apply(argument));
@@ -2351,6 +2634,7 @@ export const updateFunction = (
2351
2634
  domain: functionValue.domain,
2352
2635
  apply: (key) => (isEqualLikeTlc(argument, key) ? updated : functionValue.apply(key)),
2353
2636
  source: functionValue.source,
2637
+ boundTupleLengths: functionValue.boundTupleLengths,
2354
2638
  },
2355
2639
  getFunctionClass(functionValue),
2356
2640
  );
@@ -2361,6 +2645,7 @@ export const updateFunction = (
2361
2645
  );
2362
2646
  }
2363
2647
  const finite = toFiniteFunction(functionValue);
2648
+ if (isOutsideLambdaDomain(finite, argument)) return finite;
2364
2649
  const position = findKeyIndexLikeTlc(finite, argument, describeExceptKey);
2365
2650
  if (position === -1) return finite;
2366
2651
  const range = [...finite.range];
@@ -2372,6 +2657,7 @@ export const updateFunction = (
2372
2657
  getFunctionClass(finite),
2373
2658
  );
2374
2659
  updated.writtenKeys = finite.writtenKeys;
2660
+ updated.lambdaDomain = finite.lambdaDomain;
2375
2661
  if (finite.hash !== 0 && finite.hash !== UNFINGERPRINTABLE_HASH) {
2376
2662
  const nextHash = getValueHash(next);
2377
2663
  if (nextHash !== UNFINGERPRINTABLE_HASH) {
@@ -2424,9 +2710,6 @@ const getElementContribution = (elementHash: number) =>
2424
2710
  const getEntryContribution = (keyHash: number, valueHash: number) =>
2425
2711
  finalizeHash((Math.imul(keyHash, 0x27d4eb2d) + valueHash) | 0);
2426
2712
 
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
2713
  const UNFINGERPRINTABLE_HASH = 0x2f6b1c4d;
2431
2714
 
2432
2715
  const computeValueHash = (value: SetValue | FunctionValue) => {
@@ -2452,8 +2735,6 @@ const computeValueHash = (value: SetValue | FunctionValue) => {
2452
2735
  return hash;
2453
2736
  };
2454
2737
 
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
2738
  const fingerprintValue = (value: Value): void => {
2458
2739
  if (typeof value !== "object" || value.kind === "ModelValue") return;
2459
2740
  if (value.kind === "InfiniteSet" || value.kind === "SequenceSet") {
@@ -2470,8 +2751,6 @@ const fingerprintValue = (value: Value): void => {
2470
2751
  functionValue.range.forEach(fingerprintValue);
2471
2752
  };
2472
2753
 
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
2754
  export const getFingerprintError = (value: Value) => {
2476
2755
  if (typeof value !== "object" || value.kind === "ModelValue") return undefined;
2477
2756
  try {
@@ -2483,7 +2762,6 @@ export const getFingerprintError = (value: Value) => {
2483
2762
  }
2484
2763
  };
2485
2764
 
2486
- // The values a value holds, which TLC fingerprints as it fingerprints the value.
2487
2765
  export const getHeldValues = (value: ObjectValue): Value[] => {
2488
2766
  switch (value.kind) {
2489
2767
  case "Set":
@@ -2604,8 +2882,17 @@ const computeValueKey = (value: ObjectValue) => {
2604
2882
  return `(${functionValue.domain.map((key, index) => `${getValueKey(key)}:${getValueKey(functionValue.range[index])}`).join(",")})`;
2605
2883
  };
2606
2884
 
2885
+ const PRINTED_ESCAPES: Record<string, string> = {
2886
+ '"': '\\"',
2887
+ "\\": "\\\\",
2888
+ "\t": "\\t",
2889
+ "\n": "\\n",
2890
+ "\f": "\\f",
2891
+ "\r": "\\r",
2892
+ };
2893
+
2607
2894
  const formatString = (value: string) =>
2608
- `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\t/g, "\\t")}"`;
2895
+ `"${value.replace(/["\\\t\n\f\r]/g, (character) => PRINTED_ESCAPES[character])}"`;
2609
2896
 
2610
2897
  type LazySetValue =
2611
2898
  | SubsetValue
@@ -2631,24 +2918,24 @@ const expandLazySet = (value: LazySetValue) => {
2631
2918
  if (value.kind === "SetOperation" || value.kind === "FilteredSet" || value.kind === "Union") {
2632
2919
  return toFiniteSet(value);
2633
2920
  }
2634
- if (
2635
- value.kind === "FunctionSet" &&
2636
- isEnumerable(value.domain) &&
2637
- getCardinality(value.domain) === 0
2638
- ) {
2639
- return createSortedSet([createSortedFunction([], [])]);
2921
+ if (value.kind === "FunctionSet") {
2922
+ const domainSize = isEmptySet(value.domain) ? 0 : getCardinality(value.domain);
2923
+ const size = domainSize === 0 ? 1 : getCardinality(value.range) ** domainSize;
2924
+ return size <= MAXIMUM_EXPANDED_PRODUCT ? toFiniteSet(value) : undefined;
2640
2925
  }
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;
2926
+ const size = getProductSize(value.kind === "RecordSet" ? value.sets : value.factors);
2646
2927
  return size <= MAXIMUM_EXPANDED_PRODUCT ? toFiniteSet(value) : undefined;
2647
2928
  };
2648
2929
 
2649
2930
  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.
2931
+ if (isStrict || value.kind === "Union") return expandLazySet(value);
2932
+ if (
2933
+ value.kind === "Subset" &&
2934
+ isFunctionValue(value.base) &&
2935
+ (value.base.kind === "Function" || isEnumerable(value.base.domain))
2936
+ ) {
2937
+ return expandLazySet(value);
2938
+ }
2652
2939
  if (!isEnumerable(value)) return undefined;
2653
2940
  try {
2654
2941
  return expandLazySet(value);
@@ -2682,24 +2969,76 @@ const formatLazySet = (value: LazySetValue, isStrict: boolean): string => {
2682
2969
  }
2683
2970
  };
2684
2971
 
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
2972
  const isFieldName = (name: string) =>
2688
2973
  /^[\p{L}\p{Nd}_]*$/u.test(name) &&
2689
2974
  /\p{L}/u.test(name) &&
2690
2975
  (name.length < 4 || !/^[WS]F_/.test(name));
2691
2976
 
2692
- // FcnLambdaValue#toString prints a function it fails to enumerate as its parameters and body.
2693
2977
  const toPrintedFunction = (value: LazyFunctionValue) => {
2694
2978
  if (!isEnumerable(value.domain)) return undefined;
2695
2979
  try {
2696
2980
  return toFiniteFunction(value);
2697
2981
  } catch (error) {
2698
- if (error instanceof TlaEvaluationError) return undefined;
2982
+ if (error instanceof TlaEvaluationError || isStackOverflow(error)) return undefined;
2699
2983
  throw error;
2700
2984
  }
2701
2985
  };
2702
2986
 
2987
+ export const formatNormalizedCopies = (values: Value[]) => {
2988
+ const markedSets: SetValue[] = [];
2989
+ const normalize = (value: Value): void => {
2990
+ if (typeof value !== "object") return;
2991
+ switch (value.kind) {
2992
+ case "Set":
2993
+ value.elements.forEach(normalize);
2994
+ if (value.isNormalized) return;
2995
+ value.isNormalized = true;
2996
+ markedSets.push(value);
2997
+ return;
2998
+ case "MixedSet":
2999
+ value.elements.forEach(normalize);
3000
+ toFiniteSet(value);
3001
+ return;
3002
+ case "Function":
3003
+ value.range.forEach(normalize);
3004
+ return;
3005
+ case "LazyFunction":
3006
+ normalize(value.enumerated ?? value.domain);
3007
+ return;
3008
+ case "SetOperation":
3009
+ normalize(value.left);
3010
+ normalize(value.right);
3011
+ return;
3012
+ case "FunctionSet":
3013
+ normalize(value.domain);
3014
+ normalize(value.range);
3015
+ return;
3016
+ case "RecordSet":
3017
+ value.sets.forEach(normalize);
3018
+ return;
3019
+ case "ProductSet":
3020
+ value.factors.forEach(normalize);
3021
+ return;
3022
+ case "Subset":
3023
+ case "Union":
3024
+ case "FilteredSet":
3025
+ case "SequenceSet":
3026
+ normalize(value.base);
3027
+ return;
3028
+ default:
3029
+ return;
3030
+ }
3031
+ };
3032
+ try {
3033
+ values.forEach(normalize);
3034
+ return values.map((value) => formatValue(value, true, true));
3035
+ } finally {
3036
+ markedSets.forEach((set) => {
3037
+ set.isNormalized = false;
3038
+ });
3039
+ }
3040
+ };
3041
+
2703
3042
  export const formatValue = (value: Value, isStrict = false, isNormalized = false): string => {
2704
3043
  const format = (inner: Value) => formatValue(inner, isStrict, isNormalized);
2705
3044
  if (typeof value === "boolean") return value ? "TRUE" : "FALSE";
@@ -2723,7 +3062,7 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
2723
3062
  case "SetOperation":
2724
3063
  case "FilteredSet":
2725
3064
  case "Union": {
2726
- const expanded = getExpandedLazySet(value, isStrict);
3065
+ const expanded = printing.isExpanded ? getExpandedLazySet(value, isStrict) : undefined;
2727
3066
  return expanded ? format(expanded) : formatLazySet(value, isStrict);
2728
3067
  }
2729
3068
 
@@ -2731,7 +3070,12 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
2731
3070
  return `Seq(${format(value.base)})`;
2732
3071
  case "Function":
2733
3072
  case "LazyFunction": {
2734
- const functionValue = value.kind === "LazyFunction" ? toPrintedFunction(value) : value;
3073
+ const functionValue =
3074
+ value.kind !== "LazyFunction"
3075
+ ? value
3076
+ : printing.isExpanded || !value.source
3077
+ ? toPrintedFunction(value)
3078
+ : undefined;
2735
3079
  if (functionValue === undefined) {
2736
3080
  const source = value.kind === "LazyFunction" ? value.source : undefined;
2737
3081
  if (!source) return "<function>";
@@ -2742,42 +3086,117 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
2742
3086
  }
2743
3087
  if (
2744
3088
  functionValue.domain.length === 0 &&
2745
- valueVersion.is174 &&
3089
+ isVersion174 &&
2746
3090
  getFunctionClass(value) !== "tuple"
2747
3091
  ) {
2748
3092
  return "<< >>";
2749
3093
  }
2750
- // TLC normalizes a lambda's domain to print it, but evaluates its body afterward.
2751
3094
  const formatRange = (inner: Value) =>
2752
3095
  formatValue(inner, isStrict, isNormalized && getFunctionClass(value) !== "lambda");
3096
+ if (functionValue.domain.length === 0 && getFunctionClass(value) === "record") return "[]";
2753
3097
  if (functionValue.domain.every((key, index) => key === index + 1)) {
2754
3098
  return `<<${functionValue.range.map(formatRange).join(", ")}>>`;
2755
3099
  }
2756
- // A RecordValue prints as a record whatever its fields, and a FcnRcdValue only if each key
2757
- // is a name.
3100
+ const pairs = isNormalized
3101
+ ? functionValue.domain.map((key, index) => [key, functionValue.range[index]])
3102
+ : getPrintedPairs(functionValue);
2758
3103
  if (
2759
3104
  getFunctionClass(value) === "record" ||
2760
3105
  functionValue.domain.every((key) => typeof key === "string" && isFieldName(key))
2761
3106
  ) {
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
3107
  return `[${pairs.map((pair) => `${String(pair[0])} |-> ${formatRange(pair[1])}`).join(", ")}]`;
2768
3108
  }
2769
- return `(${functionValue.domain.map((key, index) => `${format(key)} :> ${formatRange(functionValue.range[index])}`).join(" @@ ")})`;
3109
+ return `(${pairs.map((pair) => `${format(pair[0])} :> ${formatRange(pair[1])}`).join(" @@ ")})`;
2770
3110
  }
2771
3111
  }
2772
3112
  };
2773
3113
 
2774
- // TLC's TLCState.toString: a line per variable, as a conjunction when there are several.
2775
- export const formatState = (state: Record<string, Value>) => {
3114
+ const isUnchanged = (previous: Value | undefined, value: Value) => {
3115
+ if (previous === undefined) return false;
3116
+ try {
3117
+ return valuesEqual(previous, value);
3118
+ } catch (error) {
3119
+ if (error instanceof TlaEvaluationError) return false;
3120
+ throw error;
3121
+ }
3122
+ };
3123
+
3124
+ const JAVA_FORMAT_SPECIFIER = /%(\d+\$)?([-#+ 0,(<]*)(\d+)?(\.\d+)?(.?)/gs;
3125
+
3126
+ const getJavaHashCode = (text: string) =>
3127
+ Array.from({ length: text.length }, (_value, index) => text.charCodeAt(index)).reduce(
3128
+ (hash, unit) => (Math.imul(hash, 31) + unit) | 0,
3129
+ 0,
3130
+ );
3131
+
3132
+ const formatJava = (format: string, args: string[]) => {
3133
+ let nextIndex = 0;
3134
+ let lastIndex = -1;
3135
+ let isFitting = true;
3136
+ const text = format.replace(
3137
+ JAVA_FORMAT_SPECIFIER,
3138
+ (match, explicit?: string, flags = "", width?: string, precision?: string, conversion = "") => {
3139
+ const pad = (value: string) =>
3140
+ flags.includes("-") ? value.padEnd(Number(width)) : value.padStart(Number(width ?? 0));
3141
+ const isRelative = flags.includes("<");
3142
+ const otherFlags = flags.replace("<", "");
3143
+ if (conversion === "n" && match === "%n") return "\n";
3144
+ if (conversion === "%" && precision === undefined && /^-?$/.test(otherFlags)) {
3145
+ if (otherFlags === "-" && width === undefined) isFitting = false;
3146
+ return pad("%");
3147
+ }
3148
+ const index = isRelative
3149
+ ? lastIndex
3150
+ : explicit === undefined
3151
+ ? nextIndex++
3152
+ : Number(explicit.slice(0, -1)) - 1;
3153
+ lastIndex = index;
3154
+ const arg = args[index];
3155
+ if (
3156
+ !"sSbBhH".includes(conversion) ||
3157
+ conversion === "" ||
3158
+ !/^-?$/.test(otherFlags) ||
3159
+ (otherFlags === "-" && width === undefined) ||
3160
+ arg === undefined
3161
+ ) {
3162
+ isFitting = false;
3163
+ return match;
3164
+ }
3165
+ const lower = conversion.toLowerCase();
3166
+ const value =
3167
+ lower === "s" ? arg : lower === "b" ? "true" : (getJavaHashCode(arg) >>> 0).toString(16);
3168
+ const shown = pad(
3169
+ precision === undefined ? value : value.slice(0, Number(precision.slice(1))),
3170
+ );
3171
+ return conversion === lower ? shown : shown.toUpperCase();
3172
+ },
3173
+ );
3174
+ return isFitting ? text : undefined;
3175
+ };
3176
+
3177
+ export const formatState = (state: Record<string, Value>, previous?: Record<string, Value>) => {
3178
+ const getViewText = previous ? undefined : viewTexts.get(state);
3179
+ if (getViewText) return getViewText();
2776
3180
  const entries = Object.entries(state);
3181
+ const alias = aliasNames.get(state);
3182
+ const isFormatted = alias !== undefined && "_format" in state;
3183
+ const format = isFormatted ? state._format : entries.length === 1 ? "%s = %s\n" : "/\\ %s = %s\n";
3184
+ if (typeof format !== "string") {
3185
+ throw new TlaAliasFormatError(
3186
+ `The _format field of the ALIAS ${alias} is ${formatValue(format)}, but it must be a string.`,
3187
+ );
3188
+ }
2777
3189
  return entries
2778
- .map(
2779
- ([name, value]) =>
2780
- `${entries.length === 1 ? "" : "/\\ "}${name} = ${prettyPrint(formatValue(value))}\n`,
2781
- )
3190
+ .filter(([name]) => !(isFormatted && name === "_format"))
3191
+ .filter(([name, value]) => !previous || !isUnchanged(previous[name], value))
3192
+ .map(([name, value]) => {
3193
+ const text = formatJava(format, [name, prettyPrint(formatValue(value))]);
3194
+ if (text === undefined) {
3195
+ throw new TlaAliasFormatError(
3196
+ `The _format field of the ALIAS ${alias} is ${formatValue(format)}, but it must format two strings, the name and the value of a field.`,
3197
+ );
3198
+ }
3199
+ return text;
3200
+ })
2782
3201
  .join("");
2783
3202
  };