tla-ts 0.0.3 → 0.0.4-dev.2a873ee

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 (370) hide show
  1. package/README.md +46 -115
  2. package/dist/cli.cjs +1 -1
  3. package/dist/cli.js +1 -1
  4. package/dist/deciders.cjs +366 -0
  5. package/dist/deciders.js +366 -0
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +194 -8
  8. package/dist/index.d.ts +194 -8
  9. package/dist/index.js +1 -1
  10. package/dist/parallel-worker.cjs +1 -4
  11. package/dist/parallel-worker.js +1 -4
  12. package/dist/prove-worker.cjs +9 -0
  13. package/dist/prove-worker.d.cts +9 -0
  14. package/dist/prove-worker.d.ts +9 -0
  15. package/dist/prove-worker.js +9 -0
  16. package/dist/prove.cjs +996 -0
  17. package/dist/prove.js +996 -0
  18. package/dist/run-cli.cjs +37 -20
  19. package/dist/run-cli.js +37 -20
  20. package/dist/tlapm.cjs +10 -0
  21. package/dist/tlapm.js +10 -0
  22. package/dist/transfer.cjs +1387 -18
  23. package/dist/transfer.js +1387 -18
  24. package/dist/worker.cjs +21 -0
  25. package/dist/worker.js +21 -0
  26. package/package.json +24 -11
  27. package/src/ast.ts +149 -8
  28. package/src/bags.ts +4 -7
  29. package/src/builtins.ts +29 -11
  30. package/src/bundled-modules.ts +3 -3
  31. package/src/canonical.ts +4 -3
  32. package/src/check.ts +1540 -235
  33. package/src/cli-options.ts +12 -6
  34. package/src/cli.ts +8 -1
  35. package/src/codegen.ts +98 -39
  36. package/src/config.ts +254 -181
  37. package/src/dependencies.ts +2 -2
  38. package/src/environment.ts +540 -140
  39. package/src/errors.ts +284 -4
  40. package/src/evaluate.ts +1043 -293
  41. package/src/exit-codes.ts +22 -43
  42. package/src/fingerprints.ts +46 -11
  43. package/src/index.ts +11 -0
  44. package/src/instances.ts +19 -16
  45. package/src/java-overrides.ts +104 -25
  46. package/src/levels.ts +191 -45
  47. package/src/lexer.ts +127 -30
  48. package/src/live-check.ts +867 -0
  49. package/src/liveness.ts +218 -572
  50. package/src/{obligation-action.ts → obligations/action.ts} +247 -69
  51. package/src/{obligation-anon.ts → obligations/anon.ts} +49 -47
  52. package/src/obligations/ctx.ts +64 -0
  53. package/src/{obligation-deref.ts → obligations/deref.ts} +51 -92
  54. package/src/{obligation-expression.ts → obligations/expression.ts} +117 -57
  55. package/src/{obligation-format.ts → obligations/format.ts} +7 -8
  56. package/src/{obligation-generate.ts → obligations/generate.ts} +170 -192
  57. package/src/{obligations.ts → obligations/index.ts} +32 -16
  58. package/src/{obligation-levels.ts → obligations/levels.ts} +26 -28
  59. package/src/{obligation-module.ts → obligations/module.ts} +113 -121
  60. package/src/obligations/pickle.ts +98 -0
  61. package/src/obligations/pragma.ts +189 -0
  62. package/src/{obligation-printer.ts → obligations/printer.ts} +22 -80
  63. package/src/{obligation-proof.ts → obligations/proof.ts} +7 -2
  64. package/src/{obligation-source.ts → obligations/source.ts} +156 -99
  65. package/src/obligations/temporal.ts +321 -0
  66. package/src/{obligation-tuples.ts → obligations/tuples.ts} +38 -54
  67. package/src/ocaml-marshal.ts +166 -0
  68. package/src/parallel-worker.ts +169 -224
  69. package/src/parallel.ts +140 -81
  70. package/src/parser.ts +456 -147
  71. package/src/pcal-ast.ts +770 -0
  72. package/src/pcal-parse.ts +1523 -0
  73. package/src/pcal-tokenize.ts +516 -0
  74. package/src/pcal-translate.ts +1230 -0
  75. package/src/pcal-validate.ts +454 -0
  76. package/src/prove/decide-pool.ts +95 -0
  77. package/src/prove/deciders.ts +33 -0
  78. package/src/prove/first-order.ts +78 -0
  79. package/src/prove/isabelle/LICENSE +36 -0
  80. package/src/prove/isabelle/LICENSE-tlapm +26 -0
  81. package/src/prove/isabelle/decide.ts +47 -0
  82. package/src/prove/isabelle/encode.ts +446 -0
  83. package/src/prove/isabelle/isar/inner-syntax.ts +579 -0
  84. package/src/prove/isabelle/isar/method.ts +367 -0
  85. package/src/prove/isabelle/isar/proof.ts +28 -0
  86. package/src/prove/isabelle/isar/statement.ts +57 -0
  87. package/src/prove/isabelle/isar/theory.ts +192 -0
  88. package/src/prove/isabelle/isar/type-check.ts +278 -0
  89. package/src/prove/isabelle/provers/blast/blast.ts +258 -0
  90. package/src/prove/isabelle/provers/blast/branch.ts +322 -0
  91. package/src/prove/isabelle/provers/blast/prove.ts +347 -0
  92. package/src/prove/isabelle/provers/blast/rules.ts +330 -0
  93. package/src/prove/isabelle/provers/blast/state.ts +180 -0
  94. package/src/prove/isabelle/provers/blast/term.ts +546 -0
  95. package/src/prove/isabelle/provers/clasimp.ts +150 -0
  96. package/src/prove/isabelle/provers/classical.ts +389 -0
  97. package/src/prove/isabelle/provers/hypsubst.ts +433 -0
  98. package/src/prove/isabelle/pure/bicompose.ts +174 -0
  99. package/src/prove/isabelle/pure/consts.ts +32 -0
  100. package/src/prove/isabelle/pure/conv.ts +79 -0
  101. package/src/prove/isabelle/pure/drule.ts +264 -0
  102. package/src/prove/isabelle/pure/envir.ts +331 -0
  103. package/src/prove/isabelle/pure/goal.ts +53 -0
  104. package/src/prove/isabelle/pure/interrupt.ts +16 -0
  105. package/src/prove/isabelle/pure/list.ts +12 -0
  106. package/src/prove/isabelle/pure/logic.ts +330 -0
  107. package/src/prove/isabelle/pure/name.ts +98 -0
  108. package/src/prove/isabelle/pure/net.ts +215 -0
  109. package/src/prove/isabelle/pure/object-logic.ts +41 -0
  110. package/src/prove/isabelle/pure/pattern.ts +631 -0
  111. package/src/prove/isabelle/pure/raw-simplifier.ts +338 -0
  112. package/src/prove/isabelle/pure/rewriter.ts +602 -0
  113. package/src/prove/isabelle/pure/search.ts +68 -0
  114. package/src/prove/isabelle/pure/seq.ts +133 -0
  115. package/src/prove/isabelle/pure/simplifier.ts +106 -0
  116. package/src/prove/isabelle/pure/table.ts +201 -0
  117. package/src/prove/isabelle/pure/tactic.ts +168 -0
  118. package/src/prove/isabelle/pure/tactical.ts +264 -0
  119. package/src/prove/isabelle/pure/term-ord.ts +105 -0
  120. package/src/prove/isabelle/pure/term.ts +688 -0
  121. package/src/prove/isabelle/pure/thm.ts +783 -0
  122. package/src/prove/isabelle/pure/type.ts +121 -0
  123. package/src/prove/isabelle/pure/unify.ts +753 -0
  124. package/src/prove/isabelle/pure/variable.ts +25 -0
  125. package/src/prove/isabelle/tla/classical-setup.ts +101 -0
  126. package/src/prove/isabelle/tla/context.ts +74 -0
  127. package/src/prove/isabelle/tla/logic-data.ts +5 -0
  128. package/src/prove/isabelle/tla/logic.ts +215 -0
  129. package/src/prove/isabelle/tla/simpdata.ts +241 -0
  130. package/src/prove/isabelle/tools/intuitionistic.ts +132 -0
  131. package/src/prove/ocaml.ts +22 -0
  132. package/src/prove/prep/action.ts +508 -0
  133. package/src/prove/prep/defs.ts +33 -0
  134. package/src/prove/prep/elab.ts +156 -0
  135. package/src/prove/prep/enabled-axioms.ts +189 -0
  136. package/src/prove/prep/enabled.ts +43 -0
  137. package/src/prove/prep/fingerprint.ts +388 -0
  138. package/src/prove/prep/flatten.ts +70 -0
  139. package/src/prove/prep/level-comparison.ts +529 -0
  140. package/src/prove/prep/md5.ts +67 -0
  141. package/src/prove/prep/pragma.ts +221 -0
  142. package/src/prove/prep/trivial.ts +22 -0
  143. package/src/prove/prove-worker.ts +22 -0
  144. package/src/prove/prove.ts +498 -0
  145. package/src/prove/ptl/decide.ts +68 -0
  146. package/src/prove/ptl/encode.ts +255 -0
  147. package/src/prove/ptl/sat.ts +151 -0
  148. package/src/prove/ptl/tableau.ts +276 -0
  149. package/src/prove/smt/axiomatize.ts +69 -0
  150. package/src/prove/smt/axioms.ts +209 -0
  151. package/src/prove/smt/context.ts +108 -0
  152. package/src/prove/smt/data.ts +636 -0
  153. package/src/prove/smt/encode.ts +164 -0
  154. package/src/prove/smt/extensionality.ts +65 -0
  155. package/src/prove/smt/flatten.ts +112 -0
  156. package/src/prove/smt/format.ts +154 -0
  157. package/src/prove/smt/instances.ts +181 -0
  158. package/src/prove/smt/rewrite.ts +772 -0
  159. package/src/prove/smt/simplify.ts +57 -0
  160. package/src/prove/smt/solver/act-cache.ts +265 -0
  161. package/src/prove/smt/solver/arith-rewriter.ts +962 -0
  162. package/src/prove/smt/solver/array.ts +22 -0
  163. package/src/prove/smt/solver/asserted-formulas.ts +469 -0
  164. package/src/prove/smt/solver/ast-lt.ts +157 -0
  165. package/src/prove/smt/solver/ast-util.ts +91 -0
  166. package/src/prove/smt/solver/ast.ts +1315 -0
  167. package/src/prove/smt/solver/auf-solver.ts +572 -0
  168. package/src/prove/smt/solver/case-split-queue.ts +178 -0
  169. package/src/prove/smt/solver/cg-table.ts +175 -0
  170. package/src/prove/smt/solver/clause.ts +276 -0
  171. package/src/prove/smt/solver/conflict-resolution.ts +343 -0
  172. package/src/prove/smt/solver/context.ts +1292 -0
  173. package/src/prove/smt/solver/ctx-simplify.ts +334 -0
  174. package/src/prove/smt/solver/der.ts +224 -0
  175. package/src/prove/smt/solver/dyn-ack.ts +141 -0
  176. package/src/prove/smt/solver/e-matching.ts +659 -0
  177. package/src/prove/smt/solver/enode.ts +259 -0
  178. package/src/prove/smt/solver/expr-ref.ts +21 -0
  179. package/src/prove/smt/solver/expr-safe-replace.ts +172 -0
  180. package/src/prove/smt/solver/fingerprints.ts +92 -0
  181. package/src/prove/smt/solver/flat-literals.ts +51 -0
  182. package/src/prove/smt/solver/goal.ts +138 -0
  183. package/src/prove/smt/solver/hash.ts +173 -0
  184. package/src/prove/smt/solver/hashtable.ts +166 -0
  185. package/src/prove/smt/solver/internalizer.ts +1381 -0
  186. package/src/prove/smt/solver/lbool.ts +5 -0
  187. package/src/prove/smt/solver/literal.ts +24 -0
  188. package/src/prove/smt/solver/lp/bound-propagator.ts +391 -0
  189. package/src/prove/smt/solver/lp/constraints.ts +78 -0
  190. package/src/prove/smt/solver/lp/containers.ts +296 -0
  191. package/src/prove/smt/solver/lp/core-solver.ts +504 -0
  192. package/src/prove/smt/solver/lp/cross-nested.ts +224 -0
  193. package/src/prove/smt/solver/lp/dep-intervals.ts +642 -0
  194. package/src/prove/smt/solver/lp/dependency.ts +51 -0
  195. package/src/prove/smt/solver/lp/dioph-eq.ts +1181 -0
  196. package/src/prove/smt/solver/lp/explanation.ts +46 -0
  197. package/src/prove/smt/solver/lp/gomory.ts +255 -0
  198. package/src/prove/smt/solver/lp/hnf-cutter.ts +125 -0
  199. package/src/prove/smt/solver/lp/hnf.ts +281 -0
  200. package/src/prove/smt/solver/lp/int-cube.ts +295 -0
  201. package/src/prove/smt/solver/lp/int-solver.ts +514 -0
  202. package/src/prove/smt/solver/lp/lar-solver.ts +816 -0
  203. package/src/prove/smt/solver/lp/lar-term.ts +62 -0
  204. package/src/prove/smt/solver/lp/lp-settings.ts +91 -0
  205. package/src/prove/smt/solver/lp/maximize-term.ts +347 -0
  206. package/src/prove/smt/solver/lp/nex-creator.ts +381 -0
  207. package/src/prove/smt/solver/lp/nex.ts +120 -0
  208. package/src/prove/smt/solver/lp/nla-backoff.ts +43 -0
  209. package/src/prove/smt/solver/lp/nla-basics.ts +398 -0
  210. package/src/prove/smt/solver/lp/nla-core.ts +968 -0
  211. package/src/prove/smt/solver/lp/nla-divisions.ts +332 -0
  212. package/src/prove/smt/solver/lp/nla-emonics.ts +373 -0
  213. package/src/prove/smt/solver/lp/nla-factorization.ts +30 -0
  214. package/src/prove/smt/solver/lp/nla-grobner.ts +904 -0
  215. package/src/prove/smt/solver/lp/nla-horner.ts +126 -0
  216. package/src/prove/smt/solver/lp/nla-intervals.ts +265 -0
  217. package/src/prove/smt/solver/lp/nla-monomial-bounds.ts +715 -0
  218. package/src/prove/smt/solver/lp/nla-monotone.ts +59 -0
  219. package/src/prove/smt/solver/lp/nla-order.ts +307 -0
  220. package/src/prove/smt/solver/lp/nla-patcher.ts +112 -0
  221. package/src/prove/smt/solver/lp/nla-tangents.ts +251 -0
  222. package/src/prove/smt/solver/lp/nla-throttle.ts +85 -0
  223. package/src/prove/smt/solver/lp/nla-types.ts +124 -0
  224. package/src/prove/smt/solver/lp/nla-var-eqs.ts +141 -0
  225. package/src/prove/smt/solver/lp/nra-solver.ts +440 -0
  226. package/src/prove/smt/solver/lp/numeric-pair.ts +65 -0
  227. package/src/prove/smt/solver/lp/pdd-interval.ts +31 -0
  228. package/src/prove/smt/solver/lp/pdd-simplifier.ts +184 -0
  229. package/src/prove/smt/solver/lp/pdd-solver.ts +408 -0
  230. package/src/prove/smt/solver/lp/pdd.ts +971 -0
  231. package/src/prove/smt/solver/lp/random-updater.ts +138 -0
  232. package/src/prove/smt/solver/lp/static-matrix.ts +246 -0
  233. package/src/prove/smt/solver/lp/union-find.ts +96 -0
  234. package/src/prove/smt/solver/mam-compiler.ts +847 -0
  235. package/src/prove/smt/solver/mam-interpreter.ts +400 -0
  236. package/src/prove/smt/solver/maximize-ac-sharing.ts +118 -0
  237. package/src/prove/smt/solver/model-checker.ts +347 -0
  238. package/src/prove/smt/solver/model-evaluator.ts +262 -0
  239. package/src/prove/smt/solver/model-finder.ts +155 -0
  240. package/src/prove/smt/solver/model-generator.ts +97 -0
  241. package/src/prove/smt/solver/model-macro-solver.ts +728 -0
  242. package/src/prove/smt/solver/nlsat/algebraic.ts +1161 -0
  243. package/src/prove/smt/solver/nlsat/atoms.ts +238 -0
  244. package/src/prove/smt/solver/nlsat/evaluator.ts +303 -0
  245. package/src/prove/smt/solver/nlsat/explain.ts +607 -0
  246. package/src/prove/smt/solver/nlsat/interval-set.ts +351 -0
  247. package/src/prove/smt/solver/nlsat/levelwise.ts +737 -0
  248. package/src/prove/smt/solver/nlsat/mpbq.ts +161 -0
  249. package/src/prove/smt/solver/nlsat/polynomial.ts +1722 -0
  250. package/src/prove/smt/solver/nlsat/solver.ts +911 -0
  251. package/src/prove/smt/solver/nlsat/types.ts +43 -0
  252. package/src/prove/smt/solver/nlsat/upolynomial-factorization.ts +648 -0
  253. package/src/prove/smt/solver/nlsat/upolynomial.ts +996 -0
  254. package/src/prove/smt/solver/nnf.ts +469 -0
  255. package/src/prove/smt/solver/pattern-inference.ts +351 -0
  256. package/src/prove/smt/solver/poly-rewriter.ts +477 -0
  257. package/src/prove/smt/solver/propagate-values.ts +83 -0
  258. package/src/prove/smt/solver/proto-model.ts +551 -0
  259. package/src/prove/smt/solver/pull-quant.ts +139 -0
  260. package/src/prove/smt/solver/qe-lite-der.ts +526 -0
  261. package/src/prove/smt/solver/qe-lite-fm.ts +576 -0
  262. package/src/prove/smt/solver/qe-lite.ts +381 -0
  263. package/src/prove/smt/solver/qi-queue.ts +362 -0
  264. package/src/prove/smt/solver/quant-tactics.ts +117 -0
  265. package/src/prove/smt/solver/quantifier-analyzer.ts +562 -0
  266. package/src/prove/smt/solver/quantifier-manager.ts +186 -0
  267. package/src/prove/smt/solver/random-gen.ts +10 -0
  268. package/src/prove/smt/solver/rational.ts +165 -0
  269. package/src/prove/smt/solver/ref-vector.ts +62 -0
  270. package/src/prove/smt/solver/relevancy.ts +247 -0
  271. package/src/prove/smt/solver/rewriter-tpl.ts +1159 -0
  272. package/src/prove/smt/solver/rewriter.ts +843 -0
  273. package/src/prove/smt/solver/rlimit.ts +79 -0
  274. package/src/prove/smt/solver/smtlib-parser.ts +526 -0
  275. package/src/prove/smt/solver/solver.ts +71 -0
  276. package/src/prove/smt/solver/sort.ts +35 -0
  277. package/src/prove/smt/solver/sticky-generations.ts +69 -0
  278. package/src/prove/smt/solver/theory-lra-axioms.ts +340 -0
  279. package/src/prove/smt/solver/theory-lra-bounds.ts +226 -0
  280. package/src/prove/smt/solver/theory-lra-final-check.ts +252 -0
  281. package/src/prove/smt/solver/theory-lra-internalize.ts +476 -0
  282. package/src/prove/smt/solver/theory-lra-model.ts +243 -0
  283. package/src/prove/smt/solver/theory-lra-propagate.ts +405 -0
  284. package/src/prove/smt/solver/theory-lra-state.ts +43 -0
  285. package/src/prove/smt/solver/theory-lra.ts +56 -0
  286. package/src/prove/smt/solver/var-subst.ts +258 -0
  287. package/src/prove/smt/solver/z3-license.txt +10 -0
  288. package/src/prove/smt/table.ts +170 -0
  289. package/src/prove/tlapm/tlapm.ts +96 -0
  290. package/src/prove/tlaps-module.ts +510 -0
  291. package/src/prove/verdict.ts +18 -0
  292. package/src/prove/zenon/LICENSE +32 -0
  293. package/src/prove/zenon/check/check.ts +105 -0
  294. package/src/prove/zenon/check/definitions.ts +144 -0
  295. package/src/prove/zenon/check/equality.ts +182 -0
  296. package/src/prove/zenon/check/functions.ts +62 -0
  297. package/src/prove/zenon/check/keys.ts +125 -0
  298. package/src/prove/zenon/check/propositional.ts +104 -0
  299. package/src/prove/zenon/check/records.ts +188 -0
  300. package/src/prove/zenon/check/relations.ts +121 -0
  301. package/src/prove/zenon/check/rewrites.ts +224 -0
  302. package/src/prove/zenon/check/sets.ts +302 -0
  303. package/src/prove/zenon/check/terms.ts +127 -0
  304. package/src/prove/zenon/check/tla.ts +126 -0
  305. package/src/prove/zenon/decide.ts +113 -0
  306. package/src/prove/zenon/encode.ts +379 -0
  307. package/src/prove/zenon/eqrel.ts +300 -0
  308. package/src/prove/zenon/equality-rules.ts +435 -0
  309. package/src/prove/zenon/expr.ts +551 -0
  310. package/src/prove/zenon/index-table.ts +350 -0
  311. package/src/prove/zenon/isar-case.ts +513 -0
  312. package/src/prove/zenon/isar.ts +1249 -0
  313. package/src/prove/zenon/limits.ts +15 -0
  314. package/src/prove/zenon/llproof.ts +173 -0
  315. package/src/prove/zenon/mltoll.ts +1566 -0
  316. package/src/prove/zenon/node.ts +297 -0
  317. package/src/prove/zenon/ocaml.ts +169 -0
  318. package/src/prove/zenon/parse.ts +247 -0
  319. package/src/prove/zenon/phrase.ts +191 -0
  320. package/src/prove/zenon/proof.ts +198 -0
  321. package/src/prove/zenon/propositional-rules.ts +387 -0
  322. package/src/prove/zenon/rules.ts +94 -0
  323. package/src/prove/zenon/search.ts +288 -0
  324. package/src/prove/zenon/tla/functions.ts +151 -0
  325. package/src/prove/zenon/tla/llproof.ts +480 -0
  326. package/src/prove/zenon/tla/records.ts +225 -0
  327. package/src/prove/zenon/tla/rewrites.ts +447 -0
  328. package/src/prove/zenon/tla/sets.ts +304 -0
  329. package/src/prove/zenon/tla/terms.ts +162 -0
  330. package/src/prove/zenon/tla/tla.ts +506 -0
  331. package/src/randomization.ts +24 -7
  332. package/src/resolve.ts +1481 -426
  333. package/src/run-cli.ts +1483 -212
  334. package/src/runtime.ts +19 -1
  335. package/src/sany-builtins.ts +147 -0
  336. package/src/sany-generator.ts +3128 -0
  337. package/src/sany-levels.ts +1208 -0
  338. package/src/sany-lexer.ts +545 -0
  339. package/src/sany-linter.ts +122 -0
  340. package/src/sany-modules.ts +1398 -0
  341. package/src/sany-nodes.ts +463 -0
  342. package/src/sany-parse-error.ts +2161 -0
  343. package/src/sany-report.ts +356 -0
  344. package/src/sany-selectors.ts +738 -0
  345. package/src/sany-source.ts +248 -0
  346. package/src/sany-xml.ts +1017 -0
  347. package/src/spec-description.ts +42 -11
  348. package/src/standard-modules.ts +203 -148
  349. package/src/standard-ranges.ts +116 -0
  350. package/src/state-graph.ts +180 -0
  351. package/src/subexpressions.ts +231 -171
  352. package/src/substitution-levels.ts +38 -17
  353. package/src/successors.ts +241 -110
  354. package/src/symmetry.ts +194 -54
  355. package/src/tableau.ts +54 -25
  356. package/src/tlapm-cache.ts +236 -0
  357. package/src/tlc-ext.ts +42 -29
  358. package/src/tlc-messages.ts +329 -0
  359. package/src/tlc-module.ts +52 -43
  360. package/src/tlc-modules.ts +4 -0
  361. package/src/tlc-order.ts +78 -10
  362. package/src/tlc-random.ts +84 -33
  363. package/src/tlc-replay.ts +655 -0
  364. package/src/tlc-summary.ts +20 -5
  365. package/src/tlc-version.ts +19 -0
  366. package/src/transfer.ts +15 -3
  367. package/src/values.ts +787 -190
  368. package/src/worker.ts +65 -0
  369. package/dist/parallel.cjs +0 -12
  370. package/dist/parallel.js +0 -12
package/src/values.ts CHANGED
@@ -1,10 +1,12 @@
1
1
  import { TlaEvaluationError, TlaModuleError } from "./errors";
2
2
  import { prettyPrint } from "./pretty-print";
3
+ import type { TlcVersion } from "./tlc-version";
3
4
 
4
5
  export interface ModelValue {
5
6
  kind: "ModelValue";
6
7
  name: string;
7
8
  type: string | undefined;
9
+ rank: number;
8
10
  }
9
11
 
10
12
  export interface SetValue {
@@ -12,6 +14,7 @@ export interface SetValue {
12
14
  elements: Value[];
13
15
  hash: number;
14
16
  fingerprint: number;
17
+ isFingerprinted: boolean;
15
18
  }
16
19
 
17
20
  // A set enumeration whose elements TLC can't sort, such as {1, "a"}. TLC sorts a set enumeration
@@ -28,6 +31,8 @@ export interface FunctionValue {
28
31
  hash: number;
29
32
  fingerprint: number;
30
33
  writtenKeys: Value[] | undefined;
34
+ functionClass: FunctionClass | undefined;
35
+ isFingerprinted: boolean;
31
36
  }
32
37
 
33
38
  export interface IntervalValue {
@@ -75,10 +80,17 @@ export interface SetOperationValue {
75
80
  right: Value;
76
81
  }
77
82
 
83
+ // TLC prints a set filter as its bound names and the location of its predicate.
84
+ interface FilteredSetSource {
85
+ names: string;
86
+ predicate: string;
87
+ }
88
+
78
89
  export interface FilteredSetValue {
79
90
  kind: "FilteredSet";
80
91
  base: Value;
81
92
  test: (element: Value) => boolean;
93
+ source?: FilteredSetSource;
82
94
  }
83
95
 
84
96
  // UNION S when some element of S isn't a set enumeration. TLC enumerates it only when it has to.
@@ -102,6 +114,7 @@ export interface LazyFunctionValue {
102
114
  domain: Value;
103
115
  apply: (argument: Value) => Value;
104
116
  source?: LazyFunctionSource;
117
+ functionClass?: FunctionClass;
105
118
  }
106
119
 
107
120
  export type Value =
@@ -136,6 +149,12 @@ export const isSetValue = (value: Value) =>
136
149
  value.kind !== "Function" &&
137
150
  value.kind !== "LazyFunction";
138
151
 
152
+ // TLC's Reducible values, SetEnumValue and IntervalValue, which combine with another set element by
153
+ // element.
154
+ export const isReducibleSet = (value: Value): value is SetValue | MixedSetValue | IntervalValue =>
155
+ typeof value === "object" &&
156
+ (value.kind === "Set" || value.kind === "MixedSet" || value.kind === "Interval");
157
+
139
158
  export const isFunctionValue = (value: Value): value is FunctionValue | LazyFunctionValue =>
140
159
  typeof value === "object" && (value.kind === "Function" || value.kind === "LazyFunction");
141
160
 
@@ -174,7 +193,7 @@ export const getWrittenPairs = (functionValue: FunctionValue): [Value, Value][]
174
193
  };
175
194
 
176
195
  export const createWrittenRecord = (names: Value[], range: Value[], writtenNames: Value[]) =>
177
- setWrittenOrder(createSortedFunction(names, range), writtenNames);
196
+ setWrittenOrder(createSortedRecord(names, range), writtenNames);
178
197
 
179
198
  // TLC sorts a value it compares even with itself, and every value inside it, so a value it has
180
199
  // hashed or fingerprinted is already sorted.
@@ -215,7 +234,13 @@ const compareFunctions = (left: FunctionValue, right: FunctionValue) => {
215
234
  const rightRange = right.range;
216
235
  if (leftRange === rightRange) return 0;
217
236
  for (let index = 0; index < leftRange.length; index++) {
218
- const valueComparison = compareValues(leftRange[index], rightRange[index]);
237
+ const leftValue = leftRange[index];
238
+ const rightValue = rightRange[index];
239
+ // V8 can't inline the recursive compareValues here, so two numbers skip the call.
240
+ const valueComparison =
241
+ typeof leftValue === "number" && typeof rightValue === "number"
242
+ ? leftValue - rightValue
243
+ : compareValues(leftValue, rightValue);
219
244
  if (valueComparison !== 0) return valueComparison;
220
245
  }
221
246
  return 0;
@@ -259,14 +284,26 @@ const checkModelValueTypes = (left: Value, right: Value, isEquality: boolean) =>
259
284
 
260
285
  // TLC orders strings and model value names by when it first interned the text, so every
261
286
  // check sets the order of its spec's strings before it builds any value.
262
- const stringOrder = { ranks: Object.create(null) as Record<string, number>, size: 0 };
287
+ const stringOrder: { ranks: Record<string, number>; size: number } = {
288
+ ranks: Object.create(null),
289
+ size: 0,
290
+ };
263
291
 
264
292
  export const setStringOrder = (texts: Iterable<string>) => {
265
293
  stringOrder.ranks = Object.create(null);
266
294
  stringOrder.size = 0;
295
+ modelValues.clear();
267
296
  for (const text of texts) rankString(text);
268
297
  };
269
298
 
299
+ // TLC 1.7.4 prints an empty function that isn't a tuple with a space between its brackets, and
300
+ // looks a key up in a function differently, so every check also sets the version its values follow.
301
+ const valueVersion = { is174: false };
302
+
303
+ export const setValueVersion = (version: TlcVersion | undefined) => {
304
+ valueVersion.is174 = version === "1.7.4";
305
+ };
306
+
270
307
  export const rankString = (text: string) => {
271
308
  if (stringOrder.ranks[text] === undefined) stringOrder.ranks[text] = stringOrder.size++;
272
309
  return text;
@@ -353,7 +390,7 @@ export const compareValues = (left: Value, right: Value): number => {
353
390
  if (left.type !== undefined && right.type !== undefined) {
354
391
  checkModelValueTypes(left, right, false);
355
392
  }
356
- return compareStrings(left.name, right.name);
393
+ return left.rank - right.rank;
357
394
  }
358
395
  if (leftKind === "ModelValue" || rightKind === "ModelValue") {
359
396
  checkModelValueTypes(left, right, false);
@@ -385,14 +422,15 @@ export const compareValues = (left: Value, right: Value): number => {
385
422
 
386
423
  const modelValues = new Map<string, ModelValue>();
387
424
 
425
+ // A check ranks every model value's name when it creates the value, and creates its own values.
388
426
  export const createModelValue = (name: string): ModelValue => {
389
- rankString(name);
390
427
  const known = modelValues.get(name);
391
428
  if (known) return known;
392
429
  const value: ModelValue = {
393
430
  kind: "ModelValue",
394
431
  name,
395
432
  type: name.length > 2 && name[1] === "_" ? name[0] : undefined,
433
+ rank: getStringRank(name),
396
434
  };
397
435
  modelValues.set(name, value);
398
436
  return value;
@@ -403,6 +441,7 @@ export const createSortedSet = (elements: Value[]): SetValue => ({
403
441
  elements,
404
442
  hash: 0,
405
443
  fingerprint: 0,
444
+ isFingerprinted: false,
406
445
  });
407
446
 
408
447
  export const createSortedFunction = (domain: Value[], range: Value[]): FunctionValue => ({
@@ -412,9 +451,104 @@ export const createSortedFunction = (domain: Value[], range: Value[]): FunctionV
412
451
  hash: 0,
413
452
  fingerprint: 0,
414
453
  writtenKeys: undefined,
454
+ functionClass: undefined,
455
+ isFingerprinted: false,
415
456
  });
416
457
 
458
+ // TLC words a failed function application by the Java class of the function: FcnLambdaValue for
459
+ // [x \in S |-> e], TupleValue for <<...>> and what the sequence operators build, RecordValue for
460
+ // [a |-> e], and FcnRcdValue for any other function.
461
+ export type FunctionClass = "lambda" | "tuple" | "record";
462
+
463
+ // Whether a lambda exists for markFingerprinted to find, so that a spec without one skips the walk.
464
+ const lambdaPresence = { isPresent: false };
465
+
466
+ export const setFunctionClass = <FunctionLike extends FunctionValue | LazyFunctionValue>(
467
+ functionValue: FunctionLike,
468
+ functionClass: FunctionClass | undefined,
469
+ ) => {
470
+ if (functionClass === "lambda") lambdaPresence.isPresent = true;
471
+ if (functionClass !== undefined) functionValue.functionClass = functionClass;
472
+ return functionValue;
473
+ };
474
+
475
+ export const getFunctionClass = (value: Value) =>
476
+ typeof value === "object" && (value.kind === "Function" || value.kind === "LazyFunction")
477
+ ? value.functionClass
478
+ : undefined;
479
+
480
+ export const markLambdaFunction = <FunctionLike extends FunctionValue | LazyFunctionValue>(
481
+ functionValue: FunctionLike,
482
+ ) => setFunctionClass(functionValue, "lambda");
483
+
484
+ const fingerprintedValues = new WeakSet<ObjectValue>();
485
+
486
+ // The lazy sets TLC has cached the elements of. TLC caches a set as the receiver of compareTo,
487
+ // equals, size, and fingerPrint, not as their argument, and enumerates the sets an uncached one
488
+ // combines, duplicates and all.
489
+ const cachedSets = new WeakSet<ObjectValue>();
490
+
491
+ // Whether the spec has built a UNION or \cup set, the sets that stream duplicates, so that a spec
492
+ // without one skips tracking what TLC caches.
493
+ const streamedSetPresence = { isPresent: false };
494
+
495
+ export const markStreamedSet = <Streamed extends UnionValue | SetOperationValue>(
496
+ value: Streamed,
497
+ ) => {
498
+ streamedSetPresence.isPresent = true;
499
+ return value;
500
+ };
501
+
502
+ // The sets that stream their elements apart from the normalized set until TLC caches them.
503
+ const STREAMING_KINDS = new Set<ObjectValue["kind"]>([
504
+ "Union",
505
+ "SetOperation",
506
+ "FilteredSet",
507
+ "ProductSet",
508
+ "RecordSet",
509
+ "FunctionSet",
510
+ ]);
511
+
512
+ const cacheSet = (value: Value) => {
513
+ if (
514
+ streamedSetPresence.isPresent &&
515
+ typeof value === "object" &&
516
+ STREAMING_KINDS.has(value.kind)
517
+ ) {
518
+ cachedSets.add(value);
519
+ }
520
+ };
521
+
522
+ // FcnLambdaValue#fingerPrint caches the FcnRcdValue the function enumerates to, which applies it
523
+ // from then on, so a function TLC has fingerprinted is no longer a lambda.
524
+ export const markFingerprinted = (value: Value): void => {
525
+ if ((!lambdaPresence.isPresent && !streamedSetPresence.isPresent) || typeof value !== "object") {
526
+ return;
527
+ }
528
+ if (value.kind === "Function" || value.kind === "Set") {
529
+ if (value.isFingerprinted) return;
530
+ value.isFingerprinted = true;
531
+ } else {
532
+ if (fingerprintedValues.has(value)) return;
533
+ fingerprintedValues.add(value);
534
+ }
535
+ if (value.kind === "Function") {
536
+ if (value.functionClass === "lambda") value.functionClass = undefined;
537
+ value.domain.forEach(markFingerprinted);
538
+ value.range.forEach(markFingerprinted);
539
+ } else if (value.kind === "Set" || value.kind === "MixedSet") {
540
+ value.elements.forEach(markFingerprinted);
541
+ } else if (isSetValue(value) && isEnumerable(value)) {
542
+ cacheSet(value);
543
+ toFiniteSet(value).elements.forEach(markFingerprinted);
544
+ }
545
+ };
546
+
547
+ export const createSortedRecord = (names: Value[], range: Value[]) =>
548
+ setFunctionClass(createSortedFunction(names, range), "record");
549
+
417
550
  export const valuesEqual = (left: Value, right: Value): boolean => {
551
+ cacheSet(left);
418
552
  if (left === right) {
419
553
  if (writtenOrderUse.isUsed) forgetWrittenOrder(left);
420
554
  return left !== ANY_SET || compareAny(left);
@@ -488,28 +622,41 @@ export const valuesEqual = (left: Value, right: Value): boolean => {
488
622
  return compareValues(left, right) === 0;
489
623
  };
490
624
 
491
- const areSameValues = (left: Value[], right: Value[]) =>
492
- left === right ||
493
- (left.length === right.length &&
494
- left.every((element, index) => isSameValue(element, right[index])));
495
-
496
- export const isSameValue = (left: Value, right: Value): boolean => {
497
- if (left === right) return true;
498
- if (typeof left !== "object" || typeof right !== "object") return false;
499
- if (left.kind === "Set" && right.kind === "Set")
500
- return (
501
- (left.hash === 0 || right.hash === 0 || left.hash === right.hash) &&
502
- areSameValues(left.elements, right.elements)
503
- );
504
- if (left.kind === "Function" && right.kind === "Function")
505
- return (
506
- (left.hash === 0 || right.hash === 0 || left.hash === right.hash) &&
507
- areSameValues(left.domain, right.domain) &&
508
- areSameValues(left.range, right.range)
509
- );
510
- return getValueKey(left) === getValueKey(right);
625
+ // TLC prints and words errors about an equal function by its Java class, so a value can stand for
626
+ // another in a state only if each function in it has the same class.
627
+ const createSameValueCheck = (isClassSensitive: boolean) => {
628
+ const areSameValues = (left: Value[], right: Value[]) => {
629
+ if (left === right) return true;
630
+ if (left.length !== right.length) return false;
631
+ for (let index = 0; index < left.length; index++) {
632
+ if (!isSame(left[index], right[index])) return false;
633
+ }
634
+ return true;
635
+ };
636
+ const isSame = (left: Value, right: Value): boolean => {
637
+ if (left === right) return true;
638
+ if (typeof left !== "object" || typeof right !== "object") return false;
639
+ if (left.kind === "Set" && right.kind === "Set")
640
+ return (
641
+ (left.hash === 0 || right.hash === 0 || left.hash === right.hash) &&
642
+ areSameValues(left.elements, right.elements)
643
+ );
644
+ if (left.kind === "Function" && right.kind === "Function")
645
+ return (
646
+ (!isClassSensitive || left.functionClass === right.functionClass) &&
647
+ (left.hash === 0 || right.hash === 0 || left.hash === right.hash) &&
648
+ areSameValues(left.domain, right.domain) &&
649
+ areSameValues(left.range, right.range)
650
+ );
651
+ return getValueKey(left) === getValueKey(right);
652
+ };
653
+ return isSame;
511
654
  };
512
655
 
656
+ export const isSameValue = createSameValueCheck(false);
657
+
658
+ export const isInterchangeableValue = createSameValueCheck(true);
659
+
513
660
  // The comparisons above fail with their own messages. These follow the compareTo and equals
514
661
  // methods of TLC's Java value classes, which word a failure by the class of the left operand, so a
515
662
  // failed comparison runs again through them to fail as TLC does.
@@ -562,7 +709,7 @@ const equalsModelValueWith = (modelValue: ModelValue, other: Value) => {
562
709
 
563
710
  const compareModelValue = (left: ModelValue, right: Value) => {
564
711
  const type = getModelValueType(left);
565
- if (type === undefined) return isModelValue(right) ? compareStrings(left.name, right.name) : -1;
712
+ if (type === undefined) return isModelValue(right) ? left.rank - right.rank : -1;
566
713
  if (!isModelValue(right)) {
567
714
  throw new TlaEvaluationError(
568
715
  `Attempted to compare the typed model value ${formatValue(left)} and non-model value\n${formatValue(right)}`,
@@ -574,7 +721,7 @@ const compareModelValue = (left: ModelValue, right: Value) => {
574
721
  `Attempted to compare the differently-typed model values ${formatValue(left)} and ${formatValue(right)}`,
575
722
  );
576
723
  }
577
- return compareStrings(left.name, right.name);
724
+ return left.rank - right.rank;
578
725
  };
579
726
 
580
727
  const equalsModelValue = (left: ModelValue, right: Value) => {
@@ -665,7 +812,7 @@ const compareFunctionLikeTlc = (left: FunctionValue | LazyFunctionValue, right:
665
812
  compareElementsLikeTlc(functionValue.range, tuple)
666
813
  );
667
814
  }
668
- if (left.kind === "Function" && functionValue.domain.every((key) => typeof key === "string")) {
815
+ if (getFunctionClass(left) === "record") {
669
816
  const record = toTlcRecord(right);
670
817
  if (!record) {
671
818
  if (isModelValue(right)) return compareModelValueWith(right, left);
@@ -783,7 +930,7 @@ const equalsFunctionLikeTlc = (left: FunctionValue | LazyFunctionValue, right: V
783
930
  equalsElementsLikeTlc(functionValue.range, tuple)
784
931
  );
785
932
  }
786
- if (left.kind === "Function" && functionValue.domain.every((key) => typeof key === "string")) {
933
+ if (getFunctionClass(left) === "record") {
787
934
  const record = toTlcRecord(right);
788
935
  if (!record) {
789
936
  if (isModelValue(right)) return equalsModelValueWith(right, left);
@@ -835,32 +982,62 @@ const equalsLikeTlc = (left: Value, right: Value): boolean => {
835
982
  const sortLikeTlc = (elements: Value[]) => {
836
983
  const sorted: Value[] = [];
837
984
  for (const element of elements) {
838
- const bounds = { low: 0, high: sorted.length, comparison: 1 };
839
- while (bounds.low < bounds.high) {
840
- const middle = bounds.low + ((bounds.high - bounds.low) >> 1);
841
- bounds.comparison = compareLikeTlc(element, sorted[middle]);
842
- if (bounds.comparison === 0) break;
843
- if (bounds.comparison < 0) bounds.high = middle;
844
- else bounds.low = middle + 1;
845
- }
846
- if (bounds.comparison !== 0) sorted.splice(bounds.low, 0, element);
985
+ const found = searchLikeTlc(element, sorted);
986
+ if (!found.isFound) sorted.splice(found.index, 0, element);
847
987
  }
848
988
  return sorted;
849
989
  };
850
990
 
851
- // TLC checks membership in a set enumeration it hasn't sorted element by element.
991
+ // Calls a method of a value as TLC does, whose failure the value heads when it has a source.
992
+ const callTracedMethod = <Result>(receiver: Value, method: () => Result) => {
993
+ const sets = setTrace.sets;
994
+ if (sets === undefined) return method();
995
+ sets.push(receiver);
996
+ const result = method();
997
+ sets.pop();
998
+ return result;
999
+ };
1000
+
1001
+ // ValueVec.search on sorted elements: a binary search with compareTo, which ends where the element
1002
+ // is or would go.
1003
+ const searchLikeTlc = (element: Value, sorted: Value[]) => {
1004
+ const bounds = { low: 0, high: sorted.length };
1005
+ while (bounds.low < bounds.high) {
1006
+ const middle = bounds.low + ((bounds.high - bounds.low) >> 1);
1007
+ const comparison = callTracedMethod(element, () => compareLikeTlc(element, sorted[middle]));
1008
+ if (comparison === 0) return { index: middle, isFound: true };
1009
+ if (comparison < 0) bounds.high = middle;
1010
+ else bounds.low = middle + 1;
1011
+ }
1012
+ return { index: bounds.low, isFound: false };
1013
+ };
1014
+
1015
+ // TLC checks membership in a set enumeration it hasn't sorted element by element, with the equals
1016
+ // method of each member.
852
1017
  const isElementOfLikeTlc = (element: Value, elements: Value[]) =>
853
- elements.some((member) => equalsLikeTlc(member, element));
1018
+ elements.some((member) => callTracedMethod(member, () => equalsLikeTlc(member, element)));
854
1019
 
855
- export const isEqualLikeTlc = (left: Value, right: Value) => {
856
- try {
857
- return valuesEqual(left, right);
858
- } catch (error) {
859
- if (!(error instanceof TlaEvaluationError)) throw error;
860
- return equalsLikeTlc(left, right);
1020
+ // The sets TLC has normalized, whose membership ValueVec.search checks by binary search with
1021
+ // compareTo instead of element by element.
1022
+ const normalizedSets = new WeakSet<SetValue>();
1023
+
1024
+ // IValue.deepNormalize, which TLC applies to the constants of the config and the constant
1025
+ // definitions it computes as it starts.
1026
+ export const markNormalized = (value: Value): void => {
1027
+ if (typeof value !== "object") return;
1028
+ if (value.kind === "Set") {
1029
+ normalizedSets.add(value);
1030
+ value.elements.forEach(markNormalized);
1031
+ }
1032
+ if (value.kind === "Function") {
1033
+ value.domain.forEach(markNormalized);
1034
+ value.range.forEach(markNormalized);
861
1035
  }
862
1036
  };
863
1037
 
1038
+ export const isEqualLikeTlc = (left: Value, right: Value) =>
1039
+ computeLikeTlcOnFailure(valuesEqual, equalsLikeTlc, left, right);
1040
+
864
1041
  const isStrictlySorted = (elements: Value[]) => {
865
1042
  for (let index = 1; index < elements.length; index++) {
866
1043
  if (compareValues(elements[index - 1], elements[index]) >= 0) return false;
@@ -869,6 +1046,8 @@ const isStrictlySorted = (elements: Value[]) => {
869
1046
  };
870
1047
 
871
1048
  export const createSet = (elements: Value[]): SetValue => {
1049
+ // ValueVec.sort compares each element after the first with those before it.
1050
+ for (let index = 1; index < elements.length; index++) cacheSet(elements[index]);
872
1051
  if (elements.length < 2 || isStrictlySorted(elements)) return createSortedSet(elements);
873
1052
  const sorted = [...elements].sort(compareValues);
874
1053
  const unique = [sorted[0]];
@@ -880,14 +1059,13 @@ export const createSet = (elements: Value[]): SetValue => {
880
1059
 
881
1060
  // TLC builds a set enumeration without sorting it, so one whose elements it can't compare still
882
1061
  // evaluates.
883
- export const createEnumeratedSet = (elements: Value[]): SetValue | MixedSetValue => {
884
- try {
885
- return createSet(elements);
886
- } catch (error) {
887
- if (!(error instanceof TlaEvaluationError)) throw error;
888
- return { kind: "MixedSet", elements };
889
- }
890
- };
1062
+ export const createEnumeratedSet = (elements: Value[]): SetValue | MixedSetValue =>
1063
+ computeLikeTlcOnFailure<Value[], undefined, SetValue | MixedSetValue>(
1064
+ createSet,
1065
+ (mixed) => ({ kind: "MixedSet", elements: mixed }),
1066
+ elements,
1067
+ undefined,
1068
+ );
891
1069
 
892
1070
  export const EMPTY_SET = createSortedSet([]);
893
1071
 
@@ -966,12 +1144,15 @@ export const unionSorted = (left: SetValue, right: SetValue): SetValue => {
966
1144
  }
967
1145
  if (added.length === 0) return left;
968
1146
  const union = createSortedSet(merged);
969
- if (left.hash !== 0) {
1147
+ if (left.hash !== 0 && left.hash !== UNFINGERPRINTABLE_HASH) {
970
1148
  let hash = left.hash;
971
- for (let index = 0; index < added.length; index++) {
972
- hash = (hash + getElementContribution(added[index])) | 0;
1149
+ let index = 0;
1150
+ for (; index < added.length; index++) {
1151
+ const elementHash = getValueHash(added[index]);
1152
+ if (elementHash === UNFINGERPRINTABLE_HASH) break;
1153
+ hash = (hash + getElementContribution(elementHash)) | 0;
973
1154
  }
974
- union.hash = hash;
1155
+ if (index === added.length) union.hash = hash;
975
1156
  }
976
1157
  if (left.fingerprint !== 0) {
977
1158
  let fingerprint = left.fingerprint;
@@ -1056,23 +1237,27 @@ const getIntervalValue = (high: number): IntervalValue => {
1056
1237
  };
1057
1238
 
1058
1239
  export const createTuple = (elements: Value[]): FunctionValue =>
1059
- createSortedFunction(getIntervalDomain(elements.length), elements);
1240
+ setFunctionClass(createSortedFunction(getIntervalDomain(elements.length), elements), "tuple");
1060
1241
 
1061
- export const createRecord = (fields: [string, Value][]): FunctionValue => createFunction(fields);
1242
+ export const createRecord = (fields: [string, Value][]): FunctionValue =>
1243
+ setFunctionClass(createFunction(fields), "record");
1062
1244
 
1063
1245
  // TLC's Enumerable classes: every set except the ones it implements in Java.
1064
- const isTlcEnumerable = (value: Value) => isSetValue(value) && !isOverriddenSet(value);
1246
+ export const isTlcEnumerable = (value: Value) => isSetValue(value) && !isOverriddenSet(value);
1065
1247
 
1066
1248
  const formatUnion = (value: UnionValue, isStrict = false) =>
1067
1249
  `UNION(${formatValue(value.base, isStrict)})`;
1068
1250
 
1069
- const getUnionSets = (value: UnionValue) => {
1251
+ const getUnionSets = (
1252
+ value: UnionValue,
1253
+ getElements = (set: Value) => toFiniteSet(set).elements,
1254
+ ) => {
1070
1255
  if (!isTlcEnumerable(value.base)) {
1071
1256
  throw new TlaEvaluationError(
1072
1257
  `Attempted to enumerate the nonenumerable set:\n${formatUnion(value)}`,
1073
1258
  );
1074
1259
  }
1075
- return toFiniteSet(value.base).elements;
1260
+ return getElements(value.base);
1076
1261
  };
1077
1262
 
1078
1263
  const getUnionSet = (set: Value, index: number, union: UnionValue) => {
@@ -1108,7 +1293,7 @@ export const isEnumerable = (value: Value): boolean => {
1108
1293
  case "ProductSet":
1109
1294
  return value.factors.every(isEnumerable) || getEmptiness(value) === true;
1110
1295
  case "Union":
1111
- return isEnumerable(value.base) && toFiniteSet(value.base).elements.every(isEnumerable);
1296
+ return isEnumerable(value.base) && getStreamedElements(value.base).every(isEnumerable);
1112
1297
  case "SetOperation":
1113
1298
  if (value.operator === "\\cup") return isEnumerable(value.left) && isEnumerable(value.right);
1114
1299
  if (value.operator === "\\cap") return isEnumerable(value.left) || isEnumerable(value.right);
@@ -1181,6 +1366,41 @@ const advanceCombination = (indices: number[], length: number) => {
1181
1366
  return false;
1182
1367
  };
1183
1368
 
1369
+ // TLC enumerates SUBSET S lazily, by size and then in the order of S, so a quantifier that finds
1370
+ // its witness early never builds the rest. For a power set too large to build, the elements are
1371
+ // computed in that order as a loop reads them.
1372
+ export const getLazySubsets = (value: Value): Value[] | undefined => {
1373
+ if (typeof value !== "object" || value.kind !== "Subset" || isOverriddenSet(value.base)) {
1374
+ return undefined;
1375
+ }
1376
+ const base = toFiniteSet(value.base).elements;
1377
+ if (base.length <= MAXIMUM_ENUMERATED_SUBSET_BASE) return undefined;
1378
+ const cursor = { index: -1, indices: [0] };
1379
+ const getSubset = (index: number) => {
1380
+ if (index <= cursor.index) cursor.index = -1;
1381
+ while (cursor.index < index) {
1382
+ if (cursor.index === -1) cursor.indices = [];
1383
+ else if (!advanceCombination(cursor.indices, base.length)) {
1384
+ cursor.indices = Array.from({ length: cursor.indices.length + 1 }, (_, item) => item);
1385
+ }
1386
+ cursor.index++;
1387
+ }
1388
+ return createSortedSet(cursor.indices.map((item) => base[item]));
1389
+ };
1390
+ const length = 2 ** base.length;
1391
+ const isIndex = (property: string | symbol) =>
1392
+ typeof property === "string" && /^\d+$/.test(property) && Number(property) < length;
1393
+ return new Proxy<Value[]>([], {
1394
+ get: (target, property, receiver) => {
1395
+ if (property === "length") return length;
1396
+ return isIndex(property)
1397
+ ? getSubset(Number(property))
1398
+ : Reflect.get(target, property, receiver);
1399
+ },
1400
+ has: (target, property) => isIndex(property) || Reflect.has(target, property),
1401
+ });
1402
+ };
1403
+
1184
1404
  const getSortedSubsets = (base: Value[]) => {
1185
1405
  const subsets: Value[] = [];
1186
1406
  for (let size = 0; size <= base.length; size++) {
@@ -1192,7 +1412,30 @@ const getSortedSubsets = (base: Value[]) => {
1192
1412
  return subsets;
1193
1413
  };
1194
1414
 
1195
- const enumerateSet = (value: Value): Value[] => {
1415
+ // The Enumerator of a set of records or tuples enumerates its sets in turn and stops at the first
1416
+ // empty one, which leaves the product empty. Later versions of TLC decide that the set is empty
1417
+ // before they enumerate it.
1418
+ const getComponentElements = (
1419
+ sets: Value[],
1420
+ getElements: (set: Value) => Value[],
1421
+ describeUnenumerable: (set: Value, index: number) => string,
1422
+ ) => {
1423
+ const lists: Value[][] = [];
1424
+ for (let index = 0; index < sets.length; index++) {
1425
+ const set = sets[index];
1426
+ if (isOverriddenSet(set)) throw new TlaEvaluationError(describeUnenumerable(set, index));
1427
+ const elements = getElements(set);
1428
+ if (elements.length === 0) return [[]];
1429
+ lists.push(elements);
1430
+ }
1431
+ return lists;
1432
+ };
1433
+
1434
+ // getElements enumerates the sets a set of functions, records, or tuples combines.
1435
+ const enumerateSet = (
1436
+ value: Value,
1437
+ getElements = (set: Value) => toFiniteSet(set).elements,
1438
+ ): Value[] => {
1196
1439
  if (typeof value !== "object")
1197
1440
  throw new TlaEvaluationError(`Expected a set but found ${formatValue(value)}`);
1198
1441
  switch (value.kind) {
@@ -1206,61 +1449,63 @@ const enumerateSet = (value: Value): Value[] => {
1206
1449
  return elements;
1207
1450
  }
1208
1451
  case "Subset": {
1209
- if (isOverriddenSet(value.base)) getCardinality(value.base);
1210
- const base = toFiniteSet(value.base).elements;
1211
- if (base.length > MAXIMUM_ENUMERATED_SUBSET_BASE) {
1452
+ // SubsetValue.toSetEnum sizes the set before it enumerates it, and enumerates only the empty
1453
+ // set of a value of size 0, a function with an empty domain among them.
1454
+ if (getCardinality(value.base) === 0) return getSortedSubsets([]);
1455
+ if (!isSetValue(value.base)) {
1212
1456
  throw new TlaEvaluationError(
1213
- `SUBSET of a set with ${base.length} elements is too large to enumerate`,
1457
+ `Attempted to compute the value of an expression of form\nSUBSET S, but S is a non-enumerable value:\n${prettyPrint(formatValue(value.base))}`,
1214
1458
  );
1215
1459
  }
1460
+ const base = toFiniteSet(value.base).elements;
1461
+ if (base.length > MAXIMUM_ENUMERATED_SUBSET_BASE) {
1462
+ throw new TlaEvaluationError(describeOverflow(value));
1463
+ }
1216
1464
  return getSortedSubsets(base);
1217
1465
  }
1218
1466
  case "FunctionSet": {
1219
- if (isEmptySet(value)) return [];
1467
+ if (!valueVersion.is174 && isEmptySet(value)) return [];
1220
1468
  if (isOverriddenSet(value.domain)) {
1221
1469
  throw new TlaEvaluationError(
1222
1470
  `Attempted to enumerate a set of the form [D -> R],but the domain D:\n${formatValue(value.domain)}\ncannot be enumerated.`,
1223
1471
  );
1224
1472
  }
1225
1473
  const domain = getFunctionDomain(value.domain);
1226
- if (domain.length > 0 && isOverriddenSet(value.range)) {
1474
+ // TLC 1.7.4 requires an enumerable range even of an empty domain.
1475
+ if ((domain.length > 0 || valueVersion.is174) && isOverriddenSet(value.range)) {
1227
1476
  throw new TlaEvaluationError(
1228
1477
  `Attempted to enumerate a set of the form [D -> R],but the range R:\n${formatValue(value.range)}\ncannot be enumerated.`,
1229
1478
  );
1230
1479
  }
1231
- const range = domain.length === 0 ? [] : toFiniteSet(value.range).elements;
1480
+ const range = domain.length === 0 ? [] : getElements(value.range);
1232
1481
  return getCartesianProduct(domain.map(() => range)).map((combination): Value =>
1233
1482
  createSortedFunction(domain, combination),
1234
1483
  );
1235
1484
  }
1236
1485
  case "RecordSet": {
1237
- if (isEmptySet(value)) return [];
1238
- const fields = value.sets.map((set, index) => {
1239
- if (isOverriddenSet(set)) {
1240
- throw new TlaEvaluationError(
1241
- `Attempted to enumerate a set of the form [l1 : v1, ..., ln : vn],\nbut can't enumerate the value of the \`${value.names[index]}' field:\n${formatValue(set)}`,
1242
- );
1243
- }
1244
- return toFiniteSet(set).elements;
1245
- });
1486
+ if (!valueVersion.is174 && isEmptySet(value)) return [];
1487
+ const fields = getComponentElements(
1488
+ value.sets,
1489
+ getElements,
1490
+ (set, index) =>
1491
+ `Attempted to enumerate a set of the form [l1 : v1, ..., ln : vn],\nbut can't enumerate the value of the \`${value.names[index]}' field:\n${formatValue(set)}`,
1492
+ );
1246
1493
  return getCartesianProduct(fields).map((combination) =>
1247
1494
  createRecord(value.names.map((name, index): [string, Value] => [name, combination[index]])),
1248
1495
  );
1249
1496
  }
1250
1497
  case "ProductSet": {
1251
- if (isEmptySet(value)) return [];
1252
- const factors = value.factors.map((factor, index) => {
1253
- if (isOverriddenSet(factor)) {
1254
- throw new TlaEvaluationError(
1255
- `Attempted to enumerate a set of the form s1 \\X s2 ... \\X sn,\nbut can't enumerate s${index}:\n${formatValue(factor)}`,
1256
- );
1257
- }
1258
- return toFiniteSet(factor).elements;
1259
- });
1498
+ if (!valueVersion.is174 && isEmptySet(value)) return [];
1499
+ const factors = getComponentElements(
1500
+ value.factors,
1501
+ getElements,
1502
+ (factor, index) =>
1503
+ `Attempted to enumerate a set of the form s1 \\X s2 ... \\X sn,\nbut can't enumerate s${index}:\n${formatValue(factor)}`,
1504
+ );
1260
1505
  return getCartesianProduct(factors).map(createTuple);
1261
1506
  }
1262
1507
  case "FilteredSet":
1263
- if (isOverriddenSet(value.base)) {
1508
+ if (!isSetValue(value.base) || isOverriddenSet(value.base)) {
1264
1509
  throw new TlaEvaluationError(
1265
1510
  `Attempted to enumerate { x \\in S : p(x) } when S:\n${formatValue(value.base)}\nis not enumerable`,
1266
1511
  );
@@ -1275,7 +1520,7 @@ const enumerateSet = (value: Value): Value[] => {
1275
1520
  case "SetOperation": {
1276
1521
  if (
1277
1522
  value.operator === "\\cup" &&
1278
- (isOverriddenSet(value.left) || isOverriddenSet(value.right))
1523
+ (!isTlcEnumerable(value.left) || !isTlcEnumerable(value.right))
1279
1524
  ) {
1280
1525
  throw new TlaEvaluationError(
1281
1526
  `Attempted to enumerate S \\cup T when S:\n${formatValue(value.left)}\nand T:\n${formatValue(value.right)}\nare not both enumerable`,
@@ -1283,21 +1528,21 @@ const enumerateSet = (value: Value): Value[] => {
1283
1528
  }
1284
1529
  if (
1285
1530
  value.operator === "\\cap" &&
1286
- isOverriddenSet(value.left) &&
1287
- isOverriddenSet(value.right)
1531
+ !isTlcEnumerable(value.left) &&
1532
+ !isTlcEnumerable(value.right)
1288
1533
  ) {
1289
1534
  throw new TlaEvaluationError(
1290
1535
  `Attempted to enumerate S \\cap T when neither S:\n${formatValue(value.left)}\nnor T:\n${formatValue(value.right)}\nis enumerable`,
1291
1536
  );
1292
1537
  }
1293
- if (value.operator === "\\" && isOverriddenSet(value.left)) {
1538
+ if (value.operator === "\\" && !isTlcEnumerable(value.left)) {
1294
1539
  throw new TlaEvaluationError(
1295
1540
  `Attempted to enumerate S \\ T when S:\n${formatValue(value.left)}\nis not enumerable.`,
1296
1541
  );
1297
1542
  }
1298
1543
  if (value.operator === "\\cup")
1299
1544
  return unionSorted(toFiniteSet(value.left), toFiniteSet(value.right)).elements;
1300
- const isLeftEnumerated = value.operator === "\\" || isEnumerable(value.left);
1545
+ const isLeftEnumerated = value.operator === "\\" || isTlcEnumerable(value.left);
1301
1546
  const enumerated = isLeftEnumerated ? value.left : value.right;
1302
1547
  const other = isLeftEnumerated ? value.right : value.left;
1303
1548
  return toFiniteSet(enumerated).elements.filter(
@@ -1323,7 +1568,10 @@ export const toFiniteSet = (value: Value): SetValue => {
1323
1568
  }
1324
1569
  const cached = typeof value === "object" ? finiteSets.get(value) : undefined;
1325
1570
  if (cached) return cached;
1571
+ const sets = setTrace.sets;
1572
+ sets?.push(value);
1326
1573
  const elements = enumerateSet(value);
1574
+ sets?.pop();
1327
1575
  const isSorted =
1328
1576
  typeof value === "object" &&
1329
1577
  (value.kind === "MixedSet" ||
@@ -1341,25 +1589,92 @@ export const toFiniteSet = (value: Value): SetValue => {
1341
1589
  // TLC's Enumerator for a lazy set streams the sets it combines until the set caches its elements,
1342
1590
  // so an element that two of them share comes up once for each.
1343
1591
  export const getStreamedElements = (value: Value): Value[] => {
1344
- if (typeof value !== "object" || finiteSets.has(value)) return toFiniteSet(value).elements;
1592
+ if (typeof value !== "object" || cachedSets.has(value)) return toFiniteSet(value).elements;
1593
+ const sets = setTrace.sets;
1594
+ sets?.push(value);
1595
+ const elements = streamElements(value);
1596
+ sets?.pop();
1597
+ return elements;
1598
+ };
1599
+
1600
+ const getCombinedSets = (value: ObjectValue) =>
1601
+ value.kind === "ProductSet"
1602
+ ? value.factors
1603
+ : value.kind === "RecordSet"
1604
+ ? value.sets
1605
+ : value.kind === "FunctionSet"
1606
+ ? [value.range]
1607
+ : undefined;
1608
+
1609
+ // Whether a value TLC builds alike at each evaluation and that enumerating, comparing or
1610
+ // fingerprinting it leaves alike, so that one evaluation can stand for the next. It holds no UNION or
1611
+ // \cup, which streams until TLC caches it, no lambda, which fingerprinting turns into a record, and
1612
+ // no record a comparison reorders.
1613
+ export const isSettledValue = (value: Value): boolean => {
1614
+ if (typeof value !== "object") return true;
1615
+ switch (value.kind) {
1616
+ case "ModelValue":
1617
+ case "Interval":
1618
+ return true;
1619
+ case "Set":
1620
+ return value.elements.every(isSettledValue);
1621
+ case "Function":
1622
+ return (
1623
+ value.functionClass !== "lambda" &&
1624
+ value.writtenKeys === undefined &&
1625
+ value.domain.every(isSettledValue) &&
1626
+ value.range.every(isSettledValue)
1627
+ );
1628
+ case "SetOperation":
1629
+ return (
1630
+ value.operator !== "\\cup" && isSettledValue(value.left) && isSettledValue(value.right)
1631
+ );
1632
+ case "FilteredSet":
1633
+ return isSettledValue(value.base);
1634
+ case "ProductSet":
1635
+ return value.factors.every(isSettledValue);
1636
+ default:
1637
+ return false;
1638
+ }
1639
+ };
1640
+
1641
+ // Whether a set streams its elements in another order than the normalized set, so that a set of
1642
+ // tuples, records, or functions it is a component of has to stream too.
1643
+ const isStreamedApart = (value: Value): boolean => {
1644
+ if (typeof value !== "object" || cachedSets.has(value)) return false;
1645
+ if (value.kind === "Union") return true;
1646
+ if (value.kind === "FilteredSet") return isStreamedApart(value.base);
1647
+ if (value.kind === "SetOperation") {
1648
+ return (
1649
+ value.operator === "\\cup" || isStreamedApart(value.left) || isStreamedApart(value.right)
1650
+ );
1651
+ }
1652
+ return getCombinedSets(value)?.some(isStreamedApart) ?? false;
1653
+ };
1654
+
1655
+ const streamElements = (value: ObjectValue): Value[] => {
1656
+ // TLC streams the sets of a UNION it hasn't enumerated, so a set that appears twice there yields
1657
+ // its elements twice.
1345
1658
  if (value.kind === "Union") {
1346
- return getUnionSets(value).flatMap((set, index) =>
1659
+ return getUnionSets(value, getStreamedElements).flatMap((set, index) =>
1347
1660
  getStreamedElements(getUnionSet(set, index, value)),
1348
1661
  );
1349
1662
  }
1350
1663
  if (value.kind === "FilteredSet" && !isOverriddenSet(value.base)) {
1351
1664
  return getStreamedElements(value.base).filter(value.test);
1352
1665
  }
1666
+ const components = getCombinedSets(value);
1667
+ if (components?.some(isStreamedApart)) return enumerateSet(value, getStreamedElements);
1353
1668
  if (value.kind !== "SetOperation") return toFiniteSet(value).elements;
1354
1669
  if (value.operator === "\\cup") {
1355
- return isOverriddenSet(value.left) || isOverriddenSet(value.right)
1670
+ return !isTlcEnumerable(value.left) || !isTlcEnumerable(value.right)
1356
1671
  ? toFiniteSet(value).elements
1357
1672
  : [...getStreamedElements(value.left), ...getStreamedElements(value.right)];
1358
1673
  }
1359
- const isLeftEnumerated = value.operator === "\\" || isEnumerable(value.left);
1674
+ const isLeftEnumerated = value.operator === "\\" || isTlcEnumerable(value.left);
1360
1675
  const enumerated = isLeftEnumerated ? value.left : value.right;
1361
1676
  const other = isLeftEnumerated ? value.right : value.left;
1362
- if (isOverriddenSet(enumerated)) return toFiniteSet(value).elements;
1677
+ if (!isTlcEnumerable(enumerated)) return toFiniteSet(value).elements;
1363
1678
  return getStreamedElements(enumerated).filter(
1364
1679
  (element) => isElementOf(element, other) === (value.operator === "\\cap"),
1365
1680
  );
@@ -1396,9 +1711,13 @@ export const isEmptySet = (value: Value): boolean => {
1396
1711
  }
1397
1712
  };
1398
1713
 
1399
- const getProductCardinality = (sets: Value[], describe: () => string) =>
1714
+ const getProductCardinality = (
1715
+ sets: Value[],
1716
+ version: TlcVersion | undefined,
1717
+ describe: () => string,
1718
+ ) =>
1400
1719
  sets.reduce<number>((product, set) => {
1401
- const size = product * getCardinality(set);
1720
+ const size = product * getCardinality(set, version);
1402
1721
  if (size > MAXIMUM_INTEGER) throw new TlaEvaluationError(describe());
1403
1722
  return size;
1404
1723
  }, 1);
@@ -1406,9 +1725,25 @@ const getProductCardinality = (sets: Value[], describe: () => string) =>
1406
1725
  const describeOverflow = (value: Value) =>
1407
1726
  `Overflow when computing the number of elements in:\n${formatValue(value)}`;
1408
1727
 
1409
- export const getCardinality = (value: Value): number => {
1410
- if (typeof value !== "object") return toFiniteSet(value).elements.length;
1728
+ // TLC 1.7.4 sizes every component of a set of functions, records, or tuples without first
1729
+ // checking whether one is empty, so an infinite component fails even beside an empty one.
1730
+ export const getCardinality = (value: Value, version?: TlcVersion): number => {
1731
+ if (typeof value !== "object") {
1732
+ const kind =
1733
+ typeof value === "number" ? "integer" : typeof value === "string" ? "string" : "boolean";
1734
+ throw new TlaEvaluationError(
1735
+ `Attempted to compute the number of elements in the ${kind} ${formatValue(value)}.`,
1736
+ );
1737
+ }
1411
1738
  switch (value.kind) {
1739
+ case "ModelValue":
1740
+ throw new TlaEvaluationError(
1741
+ `Attempted to compute the number of elements in the model value ${formatValue(value)}.`,
1742
+ );
1743
+ case "Function":
1744
+ return value.domain.length;
1745
+ case "LazyFunction":
1746
+ return getCardinality(value.domain, version);
1412
1747
  case "Interval": {
1413
1748
  const size = Math.max(0, value.high - value.low + 1);
1414
1749
  if (size > MAXIMUM_INTEGER) {
@@ -1424,16 +1759,19 @@ export const getCardinality = (value: Value): number => {
1424
1759
  `Attempted to compute the number of elements in the overridden value ${formatValue(value)}.`,
1425
1760
  );
1426
1761
  case "Subset": {
1427
- const size = getCardinality(value.base);
1762
+ const size = getCardinality(value.base, version);
1428
1763
  if (size >= 31) throw new TlaEvaluationError(describeOverflow(value));
1429
1764
  return 2 ** size;
1430
1765
  }
1431
1766
  case "FunctionSet": {
1432
- if (isEmptySet(value.domain)) return 1;
1433
- if (isEmptySet(value.range)) return 0;
1434
- const rangeSize = getCardinality(value.range);
1435
- if (rangeSize === 1) return 1;
1436
- const domainSize = getCardinality(value.domain);
1767
+ if (version !== "1.7.4") {
1768
+ if (isEmptySet(value.domain)) return 1;
1769
+ if (isEmptySet(value.range)) return 0;
1770
+ if (getCardinality(value.range, version) === 1) return 1;
1771
+ }
1772
+ const domainSize = getCardinality(value.domain, version);
1773
+ const rangeSize = getCardinality(value.range, version);
1774
+ if (rangeSize <= 1) return domainSize === 0 ? 1 : rangeSize;
1437
1775
  const size = { value: 1 };
1438
1776
  for (let index = 0; index < domainSize; index++) {
1439
1777
  size.value *= rangeSize;
@@ -1442,15 +1780,17 @@ export const getCardinality = (value: Value): number => {
1442
1780
  return size.value;
1443
1781
  }
1444
1782
  case "RecordSet":
1445
- if (isEmptySet(value)) return 0;
1446
- return getProductCardinality(value.sets, () => describeOverflow(value));
1783
+ if (version !== "1.7.4" && isEmptySet(value)) return 0;
1784
+ return getProductCardinality(value.sets, version, () => describeOverflow(value));
1447
1785
  case "ProductSet":
1448
- if (isEmptySet(value)) return 0;
1786
+ if (version !== "1.7.4" && isEmptySet(value)) return 0;
1449
1787
  return getProductCardinality(
1450
1788
  value.factors,
1789
+ version,
1451
1790
  () => `Overflow when computing the number of elements in ${formatValue(value)}`,
1452
1791
  );
1453
1792
  default:
1793
+ cacheSet(value);
1454
1794
  return toFiniteSet(value).elements.length;
1455
1795
  }
1456
1796
  };
@@ -1525,11 +1865,11 @@ export const isFiniteSet = (value: Value): boolean => {
1525
1865
  }
1526
1866
  };
1527
1867
 
1528
- const findIndex = (sortedValues: Value[], target: Value) => {
1868
+ const findIndex = (sortedValues: Value[], target: Value, compare = compareValues) => {
1529
1869
  const bounds = { low: 0, high: sortedValues.length - 1 };
1530
1870
  while (bounds.low <= bounds.high) {
1531
1871
  const middle = (bounds.low + bounds.high) >> 1;
1532
- const comparison = compareValues(sortedValues[middle], target);
1872
+ const comparison = compare(sortedValues[middle], target);
1533
1873
  if (comparison === 0) return middle;
1534
1874
  if (comparison < 0) bounds.low = middle + 1;
1535
1875
  else bounds.high = middle - 1;
@@ -1545,33 +1885,82 @@ export const getSequenceElements = (value: Value): Value[] | undefined => {
1545
1885
  : undefined;
1546
1886
  };
1547
1887
 
1548
- const describeMembership = (element: Value, set: Value) =>
1549
- `Attempted to check if the value ${formatValue(element)} is an element of ${formatValue(set)}`;
1550
-
1551
1888
  const describeNonSetMembership = (element: Value, value: Value) => {
1552
1889
  const prefix = `Attempted to check if the value:\n${formatValue(element)}\nis an element of the`;
1553
1890
  if (!isFunctionValue(value)) return `${prefix} ${describeKind(value)} ${formatValue(value)}`;
1554
- const domain =
1555
- value.kind === "Function" || isEnumerable(value.domain) ? toFiniteFunction(value).domain : [];
1556
- if (domain.length > 0 && domain.every((key) => typeof key === "string")) {
1891
+ const functionClass = getFunctionClass(value);
1892
+ if (functionClass === "record") {
1557
1893
  return `Attempted to check if element:\n${formatValue(element)}\nis in the record:\n${formatValue(value)}`;
1558
1894
  }
1559
- if (domain.every((key, index) => key === index + 1)) {
1560
- return "Attempted to check set membership in a tuple value.";
1561
- }
1895
+ if (functionClass === "tuple") return "Attempted to check set membership in a tuple value.";
1562
1896
  return `${prefix} function ${formatValue(value)}`;
1563
1897
  };
1564
1898
 
1899
+ // The call stack of the replay, which a failed fast path leaves frozen.
1900
+ interface TracedCallStack {
1901
+ expressions: unknown[];
1902
+ isFrozen: boolean;
1903
+ fingerprint?: unknown;
1904
+ }
1905
+
1906
+ // The sets whose membership is being checked or whose elements are being enumerated, and the
1907
+ // members being compared, outermost first, while TLC's CallStackTool replays a computation. A failed
1908
+ // check or enumeration leaves the values it was in, each of which TLC adds to the
1909
+ // FingerprintException when it has a source.
1910
+ export const setTrace: { sets: Value[] | undefined; callStack?: TracedCallStack } = {
1911
+ sets: undefined,
1912
+ };
1913
+
1914
+ // Takes a fast path, and computes as TLC does where it fails. TLC never takes the fast path, so
1915
+ // the failure's leftovers in the replay's trace go first. Both paths take their operands as
1916
+ // arguments, so a hot caller passes functions it doesn't allocate.
1917
+ export const computeLikeTlcOnFailure = <Left, Right, Result>(
1918
+ compute: (left: Left, right: Right) => Result,
1919
+ computeLikeTlc: (left: Left, right: Right, error: TlaEvaluationError) => Result,
1920
+ left: Left,
1921
+ right: Right,
1922
+ ): Result => {
1923
+ const sets = setTrace.sets;
1924
+ const callStack = setTrace.callStack;
1925
+ const depth = sets?.length ?? 0;
1926
+ const trace = callStack && { ...callStack, length: callStack.expressions.length };
1927
+ try {
1928
+ return compute(left, right);
1929
+ } catch (error) {
1930
+ if (!(error instanceof TlaEvaluationError)) throw error;
1931
+ if (sets) sets.length = depth;
1932
+ if (callStack && trace) {
1933
+ callStack.expressions.length = trace.length;
1934
+ callStack.isFrozen = trace.isFrozen;
1935
+ callStack.fingerprint = trace.fingerprint;
1936
+ }
1937
+ return computeLikeTlc(left, right, error);
1938
+ }
1939
+ };
1940
+
1565
1941
  export const isElementOf = (element: Value, set: Value): boolean => {
1942
+ const sets = setTrace.sets;
1943
+ if (sets === undefined) return isElementOfSet(element, set);
1944
+ sets.push(set);
1945
+ const isElement = isElementOfSet(element, set);
1946
+ sets.pop();
1947
+ return isElement;
1948
+ };
1949
+
1950
+ const isInSortedSet = (element: Value, set: SetValue) => findIndex(set.elements, element) !== -1;
1951
+
1952
+ const isInSortedSetLikeTlc = (element: Value, set: SetValue) =>
1953
+ normalizedSets.has(set)
1954
+ ? searchLikeTlc(element, set.elements).isFound
1955
+ : isElementOfLikeTlc(element, set.elements);
1956
+
1957
+ const isElementOfSet = (element: Value, set: Value): boolean => {
1566
1958
  if (!isSetValue(set)) throw new TlaEvaluationError(describeNonSetMembership(element, set));
1567
1959
  switch (set.kind) {
1568
1960
  case "Set":
1569
- try {
1570
- return findIndex(set.elements, element) !== -1;
1571
- } catch (error) {
1572
- if (!(error instanceof TlaEvaluationError)) throw error;
1573
- return isElementOfLikeTlc(element, set.elements);
1574
- }
1961
+ // SetEnumValue.member compares the element with the set's.
1962
+ cacheSet(element);
1963
+ return computeLikeTlcOnFailure(isInSortedSet, isInSortedSetLikeTlc, element, set);
1575
1964
  case "MixedSet":
1576
1965
  return isElementOfLikeTlc(element, set.elements);
1577
1966
  case "Interval":
@@ -1595,12 +1984,21 @@ export const isElementOf = (element: Value, set: Value): boolean => {
1595
1984
  return set.name !== "Nat" || (typeof element === "number" && element >= 0);
1596
1985
  }
1597
1986
  case "Subset":
1598
- if (!isSetValue(element)) throw new TlaEvaluationError(describeMembership(element, set));
1987
+ // SubsetValue.member fails on any value that is not Enumerable, model values and the sets a
1988
+ // Java class overrides included.
1989
+ if (!isSetValue(element) || isOverriddenSet(element)) {
1990
+ throw new TlaEvaluationError(
1991
+ `Attempted to check if the non-enumerable value\n${prettyPrint(formatValue(element))}\nis element of\n${prettyPrint(formatValue(set))}`,
1992
+ );
1993
+ }
1599
1994
  return toFiniteSet(element).elements.every((item) => isElementOf(item, set.base));
1600
1995
  case "FunctionSet": {
1601
1996
  if (!isFunctionValue(element)) {
1602
1997
  if (isModelValue(element)) return false;
1603
- throw new TlaEvaluationError(describeMembership(element, set));
1998
+ // SetOfFcnsValue.member prints the element without Values.ppr.
1999
+ throw new TlaEvaluationError(
2000
+ `Attempted to check if \n${formatValue(element)}\nwhich is not a TLC function value, is in the set of functions:\n${prettyPrint(formatValue(set))}`,
2001
+ );
1604
2002
  }
1605
2003
  const functionValue = toFiniteFunction(element);
1606
2004
  const low = getIntervalLow(functionValue.domain);
@@ -1665,7 +2063,10 @@ export const isElementOf = (element: Value, set: Value): boolean => {
1665
2063
  const elements = getSequenceElements(element);
1666
2064
  if (elements === undefined) {
1667
2065
  if (isModelValue(element)) return false;
1668
- throw new TlaEvaluationError(describeMembership(element, set));
2066
+ // Sequences.member raises TLC_MODULE_CHECK_MEMBER_OF.
2067
+ throw new TlaEvaluationError(
2068
+ `Attempted to check if the value:\n${prettyPrint(formatValue(element))}\nis an element of ${prettyPrint(formatValue(set))}.`,
2069
+ );
1669
2070
  }
1670
2071
  return elements.every((item) => isElementOf(item, set.base));
1671
2072
  }
@@ -1698,50 +2099,122 @@ export const toFiniteFunction = (value: Value): FunctionValue => {
1698
2099
  if (typeof value === "object" && value.kind === "LazyFunction") {
1699
2100
  if (!isEnumerable(value.domain)) getCardinality(value.domain);
1700
2101
  const domain = getFunctionDomain(value.domain);
1701
- return createSortedFunction(
1702
- domain,
1703
- domain.map((key) => value.apply(key)),
2102
+ return setFunctionClass(
2103
+ createSortedFunction(
2104
+ domain,
2105
+ domain.map((key) => value.apply(key)),
2106
+ ),
2107
+ getFunctionClass(value),
1704
2108
  );
1705
2109
  }
1706
2110
  throw new TlaEvaluationError(`Expected a function but found ${formatValue(value)}`);
1707
2111
  };
1708
2112
 
1709
- const lambdaFunctions = new WeakSet<ObjectValue>();
1710
-
1711
- export const markLambdaFunction = <FunctionLike extends FunctionValue | LazyFunctionValue>(
1712
- functionValue: FunctionLike,
2113
+ export const describeMissingArgument = (
2114
+ functionValue: Value,
2115
+ argument: Value,
2116
+ version?: TlcVersion,
1713
2117
  ) => {
1714
- lambdaFunctions.add(functionValue);
1715
- return functionValue;
2118
+ const shown = prettyPrint(formatValue(functionValue));
2119
+ const shownArgument = prettyPrint(formatValue(argument));
2120
+ const is174 = version === "1.7.4";
2121
+ switch (getFunctionClass(functionValue)) {
2122
+ case "lambda":
2123
+ return `In applying the function\n${shown},\nthe first argument is:\n${shownArgument}\nwhich is not in its domain.\n`;
2124
+ case "tuple":
2125
+ if (typeof argument !== "number") {
2126
+ return is174
2127
+ ? "Attempted to apply tuple to a non-integer argument."
2128
+ : `Attempted to access tuple at a non integral index: ${shownArgument}`;
2129
+ }
2130
+ return is174
2131
+ ? `Attempted to apply tuple\n${shown}\nto integer ${argument} which is out of domain.`
2132
+ : `Attempted to access index ${argument} of tuple\n${shown}\nwhich is out of bounds.`;
2133
+ case "record":
2134
+ if (typeof argument !== "string") {
2135
+ return is174
2136
+ ? `Attempted to apply record to a non-string value ${shownArgument}.`
2137
+ : `Attempted to access record by a non-string argument: ${shownArgument}`;
2138
+ }
2139
+ return is174
2140
+ ? `Attempted to apply the record\n${shown}\nto nonexistent record field ${argument}.`
2141
+ : `Attempted to access nonexistent field '${argument}' of record\n${shown}`;
2142
+ default:
2143
+ return `Attempted to apply function:\n${shown}\nto argument ${shownArgument}, which is not in the domain of the function.`;
2144
+ }
1716
2145
  };
1717
2146
 
1718
- const describeMissingArgument = (functionValue: Value, argument: Value) =>
1719
- typeof functionValue === "object" && lambdaFunctions.has(functionValue)
1720
- ? `In applying the function\n${prettyPrint(formatValue(functionValue))},\nthe first argument is:\n${prettyPrint(formatValue(argument))}\nwhich is not in its domain.\n`
1721
- : `Attempted to apply function ${formatValue(functionValue)} to ${formatValue(argument)}, which is not in its domain`;
2147
+ // TLC 1.7.4 words a key of the wrong type in an EXCEPT, which selects rather than applies, apart.
2148
+ const describeExceptKey = (functionValue: FunctionValue, argument: Value) => {
2149
+ if (!valueVersion.is174) return describeMissingArgument(functionValue, argument);
2150
+ const shown = prettyPrint(formatValue(argument));
2151
+ return getFunctionClass(functionValue) === "tuple"
2152
+ ? `Attempted to apply tuple to a non-integer argument ${shown}.`
2153
+ : `Attempted to apply record to a non-string argument ${shown}.`;
2154
+ };
1722
2155
 
1723
- const findKeyIndex = (domain: Value[], argument: Value) => {
2156
+ // A key the domain holds itself, which TLC finds without a comparison that can fail.
2157
+ const findIdenticalKey = (domain: Value[], argument: Value) => {
1724
2158
  const first = domain[0];
1725
2159
  if (typeof argument === "number" && typeof first === "number") {
1726
2160
  const offset = argument - first;
1727
2161
  if (domain[offset] === argument) return offset;
1728
2162
  }
1729
- if (domain.length <= 8) {
1730
- for (let index = 0; index < domain.length; index++)
1731
- if (domain[index] === argument) return index;
2163
+ return domain.length <= 8 ? domain.indexOf(argument) : -1;
2164
+ };
2165
+
2166
+ export const createNonIntegerKeyError = (argument: Value) =>
2167
+ new TlaEvaluationError(
2168
+ `Attempted to apply function with integer domain to the non-integer argument ${prettyPrint(formatValue(argument))}`,
2169
+ );
2170
+
2171
+ // TLC's FcnRcdValue searches a domain this small linearly with equals, and a larger normalized one by
2172
+ // binary search with compareTo.
2173
+ const LINEAR_SEARCH_LIMIT = 32;
2174
+
2175
+ const failKeyLikeTlc = (domain: Value[], argument: Value, error: TlaEvaluationError): never => {
2176
+ if (valueVersion.is174 || domain.length < LINEAR_SEARCH_LIMIT) {
2177
+ domain.forEach((key) => equalsLikeTlc(key, argument));
2178
+ } else {
2179
+ findIndex(domain, argument, compareLikeTlc);
2180
+ }
2181
+ throw error;
2182
+ };
2183
+
2184
+ // TLC looks a key up by the Java class of the function: a tuple or a record rejects a key of the
2185
+ // wrong type, and another function rejects a non-integer for a domain it keeps as an interval, which
2186
+ // TLC 1.7.4 doesn't. A key of another type than the domain's keys otherwise fails TLC's comparison.
2187
+ const findKeyIndexLikeTlc = (
2188
+ functionValue: FunctionValue,
2189
+ argument: Value,
2190
+ describeWrongKey: (functionValue: FunctionValue, argument: Value) => string,
2191
+ ) => {
2192
+ const domain = functionValue.domain;
2193
+ if (typeof argument !== typeof domain[0]) {
2194
+ const functionClass = getFunctionClass(functionValue);
2195
+ const keyType =
2196
+ functionClass === "tuple" ? "number" : functionClass === "record" ? "string" : undefined;
2197
+ if (keyType !== undefined && typeof argument !== keyType) {
2198
+ throw new TlaEvaluationError(describeWrongKey(functionValue, argument));
2199
+ }
2200
+ if (keyType === undefined && !valueVersion.is174 && isIntervalDomain(domain)) {
2201
+ throw createNonIntegerKeyError(argument);
2202
+ }
1732
2203
  }
1733
- return findIndex(domain, argument);
2204
+ const identical = findIdenticalKey(domain, argument);
2205
+ if (identical !== -1) return identical;
2206
+ return computeLikeTlcOnFailure(findIndex, failKeyLikeTlc, domain, argument);
1734
2207
  };
1735
2208
 
1736
2209
  export const applyFunction = (
1737
2210
  functionValue: Value,
1738
2211
  argument: Value,
1739
- describeMissing?: (functionValue: FunctionValue) => string,
2212
+ describeMissing?: (functionValue: FunctionValue, argument: Value) => string,
1740
2213
  ): Value => {
1741
2214
  if (typeof functionValue === "object" && functionValue.kind === "LazyFunction") {
1742
2215
  if (!isElementOf(argument, functionValue.domain)) {
1743
2216
  throw new TlaEvaluationError(
1744
- lambdaFunctions.has(functionValue)
2217
+ getFunctionClass(functionValue) === "lambda"
1745
2218
  ? describeMissingArgument(functionValue, argument)
1746
2219
  : `Attempted to apply a function to ${formatValue(argument)}, which is not in its domain`,
1747
2220
  );
@@ -1753,12 +2226,9 @@ export const applyFunction = (
1753
2226
  `Attempted to apply ${formatValue(functionValue)}, which is not a function`,
1754
2227
  );
1755
2228
  }
1756
- const position = findKeyIndex(functionValue.domain, argument);
1757
- if (position === -1) {
1758
- throw new TlaEvaluationError(
1759
- describeMissing?.(functionValue) ?? describeMissingArgument(functionValue, argument),
1760
- );
1761
- }
2229
+ const describe = describeMissing ?? describeMissingArgument;
2230
+ const position = findKeyIndexLikeTlc(functionValue, argument, describe);
2231
+ if (position === -1) throw new TlaEvaluationError(describe(functionValue, argument));
1762
2232
  return functionValue.range[position];
1763
2233
  };
1764
2234
 
@@ -1787,28 +2257,45 @@ export const updateFunction = (
1787
2257
  if (isLazy) {
1788
2258
  if (!isElementOf(argument, functionValue.domain)) return functionValue;
1789
2259
  const updated = update(functionValue.apply(argument));
1790
- return {
1791
- kind: "LazyFunction",
1792
- domain: functionValue.domain,
1793
- apply: (key) => (isEqualLikeTlc(argument, key) ? updated : functionValue.apply(key)),
1794
- source: functionValue.source,
1795
- };
2260
+ return setFunctionClass<LazyFunctionValue>(
2261
+ {
2262
+ kind: "LazyFunction",
2263
+ domain: functionValue.domain,
2264
+ apply: (key) => (isEqualLikeTlc(argument, key) ? updated : functionValue.apply(key)),
2265
+ source: functionValue.source,
2266
+ },
2267
+ getFunctionClass(functionValue),
2268
+ );
2269
+ }
2270
+ if (!isFunctionValue(functionValue)) {
2271
+ throw new TlaEvaluationError(
2272
+ `Attempted to apply EXCEPT construct to the value ${prettyPrint(formatValue(functionValue))}.`,
2273
+ );
1796
2274
  }
1797
2275
  const finite = toFiniteFunction(functionValue);
1798
- const position = findKeyIndex(finite.domain, argument);
2276
+ const position = findKeyIndexLikeTlc(finite, argument, describeExceptKey);
1799
2277
  if (position === -1) return finite;
1800
2278
  const range = [...finite.range];
1801
2279
  const previous = finite.range[position];
1802
2280
  const next = update(previous);
1803
2281
  range[position] = next;
1804
- const updated = createSortedFunction(finite.domain, range);
2282
+ const updated = setFunctionClass(
2283
+ createSortedFunction(finite.domain, range),
2284
+ getFunctionClass(finite),
2285
+ );
1805
2286
  updated.writtenKeys = finite.writtenKeys;
1806
- if (finite.hash !== 0) {
1807
- const key = finite.domain[position];
1808
- updated.hash =
1809
- previous === next
1810
- ? finite.hash
1811
- : (finite.hash - getEntryContribution(key, previous) + getEntryContribution(key, next)) | 0;
2287
+ if (finite.hash !== 0 && finite.hash !== UNFINGERPRINTABLE_HASH) {
2288
+ const nextHash = getValueHash(next);
2289
+ if (nextHash !== UNFINGERPRINTABLE_HASH) {
2290
+ const keyHash = getValueHash(finite.domain[position]);
2291
+ updated.hash =
2292
+ previous === next
2293
+ ? finite.hash
2294
+ : (finite.hash -
2295
+ getEntryContribution(keyHash, getValueHash(previous)) +
2296
+ getEntryContribution(keyHash, nextHash)) |
2297
+ 0;
2298
+ }
1812
2299
  }
1813
2300
  if (finite.fingerprint !== 0) {
1814
2301
  const key = finite.domain[position];
@@ -1845,32 +2332,103 @@ const hashString = (value: string) => {
1845
2332
  const SET_HASH_SEED = 0x73a5c3e1;
1846
2333
  const FUNCTION_HASH_SEED = 0x66d1b4f7;
1847
2334
 
1848
- const getElementContribution = (element: Value) =>
1849
- finalizeHash((getValueHash(element) + 0x9e3779b9) | 0);
2335
+ const getElementContribution = (elementHash: number) =>
2336
+ finalizeHash((elementHash + 0x9e3779b9) | 0);
1850
2337
 
1851
- const getEntryContribution = (key: Value, value: Value) =>
1852
- finalizeHash((Math.imul(getValueHash(key), 0x27d4eb2d) + getValueHash(value)) | 0);
2338
+ const getEntryContribution = (keyHash: number, valueHash: number) =>
2339
+ finalizeHash((Math.imul(keyHash, 0x27d4eb2d) + valueHash) | 0);
2340
+
2341
+ // The hash of each value that TLC fails to fingerprint, such as Nat or a set that holds it. Calls
2342
+ // with such a value as an argument still share their result, and a state that holds one fails
2343
+ // when TLC fingerprints it.
2344
+ const UNFINGERPRINTABLE_HASH = 0x2f6b1c4d;
1853
2345
 
1854
2346
  const computeValueHash = (value: ObjectValue) => {
1855
2347
  if (value.kind === "ModelValue") return finalizeHash(combineHash(hashString(value.name), 0x6d));
1856
2348
  if (isSetValue(value)) {
1857
- if (!isEnumerable(value)) return hashString(getValueKey(value));
2349
+ if (!isEnumerable(value)) return UNFINGERPRINTABLE_HASH;
1858
2350
  const elements = toFiniteSet(value).elements;
1859
2351
  let hash = SET_HASH_SEED;
1860
2352
  for (let index = 0; index < elements.length; index++) {
1861
- hash = (hash + getElementContribution(elements[index])) | 0;
2353
+ const elementHash = getValueHash(elements[index]);
2354
+ if (elementHash === UNFINGERPRINTABLE_HASH) return UNFINGERPRINTABLE_HASH;
2355
+ hash = (hash + getElementContribution(elementHash)) | 0;
1862
2356
  }
1863
2357
  return hash;
1864
2358
  }
2359
+ if (value.kind === "LazyFunction" && !isEnumerable(value.domain)) return UNFINGERPRINTABLE_HASH;
1865
2360
  const functionValue = toFiniteFunction(value);
1866
2361
  let hash = FUNCTION_HASH_SEED;
1867
2362
  for (let index = 0; index < functionValue.domain.length; index++) {
1868
- hash =
1869
- (hash + getEntryContribution(functionValue.domain[index], functionValue.range[index])) | 0;
2363
+ const keyHash = getValueHash(functionValue.domain[index]);
2364
+ const itemHash = getValueHash(functionValue.range[index]);
2365
+ if (keyHash === UNFINGERPRINTABLE_HASH || itemHash === UNFINGERPRINTABLE_HASH) {
2366
+ return UNFINGERPRINTABLE_HASH;
2367
+ }
2368
+ hash = (hash + getEntryContribution(keyHash, itemHash)) | 0;
1870
2369
  }
1871
2370
  return hash;
1872
2371
  };
1873
2372
 
2373
+ // TLC's fingerPrint enumerates each set and function a value holds, and fails on Nat, Seq(S) and
2374
+ // the like, which it never enumerates.
2375
+ const fingerprintValue = (value: Value): void => {
2376
+ if (typeof value !== "object" || value.kind === "ModelValue") return;
2377
+ if (value.kind === "InfiniteSet" || value.kind === "SequenceSet") {
2378
+ throw new TlaEvaluationError(
2379
+ `TLC has found a state in which the value of a variable contains ${formatValue(value)}`,
2380
+ );
2381
+ }
2382
+ if (isSetValue(value)) {
2383
+ toFiniteSet(value).elements.forEach(fingerprintValue);
2384
+ return;
2385
+ }
2386
+ const functionValue = toFiniteFunction(value);
2387
+ functionValue.domain.forEach(fingerprintValue);
2388
+ functionValue.range.forEach(fingerprintValue);
2389
+ };
2390
+
2391
+ // The error TLC raises as it fingerprints a value: one that hashing the value raises, as for a set
2392
+ // too large to enumerate, or one of a value with the hash of the values TLC fails on.
2393
+ export const getFingerprintError = (value: Value) => {
2394
+ if (typeof value !== "object" || value.kind === "ModelValue") return undefined;
2395
+ try {
2396
+ if (getValueHash(value) === UNFINGERPRINTABLE_HASH) fingerprintValue(value);
2397
+ return undefined;
2398
+ } catch (error) {
2399
+ if (!(error instanceof TlaEvaluationError)) throw error;
2400
+ return error;
2401
+ }
2402
+ };
2403
+
2404
+ // The values a value holds, which TLC fingerprints as it fingerprints the value.
2405
+ export const getHeldValues = (value: ObjectValue): Value[] => {
2406
+ switch (value.kind) {
2407
+ case "Set":
2408
+ case "MixedSet":
2409
+ return value.elements;
2410
+ case "Function":
2411
+ return [...value.domain, ...value.range];
2412
+ case "Subset":
2413
+ case "SequenceSet":
2414
+ case "FilteredSet":
2415
+ case "Union":
2416
+ return [value.base];
2417
+ case "FunctionSet":
2418
+ return [value.domain, value.range];
2419
+ case "RecordSet":
2420
+ return value.sets;
2421
+ case "ProductSet":
2422
+ return value.factors;
2423
+ case "SetOperation":
2424
+ return [value.left, value.right];
2425
+ case "LazyFunction":
2426
+ return [value.domain];
2427
+ default:
2428
+ return [];
2429
+ }
2430
+ };
2431
+
1874
2432
  export const getValueHash = (value: Value): number => {
1875
2433
  if (typeof value === "number") return finalizeHash(value ^ 0x5bd1e995);
1876
2434
  if (typeof value === "boolean") return value ? 0x2b7e1516 : 0x28aed2a6;
@@ -2045,7 +2603,9 @@ const formatLazySet = (value: LazySetValue, isStrict: boolean): string => {
2045
2603
  case "SetOperation":
2046
2604
  return `${format(value.left)} ${value.operator} ${format(value.right)}`;
2047
2605
  case "FilteredSet":
2048
- return `{x \\in ${format(value.base)} : ...}`;
2606
+ return value.source
2607
+ ? `{${value.source.names} \\in ${format(value.base)} : <expression ${value.source.predicate}> }`
2608
+ : `{x \\in ${format(value.base)} : ...}`;
2049
2609
  case "Union":
2050
2610
  return formatUnion(value, isStrict);
2051
2611
  }
@@ -2058,6 +2618,17 @@ const isFieldName = (name: string) =>
2058
2618
  /\p{L}/u.test(name) &&
2059
2619
  (name.length < 4 || !/^[WS]F_/.test(name));
2060
2620
 
2621
+ // FcnLambdaValue#toString prints a function it fails to enumerate as its parameters and body.
2622
+ const toPrintedFunction = (value: LazyFunctionValue) => {
2623
+ if (!isEnumerable(value.domain)) return undefined;
2624
+ try {
2625
+ return toFiniteFunction(value);
2626
+ } catch (error) {
2627
+ if (error instanceof TlaEvaluationError) return undefined;
2628
+ throw error;
2629
+ }
2630
+ };
2631
+
2061
2632
  export const formatValue = (value: Value, isStrict = false, isNormalized = false): string => {
2062
2633
  const format = (inner: Value) => formatValue(inner, isStrict, isNormalized);
2063
2634
  if (typeof value === "boolean") return value ? "TRUE" : "FALSE";
@@ -2089,27 +2660,53 @@ export const formatValue = (value: Value, isStrict = false, isNormalized = false
2089
2660
  return `Seq(${format(value.base)})`;
2090
2661
  case "Function":
2091
2662
  case "LazyFunction": {
2092
- if (value.kind === "LazyFunction" && !isEnumerable(value.domain)) {
2093
- const source = value.source;
2663
+ const functionValue = value.kind === "LazyFunction" ? toPrintedFunction(value) : value;
2664
+ if (functionValue === undefined) {
2665
+ const source = value.kind === "LazyFunction" ? value.source : undefined;
2094
2666
  if (!source) return "<function>";
2095
2667
  const parameters = source.parameters
2096
2668
  .map((parameter) => `${parameter.name} \\in ${formatValue(parameter.domain)}`)
2097
2669
  .join(", ");
2098
2670
  return `[${parameters} |-> <expression ${source.body}>]`;
2099
2671
  }
2100
- const functionValue = toFiniteFunction(value);
2672
+ if (
2673
+ functionValue.domain.length === 0 &&
2674
+ valueVersion.is174 &&
2675
+ getFunctionClass(value) !== "tuple"
2676
+ ) {
2677
+ return "<< >>";
2678
+ }
2679
+ // TLC normalizes a lambda's domain to print it, but evaluates its body afterward.
2680
+ const formatRange = (inner: Value) =>
2681
+ formatValue(inner, isStrict, isNormalized && getFunctionClass(value) !== "lambda");
2101
2682
  if (functionValue.domain.every((key, index) => key === index + 1)) {
2102
- return `<<${functionValue.range.map(format).join(", ")}>>`;
2683
+ return `<<${functionValue.range.map(formatRange).join(", ")}>>`;
2103
2684
  }
2104
- if (functionValue.domain.every((key) => typeof key === "string" && isFieldName(key))) {
2685
+ // A RecordValue prints as a record whatever its fields, and a FcnRcdValue only if each key
2686
+ // is a name.
2687
+ if (
2688
+ getFunctionClass(value) === "record" ||
2689
+ functionValue.domain.every((key) => typeof key === "string" && isFieldName(key))
2690
+ ) {
2105
2691
  const isSorted =
2106
2692
  isNormalized || functionValue.hash !== 0 || functionValue.fingerprint !== 0;
2107
2693
  const pairs = isSorted
2108
2694
  ? functionValue.domain.map((key, index) => [key, functionValue.range[index]])
2109
2695
  : getWrittenPairs(functionValue);
2110
- return `[${pairs.map((pair) => `${String(pair[0])} |-> ${format(pair[1])}`).join(", ")}]`;
2696
+ return `[${pairs.map((pair) => `${String(pair[0])} |-> ${formatRange(pair[1])}`).join(", ")}]`;
2111
2697
  }
2112
- return `(${functionValue.domain.map((key, index) => `${format(key)} :> ${format(functionValue.range[index])}`).join(" @@ ")})`;
2698
+ return `(${functionValue.domain.map((key, index) => `${format(key)} :> ${formatRange(functionValue.range[index])}`).join(" @@ ")})`;
2113
2699
  }
2114
2700
  }
2115
2701
  };
2702
+
2703
+ // TLC's TLCState.toString: a line per variable, as a conjunction when there are several.
2704
+ export const formatState = (state: Record<string, Value>) => {
2705
+ const entries = Object.entries(state);
2706
+ return entries
2707
+ .map(
2708
+ ([name, value]) =>
2709
+ `${entries.length === 1 ? "" : "/\\ "}${name} = ${prettyPrint(formatValue(value))}\n`,
2710
+ )
2711
+ .join("");
2712
+ };