tla-ts 0.0.9 → 0.0.10-dev.63a6693bd

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 (400) hide show
  1. package/README.md +29 -1
  2. package/dist/compile.cjs +23 -0
  3. package/dist/compile.js +23 -0
  4. package/dist/deciders.cjs +29 -29
  5. package/dist/deciders.js +42 -42
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +106 -10
  8. package/dist/index.d.ts +106 -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 +117 -37
  15. package/dist/prove.js +116 -36
  16. package/dist/run.cjs +143 -31
  17. package/dist/run.js +143 -31
  18. package/dist/tlapm.cjs +2 -2
  19. package/dist/tlapm.js +2 -2
  20. package/dist/transfer.cjs +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 +3 -1
  25. package/src/ast.ts +48 -62
  26. package/src/bags.ts +99 -102
  27. package/src/builtins.ts +28 -75
  28. package/src/bundled-modules.ts +1 -8
  29. package/src/check-failure.ts +116 -0
  30. package/src/check-trace.ts +282 -0
  31. package/src/check.ts +599 -754
  32. package/src/cli/options.ts +12 -32
  33. package/src/cli/run.ts +0 -2
  34. package/src/cli/runtime-invariants.ts +136 -0
  35. package/src/cli/shared.ts +19 -12
  36. package/src/cli/tlapm.ts +14 -25
  37. package/src/cli/tlc-arguments.ts +652 -0
  38. package/src/cli/tlc-output.ts +687 -0
  39. package/src/cli/tlc-usage.ts +361 -0
  40. package/src/cli/tlc.ts +309 -658
  41. package/src/cli/typescript.ts +23 -0
  42. package/src/cli/xml-exporter.ts +27 -49
  43. package/src/cli.ts +0 -1
  44. package/src/codegen.ts +196 -74
  45. package/src/config.ts +140 -109
  46. package/src/coverage.ts +830 -0
  47. package/src/dependencies.ts +14 -53
  48. package/src/dfid.ts +618 -0
  49. package/src/environment-config.ts +315 -0
  50. package/src/environment.ts +169 -335
  51. package/src/errors.ts +71 -55
  52. package/src/evaluate.ts +598 -340
  53. package/src/exit-codes.ts +37 -3
  54. package/src/fingerprints.ts +75 -11
  55. package/src/index.ts +3 -0
  56. package/src/instances.ts +126 -21
  57. package/src/java-hash.ts +7 -0
  58. package/src/java-overrides.ts +4 -19
  59. package/src/json-reader.ts +455 -0
  60. package/src/json.ts +252 -139
  61. package/src/levels.ts +46 -58
  62. package/src/lexer.ts +80 -100
  63. package/src/liveness-checker.ts +103 -153
  64. package/src/liveness.ts +150 -109
  65. package/src/obligations/action.ts +8 -39
  66. package/src/obligations/anonymize.ts +88 -82
  67. package/src/obligations/equality.ts +1 -1
  68. package/src/obligations/expression.ts +20 -21
  69. package/src/obligations/format.ts +1 -9
  70. package/src/obligations/generate.ts +46 -49
  71. package/src/obligations/index.ts +2 -13
  72. package/src/obligations/levels.ts +4 -8
  73. package/src/obligations/module.ts +28 -53
  74. package/src/obligations/normalize.ts +7 -25
  75. package/src/obligations/operators.ts +1 -2
  76. package/src/obligations/pragma.ts +1 -10
  77. package/src/obligations/printer.ts +47 -46
  78. package/src/obligations/proof.ts +1 -5
  79. package/src/obligations/regroup.ts +1 -4
  80. package/src/obligations/simplify.ts +42 -58
  81. package/src/obligations/source.ts +48 -78
  82. package/src/obligations/subexpression.ts +5 -11
  83. package/src/obligations/substitution.ts +1 -3
  84. package/src/obligations/temporal.ts +13 -19
  85. package/src/obligations/tuples.ts +3 -9
  86. package/src/parallel-worker.ts +30 -60
  87. package/src/parallel.ts +57 -71
  88. package/src/parser.ts +584 -316
  89. package/src/pcal/ast.ts +53 -86
  90. package/src/pcal/parse.ts +144 -219
  91. package/src/pcal/tokenize.ts +91 -131
  92. package/src/pcal/translate.ts +83 -130
  93. package/src/pcal/validate.ts +48 -68
  94. package/src/pretty-print.ts +7 -8
  95. package/src/prover/decide-pool.ts +8 -13
  96. package/src/prover/deciders.ts +3 -7
  97. package/src/prover/first-order.ts +0 -11
  98. package/src/prover/isabelle/decide.ts +0 -6
  99. package/src/prover/isabelle/encode.ts +11 -23
  100. package/src/prover/isabelle/isar/inner-syntax.ts +114 -115
  101. package/src/prover/isabelle/isar/method.ts +29 -53
  102. package/src/prover/isabelle/isar/proof.ts +1 -10
  103. package/src/prover/isabelle/isar/statement.ts +1 -6
  104. package/src/prover/isabelle/isar/theory.ts +26 -36
  105. package/src/prover/isabelle/isar/type-check.ts +17 -31
  106. package/src/prover/isabelle/provers/blast/blast.ts +17 -104
  107. package/src/prover/isabelle/provers/blast/branch.ts +1 -32
  108. package/src/prover/isabelle/provers/blast/prove.ts +1 -35
  109. package/src/prover/isabelle/provers/blast/rules.ts +6 -44
  110. package/src/prover/isabelle/provers/blast/state.ts +2 -28
  111. package/src/prover/isabelle/provers/blast/term.ts +9 -36
  112. package/src/prover/isabelle/provers/clasimp.ts +1 -13
  113. package/src/prover/isabelle/provers/classical.ts +14 -42
  114. package/src/prover/isabelle/provers/hypsubst.ts +28 -51
  115. package/src/prover/isabelle/pure/bicompose.ts +25 -38
  116. package/src/prover/isabelle/pure/consts.ts +1 -7
  117. package/src/prover/isabelle/pure/conv.ts +3 -17
  118. package/src/prover/isabelle/pure/drule.ts +33 -42
  119. package/src/prover/isabelle/pure/envir.ts +3 -52
  120. package/src/prover/isabelle/pure/goal.ts +1 -7
  121. package/src/prover/isabelle/pure/interrupt.ts +0 -5
  122. package/src/prover/isabelle/pure/list.ts +0 -3
  123. package/src/prover/isabelle/pure/logic.ts +2 -15
  124. package/src/prover/isabelle/pure/name.ts +2 -9
  125. package/src/prover/isabelle/pure/net.ts +3 -59
  126. package/src/prover/isabelle/pure/object-logic.ts +3 -10
  127. package/src/prover/isabelle/pure/pattern.ts +2 -19
  128. package/src/prover/isabelle/pure/raw-simplifier.ts +17 -62
  129. package/src/prover/isabelle/pure/rewriter.ts +31 -67
  130. package/src/prover/isabelle/pure/search.ts +3 -10
  131. package/src/prover/isabelle/pure/seq.ts +1 -10
  132. package/src/prover/isabelle/pure/simplifier.ts +4 -12
  133. package/src/prover/isabelle/pure/table.ts +3 -32
  134. package/src/prover/isabelle/pure/tactic.ts +12 -22
  135. package/src/prover/isabelle/pure/tactical.ts +48 -47
  136. package/src/prover/isabelle/pure/term-ord.ts +2 -6
  137. package/src/prover/isabelle/pure/term.ts +2 -43
  138. package/src/prover/isabelle/pure/thm.ts +27 -47
  139. package/src/prover/isabelle/pure/type.ts +2 -15
  140. package/src/prover/isabelle/pure/unify.ts +20 -30
  141. package/src/prover/isabelle/pure/variable.ts +3 -7
  142. package/src/prover/isabelle/tla/classical-setup.ts +17 -24
  143. package/src/prover/isabelle/tla/context.ts +15 -18
  144. package/src/prover/isabelle/tla/logic.ts +14 -32
  145. package/src/prover/isabelle/tla/simpdata.ts +46 -43
  146. package/src/prover/isabelle/tools/intuitionistic.ts +1 -10
  147. package/src/prover/ocaml.ts +0 -6
  148. package/src/prover/prep/action.ts +14 -54
  149. package/src/prover/prep/enabled-axioms.ts +12 -19
  150. package/src/prover/prep/fingerprint.ts +2 -21
  151. package/src/prover/prep/level-comparison.ts +8 -12
  152. package/src/prover/prep/md5.ts +0 -2
  153. package/src/prover/prep/methods.ts +33 -39
  154. package/src/prover/prep/normalize.ts +4 -28
  155. package/src/prover/prove-worker.ts +0 -2
  156. package/src/prover/prove.ts +87 -100
  157. package/src/prover/ptl/decide.ts +7 -12
  158. package/src/prover/ptl/encode.ts +14 -36
  159. package/src/prover/ptl/sat.ts +24 -32
  160. package/src/prover/ptl/tableau.ts +12 -26
  161. package/src/prover/smt/axioms.ts +0 -7
  162. package/src/prover/smt/context.ts +20 -28
  163. package/src/prover/smt/data.ts +433 -424
  164. package/src/prover/smt/encode.ts +43 -52
  165. package/src/prover/smt/extensionality.ts +0 -10
  166. package/src/prover/smt/flatten.ts +3 -22
  167. package/src/prover/smt/format.ts +5 -10
  168. package/src/prover/smt/instances.ts +0 -10
  169. package/src/prover/smt/rewrite.ts +663 -667
  170. package/src/prover/smt/solver/act-cache.ts +0 -15
  171. package/src/prover/smt/solver/arith-rewriter.ts +3 -48
  172. package/src/prover/smt/solver/array.ts +1 -3
  173. package/src/prover/smt/solver/asserted-formulas.ts +1 -43
  174. package/src/prover/smt/solver/ast-lt.ts +1 -11
  175. package/src/prover/smt/solver/ast-util.ts +1 -6
  176. package/src/prover/smt/solver/ast.ts +1 -165
  177. package/src/prover/smt/solver/auf-solver.ts +8 -44
  178. package/src/prover/smt/solver/case-split-queue.ts +1 -9
  179. package/src/prover/smt/solver/cg-table.ts +1 -18
  180. package/src/prover/smt/solver/clause.ts +1 -27
  181. package/src/prover/smt/solver/conflict-resolution.ts +0 -9
  182. package/src/prover/smt/solver/context.ts +7 -64
  183. package/src/prover/smt/solver/ctx-simplify.ts +14 -41
  184. package/src/prover/smt/solver/der.ts +2 -21
  185. package/src/prover/smt/solver/dyn-ack.ts +1 -11
  186. package/src/prover/smt/solver/e-matching.ts +4 -35
  187. package/src/prover/smt/solver/enode.ts +1 -21
  188. package/src/prover/smt/solver/expr-ref.ts +1 -5
  189. package/src/prover/smt/solver/expr-safe-replace.ts +1 -6
  190. package/src/prover/smt/solver/fingerprints.ts +1 -12
  191. package/src/prover/smt/solver/flat-literals.ts +1 -9
  192. package/src/prover/smt/solver/goal.ts +2 -14
  193. package/src/prover/smt/solver/hash.ts +0 -8
  194. package/src/prover/smt/solver/hashtable.ts +1 -12
  195. package/src/prover/smt/solver/internalizer.ts +7 -100
  196. package/src/prover/smt/solver/lbool.ts +1 -2
  197. package/src/prover/smt/solver/literal.ts +0 -3
  198. package/src/prover/smt/solver/lp/bound-propagator.ts +8 -26
  199. package/src/prover/smt/solver/lp/constraints.ts +2 -8
  200. package/src/prover/smt/solver/lp/containers.ts +12 -30
  201. package/src/prover/smt/solver/lp/core-solver.ts +10 -31
  202. package/src/prover/smt/solver/lp/cross-nested.ts +6 -20
  203. package/src/prover/smt/solver/lp/dep-intervals.ts +7 -22
  204. package/src/prover/smt/solver/lp/dependency.ts +1 -4
  205. package/src/prover/smt/solver/lp/dioph-eq.ts +9 -102
  206. package/src/prover/smt/solver/lp/explanation.ts +1 -6
  207. package/src/prover/smt/solver/lp/gomory.ts +9 -22
  208. package/src/prover/smt/solver/lp/hnf-cutter.ts +17 -23
  209. package/src/prover/smt/solver/lp/hnf.ts +11 -26
  210. package/src/prover/smt/solver/lp/int-cube.ts +15 -36
  211. package/src/prover/smt/solver/lp/int-solver.ts +4 -34
  212. package/src/prover/smt/solver/lp/lar-solver.ts +32 -81
  213. package/src/prover/smt/solver/lp/lar-term.ts +1 -5
  214. package/src/prover/smt/solver/lp/lp-settings.ts +1 -14
  215. package/src/prover/smt/solver/lp/maximize-term.ts +20 -45
  216. package/src/prover/smt/solver/lp/nex-creator.ts +5 -28
  217. package/src/prover/smt/solver/lp/nex.ts +1 -6
  218. package/src/prover/smt/solver/lp/nla-backoff.ts +1 -4
  219. package/src/prover/smt/solver/lp/nla-basics.ts +5 -30
  220. package/src/prover/smt/solver/lp/nla-core.ts +36 -135
  221. package/src/prover/smt/solver/lp/nla-divisions.ts +32 -42
  222. package/src/prover/smt/solver/lp/nla-emonics.ts +4 -21
  223. package/src/prover/smt/solver/lp/nla-factorization.ts +1 -4
  224. package/src/prover/smt/solver/lp/nla-grobner.ts +15 -69
  225. package/src/prover/smt/solver/lp/nla-horner.ts +3 -11
  226. package/src/prover/smt/solver/lp/nla-intervals.ts +2 -12
  227. package/src/prover/smt/solver/lp/nla-monomial-bounds.ts +16 -41
  228. package/src/prover/smt/solver/lp/nla-monotone.ts +2 -6
  229. package/src/prover/smt/solver/lp/nla-order.ts +2 -13
  230. package/src/prover/smt/solver/lp/nla-patcher.ts +4 -7
  231. package/src/prover/smt/solver/lp/nla-tangents.ts +1 -9
  232. package/src/prover/smt/solver/lp/nla-throttle.ts +1 -6
  233. package/src/prover/smt/solver/lp/nla-types.ts +1 -11
  234. package/src/prover/smt/solver/lp/nla-var-eqs.ts +4 -25
  235. package/src/prover/smt/solver/lp/nra-solver.ts +5 -52
  236. package/src/prover/smt/solver/lp/numeric-pair.ts +1 -4
  237. package/src/prover/smt/solver/lp/pdd-interval.ts +1 -3
  238. package/src/prover/smt/solver/lp/pdd-simplifier.ts +2 -14
  239. package/src/prover/smt/solver/lp/pdd-solver.ts +4 -33
  240. package/src/prover/smt/solver/lp/pdd.ts +7 -70
  241. package/src/prover/smt/solver/lp/random-updater.ts +1 -8
  242. package/src/prover/smt/solver/lp/static-matrix.ts +9 -19
  243. package/src/prover/smt/solver/lp/union-find.ts +1 -6
  244. package/src/prover/smt/solver/mam-compiler.ts +18 -58
  245. package/src/prover/smt/solver/mam-interpreter.ts +1 -21
  246. package/src/prover/smt/solver/maximize-ac-sharing.ts +2 -17
  247. package/src/prover/smt/solver/model-checker.ts +3 -37
  248. package/src/prover/smt/solver/model-evaluator.ts +3 -29
  249. package/src/prover/smt/solver/model-finder.ts +15 -32
  250. package/src/prover/smt/solver/model-generator.ts +1 -12
  251. package/src/prover/smt/solver/model-macro-solver.ts +23 -88
  252. package/src/prover/smt/solver/nlsat/algebraic.ts +63 -159
  253. package/src/prover/smt/solver/nlsat/atoms.ts +25 -23
  254. package/src/prover/smt/solver/nlsat/evaluator.ts +17 -22
  255. package/src/prover/smt/solver/nlsat/explain.ts +10 -69
  256. package/src/prover/smt/solver/nlsat/interval-set.ts +9 -50
  257. package/src/prover/smt/solver/nlsat/levelwise.ts +49 -135
  258. package/src/prover/smt/solver/nlsat/mpbq.ts +3 -14
  259. package/src/prover/smt/solver/nlsat/polynomial.ts +29 -159
  260. package/src/prover/smt/solver/nlsat/solver.ts +18 -90
  261. package/src/prover/smt/solver/nlsat/types.ts +1 -8
  262. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +2 -45
  263. package/src/prover/smt/solver/nlsat/upolynomial.ts +11 -92
  264. package/src/prover/smt/solver/nnf.ts +3 -38
  265. package/src/prover/smt/solver/pattern-inference.ts +2 -15
  266. package/src/prover/smt/solver/poly-rewriter.ts +3 -23
  267. package/src/prover/smt/solver/propagate-values.ts +1 -10
  268. package/src/prover/smt/solver/proto-model.ts +3 -52
  269. package/src/prover/smt/solver/pull-quant.ts +1 -12
  270. package/src/prover/smt/solver/qe-lite-der.ts +1 -29
  271. package/src/prover/smt/solver/qe-lite-fm.ts +2 -25
  272. package/src/prover/smt/solver/qe-lite.ts +3 -33
  273. package/src/prover/smt/solver/qi-queue.ts +1 -16
  274. package/src/prover/smt/solver/quant-tactics.ts +5 -22
  275. package/src/prover/smt/solver/quantifier-analyzer.ts +27 -47
  276. package/src/prover/smt/solver/quantifier-manager.ts +2 -13
  277. package/src/prover/smt/solver/random-gen.ts +1 -2
  278. package/src/prover/smt/solver/rational.ts +1 -8
  279. package/src/prover/smt/solver/ref-vector.ts +1 -6
  280. package/src/prover/smt/solver/relevancy.ts +2 -15
  281. package/src/prover/smt/solver/rewriter-tpl.ts +3 -147
  282. package/src/prover/smt/solver/rewriter.ts +3 -85
  283. package/src/prover/smt/solver/rlimit.ts +2 -20
  284. package/src/prover/smt/solver/smtlib-parser.ts +80 -131
  285. package/src/prover/smt/solver/solver.ts +23 -34
  286. package/src/prover/smt/solver/sort.ts +1 -5
  287. package/src/prover/smt/solver/sticky-generations.ts +0 -5
  288. package/src/prover/smt/solver/theory-lra-axioms.ts +3 -24
  289. package/src/prover/smt/solver/theory-lra-bounds.ts +1 -7
  290. package/src/prover/smt/solver/theory-lra-final-check.ts +4 -22
  291. package/src/prover/smt/solver/theory-lra-internalize.ts +6 -43
  292. package/src/prover/smt/solver/theory-lra-model.ts +4 -19
  293. package/src/prover/smt/solver/theory-lra-propagate.ts +1 -15
  294. package/src/prover/smt/solver/theory-lra-state.ts +3 -8
  295. package/src/prover/smt/solver/theory-lra.ts +1 -8
  296. package/src/prover/smt/solver/var-subst.ts +2 -26
  297. package/src/prover/smt/table.ts +0 -8
  298. package/src/prover/tlapm/cache.ts +45 -40
  299. package/src/prover/tlapm/ocaml-marshal.ts +19 -21
  300. package/src/prover/tlapm/tlapm.ts +21 -20
  301. package/src/prover/verdict.ts +7 -2
  302. package/src/prover/zenon/check/check.ts +1 -11
  303. package/src/prover/zenon/check/definitions.ts +5 -15
  304. package/src/prover/zenon/check/equality.ts +0 -8
  305. package/src/prover/zenon/check/functions.ts +0 -4
  306. package/src/prover/zenon/check/keys.ts +0 -7
  307. package/src/prover/zenon/check/propositional.ts +0 -3
  308. package/src/prover/zenon/check/records.ts +1 -6
  309. package/src/prover/zenon/check/relations.ts +2 -14
  310. package/src/prover/zenon/check/rewrites.ts +2 -21
  311. package/src/prover/zenon/check/sets.ts +40 -61
  312. package/src/prover/zenon/check/terms.ts +1 -19
  313. package/src/prover/zenon/check/tla.ts +0 -6
  314. package/src/prover/zenon/decide.ts +0 -12
  315. package/src/prover/zenon/encode.ts +1 -8
  316. package/src/prover/zenon/eqrel.ts +2 -13
  317. package/src/prover/zenon/equality-rules.ts +0 -4
  318. package/src/prover/zenon/expr.ts +8 -26
  319. package/src/prover/zenon/index-table.ts +26 -57
  320. package/src/prover/zenon/isar-case.ts +9 -19
  321. package/src/prover/zenon/isar.ts +36 -64
  322. package/src/prover/zenon/limits.ts +0 -4
  323. package/src/prover/zenon/llproof.ts +2 -20
  324. package/src/prover/zenon/mltoll.ts +66 -104
  325. package/src/prover/zenon/node.ts +1 -11
  326. package/src/prover/zenon/ocaml.ts +1 -17
  327. package/src/prover/zenon/parse.ts +4 -12
  328. package/src/prover/zenon/phrase.ts +1 -11
  329. package/src/prover/zenon/proof.ts +0 -9
  330. package/src/prover/zenon/propositional-rules.ts +0 -5
  331. package/src/prover/zenon/rules.ts +2 -6
  332. package/src/prover/zenon/search.ts +5 -31
  333. package/src/prover/zenon/tla/functions.ts +59 -31
  334. package/src/prover/zenon/tla/llproof.ts +67 -76
  335. package/src/prover/zenon/tla/records.ts +57 -33
  336. package/src/prover/zenon/tla/rewrites.ts +12 -19
  337. package/src/prover/zenon/tla/sets.ts +83 -53
  338. package/src/prover/zenon/tla/terms.ts +0 -6
  339. package/src/prover/zenon/tla/tla.ts +66 -64
  340. package/src/randomization.ts +81 -35
  341. package/src/resolve.ts +67 -184
  342. package/src/runtime.ts +22 -22
  343. package/src/sany/builtins.ts +2 -5
  344. package/src/sany/generation.ts +394 -0
  345. package/src/sany/generator-def-entries.ts +210 -0
  346. package/src/sany/generator-definitions.ts +686 -0
  347. package/src/sany/generator-expressions.ts +1100 -0
  348. package/src/sany/generator-proofs.ts +662 -0
  349. package/src/sany/generator.ts +191 -2764
  350. package/src/sany/levels.ts +6 -34
  351. package/src/sany/lexer.ts +58 -77
  352. package/src/sany/linter.ts +1 -9
  353. package/src/sany/modules.ts +1 -5
  354. package/src/sany/nodes.ts +5 -43
  355. package/src/sany/parse-error.ts +39 -117
  356. package/src/sany/report.ts +32 -69
  357. package/src/sany/selectors.ts +49 -76
  358. package/src/sany/source.ts +1 -17
  359. package/src/sany/xml.ts +35 -117
  360. package/src/search.ts +541 -163
  361. package/src/simulate.ts +709 -0
  362. package/src/spec-description.ts +192 -100
  363. package/src/standard-definitions.ts +0 -4
  364. package/src/standard-modules.ts +264 -95
  365. package/src/state-graph.ts +52 -31
  366. package/src/subexpressions.ts +69 -52
  367. package/src/substitution-levels.ts +7 -7
  368. package/src/successors.ts +266 -99
  369. package/src/symmetry.ts +33 -25
  370. package/src/tableau.ts +27 -24
  371. package/src/tlc/fingerprint.ts +183 -67
  372. package/src/tlc/jar-data.ts +112 -6
  373. package/src/tlc/messages.ts +125 -54
  374. package/src/tlc/order.ts +39 -69
  375. package/src/tlc/random.ts +37 -49
  376. package/src/tlc/replay.ts +553 -228
  377. package/src/tlc/summary.ts +36 -47
  378. package/src/tlc/tlc-operators.ts +78 -44
  379. package/src/tlc/tlcext-operators.ts +139 -122
  380. package/src/tlc/trace-spec.ts +249 -0
  381. package/src/tlc/value-stream.ts +139 -0
  382. package/src/tlc/version.ts +1 -4
  383. package/src/transfer.ts +22 -25
  384. package/src/typescript/actions.ts +479 -0
  385. package/src/typescript/collections.ts +614 -0
  386. package/src/typescript/compile.ts +63 -0
  387. package/src/typescript/context.ts +94 -0
  388. package/src/typescript/emit.ts +121 -0
  389. package/src/typescript/expressions.ts +496 -0
  390. package/src/typescript/formula.ts +154 -0
  391. package/src/typescript/functions.ts +284 -0
  392. package/src/typescript/model.ts +162 -0
  393. package/src/typescript/names.ts +114 -0
  394. package/src/typescript/program.ts +48 -0
  395. package/src/typescript/properties.ts +139 -0
  396. package/src/typescript/scope.ts +112 -0
  397. package/src/typescript/steps.ts +167 -0
  398. package/src/typescript/types.ts +171 -0
  399. package/src/values.ts +832 -484
  400. package/src/worker.ts +7 -8
package/src/values.ts CHANGED
@@ -1,5 +1,14 @@
1
- import { TlaEvaluationError } from "./errors";
1
+ import {
2
+ isStackOverflow,
3
+ TlaAliasFormatError,
4
+ TlaEvaluationError,
5
+ TlaFeatureUnsupportedError,
6
+ TlaModuleError,
7
+ TlaSetBoundError,
8
+ } from "./errors";
9
+ import { getJavaHashCode } from "./java-hash";
2
10
  import { prettyPrint } from "./pretty-print";
11
+ import { isEvalException } from "./tlc/messages";
3
12
  import type { TlcVersion } from "./tlc/version";
4
13
 
5
14
  export interface ModelValue {
@@ -11,8 +20,6 @@ export interface ModelValue {
11
20
  fingerprint: number;
12
21
  }
13
22
 
14
- // What TLC keeps on a set it builds lazily: the enumeration it converted to and cached, as
15
- // SetPredValue#convertAndCache does, whether it has cached it, and whether it has fingerprinted it.
16
23
  interface LazySet {
17
24
  enumerated?: SetValue;
18
25
  isCached?: boolean;
@@ -22,13 +29,13 @@ interface LazySet {
22
29
  export interface SetValue {
23
30
  kind: "Set";
24
31
  elements: Value[];
32
+ writtenElements: Value[] | undefined;
33
+ isNormalized: boolean;
25
34
  hash: number;
26
35
  fingerprint: number;
27
36
  isFingerprinted: boolean;
28
37
  }
29
38
 
30
- // A set enumeration whose elements TLC can't sort, such as {1, "a"}. TLC sorts a set enumeration
31
- // only when it has to, so it still checks membership in one element by element.
32
39
  export interface MixedSetValue extends LazySet {
33
40
  kind: "MixedSet";
34
41
  elements: Value[];
@@ -42,6 +49,7 @@ export interface FunctionValue {
42
49
  fingerprint: number;
43
50
  writtenKeys: Value[] | undefined;
44
51
  functionClass: FunctionClass | undefined;
52
+ lambdaDomain: Value | undefined;
45
53
  isFingerprinted: boolean;
46
54
  }
47
55
 
@@ -90,7 +98,6 @@ export interface SetOperationValue extends LazySet {
90
98
  right: Value;
91
99
  }
92
100
 
93
- // TLC prints a set filter as its bound names and the location of its predicate.
94
101
  interface FilteredSetSource {
95
102
  names: string;
96
103
  predicate: string;
@@ -99,11 +106,10 @@ interface FilteredSetSource {
99
106
  export interface FilteredSetValue extends LazySet {
100
107
  kind: "FilteredSet";
101
108
  base: Value;
102
- test: (element: Value) => boolean;
109
+ test: (element: Value, isMember: boolean) => boolean;
103
110
  source?: FilteredSetSource;
104
111
  }
105
112
 
106
- // UNION S when some element of S isn't a set enumeration. TLC enumerates it only when it has to.
107
113
  export interface UnionValue extends LazySet {
108
114
  kind: "Union";
109
115
  base: Value;
@@ -119,12 +125,11 @@ export interface LazyFunctionSource {
119
125
  body: string;
120
126
  }
121
127
 
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
128
  export interface LazyFunctionValue {
125
129
  kind: "LazyFunction";
126
130
  domain: Value;
127
131
  apply: (argument: Value) => Value;
132
+ boundTupleLengths?: (number | undefined)[];
128
133
  source?: LazyFunctionSource;
129
134
  functionClass?: FunctionClass;
130
135
  enumerated?: FunctionValue;
@@ -153,7 +158,6 @@ export type Value =
153
158
 
154
159
  export type ObjectValue = Exclude<Value, boolean | number | string>;
155
160
 
156
- // The sets TLC builds lazily, which it converts and caches as it uses them.
157
161
  type ConvertibleSetValue =
158
162
  | MixedSetValue
159
163
  | SubsetValue
@@ -174,8 +178,39 @@ const isLazySet = (value: ObjectValue): value is ConvertibleSetValue =>
174
178
  value.kind !== "LazyFunction";
175
179
 
176
180
  export const MAXIMUM_INTEGER = 2147483647;
181
+
182
+ const DEFAULT_SET_BOUND = 1000000;
183
+ const VALUE_VEC_CAPACITY = 10;
184
+
185
+ let setBound = DEFAULT_SET_BOUND;
186
+
187
+ export const getSetBound = () => setBound;
188
+
189
+ export const getMaximumSetSize = () => Math.max(setBound, VALUE_VEC_CAPACITY);
190
+
191
+ export const getSetBoundMessage = () =>
192
+ `Attempted to construct a set with too many elements (>${setBound}).`;
193
+
194
+ export const addBoundedElement = (elements: Value[], element: Value) => {
195
+ if (elements.length === getMaximumSetSize()) throw new TlaSetBoundError(getSetBoundMessage());
196
+ elements.push(element);
197
+ };
198
+
199
+ export const isBeyondSetBound = (value: Value): value is IntervalValue =>
200
+ typeof value === "object" &&
201
+ value.kind === "Interval" &&
202
+ value.high - value.low >= getMaximumSetSize();
203
+
204
+ export const forEachElement = (
205
+ elements: IntervalValue | Value[],
206
+ visit: (element: Value) => void,
207
+ ) => {
208
+ if (Array.isArray(elements)) return elements.forEach(visit);
209
+ for (let element = elements.low; element <= elements.high; element++) visit(element);
210
+ };
177
211
  export const MINIMUM_INTEGER = -2147483648;
178
212
  const MAXIMUM_ENUMERATED_SUBSET_BASE = 30;
213
+ const MAXIMUM_BUILT_SUBSET_BASE = 20;
179
214
 
180
215
  export const isSetValue = (value: Value) =>
181
216
  typeof value === "object" &&
@@ -183,8 +218,6 @@ export const isSetValue = (value: Value) =>
183
218
  value.kind !== "Function" &&
184
219
  value.kind !== "LazyFunction";
185
220
 
186
- // TLC's Reducible values, SetEnumValue and IntervalValue, which combine with another set element by
187
- // element.
188
221
  export const isReducibleSet = (value: Value): value is SetValue | MixedSetValue | IntervalValue =>
189
222
  typeof value === "object" &&
190
223
  (value.kind === "Set" || value.kind === "MixedSet" || value.kind === "Interval");
@@ -209,27 +242,33 @@ export const describeKind = (value: Value) => {
209
242
  export const isTlcInteger = (value: number) =>
210
243
  Number.isInteger(value) && value <= MAXIMUM_INTEGER && value >= MINIMUM_INTEGER;
211
244
 
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 };
245
+ let isWrittenOrderUsed = false;
216
246
 
217
247
  const setWrittenOrder = (functionValue: FunctionValue, keys: Value[]) => {
218
- writtenOrderUse.isUsed = true;
248
+ isWrittenOrderUsed = true;
219
249
  functionValue.writtenKeys = keys;
220
250
  return functionValue;
221
251
  };
222
252
 
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
- };
253
+ const getWrittenKeys = (functionValue: FunctionValue) =>
254
+ (functionValue.hash !== 0 || functionValue.fingerprint !== 0
255
+ ? undefined
256
+ : functionValue.writtenKeys) ?? functionValue.domain;
257
+
258
+ export const getWrittenPairs = (functionValue: FunctionValue): [Value, Value][] =>
259
+ getWrittenKeys(functionValue).map((key) => [
260
+ key,
261
+ functionValue.range[functionValue.domain.indexOf(key)],
262
+ ]);
263
+
264
+ export const getPrintedPairs = (functionValue: FunctionValue): [Value, Value][] =>
265
+ functionValue.domain.every((key) => typeof key === "number")
266
+ ? functionValue.domain.map((key, index) => [key, functionValue.range[index]])
267
+ : getWrittenPairs(functionValue);
227
268
 
228
269
  export const createWrittenRecord = (names: Value[], range: Value[], writtenNames: Value[]) =>
229
270
  setWrittenOrder(createSortedRecord(names, range), writtenNames);
230
271
 
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
272
  const forgetWrittenOrder = (value: Value): void => {
234
273
  if (typeof value !== "object" || (value.kind !== "Function" && value.kind !== "Set")) return;
235
274
  if (value.hash !== 0 || value.fingerprint !== 0) return;
@@ -240,13 +279,11 @@ const forgetWrittenOrder = (value: Value): void => {
240
279
 
241
280
  const isRecordDomain = (domain: Value[]) => domain.every((key) => typeof key === "string");
242
281
 
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
282
  const isRecordMismatch = (left: Value[], right: Value[]) =>
246
283
  left.length > 0 && right.length > 0 && isRecordDomain(left) !== isRecordDomain(right);
247
284
 
248
285
  const compareFunctions = (left: FunctionValue, right: FunctionValue) => {
249
- if (writtenOrderUse.isUsed) {
286
+ if (isWrittenOrderUsed) {
250
287
  left.writtenKeys = undefined;
251
288
  right.writtenKeys = undefined;
252
289
  }
@@ -315,26 +352,64 @@ const checkModelValueTypes = (left: Value, right: Value, isEquality: boolean) =>
315
352
  );
316
353
  };
317
354
 
318
- // TLC orders strings and model value names by when it first interned the text, so every
319
- // check sets the order of its spec's strings before it builds any value.
320
- const stringOrder: { ranks: Record<string, number>; size: number } = {
355
+ interface StringOrder {
356
+ ranks: Record<string, number>;
357
+ size: number;
358
+ searchRank: number | undefined;
359
+ unorderedString: string | undefined;
360
+ }
361
+
362
+ const createStringOrder = (): StringOrder => ({
321
363
  ranks: Object.create(null),
322
364
  size: 0,
323
- };
365
+ searchRank: undefined,
366
+ unorderedString: undefined,
367
+ });
368
+
369
+ const stringOrder = createStringOrder();
324
370
 
325
371
  export const setStringOrder = (texts: Iterable<string>) => {
326
- stringOrder.ranks = Object.create(null);
327
- stringOrder.size = 0;
372
+ Object.assign(stringOrder, createStringOrder());
328
373
  modelValues.clear();
329
374
  for (const text of texts) rankString(text);
330
375
  };
331
376
 
332
- // TLC 1.7.4 prints an empty function that isn't a tuple with a space between its brackets, and
333
- // looks a key up in a function differently, so every check also sets the version its values follow.
334
- const valueVersion = { is174: false };
377
+ export const freezeStringOrder = () => {
378
+ stringOrder.searchRank = stringOrder.size;
379
+ };
380
+
381
+ export const getUnorderedString = () => stringOrder.unorderedString;
382
+
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
+ }
335
393
 
336
- export const setValueVersion = (version: TlcVersion | undefined) => {
337
- valueVersion.is174 = version === "1.7.4";
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>();
402
+
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;
338
413
  };
339
414
 
340
415
  export const rankString = (text: string) => {
@@ -342,11 +417,6 @@ export const rankString = (text: string) => {
342
417
  return text;
343
418
  };
344
419
 
345
- export const getRankedStringCount = () => stringOrder.size;
346
-
347
- export const getRankedString = (rank: number) =>
348
- Object.keys(stringOrder.ranks).find((text) => stringOrder.ranks[text] === rank);
349
-
350
420
  export const getStringRank = (text: string) => stringOrder.ranks[rankString(text)];
351
421
 
352
422
  const compareStrings = (left: string, right: string) => {
@@ -354,6 +424,14 @@ const compareStrings = (left: string, right: string) => {
354
424
  const ranks = stringOrder.ranks;
355
425
  const leftRank = ranks[left];
356
426
  const rightRank = ranks[right];
427
+ const searchRank = stringOrder.searchRank;
428
+ if (
429
+ searchRank !== undefined &&
430
+ (leftRank === undefined || leftRank >= searchRank) &&
431
+ (rightRank === undefined || rightRank >= searchRank)
432
+ ) {
433
+ stringOrder.unorderedString ??= left;
434
+ }
357
435
  if (leftRank !== undefined && rightRank !== undefined) return leftRank - rightRank;
358
436
  if (leftRank !== undefined) return -1;
359
437
  if (rightRank !== undefined) return 1;
@@ -372,9 +450,13 @@ const isOverriddenComparison = (left: Value, right: Value) =>
372
450
  right.kind === "SequenceSet"
373
451
  );
374
452
 
375
- // TLC implements Nat, Int, STRING, Seq(S), and Any in Java classes that compare only with each
376
- // other and with model values. Comparing one with any other set is an error, worded by the class of
377
- // the left operand.
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
+
378
460
  const compareOverriddenSets = (
379
461
  left: Value,
380
462
  right: Value,
@@ -385,18 +467,14 @@ const compareOverriddenSets = (
385
467
  `Attempted to ${verb} the set ${formatValue(isEnumerable(left) ? toFiniteSet(left) : left, true)} with the value:\n${formatValue(right, true)}`,
386
468
  );
387
469
  }
388
- if (!isOverriddenSet(right)) {
389
- throw new TlaEvaluationError(
390
- `Attempted to compare overridden value ${formatValue(left, true)} with non-overridden value:\n${formatValue(right, true)}`,
391
- );
392
- }
470
+ if (!isOverriddenSet(right)) throw createComparisonError(left, right);
393
471
  const leftName = left.kind === "InfiniteSet" ? left.name : undefined;
394
472
  const rightName = right.kind === "InfiniteSet" ? right.name : undefined;
395
473
  if (leftName !== undefined && leftName === rightName) return 0;
396
474
  if ((leftName === "Nat" && rightName === "Int") || (leftName === "Int" && rightName === "Nat")) {
397
475
  return leftName === "Nat" ? -1 : 1;
398
476
  }
399
- throw new TlaEvaluationError(
477
+ throw new TlaModuleError(
400
478
  `Attempted to compare ${formatValue(left, true)} with the value\n${formatValue(right, true)}`,
401
479
  );
402
480
  };
@@ -404,13 +482,19 @@ const compareOverriddenSets = (
404
482
  export const ANY_SET: InfiniteSetValue = { kind: "InfiniteSet", name: "Any" };
405
483
 
406
484
  const compareAny = (other: Value): never => {
407
- 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);
408
492
  };
409
493
 
410
494
  export const compareValues = (left: Value, right: Value): number => {
411
495
  if (left === right) {
412
- if (writtenOrderUse.isUsed) forgetWrittenOrder(left);
413
- return left === ANY_SET ? compareAny(left) : 0;
496
+ compareWithItself(left);
497
+ return 0;
414
498
  }
415
499
  if (typeof left === "object" && typeof right === "object") {
416
500
  const leftKind = left.kind;
@@ -438,9 +522,15 @@ export const compareValues = (left: Value, right: Value): number => {
438
522
  }
439
523
  const isLeftSet = isSetValue(left);
440
524
  if (isLeftSet !== isSetValue(right)) {
441
- throw new TlaEvaluationError(
442
- `Attempted to compare ${describeKind(left)} ${formatValue(left)} with ${describeKind(right)} ${formatValue(right)}`,
443
- );
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;
444
534
  }
445
535
  if (isLeftSet) return compareSets(toFiniteSet(left), toFiniteSet(right));
446
536
  return compareFunctions(toFiniteFunction(left), toFiniteFunction(right));
@@ -451,17 +541,21 @@ export const compareValues = (left: Value, right: Value): number => {
451
541
  checkModelValueTypes(left, right, false);
452
542
  if (isModelValue(left)) return -1;
453
543
  if (isModelValue(right)) return 1;
454
- throw new TlaEvaluationError(
455
- `Attempted to compare ${describeKind(left)} ${formatValue(left)} with ${describeKind(right)} ${formatValue(right)}`,
456
- );
544
+ throw createComparisonError(left, right);
457
545
  };
458
546
 
459
547
  const modelValues = new Map<string, ModelValue>();
460
548
 
461
- // setStringOrder clears the model values, so each check ranks and creates its own.
549
+ const MAXIMUM_MODEL_VALUES = 32768;
550
+
462
551
  export const createModelValue = (name: string): ModelValue => {
463
552
  const known = modelValues.get(name);
464
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
+ }
465
559
  const value: ModelValue = {
466
560
  kind: "ModelValue",
467
561
  name,
@@ -474,14 +568,24 @@ export const createModelValue = (name: string): ModelValue => {
474
568
  return value;
475
569
  };
476
570
 
571
+ export const getModelValues = () => [...modelValues.values()];
572
+
477
573
  export const createSortedSet = (elements: Value[]): SetValue => ({
478
574
  kind: "Set",
479
575
  elements,
576
+ writtenElements: undefined,
577
+ isNormalized: false,
480
578
  hash: 0,
481
579
  fingerprint: 0,
482
580
  isFingerprinted: false,
483
581
  });
484
582
 
583
+ export const createNormalizedSet = (elements: Value[]): SetValue => {
584
+ const set = createSortedSet(elements);
585
+ set.isNormalized = true;
586
+ return set;
587
+ };
588
+
485
589
  export const createSortedFunction = (domain: Value[], range: Value[]): FunctionValue => ({
486
590
  kind: "Function",
487
591
  domain,
@@ -490,22 +594,19 @@ export const createSortedFunction = (domain: Value[], range: Value[]): FunctionV
490
594
  fingerprint: 0,
491
595
  writtenKeys: undefined,
492
596
  functionClass: undefined,
597
+ lambdaDomain: undefined,
493
598
  isFingerprinted: false,
494
599
  });
495
600
 
496
- // TLC words a failed function application by the Java class of the function: FcnLambdaValue for
497
- // [x \in S |-> e], TupleValue for <<...>> and what the sequence operators build, RecordValue for
498
- // [a |-> e], and FcnRcdValue for any other function.
499
601
  export type FunctionClass = "lambda" | "tuple" | "record";
500
602
 
501
- // Whether a lambda exists for markFingerprinted to find, so that a spec without one skips the walk.
502
- const lambdaPresence = { isPresent: false };
603
+ let hasLambda = false;
503
604
 
504
605
  export const setFunctionClass = <FunctionLike extends FunctionValue | LazyFunctionValue>(
505
606
  functionValue: FunctionLike,
506
607
  functionClass: FunctionClass | undefined,
507
608
  ) => {
508
- if (functionClass === "lambda") lambdaPresence.isPresent = true;
609
+ if (functionClass === "lambda") hasLambda = true;
509
610
  if (functionClass !== undefined) functionValue.functionClass = functionClass;
510
611
  return functionValue;
511
612
  };
@@ -519,22 +620,17 @@ export const markLambdaFunction = <FunctionLike extends FunctionValue | LazyFunc
519
620
  functionValue: FunctionLike,
520
621
  ) => setFunctionClass(functionValue, "lambda");
521
622
 
522
- // TLC caches a lazy set as the receiver of compareTo, equals, size, and fingerPrint, not as their
523
- // argument, and enumerates the sets an uncached one combines, duplicates and all.
524
623
  const isCachedSet = (value: ObjectValue) => isLazySet(value) && value.isCached === true;
525
624
 
526
- // Whether the spec has built a UNION or \cup set, the sets that stream duplicates, so that a spec
527
- // without one skips tracking what TLC caches.
528
- const streamedSetPresence = { isPresent: false };
625
+ let hasStreamedSet = false;
529
626
 
530
627
  export const markStreamedSet = <Streamed extends UnionValue | SetOperationValue>(
531
628
  value: Streamed,
532
629
  ) => {
533
- streamedSetPresence.isPresent = true;
630
+ hasStreamedSet = true;
534
631
  return value;
535
632
  };
536
633
 
537
- // The sets that stream their elements apart from the normalized set until TLC caches them.
538
634
  const STREAMING_KINDS = new Set<ObjectValue["kind"]>([
539
635
  "Union",
540
636
  "SetOperation",
@@ -546,7 +642,7 @@ const STREAMING_KINDS = new Set<ObjectValue["kind"]>([
546
642
 
547
643
  const cacheSet = (value: Value) => {
548
644
  if (
549
- streamedSetPresence.isPresent &&
645
+ hasStreamedSet &&
550
646
  typeof value === "object" &&
551
647
  isLazySet(value) &&
552
648
  STREAMING_KINDS.has(value.kind)
@@ -555,12 +651,8 @@ const cacheSet = (value: Value) => {
555
651
  }
556
652
  };
557
653
 
558
- // FcnLambdaValue#fingerPrint caches the FcnRcdValue the function enumerates to, which applies it
559
- // from then on, so a function TLC has fingerprinted is no longer a lambda.
560
654
  export const markFingerprinted = (value: Value): void => {
561
- if ((!lambdaPresence.isPresent && !streamedSetPresence.isPresent) || typeof value !== "object") {
562
- return;
563
- }
655
+ if ((!hasLambda && !hasStreamedSet) || typeof value !== "object") return;
564
656
  if (value.kind === "ModelValue" || value.kind === "Interval" || value.kind === "InfiniteSet") {
565
657
  return;
566
658
  }
@@ -581,8 +673,8 @@ export const markFingerprinted = (value: Value): void => {
581
673
  export const valuesEqual = (left: Value, right: Value): boolean => {
582
674
  cacheSet(left);
583
675
  if (left === right) {
584
- if (writtenOrderUse.isUsed) forgetWrittenOrder(left);
585
- return left !== ANY_SET || compareAny(left);
676
+ compareWithItself(left);
677
+ return true;
586
678
  }
587
679
  if (typeof left !== "object" || typeof right !== "object") {
588
680
  if (typeof left === typeof right) return false;
@@ -591,16 +683,17 @@ export const valuesEqual = (left: Value, right: Value): boolean => {
591
683
  }
592
684
  return compareValues(left, right) === 0;
593
685
  }
594
- const isHashed =
595
- (left.kind === "Set" || left.kind === "Function") &&
596
- (right.kind === "Set" || right.kind === "Function") &&
597
- left.hash !== 0 &&
598
- right.hash !== 0;
599
- if (isHashed && left.hash !== right.hash) return false;
600
686
  if (left.kind === "Function" && right.kind === "Function")
601
687
  return compareFunctions(left, right) === 0;
602
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
+ }
603
695
  if (isModelValue(left) || isModelValue(right)) {
696
+ if (left.kind === "LazyFunction") toFiniteFunction(left);
604
697
  checkModelValueTypes(left, right, true);
605
698
  return isModelValue(left) && isModelValue(right) && left.name === right.name;
606
699
  }
@@ -653,8 +746,6 @@ export const valuesEqual = (left: Value, right: Value): boolean => {
653
746
  return compareValues(left, right) === 0;
654
747
  };
655
748
 
656
- // TLC prints and words errors about an equal function by its Java class, so a value can stand for
657
- // another in a state only if each function in it has the same class.
658
749
  const createSameValueCheck = (isClassSensitive: boolean) => {
659
750
  const areSameValues = (left: Value[], right: Value[]) => {
660
751
  if (left === right) return true;
@@ -694,8 +785,6 @@ const canonicalizeElements = (elements: Value[], canonicalize: (value: Value) =>
694
785
  }
695
786
  };
696
787
 
697
- // Replaces each set and function in a state with the first interchangeable one it has seen, so that
698
- // the states it keeps share their values.
699
788
  export const createCanonicalizer = () => {
700
789
  const canonicalValues = new Map<number, Value | Value[]>();
701
790
  const canonicalize = (value: Value): Value => {
@@ -729,21 +818,14 @@ export const createCanonicalizer = () => {
729
818
  };
730
819
  };
731
820
 
732
- // The comparisons above fail with their own messages. These follow the compareTo and equals
733
- // methods of TLC's Java value classes, which word a failure by the class of the left operand, so a
734
- // failed comparison runs again through them to fail as TLC does.
735
821
  interface TlcFunction {
736
822
  domain: Value[];
737
823
  range: Value[];
738
824
  low: number | undefined;
739
825
  }
740
826
 
741
- const getIntervalLow = (domain: Value[]) => {
742
- const first = domain.length === 0 ? 1 : domain[0];
743
- return typeof first === "number" && domain.every((key, index) => key === first + index)
744
- ? first
745
- : undefined;
746
- };
827
+ const getIntervalLow = (value: Value, domain: Value[]) =>
828
+ domain.length === 0 || getFunctionClass(value) === "tuple" ? 1 : getDomainInterval(domain)?.low;
747
829
 
748
830
  const toTlcFunction = (value: Value) => {
749
831
  if (!isFunctionValue(value)) return undefined;
@@ -751,37 +833,21 @@ const toTlcFunction = (value: Value) => {
751
833
  return {
752
834
  domain: functionValue.domain,
753
835
  range: functionValue.range,
754
- low: getIntervalLow(functionValue.domain),
836
+ low: getIntervalLow(value, functionValue.domain),
755
837
  };
756
838
  };
757
839
 
758
840
  const toTlcRecord = (value: Value) => {
759
841
  if (!isFunctionValue(value)) return undefined;
760
842
  const functionValue = toFiniteFunction(value);
761
- return functionValue.domain.every((key) => typeof key === "string") ? functionValue : undefined;
843
+ return isRecordDomain(functionValue.domain) ? functionValue : undefined;
762
844
  };
763
845
 
764
- // A model value compared with a value of another kind. The other value is never a model value.
765
- const compareModelValueWith = (modelValue: ModelValue, other: Value) => {
766
- checkModelValueTypes(other, modelValue, false);
846
+ const compareModelValueWith = (modelValue: ModelValue, other: Value, isEquality: boolean) => {
847
+ checkModelValueTypes(other, modelValue, isEquality);
767
848
  return 1;
768
849
  };
769
850
 
770
- const equalsModelValueWith = (modelValue: ModelValue, other: Value) => {
771
- checkModelValueTypes(other, modelValue, true);
772
- return false;
773
- };
774
-
775
- const compareModelValue = (left: ModelValue, right: Value) => {
776
- if (left.type !== undefined) checkModelValueTypes(left, right, false);
777
- return isModelValue(right) ? left.rank - right.rank : -1;
778
- };
779
-
780
- const equalsModelValue = (left: ModelValue, right: Value) => {
781
- if (left.type !== undefined) checkModelValueTypes(left, right, true);
782
- return isModelValue(right) && left.name === right.name;
783
- };
784
-
785
851
  const SCALAR_KINDS = {
786
852
  number: { name: "integer", other: "non-integer", equality: "check equality of" },
787
853
  string: { name: "string", other: "non-string", equality: "check equality of" },
@@ -800,31 +866,40 @@ const describeScalarMismatch = (
800
866
  return `Attempted to ${isEquality ? kind.equality : "compare"} ${kind.name} ${formatValue(left)} with ${kind.other}:\n${formatValue(right)}`;
801
867
  };
802
868
 
803
- const compareTlcFunctions = (functionValue: TlcFunction, left: Value, right: Value) => {
869
+ const getComparisonVerb = (isEquality: boolean) => (isEquality ? "check equality of" : "compare");
870
+
871
+ const compareTlcFunctions = (
872
+ functionValue: TlcFunction,
873
+ left: Value,
874
+ right: Value,
875
+ isEquality: boolean,
876
+ ) => {
804
877
  const other = toTlcFunction(right);
805
878
  if (!other) {
806
- if (isModelValue(right)) return compareModelValueWith(right, left);
879
+ if (isModelValue(right)) return compareModelValueWith(right, left, isEquality);
807
880
  throw new TlaEvaluationError(
808
- `Attempted to compare the function ${formatValue(left)} with the value:\n${formatValue(right)}`,
881
+ `Attempted to ${getComparisonVerb(isEquality)} the function ${formatValue(left)} with the value:\n${formatValue(right)}`,
809
882
  );
810
883
  }
811
884
  if (functionValue.range.length !== other.range.length)
812
885
  return functionValue.range.length - other.range.length;
813
- const compareRanges = () => compareElementsLikeTlc(functionValue.range, other.range);
886
+ const compareRanges = () => compareElementsLikeTlc(functionValue.range, other.range, isEquality);
814
887
  if (functionValue.low !== undefined && functionValue.range.length === 0) return 0;
815
888
  if (functionValue.low !== undefined && other.low !== undefined) {
816
889
  return functionValue.low === other.low ? compareRanges() : functionValue.low - other.low;
817
890
  }
818
891
  const intervalLow = functionValue.low ?? other.low;
819
892
  if (intervalLow === undefined) {
820
- return compareElementsLikeTlc(functionValue.domain, other.domain) || compareRanges();
893
+ return (
894
+ compareElementsLikeTlc(functionValue.domain, other.domain, isEquality) || compareRanges()
895
+ );
821
896
  }
822
897
  const keys = functionValue.low === undefined ? functionValue.domain : other.domain;
823
898
  for (let index = 0; index < keys.length; index++) {
824
899
  const key = keys[index];
825
900
  if (typeof key !== "number") {
826
901
  throw new TlaEvaluationError(
827
- `Attempted to compare integer with non-integer${functionValue.low === undefined ? "" : ":"}\n${formatValue(key)}.`,
902
+ `Attempted to compare ${isEquality ? "an " : ""}integer with non-integer${isEquality || functionValue.low !== undefined ? ":" : ""}\n${formatValue(key)}.`,
828
903
  );
829
904
  }
830
905
  const difference =
@@ -834,48 +909,50 @@ const compareTlcFunctions = (functionValue: TlcFunction, left: Value, right: Val
834
909
  return compareRanges();
835
910
  };
836
911
 
837
- const compareElementsLikeTlc = (left: Value[], right: Value[]) => {
912
+ const compareElementsLikeTlc = (left: Value[], right: Value[], isEquality: boolean) => {
838
913
  for (let index = 0; index < left.length; index++) {
839
- const comparison = compareLikeTlc(left[index], right[index]);
914
+ const comparison = compareOrEqualLikeTlc(left[index], right[index], isEquality);
840
915
  if (comparison !== 0) return comparison;
841
916
  }
842
917
  return 0;
843
918
  };
844
919
 
845
- const compareFunctionLikeTlc = (left: FunctionValue | LazyFunctionValue, right: Value) => {
920
+ const compareFunctionLikeTlc = (
921
+ left: FunctionValue | LazyFunctionValue,
922
+ right: Value,
923
+ isEquality: boolean,
924
+ ) => {
846
925
  const functionValue = toFiniteFunction(left);
847
- const isTuple = left.kind === "Function" && getSequenceElements(functionValue) !== undefined;
848
- if (isTuple) {
926
+ if (getFunctionClass(left) === "tuple") {
849
927
  const tuple = isFunctionValue(right) ? getSequenceElements(right) : undefined;
850
- if (!tuple) return compareTlcFunctions({ ...functionValue, low: 1 }, left, right);
928
+ if (!tuple) return compareTlcFunctions({ ...functionValue, low: 1 }, left, right, isEquality);
851
929
  return (
852
930
  functionValue.range.length - tuple.length ||
853
- compareElementsLikeTlc(functionValue.range, tuple)
931
+ compareElementsLikeTlc(functionValue.range, tuple, isEquality)
854
932
  );
855
933
  }
856
934
  if (getFunctionClass(left) === "record") {
857
935
  const record = toTlcRecord(right);
858
936
  if (!record) {
859
- if (isModelValue(right)) return compareModelValueWith(right, left);
937
+ if (isModelValue(right)) return compareModelValueWith(right, left, isEquality);
860
938
  throw new TlaEvaluationError(
861
- `Attempted to compare record:\n${formatValue(left)}\nwith non-record\n${formatValue(right)}`,
939
+ `Attempted to ${getComparisonVerb(isEquality)} record:\n${formatValue(left)}\nwith non-record\n${formatValue(right)}`,
862
940
  );
863
941
  }
864
942
  return (
865
943
  functionValue.domain.length - record.domain.length ||
866
- compareElementsLikeTlc(functionValue.domain, record.domain) ||
867
- compareElementsLikeTlc(functionValue.range, record.range)
944
+ compareElementsLikeTlc(functionValue.domain, record.domain, isEquality) ||
945
+ compareElementsLikeTlc(functionValue.range, record.range, isEquality)
868
946
  );
869
947
  }
870
948
  return compareTlcFunctions(
871
- { ...functionValue, low: getIntervalLow(functionValue.domain) },
949
+ { ...functionValue, low: getIntervalLow(left, functionValue.domain) },
872
950
  left,
873
951
  right,
952
+ isEquality,
874
953
  );
875
954
  };
876
955
 
877
- // TLC compares a lazy set, or a set it overrides in Java, through its own class before it compares
878
- // elements. The comparisons above already fail as those classes do.
879
956
  const isComparedByClass = (left: ObjectValue, right: Value) =>
880
957
  isOverriddenSet(left) ||
881
958
  isOverriddenSet(right) ||
@@ -892,131 +969,48 @@ const getSetElementsLikeTlc = (left: SetValue | MixedSetValue, right: Value) =>
892
969
  return { elements: toFiniteSet(left).elements, otherElements: toFiniteSet(other).elements };
893
970
  };
894
971
 
895
- const compareSetLikeTlc = (left: ObjectValue, right: Value): number => {
896
- if (isComparedByClass(left, right)) return compareValues(left, right);
897
- if (!isEnumeratedSet(left)) return compareSetLikeTlc(toFiniteSet(left), right);
972
+ const compareSetLikeTlc = (left: ObjectValue, right: Value, isEquality: boolean): number => {
973
+ if (isComparedByClass(left, right)) {
974
+ if (!isEquality) return compareValues(left, right);
975
+ return valuesEqual(left, right) ? 0 : 1;
976
+ }
977
+ if (!isEnumeratedSet(left)) return compareSetLikeTlc(toFiniteSet(left), right, isEquality);
898
978
  if (!isSetValue(right)) {
899
- if (isModelValue(right)) return compareModelValueWith(right, left);
979
+ if (isModelValue(right)) return compareModelValueWith(right, left, isEquality);
900
980
  throw new TlaEvaluationError(
901
- `Attempted to compare the set ${formatValue(left)} with the value:\n${formatValue(right)}`,
981
+ `Attempted to ${getComparisonVerb(isEquality)} the set ${formatValue(left)} with the value:\n${formatValue(right)}`,
902
982
  );
903
983
  }
904
984
  const sets = getSetElementsLikeTlc(left, right);
905
985
  return (
906
986
  sets.elements.length - sets.otherElements.length ||
907
- compareElementsLikeTlc(sets.elements, sets.otherElements)
987
+ compareElementsLikeTlc(sets.elements, sets.otherElements, isEquality)
908
988
  );
909
989
  };
910
990
 
911
- const compareLikeTlc = (left: Value, right: Value): number => {
991
+ const compareOrEqualLikeTlc = (left: Value, right: Value, isEquality: boolean): number => {
912
992
  if (typeof left !== "object") {
913
- if (typeof right === typeof left) return compareValues(left, right);
914
- if (isModelValue(right)) return compareModelValueWith(right, left);
915
- throw new TlaEvaluationError(describeScalarMismatch(left, right, false));
916
- }
917
- if (left.kind === "ModelValue") return compareModelValue(left, right);
918
- if (isFunctionValue(left)) return compareFunctionLikeTlc(left, right);
919
- return compareSetLikeTlc(left, right);
920
- };
921
-
922
- const equalsElementsLikeTlc = (left: Value[], right: Value[]) =>
923
- left.every((element, index) => equalsLikeTlc(element, right[index]));
924
-
925
- const equalsTlcFunctions = (functionValue: TlcFunction, left: Value, right: Value) => {
926
- const other = toTlcFunction(right);
927
- if (!other) {
928
- if (isModelValue(right)) return equalsModelValueWith(right, left);
929
- throw new TlaEvaluationError(
930
- `Attempted to check equality of the function ${formatValue(left)} with the value:\n${formatValue(right)}`,
931
- );
932
- }
933
- if (functionValue.range.length !== other.range.length) return false;
934
- if (functionValue.low !== undefined && other.low !== undefined) {
935
- return (
936
- (functionValue.range.length === 0 || functionValue.low === other.low) &&
937
- equalsElementsLikeTlc(functionValue.range, other.range)
938
- );
939
- }
940
- const intervalLow = functionValue.low ?? other.low;
941
- if (intervalLow === undefined) {
942
- return (
943
- equalsElementsLikeTlc(functionValue.domain, other.domain) &&
944
- equalsElementsLikeTlc(functionValue.range, other.range)
945
- );
946
- }
947
- const keys = functionValue.low === undefined ? functionValue.domain : other.domain;
948
- return (
949
- keys.every((key, index) => {
950
- if (typeof key !== "number") {
951
- throw new TlaEvaluationError(
952
- `Attempted to compare an integer with non-integer:\n${formatValue(key)}.`,
953
- );
954
- }
955
- return key === intervalLow + index;
956
- }) && equalsElementsLikeTlc(functionValue.range, other.range)
957
- );
958
- };
959
-
960
- const equalsFunctionLikeTlc = (left: FunctionValue | LazyFunctionValue, right: Value) => {
961
- const functionValue = toFiniteFunction(left);
962
- const isTuple = left.kind === "Function" && getSequenceElements(functionValue) !== undefined;
963
- if (isTuple) {
964
- const tuple = isFunctionValue(right) ? getSequenceElements(right) : undefined;
965
- if (!tuple) return equalsTlcFunctions({ ...functionValue, low: 1 }, left, right);
966
- return (
967
- functionValue.range.length === tuple.length &&
968
- equalsElementsLikeTlc(functionValue.range, tuple)
969
- );
970
- }
971
- if (getFunctionClass(left) === "record") {
972
- const record = toTlcRecord(right);
973
- if (!record) {
974
- if (isModelValue(right)) return equalsModelValueWith(right, left);
975
- throw new TlaEvaluationError(
976
- `Attempted to check equality of record:\n${formatValue(left)}\nwith non-record\n${formatValue(right)}`,
977
- );
993
+ if (typeof right === typeof left) {
994
+ if (!isEquality) return compareValues(left, right);
995
+ return left === right ? 0 : 1;
978
996
  }
979
- return (
980
- functionValue.domain.length === record.domain.length &&
981
- equalsElementsLikeTlc(functionValue.domain, record.domain) &&
982
- equalsElementsLikeTlc(functionValue.range, record.range)
983
- );
997
+ if (isModelValue(right)) return compareModelValueWith(right, left, isEquality);
998
+ throw new TlaEvaluationError(describeScalarMismatch(left, right, isEquality));
984
999
  }
985
- return equalsTlcFunctions(
986
- { ...functionValue, low: getIntervalLow(functionValue.domain) },
987
- left,
988
- right,
989
- );
990
- };
991
-
992
- const equalsSetLikeTlc = (left: ObjectValue, right: Value): boolean => {
993
- if (isComparedByClass(left, right)) return valuesEqual(left, right);
994
- if (!isEnumeratedSet(left)) return equalsSetLikeTlc(toFiniteSet(left), right);
995
- if (!isSetValue(right)) {
996
- if (isModelValue(right)) return equalsModelValueWith(right, left);
997
- throw new TlaEvaluationError(
998
- `Attempted to check equality of the set ${formatValue(left)} with the value:\n${formatValue(right)}`,
999
- );
1000
+ if (left.kind === "ModelValue") {
1001
+ if (left.type !== undefined) checkModelValueTypes(left, right, isEquality);
1002
+ if (!isModelValue(right)) return -1;
1003
+ if (!isEquality) return left.rank - right.rank;
1004
+ return left.name === right.name ? 0 : 1;
1000
1005
  }
1001
- const sets = getSetElementsLikeTlc(left, right);
1002
- return (
1003
- sets.elements.length === sets.otherElements.length &&
1004
- equalsElementsLikeTlc(sets.elements, sets.otherElements)
1005
- );
1006
+ if (isFunctionValue(left)) return compareFunctionLikeTlc(left, right, isEquality);
1007
+ return compareSetLikeTlc(left, right, isEquality);
1006
1008
  };
1007
1009
 
1008
- const equalsLikeTlc = (left: Value, right: Value): boolean => {
1009
- if (typeof left !== "object") {
1010
- if (typeof right === typeof left) return left === right;
1011
- if (isModelValue(right)) return equalsModelValueWith(right, left);
1012
- throw new TlaEvaluationError(describeScalarMismatch(left, right, true));
1013
- }
1014
- if (left.kind === "ModelValue") return equalsModelValue(left, right);
1015
- if (isFunctionValue(left)) return equalsFunctionLikeTlc(left, right);
1016
- return equalsSetLikeTlc(left, right);
1017
- };
1010
+ const compareLikeTlc = (left: Value, right: Value) => compareOrEqualLikeTlc(left, right, false);
1011
+
1012
+ const equalsLikeTlc = (left: Value, right: Value) => compareOrEqualLikeTlc(left, right, true) === 0;
1018
1013
 
1019
- // TLC's ValueVec.sort, which inserts each element into the sorted prefix by binary search.
1020
1014
  const sortLikeTlc = (elements: Value[]) => {
1021
1015
  const sorted: Value[] = [];
1022
1016
  for (const element of elements) {
@@ -1026,7 +1020,6 @@ const sortLikeTlc = (elements: Value[]) => {
1026
1020
  return sorted;
1027
1021
  };
1028
1022
 
1029
- // Calls a method of a value as TLC does, whose failure the value heads when it has a source.
1030
1023
  const callTracedMethod = <Result>(receiver: Value, method: () => Result) => {
1031
1024
  const sets = setTrace.sets;
1032
1025
  if (sets === undefined) return method();
@@ -1036,35 +1029,31 @@ const callTracedMethod = <Result>(receiver: Value, method: () => Result) => {
1036
1029
  return result;
1037
1030
  };
1038
1031
 
1039
- // ValueVec.search on sorted elements: a binary search with compareTo, which ends where the element
1040
- // is or would go.
1041
1032
  const searchLikeTlc = (element: Value, sorted: Value[]) => {
1042
- const bounds = { low: 0, high: sorted.length };
1043
- while (bounds.low < bounds.high) {
1044
- const middle = bounds.low + ((bounds.high - bounds.low) >> 1);
1033
+ let low = 0;
1034
+ let high = sorted.length;
1035
+ while (low < high) {
1036
+ const middle = low + ((high - low) >> 1);
1045
1037
  const comparison = callTracedMethod(element, () => compareLikeTlc(element, sorted[middle]));
1046
1038
  if (comparison === 0) return { index: middle, isFound: true };
1047
- if (comparison < 0) bounds.high = middle;
1048
- else bounds.low = middle + 1;
1039
+ if (comparison < 0) high = middle;
1040
+ else low = middle + 1;
1049
1041
  }
1050
- return { index: bounds.low, isFound: false };
1042
+ return { index: low, isFound: false };
1051
1043
  };
1052
1044
 
1053
- // TLC checks membership in a set enumeration it hasn't sorted element by element, with the equals
1054
- // method of each member.
1055
1045
  const isElementOfLikeTlc = (element: Value, elements: Value[]) =>
1056
1046
  elements.some((member) => callTracedMethod(member, () => equalsLikeTlc(member, element)));
1057
1047
 
1058
- // The sets TLC has normalized, whose membership ValueVec.search checks by binary search with
1059
- // compareTo instead of element by element.
1060
- const normalizedSets = new WeakSet<SetValue>();
1048
+ export const getWrittenElements = (set: SetValue | MixedSetValue) =>
1049
+ set.kind === "MixedSet" || set.isNormalized
1050
+ ? set.elements
1051
+ : (set.writtenElements ?? set.elements);
1061
1052
 
1062
- // IValue.deepNormalize, which TLC applies to the constants of the config and the constant
1063
- // definitions it computes as it starts.
1064
1053
  export const markNormalized = (value: Value): void => {
1065
1054
  if (typeof value !== "object") return;
1066
1055
  if (value.kind === "Set") {
1067
- normalizedSets.add(value);
1056
+ value.isNormalized = true;
1068
1057
  value.elements.forEach(markNormalized);
1069
1058
  }
1070
1059
  if (value.kind === "Function") {
@@ -1073,6 +1062,32 @@ export const markNormalized = (value: Value): void => {
1073
1062
  }
1074
1063
  };
1075
1064
 
1065
+ export const normalizeShallowly = (value: Value): void => {
1066
+ if (typeof value !== "object" || isCachedSet(value)) return;
1067
+ switch (value.kind) {
1068
+ case "Set":
1069
+ value.isNormalized = true;
1070
+ return;
1071
+ case "MixedSet":
1072
+ toFiniteSet(value);
1073
+ return;
1074
+ case "FilteredSet":
1075
+ case "Subset":
1076
+ return normalizeShallowly(value.base);
1077
+ case "SetOperation":
1078
+ if (value.operator === "\\cup") return;
1079
+ normalizeShallowly(value.left);
1080
+ return normalizeShallowly(value.right);
1081
+ case "FunctionSet":
1082
+ normalizeShallowly(value.domain);
1083
+ return normalizeShallowly(value.range);
1084
+ case "RecordSet":
1085
+ return value.sets.forEach(normalizeShallowly);
1086
+ case "ProductSet":
1087
+ return value.factors.forEach(normalizeShallowly);
1088
+ }
1089
+ };
1090
+
1076
1091
  export const isEqualLikeTlc = (left: Value, right: Value) =>
1077
1092
  computeLikeTlcOnFailure(valuesEqual, equalsLikeTlc, left, right);
1078
1093
 
@@ -1083,8 +1098,18 @@ const isStrictlySorted = (elements: Value[]) => {
1083
1098
  return true;
1084
1099
  };
1085
1100
 
1101
+ const isAscendingIntegers = (elements: Value[]) => {
1102
+ for (let index = 0; index < elements.length; index++) {
1103
+ const element = elements[index];
1104
+ const previous = index > 0 ? elements[index - 1] : undefined;
1105
+ if (typeof element !== "number" || (typeof previous === "number" && previous >= element)) {
1106
+ return false;
1107
+ }
1108
+ }
1109
+ return true;
1110
+ };
1111
+
1086
1112
  export const createSet = (elements: Value[]): SetValue => {
1087
- // ValueVec.sort compares each element after the first with those before it.
1088
1113
  for (let index = 1; index < elements.length; index++) cacheSet(elements[index]);
1089
1114
  if (elements.length < 2 || isStrictlySorted(elements)) return createSortedSet(elements);
1090
1115
  const sorted = [...elements].sort(compareValues);
@@ -1095,15 +1120,17 @@ export const createSet = (elements: Value[]): SetValue => {
1095
1120
  return createSortedSet(unique);
1096
1121
  };
1097
1122
 
1098
- // TLC builds a set enumeration without sorting it, so one whose elements it can't compare still
1099
- // evaluates.
1100
- export const createEnumeratedSet = (elements: Value[]): SetValue | MixedSetValue =>
1101
- computeLikeTlcOnFailure<Value[], undefined, SetValue | MixedSetValue>(
1123
+ export const createEnumeratedSet = (elements: Value[]): SetValue | MixedSetValue => {
1124
+ if (isAscendingIntegers(elements)) return createSortedSet(elements);
1125
+ const set = computeLikeTlcOnFailure<Value[], undefined, SetValue | MixedSetValue>(
1102
1126
  createSet,
1103
1127
  (mixed) => ({ kind: "MixedSet", elements: mixed }),
1104
1128
  elements,
1105
1129
  undefined,
1106
1130
  );
1131
+ if (set.kind === "Set" && set.elements !== elements) set.writtenElements = elements;
1132
+ return set;
1133
+ };
1107
1134
 
1108
1135
  export const EMPTY_SET = createSortedSet([]);
1109
1136
 
@@ -1219,7 +1246,6 @@ export const createWrittenFunction = (pairs: [Value, Value][]) => {
1219
1246
  const functionValue = createFunction(pairs);
1220
1247
  const isWrittenSorted =
1221
1248
  functionValue.domain.length !== pairs.length ||
1222
- pairs.some((pair) => typeof pair[0] !== "string") ||
1223
1249
  pairs.every((pair, index) => pair[0] === functionValue.domain[index]);
1224
1250
  return isWrittenSorted
1225
1251
  ? functionValue
@@ -1229,23 +1255,21 @@ export const createWrittenFunction = (pairs: [Value, Value][]) => {
1229
1255
  );
1230
1256
  };
1231
1257
 
1258
+ const MAX_SHARED_INTERVAL_LENGTH = 1024;
1232
1259
  const intervalDomains: Value[][] = [];
1260
+ const longIntervalDomains = new Map<number, WeakRef<Value[]>>();
1233
1261
  const intervalValues: IntervalValue[] = [];
1234
1262
  const intervalArrays = new WeakMap<Value[], IntervalValue>();
1235
1263
 
1236
- // TLC keeps the domain of a tuple, or of a function built over an interval, as an interval. Every
1237
- // function over 1..n shares one domain array per length, and the elements of any other interval
1238
- // map to it, so the array's identity records it. Callers must not mutate the returned array.
1239
1264
  const getIntervalDomain = (length: number): Value[] => {
1240
- const cached = intervalDomains[length];
1265
+ const cached = intervalDomains[length] ?? longIntervalDomains.get(length)?.deref();
1241
1266
  if (cached) return cached;
1242
- const domain = Array.from({ length }, (_, index) => index + 1);
1243
- intervalDomains[length] = domain;
1267
+ const domain = Array.from({ length }, (_value, index) => index + 1);
1268
+ if (length > MAX_SHARED_INTERVAL_LENGTH) longIntervalDomains.set(length, new WeakRef(domain));
1269
+ else intervalDomains[length] = domain;
1244
1270
  return domain;
1245
1271
  };
1246
1272
 
1247
- // The elements of an interval for a caller that only iterates them, so they need not record
1248
- // the interval for DOMAIN.
1249
1273
  export const getIntervalElements = (value: IntervalValue): Value[] => {
1250
1274
  getCardinality(value);
1251
1275
  if (value.low === 1 && value.high >= 1) return getIntervalDomain(value.high);
@@ -1255,10 +1279,11 @@ export const getIntervalElements = (value: IntervalValue): Value[] => {
1255
1279
  };
1256
1280
 
1257
1281
  const isIntervalDomain = (domain: Value[]) =>
1258
- domain.length > 0 && (domain === intervalDomains[domain.length] || intervalArrays.has(domain));
1282
+ (domain.length > 0 &&
1283
+ (domain === intervalDomains[domain.length] ||
1284
+ domain === longIntervalDomains.get(domain.length)?.deref())) ||
1285
+ intervalArrays.has(domain);
1259
1286
 
1260
- // TLC keeps an interval domain only for a function built over an interval itself, so a set
1261
- // such as (1..2) \cap S, whose elements are the shared array, gets a copy.
1262
1287
  export const getFunctionDomain = (set: Value): Value[] => {
1263
1288
  const elements = toFiniteSet(set).elements;
1264
1289
  return isIntervalDomain(elements) && !(typeof set === "object" && set.kind === "Interval")
@@ -1283,7 +1308,6 @@ export const createRecord = (fields: [string, Value][]): FunctionValue =>
1283
1308
  export const createSortedRecord = (names: Value[], range: Value[]) =>
1284
1309
  setFunctionClass(createSortedFunction(names, range), "record");
1285
1310
 
1286
- // TLC's Enumerable classes: every set except the ones it implements in Java.
1287
1311
  export const isTlcEnumerable = (value: Value) => isSetValue(value) && !isOverriddenSet(value);
1288
1312
 
1289
1313
  const formatUnion = (value: UnionValue, isStrict = false) =>
@@ -1334,7 +1358,13 @@ export const isEnumerable = (value: Value): boolean => {
1334
1358
  case "ProductSet":
1335
1359
  return value.factors.every(isEnumerable) || getEmptiness(value) === true;
1336
1360
  case "Union":
1337
- return isEnumerable(value.base) && getStreamedElements(value.base).every(isEnumerable);
1361
+ return (
1362
+ isEnumerable(value.base) &&
1363
+ (isEnumeratedSet(value.base)
1364
+ ? getWrittenElements(value.base)
1365
+ : getStreamedElements(value.base)
1366
+ ).every(isEnumerable)
1367
+ );
1338
1368
  case "SetOperation":
1339
1369
  if (value.operator === "\\cup") return isEnumerable(value.left) && isEnumerable(value.right);
1340
1370
  if (value.operator === "\\cap") return isEnumerable(value.left) || isEnumerable(value.right);
@@ -1407,26 +1437,24 @@ const advanceCombination = (indices: number[], length: number) => {
1407
1437
  return false;
1408
1438
  };
1409
1439
 
1410
- // TLC enumerates SUBSET S lazily, by size and then in the order of S, so a quantifier that finds
1411
- // its witness early never builds the rest. For a power set too large to build, the elements are
1412
- // computed in that order as a loop reads them.
1413
1440
  export const getLazySubsets = (value: Value): Value[] | undefined => {
1414
1441
  if (typeof value !== "object" || value.kind !== "Subset" || isOverriddenSet(value.base)) {
1415
1442
  return undefined;
1416
1443
  }
1417
1444
  const base = toFiniteSet(value.base).elements;
1418
- if (base.length <= MAXIMUM_ENUMERATED_SUBSET_BASE) return undefined;
1419
- const cursor = { index: -1, indices: [0] };
1445
+ if (base.length <= MAXIMUM_BUILT_SUBSET_BASE) return undefined;
1446
+ let cursorIndex = -1;
1447
+ let indices = [0];
1420
1448
  const getSubset = (index: number) => {
1421
- if (index <= cursor.index) cursor.index = -1;
1422
- while (cursor.index < index) {
1423
- if (cursor.index === -1) cursor.indices = [];
1424
- else if (!advanceCombination(cursor.indices, base.length)) {
1425
- cursor.indices = Array.from({ length: cursor.indices.length + 1 }, (_, item) => item);
1449
+ if (index <= cursorIndex) cursorIndex = -1;
1450
+ while (cursorIndex < index) {
1451
+ if (cursorIndex === -1) indices = [];
1452
+ else if (!advanceCombination(indices, base.length)) {
1453
+ indices = Array.from({ length: indices.length + 1 }, (_value, position) => position);
1426
1454
  }
1427
- cursor.index++;
1455
+ cursorIndex++;
1428
1456
  }
1429
- return createSortedSet(cursor.indices.map((item) => base[item]));
1457
+ return createSortedSet(indices.map((baseIndex) => base[baseIndex]));
1430
1458
  };
1431
1459
  const length = 2 ** base.length;
1432
1460
  const isIndex = (property: string | symbol) =>
@@ -1445,7 +1473,7 @@ export const getLazySubsets = (value: Value): Value[] | undefined => {
1445
1473
  const getSortedSubsets = (base: Value[]) => {
1446
1474
  const subsets: Value[] = [];
1447
1475
  for (let size = 0; size <= base.length; size++) {
1448
- const indices = Array.from({ length: size }, (_, index) => index);
1476
+ const indices = Array.from({ length: size }, (_value, index) => index);
1449
1477
  do {
1450
1478
  subsets.push(createSortedSet(indices.map((index) => base[index])));
1451
1479
  } while (advanceCombination(indices, base.length));
@@ -1453,9 +1481,6 @@ const getSortedSubsets = (base: Value[]) => {
1453
1481
  return subsets;
1454
1482
  };
1455
1483
 
1456
- // The Enumerator of a set of records or tuples enumerates its sets in turn and stops at the first
1457
- // empty one, which leaves the product empty. Later versions of TLC decide that the set is empty
1458
- // before they enumerate it.
1459
1484
  const getComponentElements = (
1460
1485
  sets: Value[],
1461
1486
  getElements: (set: Value) => Value[],
@@ -1472,7 +1497,6 @@ const getComponentElements = (
1472
1497
  return lists;
1473
1498
  };
1474
1499
 
1475
- // getElements enumerates the sets a set of functions, records, or tuples combines.
1476
1500
  const enumerateSet = (
1477
1501
  value: Value,
1478
1502
  getElements = (set: Value) => toFiniteSet(set).elements,
@@ -1490,8 +1514,6 @@ const enumerateSet = (
1490
1514
  return elements;
1491
1515
  }
1492
1516
  case "Subset": {
1493
- // SubsetValue.toSetEnum sizes the set before it enumerates it, and enumerates only the empty
1494
- // set of a value of size 0, a function with an empty domain among them.
1495
1517
  if (getCardinality(value.base) === 0) return getSortedSubsets([]);
1496
1518
  if (!isSetValue(value.base)) {
1497
1519
  throw new TlaEvaluationError(
@@ -1505,15 +1527,14 @@ const enumerateSet = (
1505
1527
  return getSortedSubsets(base);
1506
1528
  }
1507
1529
  case "FunctionSet": {
1508
- if (!valueVersion.is174 && isEmptySet(value)) return [];
1530
+ if (!isVersion174 && isEmptySet(value)) return [];
1509
1531
  if (isOverriddenSet(value.domain)) {
1510
1532
  throw new TlaEvaluationError(
1511
1533
  `Attempted to enumerate a set of the form [D -> R],but the domain D:\n${formatValue(value.domain)}\ncannot be enumerated.`,
1512
1534
  );
1513
1535
  }
1514
1536
  const domain = getFunctionDomain(value.domain);
1515
- // TLC 1.7.4 requires an enumerable range even of an empty domain.
1516
- if ((domain.length > 0 || valueVersion.is174) && isOverriddenSet(value.range)) {
1537
+ if ((domain.length > 0 || isVersion174) && isOverriddenSet(value.range)) {
1517
1538
  throw new TlaEvaluationError(
1518
1539
  `Attempted to enumerate a set of the form [D -> R],but the range R:\n${formatValue(value.range)}\ncannot be enumerated.`,
1519
1540
  );
@@ -1524,7 +1545,7 @@ const enumerateSet = (
1524
1545
  );
1525
1546
  }
1526
1547
  case "RecordSet": {
1527
- if (!valueVersion.is174 && isEmptySet(value)) return [];
1548
+ if (!isVersion174 && isEmptySet(value)) return [];
1528
1549
  const fields = getComponentElements(
1529
1550
  value.sets,
1530
1551
  getElements,
@@ -1536,7 +1557,7 @@ const enumerateSet = (
1536
1557
  );
1537
1558
  }
1538
1559
  case "ProductSet": {
1539
- if (!valueVersion.is174 && isEmptySet(value)) return [];
1560
+ if (!isVersion174 && isEmptySet(value)) return [];
1540
1561
  const factors = getComponentElements(
1541
1562
  value.factors,
1542
1563
  getElements,
@@ -1551,22 +1572,21 @@ const enumerateSet = (
1551
1572
  `Attempted to enumerate { x \\in S : p(x) } when S:\n${formatValue(value.base)}\nis not enumerable`,
1552
1573
  );
1553
1574
  }
1554
- return toFiniteSet(value.base).elements.filter(value.test);
1575
+ return toFiniteSet(
1576
+ createEnumeratedSet(
1577
+ getStreamedElements(value.base).filter((element) => value.test(element, false)),
1578
+ ),
1579
+ ).elements;
1555
1580
  case "Union": {
1556
- const elements = getUnionSets(value).flatMap(
1557
- (set, index) => toFiniteSet(getUnionSet(set, index, value)).elements,
1558
- );
1581
+ const elements: Value[] = [];
1582
+ getUnionSets(value).forEach((set, index) => {
1583
+ const unionSet = getUnionSet(set, index, value);
1584
+ if (isBeyondSetBound(unionSet)) throw new TlaSetBoundError(getSetBoundMessage());
1585
+ getStreamedElements(unionSet).forEach((element) => addBoundedElement(elements, element));
1586
+ });
1559
1587
  return toFiniteSet(createEnumeratedSet(elements)).elements;
1560
1588
  }
1561
1589
  case "SetOperation": {
1562
- if (
1563
- value.operator === "\\cup" &&
1564
- (!isTlcEnumerable(value.left) || !isTlcEnumerable(value.right))
1565
- ) {
1566
- throw new TlaEvaluationError(
1567
- `Attempted to enumerate S \\cup T when S:\n${formatValue(value.left)}\nand T:\n${formatValue(value.right)}\nare not both enumerable`,
1568
- );
1569
- }
1570
1590
  if (
1571
1591
  value.operator === "\\cap" &&
1572
1592
  !isTlcEnumerable(value.left) &&
@@ -1582,19 +1602,23 @@ const enumerateSet = (
1582
1602
  );
1583
1603
  }
1584
1604
  if (value.operator === "\\cup") {
1585
- return computeLikeTlcOnFailure(
1586
- (union) => getSortedUnion(toFiniteSet(union.left), toFiniteSet(union.right)).elements,
1587
- (union) => sortLikeTlc(listUnionLikeTlc(union)),
1588
- value,
1589
- value,
1590
- );
1605
+ return toFiniteSet(createEnumeratedSet(listUnionLikeTlc(value))).elements;
1591
1606
  }
1592
1607
  const isLeftEnumerated = value.operator === "\\" || isTlcEnumerable(value.left);
1593
1608
  const enumerated = isLeftEnumerated ? value.left : value.right;
1594
1609
  const other = isLeftEnumerated ? value.right : value.left;
1595
- return toFiniteSet(enumerated).elements.filter(
1596
- (element) => isElementOf(element, other) === (value.operator === "\\cap"),
1610
+ const kept: Value[] = [];
1611
+ forEachElement(
1612
+ typeof enumerated === "object" && enumerated.kind === "Interval"
1613
+ ? enumerated
1614
+ : getStreamedElements(enumerated),
1615
+ (element) => {
1616
+ if (isElementOf(element, other) === (value.operator === "\\cap")) {
1617
+ addBoundedElement(kept, element);
1618
+ }
1619
+ },
1597
1620
  );
1621
+ return toFiniteSet(createEnumeratedSet(kept)).elements;
1598
1622
  }
1599
1623
  case "InfiniteSet":
1600
1624
  case "SequenceSet":
@@ -1631,32 +1655,92 @@ export const toFiniteSet = (value: Value): SetValue => {
1631
1655
  return set;
1632
1656
  };
1633
1657
 
1634
- // SetCupValue#toSetEnum.
1635
- const listUnionLikeTlc = (union: SetOperationValue) => [
1636
- ...toFiniteSet(union.left).elements,
1637
- ...toFiniteSet(union.right).elements,
1638
- ];
1639
-
1640
- // EnumerableValue#elements(NORMALIZED) sorts a union outside its methods, so a failed comparison
1641
- // isn't a fingerprint failure.
1642
- export const getNormalizedSetElements = (value: Value) =>
1643
- typeof value === "object" && value.kind === "SetOperation" && value.operator === "\\cup"
1644
- ? computeLikeTlcOnFailure(
1645
- (union) => toFiniteSet(union).elements,
1646
- (union) => sortLikeTlc(callTracedMethod(union, () => listUnionLikeTlc(union))),
1647
- value,
1648
- value,
1649
- )
1650
- : toFiniteSet(value).elements;
1658
+ const openStream = (value: Value): void => {
1659
+ if (typeof value !== "object" || isCachedSet(value)) return;
1660
+ switch (value.kind) {
1661
+ case "MixedSet":
1662
+ toFiniteSet(value);
1663
+ return;
1664
+ case "FilteredSet":
1665
+ if (!isTlcEnumerable(value.base)) toFiniteSet(value);
1666
+ return openStream(value.base);
1667
+ case "Union":
1668
+ if (!isEnumeratedSet(value.base) && isTlcEnumerable(value.base)) {
1669
+ return openStream(value.base);
1670
+ }
1671
+ getUnionSets(value)
1672
+ .slice(0, 1)
1673
+ .forEach((set) => openStream(getUnionSet(set, 0, value)));
1674
+ return;
1675
+ case "SetOperation":
1676
+ if (value.operator === "\\" && !isTlcEnumerable(value.left)) toFiniteSet(value);
1677
+ if (
1678
+ value.operator === "\\cup" &&
1679
+ (!isTlcEnumerable(value.left) || !isTlcEnumerable(value.right))
1680
+ ) {
1681
+ toFiniteSet(value);
1682
+ }
1683
+ if (value.operator !== "\\cap" || isTlcEnumerable(value.left)) openStream(value.left);
1684
+ else openStream(value.right);
1685
+ if (value.operator === "\\cup") openStream(value.right);
1686
+ }
1687
+ };
1688
+
1689
+ const listUnionLikeTlc = (union: SetOperationValue) => {
1690
+ if (!isTlcEnumerable(union.left) || !isTlcEnumerable(union.right)) {
1691
+ throw new TlaEvaluationError(
1692
+ `Attempted to enumerate S \\cup T when S:\n${formatValue(union.left)}\nand T:\n${formatValue(union.right)}\nare not both enumerable`,
1693
+ );
1694
+ }
1695
+ openStream(union.left);
1696
+ openStream(union.right);
1697
+ if (isBeyondSetBound(union.left)) throw new TlaSetBoundError(getSetBoundMessage());
1698
+ const left = getStreamedElements(union.left);
1699
+ const right = isBeyondSetBound(union.right) ? undefined : getStreamedElements(union.right);
1700
+ if (!right || left.length + right.length > getMaximumSetSize()) {
1701
+ throw new TlaSetBoundError(getSetBoundMessage());
1702
+ }
1703
+ return [...left, ...right];
1704
+ };
1705
+
1706
+ export const getNormalizedSetElements = (value: Value) => {
1707
+ if (
1708
+ typeof value !== "object" ||
1709
+ value.kind !== "SetOperation" ||
1710
+ value.operator !== "\\cup" ||
1711
+ value.enumerated
1712
+ ) {
1713
+ return toFiniteSet(value).elements;
1714
+ }
1715
+ const listed = callTracedMethod(value, () => listUnionLikeTlc(value));
1716
+ const elements = toFiniteSet(createEnumeratedSet(listed)).elements;
1717
+ value.enumerated = createSortedSet(elements);
1718
+ return elements;
1719
+ };
1651
1720
 
1652
- // TLC's Enumerator for a lazy set streams the sets it combines until the set caches its elements,
1653
- // so an element that two of them share comes up once for each.
1654
- export const getStreamedElements = (value: Value): Value[] => {
1655
- if (typeof value !== "object" || isCachedSet(value)) return toFiniteSet(value).elements;
1721
+ export const someStreamedElement = (value: Value, visit: (element: Value) => boolean): boolean => {
1722
+ if (typeof value !== "object" || isCachedSet(value)) {
1723
+ return toFiniteSet(value).elements.some(visit);
1724
+ }
1656
1725
  const sets = setTrace.sets;
1657
1726
  sets?.push(value);
1658
- const elements = streamElements(value);
1727
+ openStream(value);
1728
+ const isFound = someElementOfStream(value, (element) => {
1729
+ sets?.pop();
1730
+ const isAccepted = visit(element);
1731
+ sets?.push(value);
1732
+ return isAccepted;
1733
+ });
1659
1734
  sets?.pop();
1735
+ return isFound;
1736
+ };
1737
+
1738
+ export const getStreamedElements = (value: Value) => {
1739
+ const elements: Value[] = [];
1740
+ someStreamedElement(value, (element) => {
1741
+ elements.push(element);
1742
+ return false;
1743
+ });
1660
1744
  return elements;
1661
1745
  };
1662
1746
 
@@ -1669,10 +1753,6 @@ const getCombinedSets = (value: ObjectValue) =>
1669
1753
  ? [value.range]
1670
1754
  : undefined;
1671
1755
 
1672
- // Whether a value TLC builds alike at each evaluation and that enumerating, comparing or
1673
- // fingerprinting it leaves alike, so that one evaluation can stand for the next. It holds no UNION or
1674
- // \cup, which streams until TLC caches it, no lambda, which fingerprinting turns into a record, and
1675
- // no record a comparison reorders.
1676
1756
  export const isSettledValue = (value: Value): boolean => {
1677
1757
  if (typeof value !== "object") return true;
1678
1758
  switch (value.kind) {
@@ -1701,8 +1781,6 @@ export const isSettledValue = (value: Value): boolean => {
1701
1781
  }
1702
1782
  };
1703
1783
 
1704
- // Whether a set streams its elements in another order than the normalized set, so that a set of
1705
- // tuples, records, or functions it is a component of has to stream too.
1706
1784
  const isStreamedApart = (value: Value): boolean => {
1707
1785
  if (typeof value !== "object" || isCachedSet(value)) return false;
1708
1786
  if (value.kind === "Union") return true;
@@ -1715,31 +1793,35 @@ const isStreamedApart = (value: Value): boolean => {
1715
1793
  return getCombinedSets(value)?.some(isStreamedApart) ?? false;
1716
1794
  };
1717
1795
 
1718
- const streamElements = (value: ObjectValue): Value[] => {
1719
- // TLC streams the sets of a UNION it hasn't enumerated, so a set that appears twice there yields
1720
- // its elements twice.
1796
+ const someElementOfStream = (value: ObjectValue, visit: (element: Value) => boolean): boolean => {
1721
1797
  if (value.kind === "Union") {
1722
- return getUnionSets(value, getStreamedElements).flatMap((set, index) =>
1723
- getStreamedElements(getUnionSet(set, index, value)),
1798
+ return getUnionSets(value, getStreamedElements).some((set, index) =>
1799
+ someStreamedElement(getUnionSet(set, index, value), visit),
1724
1800
  );
1725
1801
  }
1726
- if (value.kind === "FilteredSet" && !isOverriddenSet(value.base)) {
1727
- return getStreamedElements(value.base).filter(value.test);
1802
+ if (value.kind === "FilteredSet" && isTlcEnumerable(value.base)) {
1803
+ return someStreamedElement(
1804
+ value.base,
1805
+ (element) => value.test(element, false) && visit(element),
1806
+ );
1728
1807
  }
1729
1808
  const components = getCombinedSets(value);
1730
- if (components?.some(isStreamedApart)) return enumerateSet(value, getStreamedElements);
1731
- if (value.kind !== "SetOperation") return toFiniteSet(value).elements;
1809
+ if (components?.some(isStreamedApart)) {
1810
+ return enumerateSet(value, getStreamedElements).some(visit);
1811
+ }
1812
+ if (value.kind !== "SetOperation") return toFiniteSet(value).elements.some(visit);
1732
1813
  if (value.operator === "\\cup") {
1733
1814
  return !isTlcEnumerable(value.left) || !isTlcEnumerable(value.right)
1734
- ? toFiniteSet(value).elements
1735
- : [...getStreamedElements(value.left), ...getStreamedElements(value.right)];
1815
+ ? toFiniteSet(value).elements.some(visit)
1816
+ : someStreamedElement(value.left, visit) || someStreamedElement(value.right, visit);
1736
1817
  }
1737
1818
  const isLeftEnumerated = value.operator === "\\" || isTlcEnumerable(value.left);
1738
1819
  const enumerated = isLeftEnumerated ? value.left : value.right;
1739
1820
  const other = isLeftEnumerated ? value.right : value.left;
1740
- if (!isTlcEnumerable(enumerated)) return toFiniteSet(value).elements;
1741
- return getStreamedElements(enumerated).filter(
1742
- (element) => isElementOf(element, other) === (value.operator === "\\cap"),
1821
+ if (!isTlcEnumerable(enumerated)) return toFiniteSet(value).elements.some(visit);
1822
+ return someStreamedElement(
1823
+ enumerated,
1824
+ (element) => isElementOf(element, other) === (value.operator === "\\cap") && visit(element),
1743
1825
  );
1744
1826
  };
1745
1827
 
@@ -1788,8 +1870,6 @@ const getProductCardinality = (
1788
1870
  const describeOverflow = (value: Value) =>
1789
1871
  `Overflow when computing the number of elements in:\n${formatValue(value)}`;
1790
1872
 
1791
- // TLC 1.7.4 sizes every component of a set of functions, records, or tuples without first
1792
- // checking whether one is empty, so an infinite component fails even beside an empty one.
1793
1873
  export const getCardinality = (value: Value, version?: TlcVersion): number => {
1794
1874
  if (typeof value !== "object") {
1795
1875
  throw new TlaEvaluationError(
@@ -1833,12 +1913,12 @@ export const getCardinality = (value: Value, version?: TlcVersion): number => {
1833
1913
  const domainSize = getCardinality(value.domain, version);
1834
1914
  const rangeSize = getCardinality(value.range, version);
1835
1915
  if (rangeSize <= 1) return domainSize === 0 ? 1 : rangeSize;
1836
- const size = { value: 1 };
1916
+ let size = 1;
1837
1917
  for (let index = 0; index < domainSize; index++) {
1838
- size.value *= rangeSize;
1839
- if (size.value > MAXIMUM_INTEGER) throw new TlaEvaluationError(describeOverflow(value));
1918
+ size *= rangeSize;
1919
+ if (size > MAXIMUM_INTEGER) throw new TlaEvaluationError(describeOverflow(value));
1840
1920
  }
1841
- return size.value;
1921
+ return size;
1842
1922
  }
1843
1923
  case "RecordSet":
1844
1924
  if (version !== "1.7.4" && isEmptySet(value)) return 0;
@@ -1891,12 +1971,12 @@ export const isFiniteSet = (value: Value): boolean => {
1891
1971
  case "RecordSet":
1892
1972
  case "ProductSet": {
1893
1973
  const parts = value.kind === "RecordSet" ? value.sets : value.factors;
1894
- const finiteness = { isAllFinite: true };
1974
+ let isAllFinite = true;
1895
1975
  for (const part of parts) {
1896
- if (!isFiniteSet(part)) finiteness.isAllFinite = false;
1976
+ if (!isFiniteSet(part)) isAllFinite = false;
1897
1977
  else if (isEmptySet(part)) return true;
1898
1978
  }
1899
- return finiteness.isAllFinite;
1979
+ return isAllFinite;
1900
1980
  }
1901
1981
  case "Union":
1902
1982
  if (!isTlcEnumerable(value.base)) {
@@ -1927,19 +2007,45 @@ export const isFiniteSet = (value: Value): boolean => {
1927
2007
  };
1928
2008
 
1929
2009
  const findSortedIndex = (sortedValues: Value[], target: Value, compare = compareValues) => {
1930
- const bounds = { low: 0, high: sortedValues.length - 1 };
1931
- while (bounds.low <= bounds.high) {
1932
- const middle = (bounds.low + bounds.high) >> 1;
2010
+ let low = 0;
2011
+ let high = sortedValues.length - 1;
2012
+ while (low <= high) {
2013
+ const middle = (low + high) >> 1;
1933
2014
  const comparison = compare(sortedValues[middle], target);
1934
2015
  if (comparison === 0) return middle;
1935
- if (comparison < 0) bounds.low = middle + 1;
1936
- else bounds.high = middle - 1;
2016
+ if (comparison < 0) low = middle + 1;
2017
+ else high = middle - 1;
1937
2018
  }
1938
2019
  return -1;
1939
2020
  };
1940
2021
 
2022
+ export const createUnsortedCopy = (set: SetValue, added: Value[]): SetValue => {
2023
+ const elements = set.elements;
2024
+ if (elements.length > getMaximumSetSize()) throw new TlaSetBoundError(getSetBoundMessage());
2025
+ const isAdded = Array.from({ length: elements.length }, () => false);
2026
+ const written = added.filter((element) => {
2027
+ const index = findSortedIndex(elements, element);
2028
+ if (isAdded[index]) return false;
2029
+ isAdded[index] = true;
2030
+ return true;
2031
+ });
2032
+ const copy = createSortedSet(elements);
2033
+ if (written.some((element, index) => element !== elements[index])) {
2034
+ copy.writtenElements = written;
2035
+ }
2036
+ return copy;
2037
+ };
2038
+
1941
2039
  export const getSequenceElements = (value: Value): Value[] | undefined => {
1942
2040
  if (typeof value !== "object" || !isFunctionValue(value)) return undefined;
2041
+ if (
2042
+ value.kind === "LazyFunction" &&
2043
+ (!isSetValue(value.domain) || isOverriddenSet(value.domain))
2044
+ ) {
2045
+ throw new TlaEvaluationError(
2046
+ "To convert a function of form [x \\in S |-> f(x)] to a tuple, the set S must be enumerable.",
2047
+ );
2048
+ }
1943
2049
  const functionValue = toFiniteFunction(value);
1944
2050
  return functionValue.domain.every((key, index) => key === index + 1)
1945
2051
  ? functionValue.range
@@ -1957,24 +2063,17 @@ const describeNonSetMembership = (element: Value, value: Value) => {
1957
2063
  return `${prefix} function ${formatValue(value)}`;
1958
2064
  };
1959
2065
 
1960
- // The call stack of the replay, which a failed fast path leaves frozen.
1961
2066
  interface TracedCallStack {
1962
2067
  expressions: unknown[];
1963
2068
  isFrozen: boolean;
2069
+ sources: WeakMap<ObjectValue, unknown>;
1964
2070
  fingerprint?: unknown;
1965
2071
  }
1966
2072
 
1967
- // The sets whose membership is being checked or whose elements are being enumerated, and the
1968
- // members being compared, outermost first, while TLC's CallStackTool replays a computation. A failed
1969
- // check or enumeration leaves the values it was in, each of which TLC adds to the
1970
- // FingerprintException when it has a source.
1971
2073
  export const setTrace: { sets: Value[] | undefined; callStack?: TracedCallStack } = {
1972
2074
  sets: undefined,
1973
2075
  };
1974
2076
 
1975
- // Takes a fast path, and computes as TLC does where it fails. TLC never takes the fast path, so
1976
- // the failure's leftovers in the replay's trace go first. Both paths take their operands as
1977
- // arguments, so a hot caller passes functions it doesn't allocate.
1978
2077
  export const computeLikeTlcOnFailure = <Left, Right, Result>(
1979
2078
  compute: (left: Left, right: Right) => Result,
1980
2079
  computeLikeTlc: (left: Left, right: Right, error: TlaEvaluationError) => Result,
@@ -1999,6 +2098,11 @@ export const computeLikeTlcOnFailure = <Left, Right, Result>(
1999
2098
  }
2000
2099
  };
2001
2100
 
2101
+ export const isFingerprintedSince = (depth: number) =>
2102
+ (setTrace.sets ?? [])
2103
+ .slice(depth)
2104
+ .some((set) => typeof set === "object" && setTrace.callStack?.sources.has(set) === true);
2105
+
2002
2106
  export const isElementOf = (element: Value, set: Value): boolean => {
2003
2107
  const sets = setTrace.sets;
2004
2108
  if (sets === undefined) return isElementOfSet(element, set);
@@ -2008,26 +2112,59 @@ export const isElementOf = (element: Value, set: Value): boolean => {
2008
2112
  return isElement;
2009
2113
  };
2010
2114
 
2115
+ const isIntegerInSortedSet = (element: number, set: SetValue) => {
2116
+ const elements = set.elements;
2117
+ let low = 0;
2118
+ let high = elements.length - 1;
2119
+ while (low <= high) {
2120
+ const middle = (low + high) >> 1;
2121
+ const probe = elements[middle];
2122
+ if (typeof probe !== "number") return undefined;
2123
+ if (probe === element) return true;
2124
+ if (probe < element) low = middle + 1;
2125
+ else high = middle - 1;
2126
+ }
2127
+ return false;
2128
+ };
2129
+
2011
2130
  const isInSortedSet = (element: Value, set: SetValue) =>
2012
2131
  findSortedIndex(set.elements, element) !== -1;
2013
2132
 
2014
2133
  const isInSortedSetLikeTlc = (element: Value, set: SetValue) =>
2015
- normalizedSets.has(set)
2134
+ set.isNormalized
2016
2135
  ? searchLikeTlc(element, set.elements).isFound
2017
- : isElementOfLikeTlc(element, set.elements);
2136
+ : isElementOfLikeTlc(element, getWrittenElements(set));
2018
2137
 
2138
+ const isModelValueMember = (modelValue: ModelValue, set: Value) => {
2139
+ if (modelValue.type !== undefined) {
2140
+ throw new TlaEvaluationError(
2141
+ `Attempted to check if the typed model value ${prettyPrint(formatValue(modelValue))} is an element of\n${prettyPrint(formatValue(set))}`,
2142
+ );
2143
+ }
2144
+ return false;
2145
+ };
2146
+
2147
+ // The common cases stay small enough for V8 to inline.
2019
2148
  const isElementOfSet = (element: Value, set: Value): boolean => {
2149
+ if (typeof element === "number" && typeof set === "object") {
2150
+ if (set.kind === "Set")
2151
+ return isIntegerInSortedSet(element, set) ?? isElementOfAnySet(element, set);
2152
+ if (set.kind === "Interval") return element >= set.low && element <= set.high;
2153
+ }
2154
+ return isElementOfAnySet(element, set);
2155
+ };
2156
+
2157
+ const isElementOfAnySet = (element: Value, set: Value): boolean => {
2020
2158
  if (!isSetValue(set)) throw new TlaEvaluationError(describeNonSetMembership(element, set));
2021
2159
  switch (set.kind) {
2022
2160
  case "Set":
2023
- // SetEnumValue.member compares the element with the set's.
2024
2161
  cacheSet(element);
2025
2162
  return computeLikeTlcOnFailure(isInSortedSet, isInSortedSetLikeTlc, element, set);
2026
2163
  case "MixedSet":
2027
2164
  return isElementOfLikeTlc(element, set.elements);
2028
2165
  case "Interval":
2029
2166
  if (typeof element === "number") return element >= set.low && element <= set.high;
2030
- if (set.low <= set.high && !isModelValue(element)) {
2167
+ if (set.low <= set.high && (!isModelValue(element) || element.type !== undefined)) {
2031
2168
  throw new TlaEvaluationError(
2032
2169
  `Attempted to check if the value:\n${formatValue(element)}\nis in the integer interval ${formatValue(set)}`,
2033
2170
  );
@@ -2035,19 +2172,17 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2035
2172
  return false;
2036
2173
  case "InfiniteSet": {
2037
2174
  if (set.name === "Any") return true;
2038
- if (isModelValue(element)) return false;
2175
+ if (isModelValue(element)) return isModelValueMember(element, set);
2039
2176
  const isMemberType =
2040
2177
  set.name === "STRING" ? typeof element === "string" : typeof element === "number";
2041
2178
  if (!isMemberType) {
2042
- throw new TlaEvaluationError(
2179
+ throw new TlaModuleError(
2043
2180
  `Attempted to check if the value:\n${formatValue(element)}\nis an element of ${set.name}.`,
2044
2181
  );
2045
2182
  }
2046
2183
  return set.name !== "Nat" || (typeof element === "number" && element >= 0);
2047
2184
  }
2048
2185
  case "Subset":
2049
- // SubsetValue.member fails on any value that is not Enumerable, model values and the sets a
2050
- // Java class overrides included.
2051
2186
  if (!isSetValue(element) || isOverriddenSet(element)) {
2052
2187
  throw new TlaEvaluationError(
2053
2188
  `Attempted to check if the non-enumerable value\n${prettyPrint(formatValue(element))}\nis element of\n${prettyPrint(formatValue(set))}`,
@@ -2056,14 +2191,13 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2056
2191
  return toFiniteSet(element).elements.every((item) => isElementOf(item, set.base));
2057
2192
  case "FunctionSet": {
2058
2193
  if (!isFunctionValue(element)) {
2059
- if (isModelValue(element)) return false;
2060
- // SetOfFcnsValue.member prints the element without Values.ppr.
2194
+ if (isModelValue(element)) return isModelValueMember(element, set);
2061
2195
  throw new TlaEvaluationError(
2062
2196
  `Attempted to check if \n${formatValue(element)}\nwhich is not a TLC function value, is in the set of functions:\n${prettyPrint(formatValue(set))}`,
2063
2197
  );
2064
2198
  }
2065
2199
  const functionValue = toFiniteFunction(element);
2066
- const low = getIntervalLow(functionValue.domain);
2200
+ const low = getIntervalLow(element, functionValue.domain);
2067
2201
  const isDomain =
2068
2202
  low === undefined
2069
2203
  ? isEqualLikeTlc(set.domain, createSortedSet(functionValue.domain))
@@ -2076,7 +2210,7 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2076
2210
  case "RecordSet": {
2077
2211
  const functionValue = isFunctionValue(element) ? toFiniteFunction(element) : undefined;
2078
2212
  if (!functionValue || !isRecordDomain(functionValue.domain)) {
2079
- if (isModelValue(element)) return false;
2213
+ if (isModelValue(element)) return isModelValueMember(element, set);
2080
2214
  throw new TlaEvaluationError(
2081
2215
  `Attempted to check if non-record\n${formatValue(element)}\nis in the set of records:\n${formatValue(set)}`,
2082
2216
  );
@@ -2095,7 +2229,8 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2095
2229
  const isFunction =
2096
2230
  isFunctionValue(element) &&
2097
2231
  toFiniteFunction(element).domain.every((key) => typeof key === "number");
2098
- if (isFunction || isModelValue(element)) return false;
2232
+ if (isModelValue(element)) return isModelValueMember(element, set);
2233
+ if (isFunction) return false;
2099
2234
  throw new TlaEvaluationError(
2100
2235
  `Attempted to check if non-tuple\n${formatValue(element)}\nis in the set of tuples:\n${formatValue(set)}`,
2101
2236
  );
@@ -2106,14 +2241,28 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2106
2241
  );
2107
2242
  }
2108
2243
  case "FilteredSet":
2109
- return isElementOf(element, set.base) && set.test(element);
2110
- case "Union":
2244
+ try {
2245
+ return isElementOf(element, set.base) && set.test(element, true);
2246
+ } catch (error) {
2247
+ if (!(error instanceof TlaEvaluationError) || !isEvalException(error)) throw error;
2248
+ throw new TlaEvaluationError(
2249
+ `Cannot decide if element:\n${prettyPrint(formatValue(element))}\n is element of:\n${prettyPrint(formatValue(set.base))}\nand satisfies the predicate ${set.source?.predicate}`,
2250
+ );
2251
+ }
2252
+ case "Union": {
2111
2253
  if (!isTlcEnumerable(set.base)) {
2112
2254
  throw new TlaEvaluationError(
2113
2255
  `Attempted to check if:\n ${formatValue(element)}\nis an element of the non-enumerable set:\n ${formatUnion(set)}`,
2114
2256
  );
2115
2257
  }
2116
- return toFiniteSet(set.base).elements.some((inner) => isElementOf(element, inner));
2258
+ const sets = toFiniteSet(set.base).elements;
2259
+ if (sets.length > 1) {
2260
+ sets.forEach((inner) => {
2261
+ if (typeof inner === "object" && inner.kind === "Set") inner.isNormalized = true;
2262
+ });
2263
+ }
2264
+ return sets.some((inner) => isElementOf(element, inner));
2265
+ }
2117
2266
  case "SetOperation":
2118
2267
  if (set.operator === "\\cup")
2119
2268
  return isElementOf(element, set.left) || isElementOf(element, set.right);
@@ -2124,9 +2273,8 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2124
2273
  case "SequenceSet": {
2125
2274
  const elements = getSequenceElements(element);
2126
2275
  if (elements === undefined) {
2127
- if (isModelValue(element)) return false;
2128
- // Sequences.member raises TLC_MODULE_CHECK_MEMBER_OF.
2129
- throw new TlaEvaluationError(
2276
+ if (isModelValue(element)) return isModelValueMember(element, set);
2277
+ throw new TlaModuleError(
2130
2278
  `Attempted to check if the value:\n${prettyPrint(formatValue(element))}\nis an element of ${prettyPrint(formatValue(set))}.`,
2131
2279
  );
2132
2280
  }
@@ -2137,8 +2285,6 @@ const isElementOfSet = (element: Value, set: Value): boolean => {
2137
2285
  }
2138
2286
  };
2139
2287
 
2140
- // A function that agrees with a member of a function set outside some entries is a member when
2141
- // those entries are.
2142
2288
  export const isUpdatedElementOf = (element: Value, member: Value, set: Value): boolean => {
2143
2289
  if (element === member) return true;
2144
2290
  if (
@@ -2161,6 +2307,9 @@ export const toFiniteFunction = (value: Value): FunctionValue => {
2161
2307
  if (typeof value === "object" && value.kind === "LazyFunction") {
2162
2308
  if (value.enumerated) return value.enumerated;
2163
2309
  if (!isEnumerable(value.domain)) getCardinality(value.domain);
2310
+ if (!isSetValue(value.domain)) {
2311
+ throw new TlaEvaluationError("The domains of formal parameters must be enumerable.");
2312
+ }
2164
2313
  const domain = getFunctionDomain(value.domain);
2165
2314
  value.enumerated = setFunctionClass(
2166
2315
  createSortedFunction(
@@ -2208,16 +2357,14 @@ export const describeMissingArgument = (
2208
2357
  }
2209
2358
  };
2210
2359
 
2211
- // TLC 1.7.4 words a key of the wrong type in an EXCEPT, which selects rather than applies, apart.
2212
2360
  const describeExceptKey = (functionValue: FunctionValue, argument: Value) => {
2213
- if (!valueVersion.is174) return describeMissingArgument(functionValue, argument);
2361
+ if (!isVersion174) return describeMissingArgument(functionValue, argument);
2214
2362
  const shown = prettyPrint(formatValue(argument));
2215
2363
  return getFunctionClass(functionValue) === "tuple"
2216
2364
  ? `Attempted to apply tuple to a non-integer argument ${shown}.`
2217
2365
  : `Attempted to apply record to a non-string argument ${shown}.`;
2218
2366
  };
2219
2367
 
2220
- // A key the domain holds itself, which TLC finds without a comparison that can fail.
2221
2368
  const findIdenticalKey = (domain: Value[], argument: Value) => {
2222
2369
  const first = domain[0];
2223
2370
  if (typeof argument === "number" && typeof first === "number") {
@@ -2232,22 +2379,25 @@ export const createNonIntegerKeyError = (argument: Value) =>
2232
2379
  `Attempted to apply function with integer domain to the non-integer argument ${prettyPrint(formatValue(argument))}`,
2233
2380
  );
2234
2381
 
2235
- // TLC's FcnRcdValue searches a domain this small linearly with equals, and a larger normalized one by
2236
- // binary search with compareTo.
2237
2382
  const LINEAR_SEARCH_LIMIT = 32;
2238
2383
 
2239
- const failKeyLikeTlc = (domain: Value[], argument: Value, error: TlaEvaluationError): never => {
2240
- if (valueVersion.is174 || domain.length < LINEAR_SEARCH_LIMIT) {
2241
- domain.forEach((key) => equalsLikeTlc(key, argument));
2384
+ const findDomainIndex = (functionValue: FunctionValue, argument: Value) =>
2385
+ findSortedIndex(functionValue.domain, argument);
2386
+
2387
+ const failKeyLikeTlc = (
2388
+ functionValue: FunctionValue,
2389
+ argument: Value,
2390
+ error: TlaEvaluationError,
2391
+ ): never => {
2392
+ const keys = getWrittenKeys(functionValue);
2393
+ if (isVersion174 || keys !== functionValue.domain || keys.length < LINEAR_SEARCH_LIMIT) {
2394
+ keys.forEach((key) => equalsLikeTlc(key, argument));
2242
2395
  } else {
2243
- findSortedIndex(domain, argument, compareLikeTlc);
2396
+ findSortedIndex(keys, argument, compareLikeTlc);
2244
2397
  }
2245
2398
  throw error;
2246
2399
  };
2247
2400
 
2248
- // TLC looks a key up by the Java class of the function: a tuple or a record rejects a key of the
2249
- // wrong type, and another function rejects a non-integer for a domain it keeps as an interval, which
2250
- // TLC 1.7.4 doesn't. A key of another type than the domain's keys otherwise fails TLC's comparison.
2251
2401
  const findKeyIndexLikeTlc = (
2252
2402
  functionValue: FunctionValue,
2253
2403
  argument: Value,
@@ -2261,21 +2411,84 @@ const findKeyIndexLikeTlc = (
2261
2411
  if (keyType !== undefined && typeof argument !== keyType) {
2262
2412
  throw new TlaEvaluationError(describeWrongKey(functionValue, argument));
2263
2413
  }
2264
- if (keyType === undefined && !valueVersion.is174 && isIntervalDomain(domain)) {
2414
+ if (
2415
+ keyType === undefined &&
2416
+ !isVersion174 &&
2417
+ typeof argument !== "number" &&
2418
+ isIntervalDomain(domain)
2419
+ ) {
2265
2420
  throw createNonIntegerKeyError(argument);
2266
2421
  }
2267
2422
  }
2268
2423
  const identical = findIdenticalKey(domain, argument);
2269
2424
  if (identical !== -1) return identical;
2270
- return computeLikeTlcOnFailure(findSortedIndex, failKeyLikeTlc, domain, argument);
2425
+ return computeLikeTlcOnFailure(findDomainIndex, failKeyLikeTlc, functionValue, argument);
2426
+ };
2427
+
2428
+ // Deviation from TLC: FcnLambdaValue#apply indexes past an argument tuple shorter than the bounds and ignores a longer one, where this rejects the list.
2429
+ const checkBoundArguments = (
2430
+ functionValue: LazyFunctionValue,
2431
+ tupleLengths: (number | undefined)[],
2432
+ argument: Value,
2433
+ ) => {
2434
+ const domain = functionValue.domain;
2435
+ const elements = getSequenceElements(argument);
2436
+ const describe = (position: string, shown: Value, problem: string) =>
2437
+ `In applying the function\n${prettyPrint(formatValue(functionValue))},\nthe ${position} is:\n${prettyPrint(formatValue(shown))}\nwhich ${problem}.\n`;
2438
+ const createListError = () =>
2439
+ new TlaEvaluationError(
2440
+ describe("argument list", argument, "does not match its formal parameter"),
2441
+ );
2442
+ if (elements === undefined) throw createListError();
2443
+ if (typeof domain !== "object" || domain.kind !== "ProductSet") {
2444
+ throw new TlaEvaluationError(
2445
+ `Attempted to apply a function to ${formatValue(argument)}, which is not in its domain`,
2446
+ );
2447
+ }
2448
+ tupleLengths.forEach((tupleLength, index) => {
2449
+ if (index >= elements.length) throw createListError();
2450
+ const element = elements[index];
2451
+ const position = `argument number ${index + 1}`;
2452
+ if (!isElementOf(element, domain.factors[index])) {
2453
+ throw new TlaEvaluationError(
2454
+ describe(
2455
+ position,
2456
+ element,
2457
+ tupleLength === undefined
2458
+ ? `is not in the function's domain ${formatValue(domain)}`
2459
+ : "is not in its domain",
2460
+ ),
2461
+ );
2462
+ }
2463
+ if (tupleLength !== undefined && getSequenceElements(element)?.length !== tupleLength) {
2464
+ throw new TlaEvaluationError(
2465
+ describe(position, element, "does not match its formal parameter"),
2466
+ );
2467
+ }
2468
+ });
2469
+ if (elements.length > tupleLengths.length) throw createListError();
2271
2470
  };
2272
2471
 
2472
+ const isOutsideLambdaDomain = (functionValue: FunctionValue, argument: Value) =>
2473
+ functionValue.lambdaDomain !== undefined &&
2474
+ functionValue.hash === 0 &&
2475
+ functionValue.fingerprint === 0 &&
2476
+ !isElementOf(argument, functionValue.lambdaDomain);
2477
+
2273
2478
  export const applyFunction = (
2274
2479
  functionValue: Value,
2275
2480
  argument: Value,
2276
2481
  describeMissing?: (functionValue: FunctionValue, argument: Value) => string,
2277
2482
  ): Value => {
2278
2483
  if (typeof functionValue === "object" && functionValue.kind === "LazyFunction") {
2484
+ if (functionValue.enumerated) {
2485
+ return applyFunction(functionValue.enumerated, argument, describeMissing);
2486
+ }
2487
+ const tupleLengths = functionValue.boundTupleLengths;
2488
+ if (tupleLengths !== undefined) {
2489
+ checkBoundArguments(functionValue, tupleLengths, argument);
2490
+ return functionValue.apply(argument);
2491
+ }
2279
2492
  if (!isElementOf(argument, functionValue.domain)) {
2280
2493
  throw new TlaEvaluationError(
2281
2494
  getFunctionClass(functionValue) === "lambda"
@@ -2291,6 +2504,9 @@ export const applyFunction = (
2291
2504
  );
2292
2505
  }
2293
2506
  const describe = describeMissing ?? describeMissingArgument;
2507
+ if (isOutsideLambdaDomain(functionValue, argument)) {
2508
+ throw new TlaEvaluationError(describe(functionValue, argument));
2509
+ }
2294
2510
  const position = findKeyIndexLikeTlc(functionValue, argument, describe);
2295
2511
  if (position === -1) throw new TlaEvaluationError(describe(functionValue, argument));
2296
2512
  return functionValue.range[position];
@@ -2304,8 +2520,17 @@ export const getDomainInterval = (domain: Value[]) =>
2304
2520
  export const getDomain = (functionValue: Value): Value => {
2305
2521
  if (typeof functionValue === "object" && functionValue.kind === "LazyFunction")
2306
2522
  return functionValue.domain;
2307
- const domain = toFiniteFunction(functionValue).domain;
2308
- return getDomainInterval(domain) ?? createSortedSet(domain);
2523
+ const finite = toFiniteFunction(functionValue);
2524
+ if (finite.functionClass === "lambda" && finite.lambdaDomain) return finite.lambdaDomain;
2525
+ const interval = getDomainInterval(finite.domain);
2526
+ if (interval) return interval;
2527
+ const set = createSortedSet(finite.domain);
2528
+ if (finite.functionClass === "record") {
2529
+ if (finite.writtenKeys) set.writtenElements = finite.writtenKeys;
2530
+ return set;
2531
+ }
2532
+ set.isNormalized = true;
2533
+ return set;
2309
2534
  };
2310
2535
 
2311
2536
  export const updateFunction = (
@@ -2317,7 +2542,7 @@ export const updateFunction = (
2317
2542
  const isLazy =
2318
2543
  typeof functionValue === "object" &&
2319
2544
  functionValue.kind === "LazyFunction" &&
2320
- (isKeptLazy || !isEnumerable(functionValue.domain));
2545
+ (isKeptLazy || functionValue.enumerated === undefined);
2321
2546
  if (isLazy) {
2322
2547
  if (!isElementOf(argument, functionValue.domain)) return functionValue;
2323
2548
  const updated = update(functionValue.apply(argument));
@@ -2327,6 +2552,7 @@ export const updateFunction = (
2327
2552
  domain: functionValue.domain,
2328
2553
  apply: (key) => (isEqualLikeTlc(argument, key) ? updated : functionValue.apply(key)),
2329
2554
  source: functionValue.source,
2555
+ boundTupleLengths: functionValue.boundTupleLengths,
2330
2556
  },
2331
2557
  getFunctionClass(functionValue),
2332
2558
  );
@@ -2337,6 +2563,7 @@ export const updateFunction = (
2337
2563
  );
2338
2564
  }
2339
2565
  const finite = toFiniteFunction(functionValue);
2566
+ if (isOutsideLambdaDomain(finite, argument)) return finite;
2340
2567
  const position = findKeyIndexLikeTlc(finite, argument, describeExceptKey);
2341
2568
  if (position === -1) return finite;
2342
2569
  const range = [...finite.range];
@@ -2348,6 +2575,7 @@ export const updateFunction = (
2348
2575
  getFunctionClass(finite),
2349
2576
  );
2350
2577
  updated.writtenKeys = finite.writtenKeys;
2578
+ updated.lambdaDomain = finite.lambdaDomain;
2351
2579
  if (finite.hash !== 0 && finite.hash !== UNFINGERPRINTABLE_HASH) {
2352
2580
  const nextHash = getValueHash(next);
2353
2581
  if (nextHash !== UNFINGERPRINTABLE_HASH) {
@@ -2400,9 +2628,6 @@ const getElementContribution = (elementHash: number) =>
2400
2628
  const getEntryContribution = (keyHash: number, valueHash: number) =>
2401
2629
  finalizeHash((Math.imul(keyHash, 0x27d4eb2d) + valueHash) | 0);
2402
2630
 
2403
- // The hash of each value that TLC fails to fingerprint, such as Nat or a set that holds it. Calls
2404
- // with such a value as an argument still share their result, and a state that holds one fails
2405
- // when TLC fingerprints it.
2406
2631
  const UNFINGERPRINTABLE_HASH = 0x2f6b1c4d;
2407
2632
 
2408
2633
  const computeValueHash = (value: SetValue | FunctionValue) => {
@@ -2428,8 +2653,6 @@ const computeValueHash = (value: SetValue | FunctionValue) => {
2428
2653
  return hash;
2429
2654
  };
2430
2655
 
2431
- // TLC's fingerPrint enumerates each set and function a value holds, and fails on Nat, Seq(S) and
2432
- // the like, which it never enumerates.
2433
2656
  const fingerprintValue = (value: Value): void => {
2434
2657
  if (typeof value !== "object" || value.kind === "ModelValue") return;
2435
2658
  if (value.kind === "InfiniteSet" || value.kind === "SequenceSet") {
@@ -2446,8 +2669,6 @@ const fingerprintValue = (value: Value): void => {
2446
2669
  functionValue.range.forEach(fingerprintValue);
2447
2670
  };
2448
2671
 
2449
- // The error TLC raises as it fingerprints a value: one that hashing the value raises, as for a set
2450
- // too large to enumerate, or one of a value with the hash of the values TLC fails on.
2451
2672
  export const getFingerprintError = (value: Value) => {
2452
2673
  if (typeof value !== "object" || value.kind === "ModelValue") return undefined;
2453
2674
  try {
@@ -2459,7 +2680,6 @@ export const getFingerprintError = (value: Value) => {
2459
2680
  }
2460
2681
  };
2461
2682
 
2462
- // The values a value holds, which TLC fingerprints as it fingerprints the value.
2463
2683
  export const getHeldValues = (value: ObjectValue): Value[] => {
2464
2684
  switch (value.kind) {
2465
2685
  case "Set":
@@ -2580,17 +2800,19 @@ const computeValueKey = (value: ObjectValue) => {
2580
2800
  return `(${functionValue.domain.map((key, index) => `${getValueKey(key)}:${getValueKey(functionValue.range[index])}`).join(",")})`;
2581
2801
  };
2582
2802
 
2803
+ const PRINTED_ESCAPES: Record<string, string> = {
2804
+ '"': '\\"',
2805
+ "\\": "\\\\",
2806
+ "\t": "\\t",
2807
+ "\n": "\\n",
2808
+ "\f": "\\f",
2809
+ "\r": "\\r",
2810
+ };
2811
+
2583
2812
  const formatString = (value: string) =>
2584
- `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\t/g, "\\t")}"`;
2813
+ `"${value.replace(/["\\\t\n\f\r]/g, (character) => PRINTED_ESCAPES[character])}"`;
2585
2814
 
2586
- type LazySetValue =
2587
- | SubsetValue
2588
- | FunctionSetValue
2589
- | RecordSetValue
2590
- | ProductSetValue
2591
- | SetOperationValue
2592
- | FilteredSetValue
2593
- | UnionValue;
2815
+ type LazySetValue = Exclude<ConvertibleSetValue, MixedSetValue | SequenceSetValue>;
2594
2816
 
2595
2817
  const MAXIMUM_EXPANDED_SUBSET_BASE = 6;
2596
2818
  const MAXIMUM_EXPANDED_PRODUCT = 1999;
@@ -2607,24 +2829,24 @@ const expandLazySet = (value: LazySetValue) => {
2607
2829
  if (value.kind === "SetOperation" || value.kind === "FilteredSet" || value.kind === "Union") {
2608
2830
  return toFiniteSet(value);
2609
2831
  }
2610
- if (
2611
- value.kind === "FunctionSet" &&
2612
- isEnumerable(value.domain) &&
2613
- getCardinality(value.domain) === 0
2614
- ) {
2615
- return createSortedSet([createSortedFunction([], [])]);
2832
+ if (value.kind === "FunctionSet") {
2833
+ const domainSize = isEmptySet(value.domain) ? 0 : getCardinality(value.domain);
2834
+ const size = domainSize === 0 ? 1 : getCardinality(value.range) ** domainSize;
2835
+ return size <= MAXIMUM_EXPANDED_PRODUCT ? toFiniteSet(value) : undefined;
2616
2836
  }
2617
- const size =
2618
- value.kind === "FunctionSet"
2619
- ? getCardinality(value.range) ** getCardinality(value.domain)
2620
- : getProductSize(value.kind === "RecordSet" ? value.sets : value.factors);
2621
- if (size === 0) return EMPTY_SET;
2837
+ const size = getProductSize(value.kind === "RecordSet" ? value.sets : value.factors);
2622
2838
  return size <= MAXIMUM_EXPANDED_PRODUCT ? toFiniteSet(value) : undefined;
2623
2839
  };
2624
2840
 
2625
2841
  const getExpandedLazySet = (value: LazySetValue, isStrict: boolean) => {
2626
- if (isStrict) return expandLazySet(value);
2627
- // TLC prints a set it can't enumerate symbolically, except in Print, PrintT, and ToString.
2842
+ if (isStrict || value.kind === "Union") return expandLazySet(value);
2843
+ if (
2844
+ value.kind === "Subset" &&
2845
+ isFunctionValue(value.base) &&
2846
+ (value.base.kind === "Function" || isEnumerable(value.base.domain))
2847
+ ) {
2848
+ return expandLazySet(value);
2849
+ }
2628
2850
  if (!isEnumerable(value)) return undefined;
2629
2851
  try {
2630
2852
  return expandLazySet(value);
@@ -2658,24 +2880,76 @@ const formatLazySet = (value: LazySetValue, isStrict: boolean): string => {
2658
2880
  }
2659
2881
  };
2660
2882
 
2661
- // FcnRcdValue#isName: TLC prints a function as a record when every key consists of letters,
2662
- // decimal digits, and underscores, with at least one letter.
2663
2883
  const isFieldName = (name: string) =>
2664
2884
  /^[\p{L}\p{Nd}_]*$/u.test(name) &&
2665
2885
  /\p{L}/u.test(name) &&
2666
2886
  (name.length < 4 || !/^[WS]F_/.test(name));
2667
2887
 
2668
- // FcnLambdaValue#toString prints a function it fails to enumerate as its parameters and body.
2669
2888
  const toPrintedFunction = (value: LazyFunctionValue) => {
2670
2889
  if (!isEnumerable(value.domain)) return undefined;
2671
2890
  try {
2672
2891
  return toFiniteFunction(value);
2673
2892
  } catch (error) {
2674
- if (error instanceof TlaEvaluationError) return undefined;
2893
+ if (error instanceof TlaEvaluationError || isStackOverflow(error)) return undefined;
2675
2894
  throw error;
2676
2895
  }
2677
2896
  };
2678
2897
 
2898
+ export const formatNormalizedCopies = (values: Value[]) => {
2899
+ const markedSets: SetValue[] = [];
2900
+ const normalize = (value: Value): void => {
2901
+ if (typeof value !== "object") return;
2902
+ switch (value.kind) {
2903
+ case "Set":
2904
+ value.elements.forEach(normalize);
2905
+ if (value.isNormalized) return;
2906
+ value.isNormalized = true;
2907
+ markedSets.push(value);
2908
+ return;
2909
+ case "MixedSet":
2910
+ value.elements.forEach(normalize);
2911
+ toFiniteSet(value);
2912
+ return;
2913
+ case "Function":
2914
+ value.range.forEach(normalize);
2915
+ return;
2916
+ case "LazyFunction":
2917
+ normalize(value.enumerated ?? value.domain);
2918
+ return;
2919
+ case "SetOperation":
2920
+ normalize(value.left);
2921
+ normalize(value.right);
2922
+ return;
2923
+ case "FunctionSet":
2924
+ normalize(value.domain);
2925
+ normalize(value.range);
2926
+ return;
2927
+ case "RecordSet":
2928
+ value.sets.forEach(normalize);
2929
+ return;
2930
+ case "ProductSet":
2931
+ value.factors.forEach(normalize);
2932
+ return;
2933
+ case "Subset":
2934
+ case "Union":
2935
+ case "FilteredSet":
2936
+ case "SequenceSet":
2937
+ normalize(value.base);
2938
+ return;
2939
+ default:
2940
+ return;
2941
+ }
2942
+ };
2943
+ try {
2944
+ values.forEach(normalize);
2945
+ return values.map((value) => formatValue(value, true, true));
2946
+ } finally {
2947
+ markedSets.forEach((set) => {
2948
+ set.isNormalized = false;
2949
+ });
2950
+ }
2951
+ };
2952
+
2679
2953
  export const formatValue = (value: Value, isStrict = false, isNormalized = false): string => {
2680
2954
  const format = (inner: Value) => formatValue(inner, isStrict, isNormalized);
2681
2955
  if (typeof value === "boolean") return value ? "TRUE" : "FALSE";
@@ -2699,7 +2973,7 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
2699
2973
  case "SetOperation":
2700
2974
  case "FilteredSet":
2701
2975
  case "Union": {
2702
- const expanded = getExpandedLazySet(value, isStrict);
2976
+ const expanded = printing.isExpanded ? getExpandedLazySet(value, isStrict) : undefined;
2703
2977
  return expanded ? format(expanded) : formatLazySet(value, isStrict);
2704
2978
  }
2705
2979
 
@@ -2707,7 +2981,12 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
2707
2981
  return `Seq(${format(value.base)})`;
2708
2982
  case "Function":
2709
2983
  case "LazyFunction": {
2710
- const functionValue = value.kind === "LazyFunction" ? toPrintedFunction(value) : value;
2984
+ const functionValue =
2985
+ value.kind !== "LazyFunction"
2986
+ ? value
2987
+ : printing.isExpanded || !value.source
2988
+ ? toPrintedFunction(value)
2989
+ : undefined;
2711
2990
  if (functionValue === undefined) {
2712
2991
  const source = value.kind === "LazyFunction" ? value.source : undefined;
2713
2992
  if (!source) return "<function>";
@@ -2718,42 +2997,111 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
2718
2997
  }
2719
2998
  if (
2720
2999
  functionValue.domain.length === 0 &&
2721
- valueVersion.is174 &&
3000
+ isVersion174 &&
2722
3001
  getFunctionClass(value) !== "tuple"
2723
3002
  ) {
2724
3003
  return "<< >>";
2725
3004
  }
2726
- // TLC normalizes a lambda's domain to print it, but evaluates its body afterward.
2727
3005
  const formatRange = (inner: Value) =>
2728
3006
  formatValue(inner, isStrict, isNormalized && getFunctionClass(value) !== "lambda");
3007
+ if (functionValue.domain.length === 0 && getFunctionClass(value) === "record") return "[]";
2729
3008
  if (functionValue.domain.every((key, index) => key === index + 1)) {
2730
3009
  return `<<${functionValue.range.map(formatRange).join(", ")}>>`;
2731
3010
  }
2732
- // A RecordValue prints as a record whatever its fields, and a FcnRcdValue only if each key
2733
- // is a name.
3011
+ const pairs = isNormalized
3012
+ ? functionValue.domain.map((key, index) => [key, functionValue.range[index]])
3013
+ : getPrintedPairs(functionValue);
2734
3014
  if (
2735
3015
  getFunctionClass(value) === "record" ||
2736
3016
  functionValue.domain.every((key) => typeof key === "string" && isFieldName(key))
2737
3017
  ) {
2738
- const isSorted =
2739
- isNormalized || functionValue.hash !== 0 || functionValue.fingerprint !== 0;
2740
- const pairs = isSorted
2741
- ? functionValue.domain.map((key, index) => [key, functionValue.range[index]])
2742
- : getWrittenPairs(functionValue);
2743
3018
  return `[${pairs.map((pair) => `${String(pair[0])} |-> ${formatRange(pair[1])}`).join(", ")}]`;
2744
3019
  }
2745
- return `(${functionValue.domain.map((key, index) => `${format(key)} :> ${formatRange(functionValue.range[index])}`).join(" @@ ")})`;
3020
+ return `(${pairs.map((pair) => `${format(pair[0])} :> ${formatRange(pair[1])}`).join(" @@ ")})`;
2746
3021
  }
2747
3022
  }
2748
3023
  };
2749
3024
 
2750
- // TLC's TLCState.toString: a line per variable, as a conjunction when there are several.
2751
- export const formatState = (state: Record<string, Value>) => {
3025
+ const isUnchanged = (previous: Value | undefined, value: Value) => {
3026
+ if (previous === undefined) return false;
3027
+ try {
3028
+ return valuesEqual(previous, value);
3029
+ } catch (error) {
3030
+ if (error instanceof TlaEvaluationError) return false;
3031
+ throw error;
3032
+ }
3033
+ };
3034
+
3035
+ const JAVA_FORMAT_SPECIFIER = /%(\d+\$)?([-#+ 0,(<]*)(\d+)?(\.\d+)?(.?)/gs;
3036
+
3037
+ const formatJava = (format: string, args: string[]) => {
3038
+ let nextIndex = 0;
3039
+ let lastIndex = -1;
3040
+ let isFitting = true;
3041
+ const text = format.replace(
3042
+ JAVA_FORMAT_SPECIFIER,
3043
+ (match, explicit?: string, flags = "", width?: string, precision?: string, conversion = "") => {
3044
+ const pad = (value: string) =>
3045
+ flags.includes("-") ? value.padEnd(Number(width)) : value.padStart(Number(width ?? 0));
3046
+ const isRelative = flags.includes("<");
3047
+ const otherFlags = flags.replace("<", "");
3048
+ if (conversion === "n" && match === "%n") return "\n";
3049
+ if (conversion === "%" && precision === undefined && /^-?$/.test(otherFlags)) {
3050
+ if (otherFlags === "-" && width === undefined) isFitting = false;
3051
+ return pad("%");
3052
+ }
3053
+ const index = isRelative
3054
+ ? lastIndex
3055
+ : explicit === undefined
3056
+ ? nextIndex++
3057
+ : Number(explicit.slice(0, -1)) - 1;
3058
+ lastIndex = index;
3059
+ const arg = args[index];
3060
+ if (
3061
+ !"sSbBhH".includes(conversion) ||
3062
+ conversion === "" ||
3063
+ !/^-?$/.test(otherFlags) ||
3064
+ (otherFlags === "-" && width === undefined) ||
3065
+ arg === undefined
3066
+ ) {
3067
+ isFitting = false;
3068
+ return match;
3069
+ }
3070
+ const lower = conversion.toLowerCase();
3071
+ const value =
3072
+ lower === "s" ? arg : lower === "b" ? "true" : (getJavaHashCode(arg) >>> 0).toString(16);
3073
+ const shown = pad(
3074
+ precision === undefined ? value : value.slice(0, Number(precision.slice(1))),
3075
+ );
3076
+ return conversion === lower ? shown : shown.toUpperCase();
3077
+ },
3078
+ );
3079
+ return isFitting ? text : undefined;
3080
+ };
3081
+
3082
+ export const formatState = (state: Record<string, Value>, previous?: Record<string, Value>) => {
3083
+ const getViewText = previous ? undefined : viewTexts.get(state);
3084
+ if (getViewText) return getViewText();
2752
3085
  const entries = Object.entries(state);
3086
+ const alias = aliasNames.get(state);
3087
+ const isFormatted = alias !== undefined && "_format" in state;
3088
+ const format = isFormatted ? state._format : entries.length === 1 ? "%s = %s\n" : "/\\ %s = %s\n";
3089
+ if (typeof format !== "string") {
3090
+ throw new TlaAliasFormatError(
3091
+ `The _format field of the ALIAS ${alias} is ${formatValue(format)}, but it must be a string.`,
3092
+ );
3093
+ }
2753
3094
  return entries
2754
- .map(
2755
- ([name, value]) =>
2756
- `${entries.length === 1 ? "" : "/\\ "}${name} = ${prettyPrint(formatValue(value))}\n`,
2757
- )
3095
+ .filter(([name]) => !(isFormatted && name === "_format"))
3096
+ .filter(([name, value]) => !previous || !isUnchanged(previous[name], value))
3097
+ .map(([name, value]) => {
3098
+ const text = formatJava(format, [name, prettyPrint(formatValue(value))]);
3099
+ if (text === undefined) {
3100
+ throw new TlaAliasFormatError(
3101
+ `The _format field of the ALIAS ${alias} is ${formatValue(format)}, but it must format two strings, the name and the value of a field.`,
3102
+ );
3103
+ }
3104
+ return text;
3105
+ })
2758
3106
  .join("");
2759
3107
  };