tla-ts 0.0.9 → 0.0.10-dev.28c823e4b

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (390) hide show
  1. package/README.md +29 -1
  2. package/dist/compile.cjs +23 -0
  3. package/dist/compile.js +23 -0
  4. package/dist/deciders.cjs +28 -28
  5. package/dist/deciders.js +43 -43
  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 +116 -36
  15. package/dist/prove.js +116 -36
  16. package/dist/run.cjs +143 -31
  17. package/dist/run.js +143 -31
  18. package/dist/tlapm.cjs +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 +4 -23
  26. package/src/bags.ts +99 -102
  27. package/src/builtins.ts +40 -78
  28. package/src/bundled-modules.ts +1 -8
  29. package/src/check.ts +599 -388
  30. package/src/cli/options.ts +11 -6
  31. package/src/cli/run.ts +0 -2
  32. package/src/cli/runtime-invariants.ts +136 -0
  33. package/src/cli/shared.ts +18 -11
  34. package/src/cli/tlapm.ts +0 -12
  35. package/src/cli/tlc-arguments.ts +640 -0
  36. package/src/cli/tlc-usage.ts +361 -0
  37. package/src/cli/tlc.ts +538 -220
  38. package/src/cli/typescript.ts +23 -0
  39. package/src/cli/xml-exporter.ts +4 -16
  40. package/src/cli.ts +0 -1
  41. package/src/codegen.ts +191 -64
  42. package/src/config.ts +140 -109
  43. package/src/coverage.ts +837 -0
  44. package/src/dependencies.ts +6 -40
  45. package/src/dfid.ts +618 -0
  46. package/src/environment.ts +240 -118
  47. package/src/errors.ts +70 -55
  48. package/src/evaluate.ts +596 -339
  49. package/src/exit-codes.ts +37 -3
  50. package/src/fingerprints.ts +10 -10
  51. package/src/index.ts +3 -0
  52. package/src/instances.ts +79 -11
  53. package/src/java-overrides.ts +4 -19
  54. package/src/json-reader.ts +455 -0
  55. package/src/json.ts +255 -139
  56. package/src/levels.ts +8 -17
  57. package/src/lexer.ts +80 -100
  58. package/src/liveness-checker.ts +82 -119
  59. package/src/liveness.ts +112 -64
  60. package/src/obligations/action.ts +4 -28
  61. package/src/obligations/anonymize.ts +84 -80
  62. package/src/obligations/equality.ts +1 -1
  63. package/src/obligations/expression.ts +2 -19
  64. package/src/obligations/format.ts +1 -9
  65. package/src/obligations/generate.ts +1 -11
  66. package/src/obligations/index.ts +0 -11
  67. package/src/obligations/levels.ts +4 -8
  68. package/src/obligations/module.ts +1 -15
  69. package/src/obligations/normalize.ts +5 -24
  70. package/src/obligations/operators.ts +1 -2
  71. package/src/obligations/pragma.ts +1 -10
  72. package/src/obligations/printer.ts +47 -46
  73. package/src/obligations/proof.ts +1 -5
  74. package/src/obligations/regroup.ts +1 -4
  75. package/src/obligations/simplify.ts +3 -14
  76. package/src/obligations/source.ts +1 -21
  77. package/src/obligations/subexpression.ts +5 -11
  78. package/src/obligations/substitution.ts +1 -3
  79. package/src/obligations/temporal.ts +8 -14
  80. package/src/obligations/tuples.ts +3 -9
  81. package/src/parallel-worker.ts +29 -39
  82. package/src/parallel.ts +53 -44
  83. package/src/parser.ts +565 -282
  84. package/src/pcal/ast.ts +53 -86
  85. package/src/pcal/parse.ts +144 -219
  86. package/src/pcal/tokenize.ts +91 -131
  87. package/src/pcal/translate.ts +83 -130
  88. package/src/pcal/validate.ts +48 -68
  89. package/src/pretty-print.ts +7 -8
  90. package/src/prover/decide-pool.ts +5 -10
  91. package/src/prover/deciders.ts +0 -4
  92. package/src/prover/first-order.ts +0 -11
  93. package/src/prover/isabelle/decide.ts +0 -6
  94. package/src/prover/isabelle/encode.ts +11 -23
  95. package/src/prover/isabelle/isar/inner-syntax.ts +108 -114
  96. package/src/prover/isabelle/isar/method.ts +25 -38
  97. package/src/prover/isabelle/isar/proof.ts +1 -10
  98. package/src/prover/isabelle/isar/statement.ts +1 -6
  99. package/src/prover/isabelle/isar/theory.ts +15 -26
  100. package/src/prover/isabelle/isar/type-check.ts +11 -25
  101. package/src/prover/isabelle/provers/blast/blast.ts +10 -41
  102. package/src/prover/isabelle/provers/blast/branch.ts +1 -32
  103. package/src/prover/isabelle/provers/blast/prove.ts +1 -35
  104. package/src/prover/isabelle/provers/blast/rules.ts +6 -44
  105. package/src/prover/isabelle/provers/blast/state.ts +2 -28
  106. package/src/prover/isabelle/provers/blast/term.ts +9 -36
  107. package/src/prover/isabelle/provers/clasimp.ts +1 -13
  108. package/src/prover/isabelle/provers/classical.ts +14 -42
  109. package/src/prover/isabelle/provers/hypsubst.ts +11 -25
  110. package/src/prover/isabelle/pure/bicompose.ts +16 -13
  111. package/src/prover/isabelle/pure/consts.ts +1 -7
  112. package/src/prover/isabelle/pure/conv.ts +1 -9
  113. package/src/prover/isabelle/pure/drule.ts +24 -40
  114. package/src/prover/isabelle/pure/envir.ts +3 -52
  115. package/src/prover/isabelle/pure/goal.ts +1 -7
  116. package/src/prover/isabelle/pure/interrupt.ts +0 -5
  117. package/src/prover/isabelle/pure/list.ts +0 -3
  118. package/src/prover/isabelle/pure/logic.ts +1 -14
  119. package/src/prover/isabelle/pure/name.ts +2 -9
  120. package/src/prover/isabelle/pure/net.ts +3 -59
  121. package/src/prover/isabelle/pure/object-logic.ts +3 -10
  122. package/src/prover/isabelle/pure/pattern.ts +2 -19
  123. package/src/prover/isabelle/pure/raw-simplifier.ts +13 -49
  124. package/src/prover/isabelle/pure/rewriter.ts +26 -58
  125. package/src/prover/isabelle/pure/search.ts +3 -10
  126. package/src/prover/isabelle/pure/seq.ts +1 -10
  127. package/src/prover/isabelle/pure/simplifier.ts +4 -12
  128. package/src/prover/isabelle/pure/table.ts +1 -31
  129. package/src/prover/isabelle/pure/tactic.ts +12 -22
  130. package/src/prover/isabelle/pure/tactical.ts +6 -12
  131. package/src/prover/isabelle/pure/term-ord.ts +2 -6
  132. package/src/prover/isabelle/pure/term.ts +2 -43
  133. package/src/prover/isabelle/pure/thm.ts +13 -36
  134. package/src/prover/isabelle/pure/type.ts +2 -15
  135. package/src/prover/isabelle/pure/unify.ts +20 -30
  136. package/src/prover/isabelle/pure/variable.ts +3 -7
  137. package/src/prover/isabelle/tla/classical-setup.ts +9 -19
  138. package/src/prover/isabelle/tla/context.ts +8 -16
  139. package/src/prover/isabelle/tla/logic.ts +4 -11
  140. package/src/prover/isabelle/tla/simpdata.ts +46 -34
  141. package/src/prover/isabelle/tools/intuitionistic.ts +1 -10
  142. package/src/prover/ocaml.ts +0 -6
  143. package/src/prover/prep/action.ts +4 -36
  144. package/src/prover/prep/enabled-axioms.ts +12 -19
  145. package/src/prover/prep/fingerprint.ts +0 -16
  146. package/src/prover/prep/level-comparison.ts +8 -12
  147. package/src/prover/prep/md5.ts +0 -2
  148. package/src/prover/prep/methods.ts +9 -36
  149. package/src/prover/prep/normalize.ts +4 -28
  150. package/src/prover/prove-worker.ts +0 -2
  151. package/src/prover/prove.ts +0 -36
  152. package/src/prover/ptl/decide.ts +7 -12
  153. package/src/prover/ptl/encode.ts +14 -36
  154. package/src/prover/ptl/sat.ts +24 -32
  155. package/src/prover/ptl/tableau.ts +12 -26
  156. package/src/prover/smt/axioms.ts +0 -7
  157. package/src/prover/smt/context.ts +19 -26
  158. package/src/prover/smt/data.ts +51 -54
  159. package/src/prover/smt/encode.ts +14 -35
  160. package/src/prover/smt/extensionality.ts +0 -10
  161. package/src/prover/smt/flatten.ts +3 -22
  162. package/src/prover/smt/format.ts +5 -10
  163. package/src/prover/smt/instances.ts +0 -10
  164. package/src/prover/smt/rewrite.ts +66 -101
  165. package/src/prover/smt/solver/act-cache.ts +0 -15
  166. package/src/prover/smt/solver/arith-rewriter.ts +3 -48
  167. package/src/prover/smt/solver/array.ts +1 -3
  168. package/src/prover/smt/solver/asserted-formulas.ts +1 -43
  169. package/src/prover/smt/solver/ast-lt.ts +1 -11
  170. package/src/prover/smt/solver/ast-util.ts +1 -6
  171. package/src/prover/smt/solver/ast.ts +1 -143
  172. package/src/prover/smt/solver/auf-solver.ts +6 -39
  173. package/src/prover/smt/solver/case-split-queue.ts +1 -9
  174. package/src/prover/smt/solver/cg-table.ts +1 -18
  175. package/src/prover/smt/solver/clause.ts +1 -27
  176. package/src/prover/smt/solver/conflict-resolution.ts +0 -9
  177. package/src/prover/smt/solver/context.ts +4 -61
  178. package/src/prover/smt/solver/ctx-simplify.ts +14 -41
  179. package/src/prover/smt/solver/der.ts +2 -21
  180. package/src/prover/smt/solver/dyn-ack.ts +1 -11
  181. package/src/prover/smt/solver/e-matching.ts +3 -34
  182. package/src/prover/smt/solver/enode.ts +1 -21
  183. package/src/prover/smt/solver/expr-ref.ts +1 -5
  184. package/src/prover/smt/solver/expr-safe-replace.ts +0 -5
  185. package/src/prover/smt/solver/fingerprints.ts +1 -12
  186. package/src/prover/smt/solver/flat-literals.ts +1 -9
  187. package/src/prover/smt/solver/goal.ts +2 -14
  188. package/src/prover/smt/solver/hash.ts +0 -8
  189. package/src/prover/smt/solver/hashtable.ts +1 -12
  190. package/src/prover/smt/solver/internalizer.ts +6 -98
  191. package/src/prover/smt/solver/lbool.ts +1 -2
  192. package/src/prover/smt/solver/literal.ts +0 -3
  193. package/src/prover/smt/solver/lp/bound-propagator.ts +8 -26
  194. package/src/prover/smt/solver/lp/constraints.ts +2 -8
  195. package/src/prover/smt/solver/lp/containers.ts +12 -30
  196. package/src/prover/smt/solver/lp/core-solver.ts +10 -31
  197. package/src/prover/smt/solver/lp/cross-nested.ts +6 -20
  198. package/src/prover/smt/solver/lp/dep-intervals.ts +7 -22
  199. package/src/prover/smt/solver/lp/dependency.ts +1 -4
  200. package/src/prover/smt/solver/lp/dioph-eq.ts +12 -98
  201. package/src/prover/smt/solver/lp/explanation.ts +1 -6
  202. package/src/prover/smt/solver/lp/gomory.ts +9 -22
  203. package/src/prover/smt/solver/lp/hnf-cutter.ts +17 -23
  204. package/src/prover/smt/solver/lp/hnf.ts +11 -26
  205. package/src/prover/smt/solver/lp/int-cube.ts +15 -36
  206. package/src/prover/smt/solver/lp/int-solver.ts +4 -34
  207. package/src/prover/smt/solver/lp/lar-solver.ts +32 -81
  208. package/src/prover/smt/solver/lp/lar-term.ts +1 -5
  209. package/src/prover/smt/solver/lp/lp-settings.ts +1 -14
  210. package/src/prover/smt/solver/lp/maximize-term.ts +20 -45
  211. package/src/prover/smt/solver/lp/nex-creator.ts +5 -28
  212. package/src/prover/smt/solver/lp/nex.ts +1 -6
  213. package/src/prover/smt/solver/lp/nla-backoff.ts +1 -4
  214. package/src/prover/smt/solver/lp/nla-basics.ts +5 -30
  215. package/src/prover/smt/solver/lp/nla-core.ts +35 -130
  216. package/src/prover/smt/solver/lp/nla-divisions.ts +32 -42
  217. package/src/prover/smt/solver/lp/nla-emonics.ts +4 -21
  218. package/src/prover/smt/solver/lp/nla-factorization.ts +1 -4
  219. package/src/prover/smt/solver/lp/nla-grobner.ts +15 -69
  220. package/src/prover/smt/solver/lp/nla-horner.ts +3 -11
  221. package/src/prover/smt/solver/lp/nla-intervals.ts +2 -12
  222. package/src/prover/smt/solver/lp/nla-monomial-bounds.ts +16 -41
  223. package/src/prover/smt/solver/lp/nla-monotone.ts +2 -6
  224. package/src/prover/smt/solver/lp/nla-order.ts +2 -13
  225. package/src/prover/smt/solver/lp/nla-patcher.ts +4 -7
  226. package/src/prover/smt/solver/lp/nla-tangents.ts +1 -9
  227. package/src/prover/smt/solver/lp/nla-throttle.ts +1 -6
  228. package/src/prover/smt/solver/lp/nla-types.ts +1 -11
  229. package/src/prover/smt/solver/lp/nla-var-eqs.ts +4 -25
  230. package/src/prover/smt/solver/lp/nra-solver.ts +5 -52
  231. package/src/prover/smt/solver/lp/numeric-pair.ts +1 -4
  232. package/src/prover/smt/solver/lp/pdd-interval.ts +1 -3
  233. package/src/prover/smt/solver/lp/pdd-simplifier.ts +2 -14
  234. package/src/prover/smt/solver/lp/pdd-solver.ts +4 -33
  235. package/src/prover/smt/solver/lp/pdd.ts +7 -70
  236. package/src/prover/smt/solver/lp/random-updater.ts +1 -8
  237. package/src/prover/smt/solver/lp/static-matrix.ts +9 -19
  238. package/src/prover/smt/solver/lp/union-find.ts +1 -6
  239. package/src/prover/smt/solver/mam-compiler.ts +14 -56
  240. package/src/prover/smt/solver/mam-interpreter.ts +1 -21
  241. package/src/prover/smt/solver/maximize-ac-sharing.ts +2 -17
  242. package/src/prover/smt/solver/model-checker.ts +2 -36
  243. package/src/prover/smt/solver/model-evaluator.ts +3 -29
  244. package/src/prover/smt/solver/model-finder.ts +3 -15
  245. package/src/prover/smt/solver/model-generator.ts +1 -12
  246. package/src/prover/smt/solver/model-macro-solver.ts +12 -69
  247. package/src/prover/smt/solver/nlsat/algebraic.ts +55 -151
  248. package/src/prover/smt/solver/nlsat/atoms.ts +5 -19
  249. package/src/prover/smt/solver/nlsat/evaluator.ts +17 -22
  250. package/src/prover/smt/solver/nlsat/explain.ts +3 -47
  251. package/src/prover/smt/solver/nlsat/interval-set.ts +9 -50
  252. package/src/prover/smt/solver/nlsat/levelwise.ts +48 -129
  253. package/src/prover/smt/solver/nlsat/mpbq.ts +3 -14
  254. package/src/prover/smt/solver/nlsat/polynomial.ts +17 -156
  255. package/src/prover/smt/solver/nlsat/solver.ts +7 -67
  256. package/src/prover/smt/solver/nlsat/types.ts +1 -8
  257. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +1 -44
  258. package/src/prover/smt/solver/nlsat/upolynomial.ts +11 -92
  259. package/src/prover/smt/solver/nnf.ts +3 -38
  260. package/src/prover/smt/solver/pattern-inference.ts +2 -15
  261. package/src/prover/smt/solver/poly-rewriter.ts +3 -23
  262. package/src/prover/smt/solver/propagate-values.ts +1 -10
  263. package/src/prover/smt/solver/proto-model.ts +3 -48
  264. package/src/prover/smt/solver/pull-quant.ts +1 -12
  265. package/src/prover/smt/solver/qe-lite-der.ts +1 -29
  266. package/src/prover/smt/solver/qe-lite-fm.ts +2 -25
  267. package/src/prover/smt/solver/qe-lite.ts +3 -33
  268. package/src/prover/smt/solver/qi-queue.ts +1 -16
  269. package/src/prover/smt/solver/quant-tactics.ts +5 -22
  270. package/src/prover/smt/solver/quantifier-analyzer.ts +17 -37
  271. package/src/prover/smt/solver/quantifier-manager.ts +1 -8
  272. package/src/prover/smt/solver/random-gen.ts +1 -2
  273. package/src/prover/smt/solver/rational.ts +1 -8
  274. package/src/prover/smt/solver/ref-vector.ts +1 -6
  275. package/src/prover/smt/solver/relevancy.ts +2 -15
  276. package/src/prover/smt/solver/rewriter-tpl.ts +3 -147
  277. package/src/prover/smt/solver/rewriter.ts +3 -85
  278. package/src/prover/smt/solver/rlimit.ts +2 -20
  279. package/src/prover/smt/solver/smtlib-parser.ts +2 -37
  280. package/src/prover/smt/solver/solver.ts +23 -34
  281. package/src/prover/smt/solver/sort.ts +1 -5
  282. package/src/prover/smt/solver/sticky-generations.ts +0 -5
  283. package/src/prover/smt/solver/theory-lra-axioms.ts +3 -24
  284. package/src/prover/smt/solver/theory-lra-bounds.ts +0 -5
  285. package/src/prover/smt/solver/theory-lra-final-check.ts +4 -22
  286. package/src/prover/smt/solver/theory-lra-internalize.ts +1 -27
  287. package/src/prover/smt/solver/theory-lra-model.ts +4 -19
  288. package/src/prover/smt/solver/theory-lra-propagate.ts +1 -15
  289. package/src/prover/smt/solver/theory-lra-state.ts +3 -8
  290. package/src/prover/smt/solver/theory-lra.ts +1 -8
  291. package/src/prover/smt/solver/var-subst.ts +2 -26
  292. package/src/prover/smt/table.ts +0 -8
  293. package/src/prover/tlapm/cache.ts +20 -25
  294. package/src/prover/tlapm/ocaml-marshal.ts +19 -21
  295. package/src/prover/tlapm/tlapm.ts +12 -17
  296. package/src/prover/verdict.ts +0 -2
  297. package/src/prover/zenon/check/check.ts +0 -9
  298. package/src/prover/zenon/check/definitions.ts +5 -15
  299. package/src/prover/zenon/check/equality.ts +0 -8
  300. package/src/prover/zenon/check/functions.ts +0 -4
  301. package/src/prover/zenon/check/keys.ts +0 -7
  302. package/src/prover/zenon/check/propositional.ts +0 -3
  303. package/src/prover/zenon/check/records.ts +0 -5
  304. package/src/prover/zenon/check/relations.ts +0 -13
  305. package/src/prover/zenon/check/rewrites.ts +0 -6
  306. package/src/prover/zenon/check/sets.ts +0 -3
  307. package/src/prover/zenon/check/terms.ts +0 -17
  308. package/src/prover/zenon/check/tla.ts +0 -6
  309. package/src/prover/zenon/decide.ts +0 -12
  310. package/src/prover/zenon/encode.ts +1 -8
  311. package/src/prover/zenon/eqrel.ts +0 -13
  312. package/src/prover/zenon/equality-rules.ts +0 -4
  313. package/src/prover/zenon/expr.ts +1 -26
  314. package/src/prover/zenon/index-table.ts +17 -38
  315. package/src/prover/zenon/isar-case.ts +9 -19
  316. package/src/prover/zenon/isar.ts +1 -29
  317. package/src/prover/zenon/limits.ts +0 -4
  318. package/src/prover/zenon/llproof.ts +0 -9
  319. package/src/prover/zenon/mltoll.ts +54 -76
  320. package/src/prover/zenon/node.ts +1 -11
  321. package/src/prover/zenon/ocaml.ts +1 -17
  322. package/src/prover/zenon/parse.ts +2 -7
  323. package/src/prover/zenon/phrase.ts +1 -11
  324. package/src/prover/zenon/proof.ts +0 -9
  325. package/src/prover/zenon/propositional-rules.ts +0 -5
  326. package/src/prover/zenon/rules.ts +2 -6
  327. package/src/prover/zenon/search.ts +1 -17
  328. package/src/prover/zenon/tla/functions.ts +57 -29
  329. package/src/prover/zenon/tla/llproof.ts +63 -70
  330. package/src/prover/zenon/tla/records.ts +56 -27
  331. package/src/prover/zenon/tla/rewrites.ts +12 -19
  332. package/src/prover/zenon/tla/sets.ts +68 -39
  333. package/src/prover/zenon/tla/terms.ts +0 -6
  334. package/src/prover/zenon/tla/tla.ts +59 -58
  335. package/src/randomization.ts +81 -35
  336. package/src/resolve.ts +12 -112
  337. package/src/runtime.ts +22 -22
  338. package/src/sany/builtins.ts +2 -5
  339. package/src/sany/generator.ts +149 -252
  340. package/src/sany/levels.ts +6 -34
  341. package/src/sany/lexer.ts +41 -61
  342. package/src/sany/linter.ts +1 -9
  343. package/src/sany/modules.ts +1 -5
  344. package/src/sany/nodes.ts +0 -31
  345. package/src/sany/parse-error.ts +39 -117
  346. package/src/sany/report.ts +29 -63
  347. package/src/sany/selectors.ts +15 -39
  348. package/src/sany/source.ts +1 -17
  349. package/src/sany/xml.ts +13 -63
  350. package/src/search.ts +495 -155
  351. package/src/simulate.ts +685 -0
  352. package/src/spec-description.ts +176 -69
  353. package/src/standard-definitions.ts +0 -4
  354. package/src/standard-modules.ts +254 -69
  355. package/src/state-graph.ts +50 -24
  356. package/src/subexpressions.ts +69 -52
  357. package/src/substitution-levels.ts +2 -3
  358. package/src/successors.ts +263 -94
  359. package/src/symmetry.ts +33 -25
  360. package/src/tableau.ts +27 -24
  361. package/src/tlc/fingerprint.ts +183 -67
  362. package/src/tlc/jar-data.ts +112 -6
  363. package/src/tlc/messages.ts +110 -44
  364. package/src/tlc/order.ts +37 -60
  365. package/src/tlc/random.ts +33 -45
  366. package/src/tlc/replay.ts +549 -217
  367. package/src/tlc/summary.ts +36 -47
  368. package/src/tlc/tlc-operators.ts +76 -41
  369. package/src/tlc/tlcext-operators.ts +139 -122
  370. package/src/tlc/trace-spec.ts +269 -0
  371. package/src/tlc/value-stream.ts +139 -0
  372. package/src/tlc/version.ts +1 -4
  373. package/src/transfer.ts +22 -25
  374. package/src/typescript/actions.ts +481 -0
  375. package/src/typescript/collections.ts +600 -0
  376. package/src/typescript/compile.ts +65 -0
  377. package/src/typescript/context.ts +94 -0
  378. package/src/typescript/emit.ts +121 -0
  379. package/src/typescript/expressions.ts +496 -0
  380. package/src/typescript/formula.ts +152 -0
  381. package/src/typescript/functions.ts +284 -0
  382. package/src/typescript/model.ts +163 -0
  383. package/src/typescript/names.ts +114 -0
  384. package/src/typescript/program.ts +48 -0
  385. package/src/typescript/properties.ts +139 -0
  386. package/src/typescript/scope.ts +112 -0
  387. package/src/typescript/steps.ts +165 -0
  388. package/src/typescript/types.ts +171 -0
  389. package/src/values.ts +780 -337
  390. package/src/worker.ts +7 -8
package/src/evaluate.ts CHANGED
@@ -10,12 +10,18 @@ import {
10
10
  type NumberExpression,
11
11
  type OperatorParam,
12
12
  type RecordField,
13
- type SourceRange,
14
13
  } from "./ast";
15
14
  import { getKindString } from "./builtins";
16
- import { isStackOverflow, TlaEvaluationError, TlaUnassignedError } from "./errors";
15
+ import {
16
+ isStackOverflow,
17
+ TlaEvaluationError,
18
+ TlaSetBoundError,
19
+ TlaUnassignedError,
20
+ formatRange,
21
+ } from "./errors";
17
22
  import { EXIT_STATUS, setExitCode } from "./exit-codes";
18
23
  import { generateEvaluator } from "./codegen";
24
+ import { countCoverage, getCoverageNode, runAtCoverageNode, type Coverage } from "./coverage";
19
25
  import { MESSAGE_CODE } from "./tlc/messages";
20
26
  import type { CheckerRuntime } from "./runtime";
21
27
  import {
@@ -24,7 +30,7 @@ import {
24
30
  isNonconstant,
25
31
  type DefinitionFacts,
26
32
  } from "./dependencies";
27
- import { contextualApplications } from "./instances";
33
+ import { contextualApplications, substitutionFrames } from "./instances";
28
34
  import { prettyPrint } from "./pretty-print";
29
35
  import { isEnabled } from "./successors";
30
36
  import {
@@ -32,12 +38,15 @@ import {
32
38
  describeMissingArgument,
33
39
  compareValues,
34
40
  createFunction,
41
+ addBoundedElement,
35
42
  createNonIntegerKeyError,
43
+ forEachElement,
44
+ isBeyondSetBound,
36
45
  createRecord,
37
46
  createEnumeratedSet,
38
47
  createSortedFunction,
39
48
  createSortedRecord,
40
- createSortedSet,
49
+ createNormalizedSet,
41
50
  createWrittenRecord,
42
51
  createTuple,
43
52
  formatValue,
@@ -47,6 +56,7 @@ import {
47
56
  getIntervalElements,
48
57
  getLazySubsets,
49
58
  getStreamedElements,
59
+ normalizeShallowly,
50
60
  getFunctionClass,
51
61
  getNormalizedSetElements,
52
62
  getSequenceElements,
@@ -81,7 +91,6 @@ export interface OperatorValue {
81
91
  arity: number;
82
92
  call: (args: Value[]) => Value;
83
93
  expression?: Expression;
84
- literalBody?: Value;
85
94
  }
86
95
 
87
96
  export type BuiltinArgument = Value | OperatorValue;
@@ -94,8 +103,8 @@ export interface Builtin {
94
103
  evaluateUnary: ((value: Value) => Value) | undefined;
95
104
  evaluateBinary: ((left: Value, right: Value) => Value) | undefined;
96
105
  isStateLevel?: boolean;
97
- // Whether TLC takes an application for a constant one although its value depends on the state.
98
106
  isLevelConstant?: boolean;
107
+ isActionLevel?: boolean;
99
108
  isLazy?: boolean;
100
109
  }
101
110
 
@@ -116,12 +125,14 @@ export interface Thunk {
116
125
  state: State | undefined;
117
126
  next: State | undefined;
118
127
  cache: Value | undefined;
119
- // Whether the expression may build a set that streams until TLC caches it, so that the thunk
120
- // caches only a settled value.
121
128
  isStreamed: boolean;
129
+ isReleased?: boolean;
122
130
  }
123
131
 
124
- type Binding = { kind: "Value"; value: Value } | Thunk | { kind: "Operator"; operator: Operator };
132
+ type Binding =
133
+ | { kind: "Value"; value: Value; argument?: Expression }
134
+ | Thunk
135
+ | { kind: "Operator"; operator: Operator };
125
136
 
126
137
  export interface Scope {
127
138
  name: string;
@@ -135,55 +146,36 @@ export interface Environment {
135
146
  builtins: Map<string, Builtin>;
136
147
  constants: Map<string, Value>;
137
148
  substitutions: Map<string, string>;
138
- // The name SANY gives each definition that a named instance such as `M == INSTANCE Module`
139
- // copies, such as M!Op, by the key of the copy.
140
149
  instanceNames: Map<string, string>;
141
150
  variables: string[];
142
151
  variableIndex: Map<string, number>;
143
152
  facts: DefinitionFacts;
144
- // The value of each constant definition TLC computed when it started, by the definition's id in
145
- // facts. TLC evaluates a definition it failed to compute where the spec uses it.
146
153
  startupValues: (Value | undefined)[];
147
- // The definitions an INSTANCE copies from a module that declares constants or variables. SANY
148
- // wraps the body of each in its substitutions.
149
154
  substitutedDefinitions: Set<Definition>;
150
- // The compiled code of each expression, of each expression evaluated as a whole, which generated
151
- // code can serve, and of each reference to a definition.
155
+ instanceParams: Set<OperatorParam>;
152
156
  evaluators: WeakMap<Expression, Evaluator>;
153
157
  entryEvaluators: WeakMap<Expression, Evaluator>;
154
158
  definitionEvaluators: WeakMap<Definition, Evaluator>;
155
- // The expressions being evaluated, outermost first, when the environment replays an error to
156
- // find where it occurred, as TLC's CallStackTool does.
157
159
  callStack?: CallStack;
160
+ coverage?: Coverage;
158
161
  }
159
162
 
160
163
  export interface CallStack {
161
164
  expressions: Expression[];
162
- // TLC stops popping the stack once an evaluation fails, so it keeps where the failure occurred.
163
165
  isFrozen: boolean;
164
- // The expression that built each value of the replay that TLC's CallStackTool gives a source.
165
166
  sources: WeakMap<ObjectValue, Expression>;
166
- // The value each expression of the replay last evaluated to.
167
167
  values: WeakMap<Expression, Value>;
168
- // The expression each failure last left, which tells a failure of an operand from one of the
169
- // method that computes the operator.
170
168
  failures: WeakMap<Error, Expression>;
171
- // The failure of a value with a source, which TLC raises as a FingerprintException.
172
169
  fingerprint?: FingerprintFailure;
173
170
  }
174
171
 
175
172
  export interface FingerprintFailure {
176
- // The sources of the values whose methods failed, outermost first.
177
173
  sources: Expression[];
178
- // The message of the error the innermost one raised.
179
174
  reason: string;
180
175
  }
181
176
 
182
- // The operators of Tool#evalAppl whose value TLC's CallStackTool gives a source.
183
177
  const SOURCED_OPERATORS = new Set(["SUBSET", "UNION", "DOMAIN", "\\cup", "\\cap", "\\"]);
184
178
 
185
- // CallStackTool copies the SetPredValue, FcnLambdaValue and OpLambdaValue that an evaluation
186
- // returns without their source, and a function TLC builds from a FcnLambdaValue has none.
187
179
  const SOURCED_KINDS = new Set<Expression["kind"]>([
188
180
  "SetEnumeration",
189
181
  "SetFilter",
@@ -199,8 +191,6 @@ const isSourced = (expression: Expression) =>
199
191
  SOURCED_KINDS.has(expression.kind) ||
200
192
  (expression.kind === "Apply" && SOURCED_OPERATORS.has(expression.operator));
201
193
 
202
- // The argument whose method Tool#evalAppl calls to compute an operator, as with S.member(e) for
203
- // e \in S, f.apply(e) for f[e] when f is a function, or S.diff(T) for S \ T when S is Reducible.
204
194
  const getReceiver = (expression: Expression, values: CallStack["values"]) => {
205
195
  if (expression.kind === "FunctionApplication" || expression.kind === "Except") {
206
196
  return expression.function;
@@ -221,8 +211,6 @@ export interface Context {
221
211
  scope: Scope | undefined;
222
212
  state: State | undefined;
223
213
  next: State | undefined;
224
- // EvalControl.KeepLazy, which Tool#evalAppl sets to evaluate the function it applies and which
225
- // the evaluation passes on, so that a function constructor within builds a FcnLambdaValue.
226
214
  isKeepLazy?: boolean;
227
215
  }
228
216
 
@@ -246,15 +234,23 @@ const EXCEPT_AT = "@";
246
234
  export const describeLocation = (expression: Expression) =>
247
235
  `line ${expression.location.line}, column ${expression.location.column}`;
248
236
 
249
- export const formatRange = (range: SourceRange) =>
250
- `line ${range.start.line}, col ${range.start.column} to line ${range.end.line}, col ${range.end.column} of module ${range.module}`;
251
-
252
237
  export const describeRange = (expression: Expression) => {
253
238
  const range = expression.location.range;
254
239
  return range ? formatRange(range) : describeLocation(expression);
255
240
  };
256
241
 
257
- // SANY prints a numeral as written and any other expression by its location.
242
+ const TEMPORAL_FORMS = {
243
+ Always: "[]A",
244
+ Eventually: "<>A",
245
+ WeakFairness: "WF",
246
+ StrongFairness: "SF",
247
+ };
248
+
249
+ const createTemporalFormulaError = (form: string, expression: Expression) =>
250
+ new TlaEvaluationError(
251
+ `TLC encountered a temporal formula (${form}) when evaluating a predicate or action.\n${describeRange(expression)}`,
252
+ );
253
+
258
254
  export const describeNode = (expression: Expression) =>
259
255
  expression.kind === "Number"
260
256
  ? (expression.text ?? String(expression.value))
@@ -265,8 +261,6 @@ export const createConditionError = (expression: Expression, value: Value) =>
265
261
  `A non-boolean expression (${getKindString(value)}) was used as the condition of an IF.\n${describeRange(expression)}`,
266
262
  );
267
263
 
268
- // TLC parses an infix chain of /\ or \/ as nested binary junctions and a bulleted list as one
269
- // junction list, and it words the error differently for each.
270
264
  export const createJunctionError = (
271
265
  expression: Expression & { kind: "And" | "Or" },
272
266
  index: number,
@@ -287,12 +281,10 @@ export const createJunctionError = (
287
281
  );
288
282
  };
289
283
 
290
- // TLC selects a field of a record, and of another function from the function it converts it to,
291
- // which for a tuple keeps its domain as an interval.
292
284
  export const getFieldSelector = (expression: Expression & { kind: "FieldAccess" }) => {
293
285
  const field = expression.field;
294
286
  const describeMissing = (record: Value) =>
295
- `Attempted to select nonexistent field "${field}" from the record\n${formatValue(record)}\n${describeRange(expression)}`;
287
+ `Attempted to select nonexistent field "${field}" from the record\n${prettyPrint(formatValue(record))}\n${describeRange(expression)}`;
296
288
  const describeNotInDomain = (functionValue: Value) =>
297
289
  `Attempted to apply function:\n${prettyPrint(formatValue(functionValue))}\nto argument "${field}", which is not in the domain of the function.`;
298
290
  return (value: Value) => {
@@ -303,17 +295,14 @@ export const getFieldSelector = (expression: Expression & { kind: "FieldAccess"
303
295
  }
304
296
  const functionClass = getFunctionClass(value);
305
297
  if (functionClass === "tuple") throw createNonIntegerKeyError(field);
306
- // Only TLC's RecordValue names the field it lacks. Any other function, such as a FcnRcdValue
307
- // whose keys are strings, reports an argument outside its domain.
308
298
  return applyFunction(
309
- value,
299
+ value.kind === "LazyFunction" ? toFiniteFunction(value) : value,
310
300
  field,
311
301
  functionClass === "record" ? describeMissing : describeNotInDomain,
312
302
  );
313
303
  };
314
304
  };
315
305
 
316
- // TLC 1.7.4 words what a tuple or a record lacks differently.
317
306
  export const getMissingArgumentDescriber = (version: TlcVersion | undefined) =>
318
307
  version === "1.7.4"
319
308
  ? (functionValue: Value, argument: Value) =>
@@ -336,35 +325,31 @@ export const getSubsetOperator =
336
325
  `Attempted to evaluate an expression of form S \\subseteq T, but S was not enumerable.\n${describeRange(expression)}`,
337
326
  );
338
327
  }
339
- return builtin.evaluate([left, right]);
328
+ return builtin.evaluateBinary
329
+ ? builtin.evaluateBinary(left, right)
330
+ : builtin.evaluate([left, right]);
340
331
  };
341
332
 
342
- // TLC rejects a decimal, or an integer literal too big for it, while it processes the spec.
343
333
  export const createRealNumberError = (expression: DecimalExpression) =>
344
334
  setExitCode(
345
- new TlaEvaluationError(
346
- `TLC can't handle real numbers: ${expression.text} at ${describeLocation(expression)}`,
347
- ),
335
+ new TlaEvaluationError(`TLC can't handle real numbers.\n${expression.text}`),
348
336
  EXIT_STATUS.configParseError,
349
337
  );
350
338
 
351
339
  export const createBigNumberError = (expression: NumberExpression) =>
352
340
  setExitCode(
353
341
  new TlaEvaluationError(
354
- `TLC can't handle a number this big: ${expression.text ?? expression.value} at ${describeLocation(expression)}`,
342
+ `TLC can't handle a number this big.\n${expression.text ?? expression.value}`,
355
343
  ),
356
344
  EXIT_STATUS.error,
357
345
  );
358
346
 
359
- // TLC's Tool#evalAppl fails to look up a variable the state doesn't assign.
360
347
  export const createUnassignedError = (name: string, expression: Expression) =>
361
348
  new TlaUnassignedError(
362
349
  `In evaluation, the identifier ${name} is either undefined or not an operator.\n${describeRange(expression)}`,
363
350
  name,
364
351
  );
365
352
 
366
- // TLC's Tool#enabled reads the subscript of <<A>>_v in the successor as a state of its own, and
367
- // names the fairness condition when A leaves a variable of v unassigned, unlike TLC 1.7.4's.
368
353
  export const toUnspecifiedSubscriptError = (error: unknown, version: TlcVersion | undefined) =>
369
354
  error instanceof TlaUnassignedError && version !== "1.7.4"
370
355
  ? new TlaEvaluationError(
@@ -372,11 +357,6 @@ export const toUnspecifiedSubscriptError = (error: unknown, version: TlcVersion
372
357
  )
373
358
  : error;
374
359
 
375
- export const createPrimeOutsideActionError = (expression: Expression) =>
376
- new TlaEvaluationError(
377
- `A primed expression appears outside an action at ${describeLocation(expression)}`,
378
- );
379
-
380
360
  export const lookupScope = (scope: Scope | undefined, name: string): Binding | undefined => {
381
361
  for (let current = scope; current; current = current.parent) {
382
362
  if (current.name === name) return current.binding;
@@ -390,12 +370,13 @@ export const bindValue = (scope: Scope | undefined, name: string, value: Value):
390
370
  parent: scope,
391
371
  });
392
372
 
393
- const bindPattern = (scope: Scope | undefined, pattern: BoundPattern, value: Value) => {
373
+ export const bindPattern = (scope: Scope | undefined, pattern: BoundPattern, value: Value) => {
394
374
  if (pattern.kind === "Name") return bindValue(scope, pattern.name, value);
395
375
  const elements = getSequenceElements(value);
396
376
  if (!elements || elements.length !== pattern.names.length) {
377
+ const range = pattern.ranges?.[0];
397
378
  throw new TlaEvaluationError(
398
- `Cannot bind <<${pattern.names.join(", ")}>> to ${formatValue(value)}, which is not a tuple of that length`,
379
+ `Argument mismatch in operator application.${range ? formatRange(range) : ""}`,
399
380
  );
400
381
  }
401
382
  return pattern.names.reduce<Scope | undefined>(
@@ -404,7 +385,6 @@ const bindPattern = (scope: Scope | undefined, pattern: BoundPattern, value: Val
404
385
  );
405
386
  };
406
387
 
407
- // Tool#evalAppl checks that it applies a function before it evaluates the argument.
408
388
  export const expectFunction = (value: Value, application: Expression) => {
409
389
  if (isFunctionValue(value)) return value;
410
390
  throw new TlaEvaluationError(
@@ -440,6 +420,42 @@ export const expectBoolean = (value: Value, description: string) => {
440
420
  return value;
441
421
  };
442
422
 
423
+ export const expectImplication = (value: Value, expression: Expression, side: "P" | "Q") => {
424
+ if (typeof value !== "boolean") {
425
+ throw new TlaEvaluationError(
426
+ `Attempted to evaluate an expression of form P => Q when ${side} was\n${getKindString(value)}.\n${describeRange(expression)}`,
427
+ );
428
+ }
429
+ return value;
430
+ };
431
+
432
+ export const negate = (value: Value, expression: Expression) => {
433
+ if (typeof value !== "boolean") {
434
+ throw new TlaEvaluationError(
435
+ `Attempted to apply the operator ~ to a non-boolean\n(${getKindString(value)})\n${describeRange(expression)}`,
436
+ );
437
+ }
438
+ return !value;
439
+ };
440
+
441
+ export const isEquivalent = (left: Value, right: Value, expression: Expression) => {
442
+ if (typeof left !== "boolean" || typeof right !== "boolean") {
443
+ throw new TlaEvaluationError(
444
+ `Attempted to evaluate an expression of form P <=> Q when P or Q was not a boolean.\n${describeRange(expression)}`,
445
+ );
446
+ }
447
+ return left === right;
448
+ };
449
+
450
+ export const expectBooleanBody = (value: Value, expression: Expression) => {
451
+ if (typeof value !== "boolean") {
452
+ throw new TlaEvaluationError(
453
+ `TLC expected a boolean value, but did not find one. ${describeNode(expression)}`,
454
+ );
455
+ }
456
+ return value;
457
+ };
458
+
443
459
  export const getDefinition = (name: string, environment: Environment) =>
444
460
  environment.definitions.get(environment.substitutions.get(name) ?? name);
445
461
 
@@ -459,12 +475,9 @@ const getBoundExplanation = (set: Value, text: string) => {
459
475
  return undefined;
460
476
  };
461
477
 
462
- // TLC enumerates every set except the ones it implements in Java, so any other set fails as its own
463
- // class does.
464
478
  const checkEnumerable = (set: Value, expression: Expression, version: TlcVersion) => {
465
479
  if (!isSetValue(set) || isOverriddenSet(set)) {
466
480
  const text = formatValue(set);
467
- // TLC 1.7.4 doesn't explain why it can't enumerate a set.
468
481
  const explanation = version === "1.7.4" ? undefined : getBoundExplanation(set, text);
469
482
  throw new TlaEvaluationError(
470
483
  explanation === undefined
@@ -480,16 +493,12 @@ const getEnumeratedElements = (set: Value, expression: Expression, version: TlcV
480
493
  return getLazySubsets(set) ?? getNormalizedSetElements(set);
481
494
  };
482
495
 
483
- // The elements Tool.contexts binds to the bound of a quantifier or a set map. TLC 1.7.4 streams a
484
- // lazy set's elements, where later versions normalize the set first.
485
496
  export const getContextElements = (set: Value, expression: Expression, version: TlcVersion) => {
486
497
  if (version !== "1.7.4") return getEnumeratedElements(set, expression, version);
487
498
  checkEnumerable(set, expression, version);
488
499
  return getLazySubsets(set) ?? getStreamedElements(set);
489
500
  };
490
501
 
491
- // Like TLC, a quantifier keeps an interval as an interval, so that it can stop at the first witness
492
- // in a large interval such as 1..2000000000 without listing it.
493
502
  const getKeptInterval = (set: Value) => {
494
503
  if (typeof set !== "object" || set.kind !== "Interval") return undefined;
495
504
  getCardinality(set);
@@ -499,7 +508,6 @@ const getKeptInterval = (set: Value) => {
499
508
  export const getQuantifierElements = (set: Value, expression: Expression, version: TlcVersion) =>
500
509
  getKeptInterval(set) ?? getContextElements(set, expression, version);
501
510
 
502
- // CHOOSE and a function constructor visit the elements of the normalized set.
503
511
  const getNormalizedElements = (set: Value, expression: Expression, version: TlcVersion) =>
504
512
  getKeptInterval(set) ?? getEnumeratedElements(set, expression, version);
505
513
 
@@ -514,16 +522,19 @@ const someElement = (
514
522
  return false;
515
523
  };
516
524
 
525
+ export const mapBoundSets = <Result>(bounds: Bound[], map: (set: Expression) => Result) =>
526
+ bounds.reduce<Result[]>((results, bound, index) => {
527
+ results.push(
528
+ index > 0 && bounds[index - 1].set === bound.set ? results[index - 1] : map(bound.set),
529
+ );
530
+ return results;
531
+ }, []);
532
+
517
533
  export const getBoundElements = (bounds: Bound[], context: Context) =>
518
- bounds.map((bound) =>
519
- getQuantifierElements(
520
- evaluate(bound.set, context),
521
- bound.set,
522
- context.environment.runtime.version,
523
- ),
534
+ mapBoundSets(bounds, (set) =>
535
+ getQuantifierElements(evaluate(set, context), set, context.environment.runtime.version),
524
536
  );
525
537
 
526
- // Visits each binding of the bounds to the elements of their sets, until visit returns true.
527
538
  export const forEachBoundElement = (
528
539
  bounds: Bound[],
529
540
  sets: ReturnType<typeof getBoundElements>,
@@ -546,7 +557,7 @@ export const forEachBinding = (
546
557
  ) => forEachBoundElement(bounds, getBoundElements(bounds, context), context.scope, visit);
547
558
 
548
559
  const getBoundsDomain = (bounds: Bound[], context: Context): Value => {
549
- const sets = bounds.map((bound) => evaluate(bound.set, context));
560
+ const sets = mapBoundSets(bounds, (set) => evaluate(set, context));
550
561
  return sets.length === 1 ? sets[0] : { kind: "ProductSet", factors: sets };
551
562
  };
552
563
 
@@ -559,8 +570,6 @@ const bindArgument = (bounds: Bound[], scope: Scope | undefined, argument: Value
559
570
  );
560
571
  };
561
572
 
562
- // The parameters, body and scope of each function a constructor or a definition keeps lazy, whose
563
- // body TLC's getInitStates and getNextStates walk for an argument, as they do a FcnLambdaValue's.
564
573
  interface LazyFunction {
565
574
  value: LazyFunctionValue;
566
575
  bounds: Bound[];
@@ -568,8 +577,7 @@ interface LazyFunction {
568
577
  scope: Scope | undefined;
569
578
  }
570
579
 
571
- // The function keeps its parameters, body and scope itself, since a WeakMap entry for each
572
- // short-lived function makes every garbage collection slower.
580
+ // Kept on the value itself, since a WeakMap entry per short-lived function slows every GC.
573
581
  interface KeptLazyFunctionValue extends LazyFunctionValue {
574
582
  lambda: LazyFunction;
575
583
  }
@@ -582,8 +590,6 @@ const keepLambda = (lambda: LazyFunction) => Object.assign(lambda.value, { lambd
582
590
  export const getLazyFunction = (value: Value) =>
583
591
  isKeptLazyFunction(value) ? value.lambda : undefined;
584
592
 
585
- // Tool.getFcnContext: the scope of a lazy function's body for the arguments of an application. It
586
- // ignores arguments beyond the parameters.
587
593
  export const bindLazyArguments = (
588
594
  lambda: LazyFunction,
589
595
  expression: Expression & { kind: "FunctionApplication" },
@@ -608,12 +614,14 @@ export const bindLazyArguments = (
608
614
  typeof value.domain === "object" && value.domain.kind === "ProductSet"
609
615
  ? value.domain.factors
610
616
  : [];
611
- if (elements === undefined || elements.length < bounds.length) {
612
- throw new TlaEvaluationError(
613
- `Attempted to apply a function to an argument not in its domain.\n${describeRange(expression.function)}`,
617
+ // Deviation from TLC: FcnLambdaValue#apply indexes past an argument tuple shorter than the bounds and ignores a longer one.
618
+ const createListError = () =>
619
+ new TlaEvaluationError(
620
+ `In applying the function\n${prettyPrint(formatValue(value))},\nthe argument list is:\n${prettyPrint(formatValue(argument))}\nwhich does not match its formal parameter.\n`,
614
621
  );
615
- }
622
+ if (elements === undefined) throw createListError();
616
623
  bounds.forEach((bound, index) => {
624
+ if (index >= elements.length) throw createListError();
617
625
  const element = elements[index];
618
626
  const ordinal = `argument number ${index + 1}`;
619
627
  if (!isElementOf(element, domains[index])) {
@@ -634,11 +642,10 @@ export const bindLazyArguments = (
634
642
  );
635
643
  }
636
644
  });
637
- return bindArgument(bounds, lambda.scope, createTuple(elements.slice(0, bounds.length)));
645
+ if (elements.length > bounds.length) throw createListError();
646
+ return bindArgument(bounds, lambda.scope, argument);
638
647
  };
639
648
 
640
- // TLC prints a function it can't enumerate as its parameters and the location of its body. It
641
- // prints only the first name of a group such as `m, n \in S`.
642
649
  interface LazyFunctionTemplate {
643
650
  parameters: { index: number; name: string }[];
644
651
  body: string;
@@ -684,22 +691,29 @@ const getLazyFunctionSource = (
684
691
  };
685
692
  };
686
693
 
687
- // TLC's FcnLambdaValue evaluates its body at each application.
688
694
  const createLazyFunction = (
689
695
  domain: Value,
690
696
  compute: (argument: Value, self: LazyFunctionValue) => Value,
691
697
  source: LazyFunctionSource | undefined,
698
+ boundTupleLengths: (number | undefined)[] | undefined,
692
699
  ) => {
693
700
  const self: LazyFunctionValue = {
694
701
  kind: "LazyFunction",
695
702
  domain,
696
703
  source,
704
+ boundTupleLengths,
697
705
  apply: (argument) => compute(argument, self),
698
706
  };
699
707
  return self;
700
708
  };
701
709
 
702
- // The function constructor of a definition, which SANY locates at the whole definition.
710
+ const getBoundTupleLengths = (bounds: Bound[]) =>
711
+ bounds.length === 1
712
+ ? undefined
713
+ : bounds.map((bound) =>
714
+ bound.pattern.kind === "Tuple" ? bound.pattern.names.length : undefined,
715
+ );
716
+
703
717
  const getDefinitionSource = (definition: FunctionDefinition): Expression => ({
704
718
  kind: "FunctionConstruction",
705
719
  bounds: definition.bounds,
@@ -707,7 +721,10 @@ const getDefinitionSource = (definition: FunctionDefinition): Expression => ({
707
721
  location: definition.location,
708
722
  });
709
723
 
710
- const createRecursiveFunction = (definition: FunctionDefinition, context: Context) => {
724
+ const createRecursiveFunction = (
725
+ definition: FunctionDefinition,
726
+ context: Context,
727
+ ): RebindableLazyFunction => {
711
728
  const domain = getBoundsDomain(definition.bounds, context);
712
729
  const functionValue = createLazyFunction(
713
730
  domain,
@@ -724,6 +741,7 @@ const createRecursiveFunction = (definition: FunctionDefinition, context: Contex
724
741
  definition.bounds,
725
742
  domain,
726
743
  ),
744
+ getBoundTupleLengths(definition.bounds),
727
745
  );
728
746
  keepLambda({
729
747
  value: functionValue,
@@ -731,11 +749,16 @@ const createRecursiveFunction = (definition: FunctionDefinition, context: Contex
731
749
  body: definition.body,
732
750
  scope: bindValue(undefined, definition.name, functionValue),
733
751
  });
734
- return definition.bounds.length === 1 ? markLambdaFunction(functionValue) : functionValue;
752
+ const rebindable: RebindableLazyFunction = Object.assign(functionValue, {
753
+ rebind: (tracing: Environment) => {
754
+ const rebound = createRecursiveFunction(definition, { ...context, environment: tracing });
755
+ rebound.enumerated = functionValue.enumerated;
756
+ return rebound;
757
+ },
758
+ });
759
+ return definition.bounds.length === 1 ? markLambdaFunction(rebindable) : rebindable;
735
760
  };
736
761
 
737
- // TLC computes a constant definition when it starts, without keeping a function it constructs
738
- // lazy, so a function over an interval or an enumerated set is a FcnRcdValue.
739
762
  const toStartupValue = (definition: Definition, value: Value): Value => {
740
763
  if (typeof value !== "object" || getFunctionClass(value) !== "lambda") return value;
741
764
  if (
@@ -750,14 +773,11 @@ const toStartupValue = (definition: Definition, value: Value): Value => {
750
773
  const finite = toFiniteFunction(value);
751
774
  return createSortedFunction(finite.domain, finite.range);
752
775
  } catch (error) {
753
- // TLC leaves a definition it fails to compute to evaluate where the spec uses it.
754
776
  if (error instanceof TlaEvaluationError) return value;
755
777
  throw error;
756
778
  }
757
779
  };
758
780
 
759
- // The code of a definition's body, evaluated as a whole. TLC evaluates a function definition that
760
- // isn't recursive as it does a function constructor.
761
781
  const compileDefinitionBody = (definition: Definition, environment: Environment): Evaluator => {
762
782
  if (definition.kind === "Operator" && definition.params.length > 0) {
763
783
  return () => {
@@ -772,55 +792,83 @@ const compileDefinitionBody = (definition: Definition, environment: Environment)
772
792
  return getEntryEvaluator(getDefinitionSource(definition), environment);
773
793
  };
774
794
 
775
- // The code that evaluates a reference to a definition: the value TLC computed at startup when it
776
- // has one, and the body at the top level otherwise.
777
795
  const getDefinitionEvaluator = (definition: Definition, environment: Environment): Evaluator => {
778
796
  const compiled = environment.definitionEvaluators.get(definition);
779
797
  if (compiled) return compiled;
780
798
  const body = compileDefinitionBody(definition, environment);
781
- const id = environment.facts.ids.get(definition);
799
+ const definitionId = environment.facts.ids.get(definition);
782
800
  const startupValues = environment.startupValues;
783
801
  const evaluator: Evaluator =
784
- id === undefined
802
+ definitionId === undefined
785
803
  ? (context) => body(withScope(context, undefined))
786
- : (context) => startupValues[id] ?? body(withScope(context, undefined));
804
+ : (context) => startupValues[definitionId] ?? body(withScope(context, undefined));
787
805
  environment.definitionEvaluators.set(definition, evaluator);
788
806
  return evaluator;
789
807
  };
790
808
 
791
809
  export const getStartupValue = (definition: Definition, environment: Environment) => {
792
- const id = environment.facts.ids.get(definition);
793
- return id === undefined ? undefined : environment.startupValues[id];
810
+ const definitionId = environment.facts.ids.get(definition);
811
+ return definitionId === undefined ? undefined : environment.startupValues[definitionId];
794
812
  };
795
813
 
796
- // TLC computes each constant definition the configuration doesn't replace when it starts, and
797
- // leaves one it fails to compute to evaluate where the spec uses it.
798
814
  export const evaluateStartupDefinitions = (definitions: Definition[], environment: Environment) =>
799
815
  definitions.forEach((definition) => {
800
816
  if (definition.kind === "Operator" && definition.params.length > 0) return;
801
817
  const name = definition.name;
802
818
  if (environment.constants.has(name) || environment.substitutions.has(name)) return;
803
819
  if (!isConstantLevel(definition, environment)) return;
804
- const id = environment.facts.ids.get(definition);
805
- if (id === undefined || environment.startupValues[id] !== undefined) return;
820
+ const definitionId = environment.facts.ids.get(definition);
821
+ if (definitionId === undefined || environment.startupValues[definitionId] !== undefined) return;
806
822
  const context = { environment, scope: undefined, state: undefined, next: undefined };
807
823
  try {
808
824
  const value = environment.runtime.evaluateAtStartup(() =>
809
825
  toStartupValue(definition, compileDefinitionBody(definition, environment)(context)),
810
826
  );
811
827
  markNormalized(value);
812
- environment.startupValues[id] = value;
828
+ environment.startupValues[definitionId] = value;
813
829
  } catch (error) {
814
830
  // TLC swallows whatever the definition throws, a stack overflow included.
815
831
  if (!(error instanceof TlaEvaluationError) && !isStackOverflow(error)) throw error;
816
832
  }
817
833
  });
818
834
 
835
+ const isStateWithin = (state: State | undefined, cached: State | undefined) => {
836
+ if (cached === undefined || state === cached) return true;
837
+ try {
838
+ return cached.every(
839
+ (value, index) =>
840
+ value === undefined || (state?.[index] !== undefined && valuesEqual(state[index], value)),
841
+ );
842
+ } catch (error) {
843
+ if (error instanceof TlaEvaluationError) return false;
844
+ throw error;
845
+ }
846
+ };
847
+
819
848
  const forceThunk = (thunk: Thunk, context: Context) => {
820
- const isSameState = thunk.state === context.state && thunk.next === context.next;
821
- if (isSameState && thunk.cache !== undefined) return thunk.cache;
822
- const value = evaluate(thunk.expression, withScope(context, thunk.scope));
823
- if (isSameState && (!thunk.isStreamed || isSettledValue(value))) thunk.cache = value;
849
+ const cache = thunk.cache;
850
+ const isCached =
851
+ cache !== undefined &&
852
+ isStateWithin(context.state, thunk.state) &&
853
+ isStateWithin(context.next, thunk.next);
854
+ if (isCached) return cache;
855
+ const coverage = context.environment.coverage;
856
+ const node = coverage?.current === -1 ? undefined : coverage?.values.get(thunk);
857
+ const value =
858
+ coverage && node !== undefined
859
+ ? runAtCoverageNode(coverage, node, () =>
860
+ evaluate(thunk.expression, withScope(context, thunk.scope)),
861
+ )
862
+ : evaluate(thunk.expression, withScope(context, thunk.scope));
863
+ if (!thunk.isStreamed || isSettledValue(value)) {
864
+ thunk.cache = value;
865
+ thunk.state = context.state;
866
+ thunk.next = context.next;
867
+ }
868
+ if (thunk.cache !== undefined && thunk.state === undefined && thunk.next === undefined) {
869
+ thunk.scope = undefined;
870
+ thunk.isReleased = true;
871
+ }
824
872
  return value;
825
873
  };
826
874
 
@@ -888,6 +936,12 @@ const evaluateOperatorArgument = (expression: Expression, context: Context): Ope
888
936
  };
889
937
 
890
938
  const callOperatorWithValues = (operator: Operator, args: Value[], context: Context): Value => {
939
+ if (operator.kind === "Builtin" && operator.isLazy) {
940
+ return operator.evaluate(
941
+ args.map((value) => ({ kind: "Operator", name: "argument", arity: 0, call: () => value })),
942
+ context,
943
+ );
944
+ }
891
945
  if (operator.kind === "Builtin") return operator.evaluate(args, context);
892
946
  if (operator.kind === "Operator") return operator.call(args);
893
947
  const scope = operator.params.reduce<Scope | undefined>(
@@ -905,11 +959,6 @@ const toOperatorValue = (operator: Operator, context: Context): OperatorValue =>
905
959
  name: operator.name,
906
960
  arity: getArity(operator),
907
961
  call: (args) => callOperatorWithValues(operator, args, context),
908
- literalBody:
909
- operator.kind === "Closure" &&
910
- (operator.body.kind === "Number" || operator.body.kind === "String")
911
- ? operator.body.value
912
- : undefined,
913
962
  };
914
963
 
915
964
  const isOperatorArgument = (expression: Expression, context: Context) => {
@@ -961,9 +1010,17 @@ const compileArgumentBinder = (argument: Expression, environment: Environment):
961
1010
  const isLiteral =
962
1011
  argument.kind === "String" || (argument.kind === "Number" && isTlcInteger(argument.value));
963
1012
  if (isLiteral) {
964
- const binding: Binding = { kind: "Value", value: argument.value };
1013
+ const binding: Binding = { kind: "Value", value: argument.value, argument };
965
1014
  return () => binding;
966
1015
  }
1016
+ const coverage = environment.coverage;
1017
+ if (coverage) {
1018
+ return (context) => {
1019
+ const thunk = createThunk(argument, context);
1020
+ if (coverage.current !== -1) coverage.values.set(thunk, coverage.current);
1021
+ return thunk;
1022
+ };
1023
+ }
967
1024
  if (argument.kind === "Identifier") {
968
1025
  const global = isLocallyResolved(argument)
969
1026
  ? undefined
@@ -972,7 +1029,7 @@ const compileArgumentBinder = (argument: Expression, environment: Environment):
972
1029
  const binding: Binding = { kind: "Value", value: global.value };
973
1030
  return () => binding;
974
1031
  }
975
- if (global === undefined) {
1032
+ if (global === undefined && !environment.callStack) {
976
1033
  return (context) => {
977
1034
  const binding = lookupScope(context.scope, argument.name);
978
1035
  return binding?.kind === "Value" || binding?.kind === "Thunk"
@@ -1020,65 +1077,82 @@ const callOperator = (
1020
1077
  return operator.evaluate(evaluateBuiltinArguments(args, context), context);
1021
1078
  };
1022
1079
 
1023
- // The LET definitions that a reference evaluates again, and those that cache only a settled value.
1024
1080
  interface ReevaluatedDefinitions {
1025
1081
  impure: ReadonlySet<Definition>;
1026
1082
  streamed: ReadonlySet<Definition>;
1027
1083
  }
1028
1084
 
1085
+ const letFunctionConstructions = new WeakMap<FunctionDefinition, Expression>();
1086
+
1087
+ const getLetFunctionConstruction = (definition: FunctionDefinition): Expression => {
1088
+ const known = letFunctionConstructions.get(definition);
1089
+ if (known) return known;
1090
+ const construction: Expression = {
1091
+ kind: "FunctionConstruction",
1092
+ bounds: definition.bounds,
1093
+ body: definition.body,
1094
+ location: definition.location,
1095
+ isRecursive: true,
1096
+ };
1097
+ letFunctionConstructions.set(definition, construction);
1098
+ return construction;
1099
+ };
1100
+
1029
1101
  export const bindDefinitions = (
1030
1102
  definitions: Definition[],
1031
1103
  context: Context,
1032
1104
  reevaluated?: ReevaluatedDefinitions,
1033
- ): Scope | undefined =>
1034
- definitions.reduce<Scope | undefined>((scope, definition) => {
1035
- const node: Scope = {
1036
- name: definition.name,
1037
- binding: { kind: "Value", value: false },
1038
- parent: scope,
1039
- };
1040
- if (definition.kind === "Function") {
1041
- node.binding = {
1042
- kind: "Thunk",
1043
- expression: {
1044
- kind: "FunctionConstruction",
1045
- bounds: definition.bounds,
1046
- body: definition.body,
1047
- location: definition.location,
1048
- isRecursive: true,
1049
- },
1050
- scope: node,
1051
- state: context.state,
1052
- next: context.next,
1053
- cache: undefined,
1054
- isStreamed: false,
1055
- };
1056
- return node;
1057
- }
1058
- if (definition.params.length > 0 || reevaluated?.impure.has(definition)) {
1059
- node.binding = {
1060
- kind: "Operator",
1061
- operator: {
1062
- kind: "Closure",
1063
- name: definition.name,
1064
- params: definition.params,
1065
- body: definition.body,
1066
- scope: node,
1067
- },
1068
- };
1069
- return node;
1070
- }
1071
- node.binding = {
1072
- kind: "Thunk",
1073
- expression: definition.body,
1074
- scope: node,
1075
- state: context.state,
1076
- next: context.next,
1077
- cache: undefined,
1078
- isStreamed: reevaluated?.streamed.has(definition) ?? false,
1079
- };
1105
+ ): Scope | undefined => {
1106
+ const nodes = definitions.map((definition): Scope => ({
1107
+ name: definition.name,
1108
+ binding: { kind: "Value", value: false },
1109
+ parent: undefined,
1110
+ }));
1111
+ const scope = nodes.reduce<Scope | undefined>((parent, node) => {
1112
+ node.parent = parent;
1080
1113
  return node;
1081
1114
  }, context.scope);
1115
+ definitions.forEach((definition, index) => {
1116
+ nodes[index].binding =
1117
+ definition.kind === "Function"
1118
+ ? {
1119
+ kind: "Thunk",
1120
+ expression: getLetFunctionConstruction(definition),
1121
+ scope,
1122
+ state: context.state,
1123
+ next: context.next,
1124
+ cache: undefined,
1125
+ isStreamed: false,
1126
+ }
1127
+ : definition.params.length > 0 || reevaluated?.impure.has(definition)
1128
+ ? {
1129
+ kind: "Operator",
1130
+ operator: {
1131
+ kind: "Closure",
1132
+ name: definition.name,
1133
+ params: definition.params,
1134
+ body: definition.body,
1135
+ scope,
1136
+ },
1137
+ }
1138
+ : {
1139
+ kind: "Thunk",
1140
+ expression: definition.body,
1141
+ scope,
1142
+ state: context.state,
1143
+ next: context.next,
1144
+ cache: undefined,
1145
+ isStreamed: reevaluated?.streamed.has(definition) ?? false,
1146
+ };
1147
+ });
1148
+ const coverage = context.environment.coverage;
1149
+ if (coverage && coverage.current !== -1) {
1150
+ nodes.forEach((node) => {
1151
+ if (node.binding.kind === "Thunk") coverage.values.set(node.binding, coverage.current);
1152
+ });
1153
+ }
1154
+ return scope;
1155
+ };
1082
1156
 
1083
1157
  const evaluateLocalIdentifier = (name: string, expression: Expression, context: Context): Value => {
1084
1158
  const binding = lookupScope(context.scope, name);
@@ -1105,9 +1179,6 @@ const evaluateLocalIdentifier = (name: string, expression: Expression, context:
1105
1179
  throw new TlaEvaluationError(`Unknown identifier ${name} at ${describeLocation(expression)}`);
1106
1180
  };
1107
1181
 
1108
- // TLC's next-state generator does not bind LET definitions to values, so each reference to one
1109
- // evaluates it again: one that calls an impure builtin repeats its effects, and a set one builds
1110
- // with UNION or \cup starts out uncached.
1111
1182
  export const getReevaluatedDefinitions = (
1112
1183
  definitions: Definition[],
1113
1184
  environment: Environment,
@@ -1123,23 +1194,39 @@ export const isImpure = (environment: Environment) =>
1123
1194
  isImpureDefinition(definition, environment),
1124
1195
  );
1125
1196
 
1126
- // Whether evaluating a definition again can show, such as by printing twice.
1127
1197
  export const hasRepeatedEffects = (environment: Environment) =>
1128
1198
  [...environment.facts.ids.keys()].some((definition) =>
1129
1199
  isImpureDefinition(definition, environment, "repeated"),
1130
1200
  );
1131
1201
 
1132
- // A set filter TLC evaluates lazily, with how to rebuild it so that its predicate runs in another
1133
- // environment.
1134
1202
  interface RebindableFilteredSet extends FilteredSetValue {
1135
1203
  rebind: (environment: Environment) => Value;
1136
1204
  }
1137
1205
 
1138
- const isRebindableFilteredSet = (value: Value): value is RebindableFilteredSet =>
1139
- typeof value === "object" && value.kind === "FilteredSet" && "rebind" in value;
1206
+ interface RebindableLazyFunction extends LazyFunctionValue {
1207
+ rebind: (environment: Environment) => Value;
1208
+ }
1209
+
1210
+ const isRebindable = (value: Value): value is RebindableFilteredSet | RebindableLazyFunction =>
1211
+ typeof value === "object" &&
1212
+ (value.kind === "FilteredSet" || value.kind === "LazyFunction") &&
1213
+ "rebind" in value;
1214
+
1215
+ const toNextContext = (context: Context): Context => ({
1216
+ environment: context.environment,
1217
+ scope: context.scope,
1218
+ state: context.next,
1219
+ next: undefined,
1220
+ isKeepLazy: context.isKeepLazy,
1221
+ });
1222
+
1223
+ const compileUnchanged =
1224
+ (evaluator: Evaluator): Evaluator =>
1225
+ (context) => {
1226
+ const current = evaluator(context);
1227
+ return valuesEqual(current, evaluator(toNextContext(context)));
1228
+ };
1140
1229
 
1141
- // TLC's CallStackTool rebinds the lazy values its evaluations return, so their later evaluation
1142
- // records its call stack too.
1143
1230
  const traceEvaluator =
1144
1231
  (
1145
1232
  expression: Expression,
@@ -1157,13 +1244,17 @@ const traceEvaluator =
1157
1244
  setTrace.callStack = callStack;
1158
1245
  try {
1159
1246
  const computed = evaluator(context);
1160
- const value = isRebindableFilteredSet(computed) ? computed.rebind(environment) : computed;
1247
+ const value = isRebindable(computed) ? computed.rebind(environment) : computed;
1161
1248
  callStack.values.set(expression, value);
1162
1249
  if (typeof value === "object" && value.kind !== "FilteredSet" && isSourced(expression)) {
1163
1250
  callStack.sources.set(value, expression);
1164
1251
  }
1165
1252
  return value;
1166
1253
  } catch (error) {
1254
+ if (error instanceof TlaSetBoundError && !callStack.isFrozen) {
1255
+ callStack.expressions.length = 0;
1256
+ callStack.isFrozen = true;
1257
+ }
1167
1258
  const failed = error instanceof Error ? callStack.failures.get(error) : undefined;
1168
1259
  if (error instanceof Error) callStack.failures.set(error, expression);
1169
1260
  const receiver = getReceiver(expression, callStack.values);
@@ -1191,20 +1282,15 @@ const traceEvaluator =
1191
1282
  }
1192
1283
  };
1193
1284
 
1194
- // A method of a value with a source raises a FingerprintException, which each value with a source
1195
- // whose method called it heads in turn. CallStack#freeze adds their sources to the stack, outermost
1196
- // first. The values are those whose methods failed, outermost first.
1197
1285
  export const freezeCallStack = (
1198
1286
  callStack: CallStack,
1199
1287
  values: (Value | undefined)[],
1200
1288
  error: unknown,
1201
1289
  ) => {
1202
- // A set that streams its elements enumerates itself too, so it can appear twice.
1203
1290
  const sources = [...new Set(values)].flatMap((item) => {
1204
1291
  const source = typeof item === "object" ? callStack.sources.get(item) : undefined;
1205
1292
  return source ? [source] : [];
1206
1293
  });
1207
- // A value with a source raises a FingerprintException even when the stack is frozen already.
1208
1294
  if (sources.length > 0 && error instanceof TlaEvaluationError) {
1209
1295
  if (!callStack.isFrozen) callStack.expressions.push(...sources);
1210
1296
  const inner = callStack.fingerprint;
@@ -1216,8 +1302,6 @@ export const freezeCallStack = (
1216
1302
  callStack.isFrozen = true;
1217
1303
  };
1218
1304
 
1219
- // A FingerprintException that a method of a value with a source raises, or that passes through one,
1220
- // takes the value's source as its new head.
1221
1305
  const headFingerprint = (callStack: CallStack, source: Expression, error: unknown) => {
1222
1306
  if (!(error instanceof TlaEvaluationError)) return;
1223
1307
  if (!callStack.isFrozen) callStack.expressions.push(source);
@@ -1229,10 +1313,9 @@ const headFingerprint = (callStack: CallStack, source: Expression, error: unknow
1229
1313
  };
1230
1314
  };
1231
1315
 
1232
- // A copy of the environment that records the call stack of each evaluation, with evaluators of its
1233
- // own since the environment's evaluators record nothing.
1234
1316
  export const createTracingEnvironment = (environment: Environment): Environment => ({
1235
1317
  ...environment,
1318
+ coverage: undefined,
1236
1319
  evaluators: new WeakMap(),
1237
1320
  entryEvaluators: new WeakMap(),
1238
1321
  definitionEvaluators: new WeakMap(),
@@ -1245,20 +1328,60 @@ export const createTracingEnvironment = (environment: Environment): Environment
1245
1328
  },
1246
1329
  });
1247
1330
 
1331
+ const traceFrames =
1332
+ (
1333
+ expression: Expression,
1334
+ frames: Expression[],
1335
+ evaluator: Evaluator,
1336
+ callStack: CallStack,
1337
+ ): Evaluator =>
1338
+ (context) => {
1339
+ if (callStack.expressions.at(-1) === expression) return evaluator(context);
1340
+ callStack.expressions.push(...frames);
1341
+ try {
1342
+ return evaluator(context);
1343
+ } finally {
1344
+ if (!callStack.isFrozen) callStack.expressions.length -= frames.length;
1345
+ }
1346
+ };
1347
+
1348
+ const countEvaluator =
1349
+ (expression: Expression, evaluator: Evaluator, coverage: Coverage): Evaluator =>
1350
+ (context) => {
1351
+ const outer = coverage.current;
1352
+ if (outer === -1 || !coverage.covered.has(expression)) return evaluator(context);
1353
+ const node = getCoverageNode(coverage, outer, expression);
1354
+ countCoverage(coverage, node);
1355
+ coverage.current = node;
1356
+ try {
1357
+ const value = evaluator(context);
1358
+ if (typeof value === "object" && expression.kind === "SetEnumeration") {
1359
+ coverage.values.set(value, node);
1360
+ }
1361
+ return value;
1362
+ } finally {
1363
+ coverage.current = outer;
1364
+ }
1365
+ };
1366
+
1248
1367
  export const getEvaluator = (expression: Expression, environment: Environment): Evaluator => {
1249
1368
  const cached = environment.evaluators.get(expression);
1250
1369
  if (cached) return cached;
1251
1370
  const compiled = compile(expression, environment);
1252
1371
  const callStack = environment.callStack;
1253
- const evaluator = callStack
1372
+ const frames = callStack && substitutionFrames.get(expression);
1373
+ const traced = callStack
1254
1374
  ? traceEvaluator(expression, compiled, environment, callStack)
1255
1375
  : compiled;
1376
+ const framed = callStack && frames ? traceFrames(expression, frames, traced, callStack) : traced;
1377
+ const coverage = environment.coverage;
1378
+ const evaluator = coverage ? countEvaluator(expression, framed, coverage) : framed;
1256
1379
  environment.evaluators.set(expression, evaluator);
1257
1380
  return evaluator;
1258
1381
  };
1259
1382
 
1260
1383
  export const getEntryEvaluator = (expression: Expression, environment: Environment) => {
1261
- if (environment.callStack) return getEvaluator(expression, environment);
1384
+ if (environment.callStack || environment.coverage) return getEvaluator(expression, environment);
1262
1385
  const compiled = environment.entryEvaluators.get(expression);
1263
1386
  if (compiled) return compiled;
1264
1387
  const evaluator =
@@ -1289,12 +1412,9 @@ const compileIdentifier = (
1289
1412
  return () => value;
1290
1413
  }
1291
1414
  if (global?.kind === "Definition") {
1292
- // The body compiles when the reference is first evaluated, as a recursive definition's body
1293
- // refers back to it.
1294
1415
  const definition = global.definition;
1295
- const compiled = { reference: undefined as Evaluator | undefined };
1296
- return (context) =>
1297
- (compiled.reference ??= getDefinitionEvaluator(definition, environment))(context);
1416
+ let compiled: Evaluator | undefined;
1417
+ return (context) => (compiled ??= getDefinitionEvaluator(definition, environment))(context);
1298
1418
  }
1299
1419
  return (context) => evaluateLocalIdentifier(name, expression, context);
1300
1420
  };
@@ -1374,11 +1494,10 @@ const compileClosureCall = (
1374
1494
  environment: Environment,
1375
1495
  ): Evaluator => {
1376
1496
  const bindArguments = compileArgumentScope(closure, args, environment);
1377
- // The body compiles when the call is first evaluated, as a recursive operator's body calls it.
1378
- const compiled = { body: undefined as Evaluator | undefined };
1497
+ let body: Evaluator | undefined;
1379
1498
  return (context) => {
1380
- compiled.body ??= getEntryEvaluator(closure.body, environment);
1381
- return compiled.body({
1499
+ body ??= getEntryEvaluator(closure.body, environment);
1500
+ return body({
1382
1501
  environment,
1383
1502
  scope: bindArguments(context),
1384
1503
  state: context.state,
@@ -1397,12 +1516,24 @@ const compileApply = (
1397
1516
  const left = getEvaluator(args[0], environment);
1398
1517
  const right = getEvaluator(args[1], environment);
1399
1518
  return (context) =>
1400
- !expectBoolean(left(context), "the left side of =>") ||
1401
- expectBoolean(right(context), "the right side of =>");
1519
+ !expectImplication(left(context), expression, "P") ||
1520
+ expectImplication(right(context), expression, "Q");
1402
1521
  }
1403
- if (expression.operator === "~>") {
1522
+ if (expression.operator === "~" && args.length === 1) {
1523
+ const operand = getEvaluator(args[0], environment);
1524
+ return (context) => negate(operand(context), expression);
1525
+ }
1526
+ if (expression.operator === "<=>") {
1527
+ const left = getEvaluator(args[0], environment);
1528
+ const right = getEvaluator(args[1], environment);
1529
+ return (context) => isEquivalent(left(context), right(context), expression);
1530
+ }
1531
+ if (expression.operator === "~>" || expression.operator === "-+->") {
1404
1532
  return () => {
1405
- throw new TlaEvaluationError("TLC cannot evaluate a temporal formula such as ~> in a state");
1533
+ throw createTemporalFormulaError(
1534
+ expression.operator === "~>" ? "a ~> b" : "a -+-> formula",
1535
+ expression,
1536
+ );
1406
1537
  };
1407
1538
  }
1408
1539
  const global = isLocallyResolved(expression)
@@ -1414,14 +1545,14 @@ const compileApply = (
1414
1545
  const domain = getDomainOperator(expression);
1415
1546
  return (context) => domain(operand(context));
1416
1547
  }
1417
- // TLC sorts the value of a constant TLCEval argument only where no context binds a name.
1418
1548
  if (global?.kind === "Builtin" && global.name === "TLCEval" && args.length === 1) {
1419
- const operand = getEvaluator(args[0], environment);
1420
- if (contextualApplications.has(expression) || isNonconstant(args[0], environment)) {
1421
- return operand;
1422
- }
1549
+ const isCached =
1550
+ !contextualApplications.has(expression) && !isNonconstant(args[0], environment);
1423
1551
  return (context) =>
1424
- context.scope === undefined ? global.evaluate([operand(context)]) : operand(context);
1552
+ global.evaluate(
1553
+ getLazyArguments(args, context),
1554
+ isCached && context.scope === undefined ? undefined : context,
1555
+ );
1425
1556
  }
1426
1557
  if (global?.kind === "Builtin" && global.name === "\\subseteq" && args.length === 2) {
1427
1558
  const left = getEvaluator(args[0], environment);
@@ -1430,7 +1561,6 @@ const compileApply = (
1430
1561
  return (context) => subset(left(context), right(context));
1431
1562
  }
1432
1563
  if (global?.kind === "Builtin") return compileBuiltinCall(global, args, environment);
1433
- // TLC refuses action composition unless a Java property enables its incomplete implementation.
1434
1564
  if (expression.operator === "\\cdot" && args.length === 2) {
1435
1565
  return () => {
1436
1566
  throw new TlaEvaluationError(
@@ -1459,7 +1589,6 @@ const compileQuantifier = (
1459
1589
  environment: Environment,
1460
1590
  ): Evaluator => {
1461
1591
  const isForall = expression.kind === "Forall";
1462
- const description = isForall ? "the body of \\A" : "the body of \\E";
1463
1592
  const body = getEvaluator(expression.body, environment);
1464
1593
  const bound = expression.bounds[0];
1465
1594
  if (expression.bounds.length === 1 && bound.pattern.kind === "Name") {
@@ -1469,9 +1598,9 @@ const compileQuantifier = (
1469
1598
  const isFound = someElement(
1470
1599
  getQuantifierElements(set(context), bound.set, environment.runtime.version),
1471
1600
  (element) =>
1472
- expectBoolean(
1601
+ expectBooleanBody(
1473
1602
  body(withScope(context, bindValue(context.scope, name, element))),
1474
- description,
1603
+ expression,
1475
1604
  ) !== isForall,
1476
1605
  );
1477
1606
  return isFound ? !isForall : isForall;
@@ -1480,14 +1609,17 @@ const compileQuantifier = (
1480
1609
  const bounds = expression.bounds;
1481
1610
  if (bounds.every((item) => item.pattern.kind === "Name")) {
1482
1611
  const names = bounds.map((item) => (item.pattern.kind === "Name" ? item.pattern.name : ""));
1483
- const sets = bounds.map((item) => getEvaluator(item.set, environment));
1484
1612
  return (context) => {
1485
- const lists = sets.map((set, index) =>
1486
- getQuantifierElements(set(context), bounds[index].set, environment.runtime.version),
1613
+ const lists = mapBoundSets(bounds, (set) =>
1614
+ getQuantifierElements(
1615
+ getEvaluator(set, environment)(context),
1616
+ set,
1617
+ environment.runtime.version,
1618
+ ),
1487
1619
  );
1488
1620
  const visit = (index: number, scope: Scope | undefined): boolean => {
1489
1621
  if (index < 0) {
1490
- return expectBoolean(body(withScope(context, scope)), description) !== isForall;
1622
+ return expectBooleanBody(body(withScope(context, scope)), expression) !== isForall;
1491
1623
  }
1492
1624
  return someElement(lists[index], (element) =>
1493
1625
  visit(index - 1, bindValue(scope, names[index], element)),
@@ -1500,7 +1632,7 @@ const compileQuantifier = (
1500
1632
  const isFound = forEachBinding(
1501
1633
  bounds,
1502
1634
  context,
1503
- (scope) => expectBoolean(body(withScope(context, scope)), description) !== isForall,
1635
+ (scope) => expectBooleanBody(body(withScope(context, scope)), expression) !== isForall,
1504
1636
  );
1505
1637
  return isFound ? !isForall : isForall;
1506
1638
  };
@@ -1519,8 +1651,6 @@ const getBoundValue = (pattern: BoundPattern, scope: Scope | undefined) => {
1519
1651
  return binding?.kind === "Value" ? binding.value : undefined;
1520
1652
  };
1521
1653
 
1522
- // TLC keeps a function constructor lazy when it is the function of an application, or the base of
1523
- // an EXCEPT that is, so it evaluates the body only at the arguments it is applied to.
1524
1654
  const keptLazyExpressions = new WeakSet<Expression>();
1525
1655
 
1526
1656
  export const keepLazy = (expression: Expression) => {
@@ -1529,34 +1659,65 @@ export const keepLazy = (expression: Expression) => {
1529
1659
  }
1530
1660
  };
1531
1661
 
1532
- const compileFunctionConstruction = (
1662
+ const scopeNames = new WeakMap<Expression, string[] | undefined>();
1663
+
1664
+ const getScopeNames = (expression: Expression) => {
1665
+ if (scopeNames.has(expression)) return scopeNames.get(expression);
1666
+ const names = new Set<string>();
1667
+ const visit = (node: Expression): boolean => {
1668
+ if (node.kind === "Subexpression") return false;
1669
+ if (node.kind === "Identifier") names.add(node.name);
1670
+ if (node.kind === "Apply" || node.kind === "OperatorReference") names.add(node.operator);
1671
+ if (node.kind === "ExceptAt") names.add(EXCEPT_AT);
1672
+ return getChildren(node).every(visit);
1673
+ };
1674
+ const result = visit(expression) ? [...names] : undefined;
1675
+ scopeNames.set(expression, result);
1676
+ return result;
1677
+ };
1678
+
1679
+ const trimScope = (scope: Scope | undefined, names: string[] | undefined) =>
1680
+ names === undefined || scope === undefined
1681
+ ? scope
1682
+ : names.reduce<Scope>(
1683
+ (trimmed, name) => {
1684
+ const binding = lookupScope(scope, name);
1685
+ return binding ? { name, binding, parent: trimmed } : trimmed;
1686
+ },
1687
+ { name: "", binding: { kind: "Value", value: false }, parent: undefined },
1688
+ );
1689
+
1690
+ export const isKeptLazy = (expression: Expression) => keptLazyExpressions.has(expression);
1691
+
1692
+ export const getFunctionBuilder = (
1533
1693
  expression: Expression & { kind: "FunctionConstruction" },
1534
1694
  environment: Environment,
1535
- ): Evaluator => {
1536
- const isKeptLazy = keptLazyExpressions.has(expression);
1695
+ ) => {
1696
+ const isKeptLazyExpression = isKeptLazy(expression);
1537
1697
  const body = getEvaluator(expression.body, environment);
1538
1698
  const bounds = expression.bounds;
1539
1699
  const bound = bounds[0];
1540
1700
  const isSingleName = bounds.length === 1 && bound.pattern.kind === "Name";
1541
- const set = getEvaluator(bound.set, environment);
1542
1701
  const construct = (domain: Value, context: Context) => {
1543
1702
  if (isSingleName && bound.pattern.kind === "Name") {
1544
1703
  const name = bound.pattern.name;
1704
+ const evaluateAt = (key: Value) =>
1705
+ body(withScope(context, bindValue(context.scope, name, key)));
1706
+ // TLC sizes the domain and evaluates the body at each element of a domain too large to hold.
1707
+ if (isBeyondSetBound(domain)) {
1708
+ getCardinality(domain);
1709
+ forEachElement(domain, evaluateAt);
1710
+ return createLazy(domain, context);
1711
+ }
1545
1712
  const keys = getFunctionDomain(domain);
1546
- const functionValue = createSortedFunction(
1547
- keys,
1548
- keys.map((key) => body(withScope(context, bindValue(context.scope, name, key)))),
1549
- );
1550
- // FcnLambdaValue#toFcnRcd builds a FcnRcdValue over an interval or an enumerated set.
1551
- return isReducibleSet(domain) ? functionValue : markLambdaFunction(functionValue);
1713
+ const functionValue = createSortedFunction(keys, keys.map(evaluateAt));
1714
+ if (isReducibleSet(domain)) return functionValue;
1715
+ functionValue.lambdaDomain = domain;
1716
+ return markLambdaFunction(functionValue);
1552
1717
  }
1553
1718
  const pairs: [Value, Value][] = [];
1554
- const sets = bounds.map((item) =>
1555
- getNormalizedElements(
1556
- evaluate(item.set, context),
1557
- item.set,
1558
- context.environment.runtime.version,
1559
- ),
1719
+ const sets = mapBoundSets(bounds, (set) =>
1720
+ getNormalizedElements(evaluate(set, context), set, context.environment.runtime.version),
1560
1721
  );
1561
1722
  forEachBoundElement(bounds, sets, context.scope, (scope) => {
1562
1723
  const key =
@@ -1569,13 +1730,17 @@ const compileFunctionConstruction = (
1569
1730
  return createFunction(pairs);
1570
1731
  };
1571
1732
  const template = getLazyFunctionTemplate(bounds, expression.body);
1733
+ const boundTupleLengths = getBoundTupleLengths(bounds);
1734
+ const bodyNames = getScopeNames(expression.body);
1572
1735
  const createLazy = (domain: Value, context: Context) => {
1573
- const scope = context.scope;
1736
+ const scope = trimScope(context.scope, bodyNames);
1737
+ const lambdaContext = withScope(context, scope);
1574
1738
  const functionValue = keepLambda({
1575
1739
  value: createLazyFunction(
1576
1740
  domain,
1577
- (argument) => body(withScope(context, bindArgument(bounds, scope, argument))),
1741
+ (argument) => body(withScope(lambdaContext, bindArgument(bounds, scope, argument))),
1578
1742
  getLazyFunctionSource(template, bounds, domain),
1743
+ boundTupleLengths,
1579
1744
  ),
1580
1745
  bounds,
1581
1746
  body: expression.body,
@@ -1584,15 +1749,22 @@ const compileFunctionConstruction = (
1584
1749
  return bounds.length === 1 ? markLambdaFunction(functionValue) : functionValue;
1585
1750
  };
1586
1751
  const callStack = environment.callStack;
1587
- return (context) => {
1588
- const domain = isSingleName ? set(context) : getBoundsDomain(bounds, context);
1589
- if (expression.isRecursive || isKeptLazy || context.isKeepLazy || !isEnumerable(domain)) {
1752
+ const build = (domain: Value, context: Context) => {
1753
+ if (
1754
+ expression.isRecursive ||
1755
+ isKeptLazyExpression ||
1756
+ context.isKeepLazy ||
1757
+ !isEnumerable(domain)
1758
+ ) {
1590
1759
  return createLazy(domain, context);
1591
1760
  }
1592
- // TLC builds a function over a domain other than a set enumeration or an interval lazily, so
1593
- // its body fails only where TLC forces it, as the replay does. Building it at once is faster
1594
- // otherwise.
1595
- if (!isReducibleSet(domain)) {
1761
+ const isReducibleDomain =
1762
+ bounds.length === 1
1763
+ ? isReducibleSet(domain)
1764
+ : typeof domain === "object" &&
1765
+ domain.kind === "ProductSet" &&
1766
+ domain.factors.every(isReducibleSet);
1767
+ if (!isReducibleDomain) {
1596
1768
  if (callStack) return createLazy(domain, context);
1597
1769
  try {
1598
1770
  return construct(domain, context);
@@ -1602,7 +1774,6 @@ const compileFunctionConstruction = (
1602
1774
  }
1603
1775
  }
1604
1776
  if (!callStack) return construct(domain, context);
1605
- // TLC builds the function in a method of the FcnLambdaValue that CallStackTool gives a source.
1606
1777
  try {
1607
1778
  return construct(domain, context);
1608
1779
  } catch (error) {
@@ -1610,14 +1781,28 @@ const compileFunctionConstruction = (
1610
1781
  throw error;
1611
1782
  }
1612
1783
  };
1784
+ return { build, createLazy };
1785
+ };
1786
+
1787
+ const compileFunctionConstruction = (
1788
+ expression: Expression & { kind: "FunctionConstruction" },
1789
+ environment: Environment,
1790
+ ): Evaluator => {
1791
+ const build = getFunctionBuilder(expression, environment).build;
1792
+ const bounds = expression.bounds;
1793
+ if (bounds.length === 1 && bounds[0].pattern.kind === "Name") {
1794
+ const set = getEvaluator(bounds[0].set, environment);
1795
+ return (context) => build(set(context), context);
1796
+ }
1797
+ return (context) => build(getBoundsDomain(bounds, context), context);
1613
1798
  };
1614
1799
 
1615
1800
  const compileExcept = (
1616
1801
  expression: Expression & { kind: "Except" },
1617
1802
  environment: Environment,
1618
1803
  ): Evaluator => {
1619
- const isKeptLazy = keptLazyExpressions.has(expression);
1620
- if (isKeptLazy) keepLazy(expression.function);
1804
+ const isKeptLazyExpression = keptLazyExpressions.has(expression);
1805
+ if (isKeptLazyExpression) keepLazy(expression.function);
1621
1806
  const evaluateFunction = getEvaluator(expression.function, environment);
1622
1807
  const updates = expression.updates.map((update) => ({
1623
1808
  path: update.path.map((step): CompiledStep =>
@@ -1650,19 +1835,18 @@ const compileExcept = (
1650
1835
  current,
1651
1836
  getKey(path[depth], context),
1652
1837
  (previous) => update(previous, path, depth + 1, context, value),
1653
- isKeptLazy && depth === 0,
1838
+ isKeptLazyExpression && depth === 0,
1654
1839
  );
1655
1840
  };
1656
1841
  return (context) => {
1657
1842
  let current = evaluateFunction(context);
1658
1843
  for (const item of updates) {
1659
- // TLC leaves the value as it is when an update's path is not in it, and warns.
1660
- const found = { value: false };
1844
+ let isFound = false;
1661
1845
  current = update(current, item.path, 0, context, (inner) => {
1662
- found.value = true;
1846
+ isFound = true;
1663
1847
  return item.value(inner);
1664
1848
  });
1665
- if (!found.value) {
1849
+ if (!isFound) {
1666
1850
  context.environment.runtime.warn(
1667
1851
  MESSAGE_CODE.exceptAppliedToUnknownField,
1668
1852
  `The EXCEPT was applied to non-existing fields of the value at\n${describeRange(expression.function)}`,
@@ -1673,6 +1857,98 @@ const compileExcept = (
1673
1857
  };
1674
1858
  };
1675
1859
 
1860
+ export const getLazyFilter = (
1861
+ expression: Expression & { kind: "SetFilter" },
1862
+ environment: Environment,
1863
+ ) => {
1864
+ const predicate = getEvaluator(expression.predicate, environment);
1865
+ const pattern = expression.bound.pattern;
1866
+ const range = expression.predicate.location.range;
1867
+ const source = range && {
1868
+ names: pattern.kind === "Name" ? pattern.name : pattern.names.join(", "),
1869
+ predicate: formatRange(range),
1870
+ };
1871
+ const predicateNode = describeNode(expression.predicate);
1872
+ const coverage = environment.coverage;
1873
+ const testCovered = (node: number, isMember: boolean, test: () => Value) => {
1874
+ if (!coverage || node === -1) return test();
1875
+ if (!isMember) coverage.secondary[node]++;
1876
+ const value = runAtCoverageNode(coverage, isMember ? -1 : node, test);
1877
+ if (!isMember && value === true) coverage.secondary[node]++;
1878
+ return value;
1879
+ };
1880
+ const createFiltered = (
1881
+ base: Value,
1882
+ context: Context,
1883
+ evaluator: Evaluator,
1884
+ node: number,
1885
+ ): RebindableFilteredSet => ({
1886
+ kind: "FilteredSet",
1887
+ base,
1888
+ test: (element, isMember) => {
1889
+ if (
1890
+ pattern.kind === "Tuple" &&
1891
+ getSequenceElements(element)?.length !== pattern.names.length
1892
+ ) {
1893
+ throw new TlaEvaluationError(
1894
+ `Attempted to check if the value:\n${prettyPrint(formatValue(element))}\nis an element of a set of ${pattern.names.length}-tuples.`,
1895
+ );
1896
+ }
1897
+ const value = testCovered(node, isMember, () =>
1898
+ evaluator(withScope(context, bindPattern(context.scope, pattern, element))),
1899
+ );
1900
+ if (typeof value !== "boolean") {
1901
+ throw new TlaEvaluationError(
1902
+ `${isMember ? "The evaluation of predicate" : "Evaluating predicate"} ${predicateNode} yielded non-Boolean value.`,
1903
+ );
1904
+ }
1905
+ return value;
1906
+ },
1907
+ source,
1908
+ rebind: (tracing) =>
1909
+ createFiltered(
1910
+ base,
1911
+ { ...context, environment: tracing },
1912
+ getEvaluator(expression.predicate, tracing),
1913
+ -1,
1914
+ ),
1915
+ });
1916
+ return (base: Value, context: Context, node = -1) =>
1917
+ createFiltered(base, context, predicate, node);
1918
+ };
1919
+
1920
+ export const expectFilterPredicate = (
1921
+ value: Value,
1922
+ expression: Expression & { kind: "SetFilter" },
1923
+ ) => {
1924
+ if (typeof value !== "boolean") {
1925
+ throw new TlaEvaluationError(
1926
+ `Attempted to evaluate an expression of form {x \\in S : P(x)} when P was ${getKindString(value)}.\n${describeNode(expression.predicate)}`,
1927
+ );
1928
+ }
1929
+ return value;
1930
+ };
1931
+
1932
+ export const getChoiceElements = (
1933
+ base: Value,
1934
+ expression: Expression & { kind: "Choose" },
1935
+ set: Expression,
1936
+ version: TlcVersion,
1937
+ ) => {
1938
+ if (!isSetValue(base) || isOverriddenSet(base)) {
1939
+ throw new TlaEvaluationError(
1940
+ `Attempted to compute the value of an expression of\nform CHOOSE x \\in S: P, but S was not enumerable.\n${describeRange(expression)}`,
1941
+ );
1942
+ }
1943
+ normalizeShallowly(base);
1944
+ return getNormalizedElements(base, set, version);
1945
+ };
1946
+
1947
+ export const createNoChoiceError = (expression: Expression & { kind: "Choose" }) =>
1948
+ new TlaEvaluationError(
1949
+ `Attempted to compute the value of an expression of form\nCHOOSE x \\in S: P, but no element of S satisfied P.\n${describeRange(expression)}`,
1950
+ );
1951
+
1676
1952
  const compileSetComprehension = (
1677
1953
  expression: Expression & { kind: "SetFilter" | "SetMap" | "Choose" },
1678
1954
  environment: Environment,
@@ -1680,38 +1956,25 @@ const compileSetComprehension = (
1680
1956
  if (expression.kind === "SetFilter") {
1681
1957
  const predicate = getEvaluator(expression.predicate, environment);
1682
1958
  const set = getEvaluator(expression.bound.set, environment);
1959
+ const filterLazily = getLazyFilter(expression, environment);
1683
1960
  const pattern = expression.bound.pattern;
1684
- const range = expression.predicate.location.range;
1685
- const source = range && {
1686
- names: pattern.kind === "Name" ? pattern.name : pattern.names.join(", "),
1687
- predicate: formatRange(range),
1688
- };
1689
- const createTest = (evaluator: Evaluator, context: Context) => (element: Value) =>
1690
- expectBoolean(
1691
- evaluator(withScope(context, bindPattern(context.scope, pattern, element))),
1692
- "a set filter predicate",
1693
- );
1694
- const createFiltered = (
1695
- base: Value,
1696
- context: Context,
1697
- evaluator: Evaluator,
1698
- ): RebindableFilteredSet => ({
1699
- kind: "FilteredSet",
1700
- base,
1701
- test: createTest(evaluator, context),
1702
- source,
1703
- rebind: (tracing) =>
1704
- createFiltered(
1705
- base,
1706
- { ...context, environment: tracing },
1707
- getEvaluator(expression.predicate, tracing),
1708
- ),
1709
- });
1961
+ const coverage = environment.coverage;
1710
1962
  return (context) => {
1711
1963
  const base = set(context);
1712
- // TLC filters any value it can't enumerate lazily, and fails only when it uses the result.
1713
- if (!isReducibleSet(base)) return createFiltered(base, context, predicate);
1714
- return createSortedSet(toFiniteSet(base).elements.filter(createTest(predicate, context)));
1964
+ if (!isReducibleSet(base)) return filterLazily(base, context, coverage?.current);
1965
+ const kept: Value[] = [];
1966
+ const visit = (element: Value) => {
1967
+ const value = predicate(withScope(context, bindPattern(context.scope, pattern, element)));
1968
+ if (expectFilterPredicate(value, expression)) addBoundedElement(kept, element);
1969
+ };
1970
+ const elements = base.kind === "Interval" ? base : toFiniteSet(base).elements;
1971
+ forEachElement(elements, visit);
1972
+ if (coverage && coverage.current !== -1) {
1973
+ coverage.secondary[coverage.current] +=
1974
+ (Array.isArray(elements) ? elements.length : elements.high - elements.low + 1) +
1975
+ kept.length;
1976
+ }
1977
+ return createNormalizedSet(kept);
1715
1978
  };
1716
1979
  }
1717
1980
  if (expression.kind === "SetMap") {
@@ -1719,7 +1982,7 @@ const compileSetComprehension = (
1719
1982
  return (context) => {
1720
1983
  const elements: Value[] = [];
1721
1984
  forEachBinding(expression.bounds, context, (scope) => {
1722
- elements.push(mapped(withScope(context, scope)));
1985
+ addBoundedElement(elements, mapped(withScope(context, scope)));
1723
1986
  return false;
1724
1987
  });
1725
1988
  return createEnumeratedSet(elements);
@@ -1729,37 +1992,40 @@ const compileSetComprehension = (
1729
1992
  if (!set) {
1730
1993
  return () => {
1731
1994
  throw new TlaEvaluationError(
1732
- `TLC cannot evaluate an unbounded CHOOSE at ${describeLocation(expression)}`,
1995
+ `TLC attempted to evaluate an unbounded CHOOSE.\nMake sure that the expression is of form CHOOSE x \\in S: P(x).\n${describeRange(expression)}`,
1733
1996
  );
1734
1997
  };
1735
1998
  }
1736
1999
  const body = getEvaluator(expression.body, environment);
1737
2000
  const evaluateSet = getEvaluator(set, environment);
1738
2001
  return (context) => {
1739
- const base = evaluateSet(context);
1740
- if (!isSetValue(base) || isOverriddenSet(base)) {
1741
- throw new TlaEvaluationError(
1742
- `Attempted to compute the value of an expression of\nform CHOOSE x \\in S: P, but S was not enumerable.\n${describeRange(expression)}`,
1743
- );
1744
- }
1745
- const chosen = { value: undefined as Value | undefined };
1746
- const elements = getNormalizedElements(base, set, context.environment.runtime.version);
2002
+ const elements = getChoiceElements(
2003
+ evaluateSet(context),
2004
+ expression,
2005
+ set,
2006
+ context.environment.runtime.version,
2007
+ );
2008
+ let chosen: Value | undefined;
2009
+ const pattern = expression.pattern;
1747
2010
  someElement(elements, (element) => {
1748
- const scope = bindPattern(context.scope, expression.pattern, element);
1749
- if (!expectBoolean(body(withScope(context, scope)), "the body of CHOOSE")) return false;
1750
- chosen.value = getBoundValue(expression.pattern, scope);
2011
+ if (
2012
+ pattern.kind === "Tuple" &&
2013
+ getSequenceElements(element)?.length !== pattern.names.length
2014
+ ) {
2015
+ throw new TlaEvaluationError(
2016
+ `Attempted to compute the value of an expression of form\nCHOOSE <<x1, ... , xN>> \\in S: P, but S was not a set\nof N-tuples.\n${describeRange(expression)}`,
2017
+ );
2018
+ }
2019
+ const scope = bindPattern(context.scope, pattern, element);
2020
+ if (!expectBooleanBody(body(withScope(context, scope)), expression)) return false;
2021
+ chosen = getBoundValue(pattern, scope);
1751
2022
  return true;
1752
2023
  });
1753
- if (chosen.value === undefined) {
1754
- throw new TlaEvaluationError(
1755
- `Attempted to compute the value of an expression of form\nCHOOSE x \\in S: P, but no element of S satisfied P.\n${describeRange(expression)}`,
1756
- );
1757
- }
1758
- return chosen.value;
2024
+ if (chosen === undefined) throw createNoChoiceError(expression);
2025
+ return chosen;
1759
2026
  };
1760
2027
  };
1761
2028
 
1762
- // TLC orders a record's fields by name.
1763
2029
  export const getSortedFields = (fields: RecordField[]) =>
1764
2030
  [...fields].sort((left, right) => compareValues(left.name, right.name));
1765
2031
 
@@ -1853,26 +2119,10 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1853
2119
  }
1854
2120
  case "Prime": {
1855
2121
  const inner = getChildEvaluator(expression.expression);
1856
- return (context) => {
1857
- if (!context.next) throw createPrimeOutsideActionError(expression);
1858
- return inner({
1859
- environment: context.environment,
1860
- scope: context.scope,
1861
- state: context.next,
1862
- next: undefined,
1863
- isKeepLazy: context.isKeepLazy,
1864
- });
1865
- };
1866
- }
1867
- case "Unchanged": {
1868
- const primed = getChildEvaluator({
1869
- kind: "Prime",
1870
- expression: expression.expression,
1871
- location: expression.location,
1872
- });
1873
- const current = getChildEvaluator(expression.expression);
1874
- return (context) => valuesEqual(primed(context), current(context));
2122
+ return (context) => inner(toNextContext(context));
1875
2123
  }
2124
+ case "Unchanged":
2125
+ return compileUnchanged(getChildEvaluator(expression.expression));
1876
2126
  case "If": {
1877
2127
  const condition = getChildEvaluator(expression.condition);
1878
2128
  const consequent = getChildEvaluator(expression.consequent);
@@ -1916,8 +2166,15 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1916
2166
  return compileQuantifier(expression, environment);
1917
2167
  case "UnboundedQuantifier":
1918
2168
  return () => {
2169
+ const operator = expression.quantifier === "Forall" ? "\\A" : "\\E";
2170
+ if (expression.isTemporal) {
2171
+ throw createTemporalFormulaError(
2172
+ expression.quantifier === "Forall" ? "\\AA" : "\\EE",
2173
+ expression,
2174
+ );
2175
+ }
1919
2176
  throw new TlaEvaluationError(
1920
- `TLC cannot evaluate an unbounded quantifier at ${describeLocation(expression)}`,
2177
+ `TLC attempted to evaluate an unbounded ${operator}.\nMake sure that the expression is of form ${operator} x \\in S: P(x).\n${describeRange(expression)}`,
1921
2178
  );
1922
2179
  };
1923
2180
  case "Choose":
@@ -1993,16 +2250,18 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1993
2250
  case "BoxAction":
1994
2251
  case "AngleAction": {
1995
2252
  const action = getChildEvaluator(expression.action);
1996
- const unchanged = getChildEvaluator({
1997
- kind: "Unchanged",
1998
- expression: expression.subscript,
1999
- location: expression.location,
2000
- });
2253
+ const unchanged = compileUnchanged(getChildEvaluator(expression.subscript));
2001
2254
  const isBox = expression.kind === "BoxAction";
2002
- return (context) =>
2003
- isBox
2004
- ? expectBoolean(action(context), "an action") || unchanged(context)
2005
- : expectBoolean(action(context), "an action") && !unchanged(context);
2255
+ const form = isBox ? "[A]_e" : "<A>_e";
2256
+ return (context) => {
2257
+ const value = action(context);
2258
+ if (typeof value !== "boolean") {
2259
+ throw new TlaEvaluationError(
2260
+ `Attempted to evaluate an expression of form ${form}, but A was not a boolean.\n${describeRange(expression)}`,
2261
+ );
2262
+ }
2263
+ return isBox ? value || unchanged(context) : value && !unchanged(context);
2264
+ };
2006
2265
  }
2007
2266
  case "Enabled": {
2008
2267
  const action = expression.expression;
@@ -2021,9 +2280,7 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
2021
2280
  case "WeakFairness":
2022
2281
  case "StrongFairness":
2023
2282
  return () => {
2024
- throw new TlaEvaluationError(
2025
- `TLC cannot evaluate a temporal formula in a state at ${describeLocation(expression)}`,
2026
- );
2283
+ throw createTemporalFormulaError(TEMPORAL_FORMS[expression.kind], expression);
2027
2284
  };
2028
2285
  }
2029
2286
  };