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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (390) hide show
  1. package/README.md +7 -0
  2. package/dist/compile.cjs +3 -3
  3. package/dist/compile.js +3 -3
  4. package/dist/deciders.cjs +28 -28
  5. package/dist/deciders.js +52 -52
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +105 -10
  8. package/dist/index.d.ts +105 -10
  9. package/dist/index.js +1 -1
  10. package/dist/parallel-worker.cjs +1 -1
  11. package/dist/parallel-worker.js +1 -1
  12. package/dist/prove-worker.cjs +1 -1
  13. package/dist/prove-worker.js +1 -1
  14. package/dist/prove.cjs +116 -36
  15. package/dist/prove.js +116 -36
  16. package/dist/run.cjs +143 -31
  17. package/dist/run.js +143 -31
  18. package/dist/tlapm.cjs +1 -1
  19. package/dist/tlapm.js +2 -2
  20. package/dist/transfer.cjs +129 -104
  21. package/dist/transfer.js +129 -104
  22. package/dist/worker.cjs +7 -7
  23. package/dist/worker.js +7 -7
  24. package/package.json +1 -1
  25. package/src/ast.ts +4 -23
  26. package/src/bags.ts +99 -102
  27. package/src/builtins.ts +40 -78
  28. package/src/bundled-modules.ts +1 -8
  29. package/src/check.ts +564 -366
  30. package/src/cli/options.ts +10 -5
  31. package/src/cli/run.ts +0 -2
  32. package/src/cli/runtime-invariants.ts +136 -0
  33. package/src/cli/shared.ts +18 -11
  34. package/src/cli/tlapm.ts +0 -12
  35. package/src/cli/tlc-arguments.ts +640 -0
  36. package/src/cli/tlc-usage.ts +361 -0
  37. package/src/cli/tlc.ts +525 -216
  38. package/src/cli/typescript.ts +0 -3
  39. package/src/cli/xml-exporter.ts +4 -16
  40. package/src/cli.ts +0 -1
  41. package/src/codegen.ts +191 -64
  42. package/src/config.ts +140 -109
  43. package/src/coverage.ts +837 -0
  44. package/src/dependencies.ts +6 -40
  45. package/src/dfid.ts +618 -0
  46. package/src/environment.ts +237 -119
  47. package/src/errors.ts +56 -56
  48. package/src/evaluate.ts +543 -341
  49. package/src/exit-codes.ts +37 -3
  50. package/src/fingerprints.ts +10 -10
  51. package/src/index.ts +3 -0
  52. package/src/instances.ts +38 -31
  53. package/src/java-overrides.ts +4 -19
  54. package/src/json-reader.ts +455 -0
  55. package/src/json.ts +255 -139
  56. package/src/levels.ts +8 -17
  57. package/src/lexer.ts +80 -100
  58. package/src/liveness-checker.ts +77 -117
  59. package/src/liveness.ts +106 -62
  60. package/src/obligations/action.ts +4 -28
  61. package/src/obligations/anonymize.ts +84 -80
  62. package/src/obligations/equality.ts +1 -1
  63. package/src/obligations/expression.ts +2 -19
  64. package/src/obligations/format.ts +1 -9
  65. package/src/obligations/generate.ts +1 -11
  66. package/src/obligations/index.ts +0 -11
  67. package/src/obligations/levels.ts +4 -8
  68. package/src/obligations/module.ts +1 -15
  69. package/src/obligations/normalize.ts +5 -24
  70. package/src/obligations/operators.ts +1 -2
  71. package/src/obligations/pragma.ts +1 -10
  72. package/src/obligations/printer.ts +47 -46
  73. package/src/obligations/proof.ts +1 -5
  74. package/src/obligations/regroup.ts +1 -4
  75. package/src/obligations/simplify.ts +3 -14
  76. package/src/obligations/source.ts +1 -21
  77. package/src/obligations/subexpression.ts +5 -11
  78. package/src/obligations/substitution.ts +1 -3
  79. package/src/obligations/temporal.ts +8 -14
  80. package/src/obligations/tuples.ts +3 -9
  81. package/src/parallel-worker.ts +24 -33
  82. package/src/parallel.ts +48 -40
  83. package/src/parser.ts +565 -282
  84. package/src/pcal/ast.ts +53 -86
  85. package/src/pcal/parse.ts +144 -219
  86. package/src/pcal/tokenize.ts +91 -131
  87. package/src/pcal/translate.ts +83 -130
  88. package/src/pcal/validate.ts +48 -68
  89. package/src/pretty-print.ts +7 -8
  90. package/src/prover/decide-pool.ts +5 -10
  91. package/src/prover/deciders.ts +0 -4
  92. package/src/prover/first-order.ts +0 -11
  93. package/src/prover/isabelle/decide.ts +0 -6
  94. package/src/prover/isabelle/encode.ts +11 -23
  95. package/src/prover/isabelle/isar/inner-syntax.ts +108 -114
  96. package/src/prover/isabelle/isar/method.ts +25 -38
  97. package/src/prover/isabelle/isar/proof.ts +1 -10
  98. package/src/prover/isabelle/isar/statement.ts +1 -6
  99. package/src/prover/isabelle/isar/theory.ts +15 -26
  100. package/src/prover/isabelle/isar/type-check.ts +11 -25
  101. package/src/prover/isabelle/provers/blast/blast.ts +10 -41
  102. package/src/prover/isabelle/provers/blast/branch.ts +1 -32
  103. package/src/prover/isabelle/provers/blast/prove.ts +1 -35
  104. package/src/prover/isabelle/provers/blast/rules.ts +6 -44
  105. package/src/prover/isabelle/provers/blast/state.ts +2 -28
  106. package/src/prover/isabelle/provers/blast/term.ts +9 -36
  107. package/src/prover/isabelle/provers/clasimp.ts +1 -13
  108. package/src/prover/isabelle/provers/classical.ts +14 -42
  109. package/src/prover/isabelle/provers/hypsubst.ts +11 -25
  110. package/src/prover/isabelle/pure/bicompose.ts +16 -13
  111. package/src/prover/isabelle/pure/consts.ts +1 -7
  112. package/src/prover/isabelle/pure/conv.ts +1 -9
  113. package/src/prover/isabelle/pure/drule.ts +24 -40
  114. package/src/prover/isabelle/pure/envir.ts +3 -52
  115. package/src/prover/isabelle/pure/goal.ts +1 -7
  116. package/src/prover/isabelle/pure/interrupt.ts +0 -5
  117. package/src/prover/isabelle/pure/list.ts +0 -3
  118. package/src/prover/isabelle/pure/logic.ts +1 -14
  119. package/src/prover/isabelle/pure/name.ts +2 -9
  120. package/src/prover/isabelle/pure/net.ts +3 -59
  121. package/src/prover/isabelle/pure/object-logic.ts +3 -10
  122. package/src/prover/isabelle/pure/pattern.ts +2 -19
  123. package/src/prover/isabelle/pure/raw-simplifier.ts +13 -49
  124. package/src/prover/isabelle/pure/rewriter.ts +26 -58
  125. package/src/prover/isabelle/pure/search.ts +3 -10
  126. package/src/prover/isabelle/pure/seq.ts +1 -10
  127. package/src/prover/isabelle/pure/simplifier.ts +4 -12
  128. package/src/prover/isabelle/pure/table.ts +1 -31
  129. package/src/prover/isabelle/pure/tactic.ts +12 -22
  130. package/src/prover/isabelle/pure/tactical.ts +6 -12
  131. package/src/prover/isabelle/pure/term-ord.ts +2 -6
  132. package/src/prover/isabelle/pure/term.ts +2 -43
  133. package/src/prover/isabelle/pure/thm.ts +13 -36
  134. package/src/prover/isabelle/pure/type.ts +2 -15
  135. package/src/prover/isabelle/pure/unify.ts +20 -30
  136. package/src/prover/isabelle/pure/variable.ts +3 -7
  137. package/src/prover/isabelle/tla/classical-setup.ts +9 -19
  138. package/src/prover/isabelle/tla/context.ts +8 -16
  139. package/src/prover/isabelle/tla/logic.ts +4 -11
  140. package/src/prover/isabelle/tla/simpdata.ts +46 -34
  141. package/src/prover/isabelle/tools/intuitionistic.ts +1 -10
  142. package/src/prover/ocaml.ts +0 -6
  143. package/src/prover/prep/action.ts +4 -36
  144. package/src/prover/prep/enabled-axioms.ts +12 -19
  145. package/src/prover/prep/fingerprint.ts +0 -16
  146. package/src/prover/prep/level-comparison.ts +8 -12
  147. package/src/prover/prep/md5.ts +0 -2
  148. package/src/prover/prep/methods.ts +9 -36
  149. package/src/prover/prep/normalize.ts +4 -28
  150. package/src/prover/prove-worker.ts +0 -2
  151. package/src/prover/prove.ts +0 -36
  152. package/src/prover/ptl/decide.ts +7 -12
  153. package/src/prover/ptl/encode.ts +14 -36
  154. package/src/prover/ptl/sat.ts +24 -32
  155. package/src/prover/ptl/tableau.ts +12 -26
  156. package/src/prover/smt/axioms.ts +0 -7
  157. package/src/prover/smt/context.ts +19 -26
  158. package/src/prover/smt/data.ts +51 -54
  159. package/src/prover/smt/encode.ts +14 -35
  160. package/src/prover/smt/extensionality.ts +0 -10
  161. package/src/prover/smt/flatten.ts +3 -22
  162. package/src/prover/smt/format.ts +5 -10
  163. package/src/prover/smt/instances.ts +0 -10
  164. package/src/prover/smt/rewrite.ts +66 -101
  165. package/src/prover/smt/solver/act-cache.ts +0 -15
  166. package/src/prover/smt/solver/arith-rewriter.ts +3 -48
  167. package/src/prover/smt/solver/array.ts +1 -3
  168. package/src/prover/smt/solver/asserted-formulas.ts +1 -43
  169. package/src/prover/smt/solver/ast-lt.ts +1 -11
  170. package/src/prover/smt/solver/ast-util.ts +1 -6
  171. package/src/prover/smt/solver/ast.ts +1 -143
  172. package/src/prover/smt/solver/auf-solver.ts +6 -39
  173. package/src/prover/smt/solver/case-split-queue.ts +1 -9
  174. package/src/prover/smt/solver/cg-table.ts +1 -18
  175. package/src/prover/smt/solver/clause.ts +1 -27
  176. package/src/prover/smt/solver/conflict-resolution.ts +0 -9
  177. package/src/prover/smt/solver/context.ts +4 -61
  178. package/src/prover/smt/solver/ctx-simplify.ts +14 -41
  179. package/src/prover/smt/solver/der.ts +2 -21
  180. package/src/prover/smt/solver/dyn-ack.ts +1 -11
  181. package/src/prover/smt/solver/e-matching.ts +3 -34
  182. package/src/prover/smt/solver/enode.ts +1 -21
  183. package/src/prover/smt/solver/expr-ref.ts +1 -5
  184. package/src/prover/smt/solver/expr-safe-replace.ts +0 -5
  185. package/src/prover/smt/solver/fingerprints.ts +1 -12
  186. package/src/prover/smt/solver/flat-literals.ts +1 -9
  187. package/src/prover/smt/solver/goal.ts +2 -14
  188. package/src/prover/smt/solver/hash.ts +0 -8
  189. package/src/prover/smt/solver/hashtable.ts +1 -12
  190. package/src/prover/smt/solver/internalizer.ts +6 -98
  191. package/src/prover/smt/solver/lbool.ts +1 -2
  192. package/src/prover/smt/solver/literal.ts +0 -3
  193. package/src/prover/smt/solver/lp/bound-propagator.ts +8 -26
  194. package/src/prover/smt/solver/lp/constraints.ts +2 -8
  195. package/src/prover/smt/solver/lp/containers.ts +12 -30
  196. package/src/prover/smt/solver/lp/core-solver.ts +10 -31
  197. package/src/prover/smt/solver/lp/cross-nested.ts +6 -20
  198. package/src/prover/smt/solver/lp/dep-intervals.ts +7 -22
  199. package/src/prover/smt/solver/lp/dependency.ts +1 -4
  200. package/src/prover/smt/solver/lp/dioph-eq.ts +12 -98
  201. package/src/prover/smt/solver/lp/explanation.ts +1 -6
  202. package/src/prover/smt/solver/lp/gomory.ts +9 -22
  203. package/src/prover/smt/solver/lp/hnf-cutter.ts +17 -23
  204. package/src/prover/smt/solver/lp/hnf.ts +11 -26
  205. package/src/prover/smt/solver/lp/int-cube.ts +15 -36
  206. package/src/prover/smt/solver/lp/int-solver.ts +4 -34
  207. package/src/prover/smt/solver/lp/lar-solver.ts +32 -81
  208. package/src/prover/smt/solver/lp/lar-term.ts +1 -5
  209. package/src/prover/smt/solver/lp/lp-settings.ts +1 -14
  210. package/src/prover/smt/solver/lp/maximize-term.ts +20 -45
  211. package/src/prover/smt/solver/lp/nex-creator.ts +5 -28
  212. package/src/prover/smt/solver/lp/nex.ts +1 -6
  213. package/src/prover/smt/solver/lp/nla-backoff.ts +1 -4
  214. package/src/prover/smt/solver/lp/nla-basics.ts +5 -30
  215. package/src/prover/smt/solver/lp/nla-core.ts +35 -130
  216. package/src/prover/smt/solver/lp/nla-divisions.ts +32 -42
  217. package/src/prover/smt/solver/lp/nla-emonics.ts +4 -21
  218. package/src/prover/smt/solver/lp/nla-factorization.ts +1 -4
  219. package/src/prover/smt/solver/lp/nla-grobner.ts +15 -69
  220. package/src/prover/smt/solver/lp/nla-horner.ts +3 -11
  221. package/src/prover/smt/solver/lp/nla-intervals.ts +2 -12
  222. package/src/prover/smt/solver/lp/nla-monomial-bounds.ts +16 -41
  223. package/src/prover/smt/solver/lp/nla-monotone.ts +2 -6
  224. package/src/prover/smt/solver/lp/nla-order.ts +2 -13
  225. package/src/prover/smt/solver/lp/nla-patcher.ts +4 -7
  226. package/src/prover/smt/solver/lp/nla-tangents.ts +1 -9
  227. package/src/prover/smt/solver/lp/nla-throttle.ts +1 -6
  228. package/src/prover/smt/solver/lp/nla-types.ts +1 -11
  229. package/src/prover/smt/solver/lp/nla-var-eqs.ts +4 -25
  230. package/src/prover/smt/solver/lp/nra-solver.ts +5 -52
  231. package/src/prover/smt/solver/lp/numeric-pair.ts +1 -4
  232. package/src/prover/smt/solver/lp/pdd-interval.ts +1 -3
  233. package/src/prover/smt/solver/lp/pdd-simplifier.ts +2 -14
  234. package/src/prover/smt/solver/lp/pdd-solver.ts +4 -33
  235. package/src/prover/smt/solver/lp/pdd.ts +7 -70
  236. package/src/prover/smt/solver/lp/random-updater.ts +1 -8
  237. package/src/prover/smt/solver/lp/static-matrix.ts +9 -19
  238. package/src/prover/smt/solver/lp/union-find.ts +1 -6
  239. package/src/prover/smt/solver/mam-compiler.ts +14 -56
  240. package/src/prover/smt/solver/mam-interpreter.ts +1 -21
  241. package/src/prover/smt/solver/maximize-ac-sharing.ts +2 -17
  242. package/src/prover/smt/solver/model-checker.ts +2 -36
  243. package/src/prover/smt/solver/model-evaluator.ts +3 -29
  244. package/src/prover/smt/solver/model-finder.ts +3 -15
  245. package/src/prover/smt/solver/model-generator.ts +1 -12
  246. package/src/prover/smt/solver/model-macro-solver.ts +12 -69
  247. package/src/prover/smt/solver/nlsat/algebraic.ts +55 -151
  248. package/src/prover/smt/solver/nlsat/atoms.ts +5 -19
  249. package/src/prover/smt/solver/nlsat/evaluator.ts +17 -22
  250. package/src/prover/smt/solver/nlsat/explain.ts +3 -47
  251. package/src/prover/smt/solver/nlsat/interval-set.ts +9 -50
  252. package/src/prover/smt/solver/nlsat/levelwise.ts +48 -129
  253. package/src/prover/smt/solver/nlsat/mpbq.ts +3 -14
  254. package/src/prover/smt/solver/nlsat/polynomial.ts +17 -156
  255. package/src/prover/smt/solver/nlsat/solver.ts +7 -67
  256. package/src/prover/smt/solver/nlsat/types.ts +1 -8
  257. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +1 -44
  258. package/src/prover/smt/solver/nlsat/upolynomial.ts +11 -92
  259. package/src/prover/smt/solver/nnf.ts +3 -38
  260. package/src/prover/smt/solver/pattern-inference.ts +2 -15
  261. package/src/prover/smt/solver/poly-rewriter.ts +3 -23
  262. package/src/prover/smt/solver/propagate-values.ts +1 -10
  263. package/src/prover/smt/solver/proto-model.ts +3 -48
  264. package/src/prover/smt/solver/pull-quant.ts +1 -12
  265. package/src/prover/smt/solver/qe-lite-der.ts +1 -29
  266. package/src/prover/smt/solver/qe-lite-fm.ts +2 -25
  267. package/src/prover/smt/solver/qe-lite.ts +3 -33
  268. package/src/prover/smt/solver/qi-queue.ts +1 -16
  269. package/src/prover/smt/solver/quant-tactics.ts +5 -22
  270. package/src/prover/smt/solver/quantifier-analyzer.ts +17 -37
  271. package/src/prover/smt/solver/quantifier-manager.ts +1 -8
  272. package/src/prover/smt/solver/random-gen.ts +1 -2
  273. package/src/prover/smt/solver/rational.ts +1 -8
  274. package/src/prover/smt/solver/ref-vector.ts +1 -6
  275. package/src/prover/smt/solver/relevancy.ts +2 -15
  276. package/src/prover/smt/solver/rewriter-tpl.ts +3 -147
  277. package/src/prover/smt/solver/rewriter.ts +3 -85
  278. package/src/prover/smt/solver/rlimit.ts +2 -20
  279. package/src/prover/smt/solver/smtlib-parser.ts +2 -37
  280. package/src/prover/smt/solver/solver.ts +1 -16
  281. package/src/prover/smt/solver/sort.ts +1 -5
  282. package/src/prover/smt/solver/sticky-generations.ts +0 -5
  283. package/src/prover/smt/solver/theory-lra-axioms.ts +3 -24
  284. package/src/prover/smt/solver/theory-lra-bounds.ts +0 -5
  285. package/src/prover/smt/solver/theory-lra-final-check.ts +4 -22
  286. package/src/prover/smt/solver/theory-lra-internalize.ts +1 -27
  287. package/src/prover/smt/solver/theory-lra-model.ts +4 -19
  288. package/src/prover/smt/solver/theory-lra-propagate.ts +1 -15
  289. package/src/prover/smt/solver/theory-lra-state.ts +3 -8
  290. package/src/prover/smt/solver/theory-lra.ts +1 -8
  291. package/src/prover/smt/solver/var-subst.ts +2 -26
  292. package/src/prover/smt/table.ts +0 -8
  293. package/src/prover/tlapm/cache.ts +20 -25
  294. package/src/prover/tlapm/ocaml-marshal.ts +19 -21
  295. package/src/prover/tlapm/tlapm.ts +12 -17
  296. package/src/prover/verdict.ts +0 -2
  297. package/src/prover/zenon/check/check.ts +0 -9
  298. package/src/prover/zenon/check/definitions.ts +5 -15
  299. package/src/prover/zenon/check/equality.ts +0 -8
  300. package/src/prover/zenon/check/functions.ts +0 -4
  301. package/src/prover/zenon/check/keys.ts +0 -7
  302. package/src/prover/zenon/check/propositional.ts +0 -3
  303. package/src/prover/zenon/check/records.ts +0 -5
  304. package/src/prover/zenon/check/relations.ts +0 -13
  305. package/src/prover/zenon/check/rewrites.ts +0 -6
  306. package/src/prover/zenon/check/sets.ts +0 -3
  307. package/src/prover/zenon/check/terms.ts +0 -17
  308. package/src/prover/zenon/check/tla.ts +0 -6
  309. package/src/prover/zenon/decide.ts +0 -12
  310. package/src/prover/zenon/encode.ts +1 -8
  311. package/src/prover/zenon/eqrel.ts +0 -13
  312. package/src/prover/zenon/equality-rules.ts +0 -4
  313. package/src/prover/zenon/expr.ts +1 -26
  314. package/src/prover/zenon/index-table.ts +17 -38
  315. package/src/prover/zenon/isar-case.ts +9 -19
  316. package/src/prover/zenon/isar.ts +1 -29
  317. package/src/prover/zenon/limits.ts +0 -4
  318. package/src/prover/zenon/llproof.ts +0 -9
  319. package/src/prover/zenon/mltoll.ts +54 -76
  320. package/src/prover/zenon/node.ts +1 -11
  321. package/src/prover/zenon/ocaml.ts +1 -17
  322. package/src/prover/zenon/parse.ts +2 -7
  323. package/src/prover/zenon/phrase.ts +1 -11
  324. package/src/prover/zenon/proof.ts +0 -9
  325. package/src/prover/zenon/propositional-rules.ts +0 -5
  326. package/src/prover/zenon/rules.ts +2 -6
  327. package/src/prover/zenon/search.ts +1 -17
  328. package/src/prover/zenon/tla/functions.ts +57 -29
  329. package/src/prover/zenon/tla/llproof.ts +63 -70
  330. package/src/prover/zenon/tla/records.ts +56 -27
  331. package/src/prover/zenon/tla/rewrites.ts +12 -19
  332. package/src/prover/zenon/tla/sets.ts +68 -39
  333. package/src/prover/zenon/tla/terms.ts +0 -6
  334. package/src/prover/zenon/tla/tla.ts +59 -58
  335. package/src/randomization.ts +81 -35
  336. package/src/resolve.ts +12 -112
  337. package/src/runtime.ts +22 -22
  338. package/src/sany/builtins.ts +2 -5
  339. package/src/sany/generator.ts +149 -252
  340. package/src/sany/levels.ts +6 -34
  341. package/src/sany/lexer.ts +41 -61
  342. package/src/sany/linter.ts +1 -9
  343. package/src/sany/modules.ts +1 -5
  344. package/src/sany/nodes.ts +0 -31
  345. package/src/sany/parse-error.ts +39 -117
  346. package/src/sany/report.ts +29 -63
  347. package/src/sany/selectors.ts +15 -39
  348. package/src/sany/source.ts +1 -17
  349. package/src/sany/xml.ts +13 -63
  350. package/src/search.ts +495 -155
  351. package/src/simulate.ts +685 -0
  352. package/src/spec-description.ts +176 -69
  353. package/src/standard-definitions.ts +0 -4
  354. package/src/standard-modules.ts +254 -69
  355. package/src/state-graph.ts +50 -24
  356. package/src/subexpressions.ts +69 -52
  357. package/src/substitution-levels.ts +2 -3
  358. package/src/successors.ts +260 -91
  359. package/src/symmetry.ts +33 -25
  360. package/src/tableau.ts +27 -24
  361. package/src/tlc/fingerprint.ts +183 -67
  362. package/src/tlc/jar-data.ts +112 -6
  363. package/src/tlc/messages.ts +110 -44
  364. package/src/tlc/order.ts +37 -60
  365. package/src/tlc/random.ts +33 -45
  366. package/src/tlc/replay.ts +549 -217
  367. package/src/tlc/summary.ts +36 -47
  368. package/src/tlc/tlc-operators.ts +76 -41
  369. package/src/tlc/tlcext-operators.ts +139 -122
  370. package/src/tlc/trace-spec.ts +269 -0
  371. package/src/tlc/value-stream.ts +139 -0
  372. package/src/tlc/version.ts +1 -4
  373. package/src/transfer.ts +22 -25
  374. package/src/typescript/actions.ts +8 -21
  375. package/src/typescript/collections.ts +0 -15
  376. package/src/typescript/compile.ts +0 -5
  377. package/src/typescript/context.ts +0 -12
  378. package/src/typescript/emit.ts +0 -1
  379. package/src/typescript/expressions.ts +0 -12
  380. package/src/typescript/formula.ts +4 -12
  381. package/src/typescript/functions.ts +6 -17
  382. package/src/typescript/model.ts +10 -11
  383. package/src/typescript/names.ts +0 -2
  384. package/src/typescript/program.ts +0 -3
  385. package/src/typescript/properties.ts +6 -8
  386. package/src/typescript/scope.ts +0 -5
  387. package/src/typescript/steps.ts +0 -10
  388. package/src/typescript/types.ts +1 -8
  389. package/src/values.ts +749 -330
  390. package/src/worker.ts +7 -8
package/src/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,14 +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;
122
- // Whether the thunk dropped its scope after caching a value that holds in every state.
123
129
  isReleased?: boolean;
124
130
  }
125
131
 
126
- 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 };
127
136
 
128
137
  export interface Scope {
129
138
  name: string;
@@ -137,55 +146,36 @@ export interface Environment {
137
146
  builtins: Map<string, Builtin>;
138
147
  constants: Map<string, Value>;
139
148
  substitutions: Map<string, string>;
140
- // The name SANY gives each definition that a named instance such as `M == INSTANCE Module`
141
- // copies, such as M!Op, by the key of the copy.
142
149
  instanceNames: Map<string, string>;
143
150
  variables: string[];
144
151
  variableIndex: Map<string, number>;
145
152
  facts: DefinitionFacts;
146
- // The value of each constant definition TLC computed when it started, by the definition's id in
147
- // facts. TLC evaluates a definition it failed to compute where the spec uses it.
148
153
  startupValues: (Value | undefined)[];
149
- // The definitions an INSTANCE copies from a module that declares constants or variables. SANY
150
- // wraps the body of each in its substitutions.
151
154
  substitutedDefinitions: Set<Definition>;
152
- // The compiled code of each expression, of each expression evaluated as a whole, which generated
153
- // code can serve, and of each reference to a definition.
155
+ instanceParams: Set<OperatorParam>;
154
156
  evaluators: WeakMap<Expression, Evaluator>;
155
157
  entryEvaluators: WeakMap<Expression, Evaluator>;
156
158
  definitionEvaluators: WeakMap<Definition, Evaluator>;
157
- // The expressions being evaluated, outermost first, when the environment replays an error to
158
- // find where it occurred, as TLC's CallStackTool does.
159
159
  callStack?: CallStack;
160
+ coverage?: Coverage;
160
161
  }
161
162
 
162
163
  export interface CallStack {
163
164
  expressions: Expression[];
164
- // TLC stops popping the stack once an evaluation fails, so it keeps where the failure occurred.
165
165
  isFrozen: boolean;
166
- // The expression that built each value of the replay that TLC's CallStackTool gives a source.
167
166
  sources: WeakMap<ObjectValue, Expression>;
168
- // The value each expression of the replay last evaluated to.
169
167
  values: WeakMap<Expression, Value>;
170
- // The expression each failure last left, which tells a failure of an operand from one of the
171
- // method that computes the operator.
172
168
  failures: WeakMap<Error, Expression>;
173
- // The failure of a value with a source, which TLC raises as a FingerprintException.
174
169
  fingerprint?: FingerprintFailure;
175
170
  }
176
171
 
177
172
  export interface FingerprintFailure {
178
- // The sources of the values whose methods failed, outermost first.
179
173
  sources: Expression[];
180
- // The message of the error the innermost one raised.
181
174
  reason: string;
182
175
  }
183
176
 
184
- // The operators of Tool#evalAppl whose value TLC's CallStackTool gives a source.
185
177
  const SOURCED_OPERATORS = new Set(["SUBSET", "UNION", "DOMAIN", "\\cup", "\\cap", "\\"]);
186
178
 
187
- // CallStackTool copies the SetPredValue, FcnLambdaValue and OpLambdaValue that an evaluation
188
- // returns without their source, and a function TLC builds from a FcnLambdaValue has none.
189
179
  const SOURCED_KINDS = new Set<Expression["kind"]>([
190
180
  "SetEnumeration",
191
181
  "SetFilter",
@@ -201,8 +191,6 @@ const isSourced = (expression: Expression) =>
201
191
  SOURCED_KINDS.has(expression.kind) ||
202
192
  (expression.kind === "Apply" && SOURCED_OPERATORS.has(expression.operator));
203
193
 
204
- // The argument whose method Tool#evalAppl calls to compute an operator, as with S.member(e) for
205
- // 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.
206
194
  const getReceiver = (expression: Expression, values: CallStack["values"]) => {
207
195
  if (expression.kind === "FunctionApplication" || expression.kind === "Except") {
208
196
  return expression.function;
@@ -223,8 +211,6 @@ export interface Context {
223
211
  scope: Scope | undefined;
224
212
  state: State | undefined;
225
213
  next: State | undefined;
226
- // EvalControl.KeepLazy, which Tool#evalAppl sets to evaluate the function it applies and which
227
- // the evaluation passes on, so that a function constructor within builds a FcnLambdaValue.
228
214
  isKeepLazy?: boolean;
229
215
  }
230
216
 
@@ -248,15 +234,23 @@ const EXCEPT_AT = "@";
248
234
  export const describeLocation = (expression: Expression) =>
249
235
  `line ${expression.location.line}, column ${expression.location.column}`;
250
236
 
251
- export const formatRange = (range: SourceRange) =>
252
- `line ${range.start.line}, col ${range.start.column} to line ${range.end.line}, col ${range.end.column} of module ${range.module}`;
253
-
254
237
  export const describeRange = (expression: Expression) => {
255
238
  const range = expression.location.range;
256
239
  return range ? formatRange(range) : describeLocation(expression);
257
240
  };
258
241
 
259
- // 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
+
260
254
  export const describeNode = (expression: Expression) =>
261
255
  expression.kind === "Number"
262
256
  ? (expression.text ?? String(expression.value))
@@ -267,8 +261,6 @@ export const createConditionError = (expression: Expression, value: Value) =>
267
261
  `A non-boolean expression (${getKindString(value)}) was used as the condition of an IF.\n${describeRange(expression)}`,
268
262
  );
269
263
 
270
- // TLC parses an infix chain of /\ or \/ as nested binary junctions and a bulleted list as one
271
- // junction list, and it words the error differently for each.
272
264
  export const createJunctionError = (
273
265
  expression: Expression & { kind: "And" | "Or" },
274
266
  index: number,
@@ -289,12 +281,10 @@ export const createJunctionError = (
289
281
  );
290
282
  };
291
283
 
292
- // TLC selects a field of a record, and of another function from the function it converts it to,
293
- // which for a tuple keeps its domain as an interval.
294
284
  export const getFieldSelector = (expression: Expression & { kind: "FieldAccess" }) => {
295
285
  const field = expression.field;
296
286
  const describeMissing = (record: Value) =>
297
- `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)}`;
298
288
  const describeNotInDomain = (functionValue: Value) =>
299
289
  `Attempted to apply function:\n${prettyPrint(formatValue(functionValue))}\nto argument "${field}", which is not in the domain of the function.`;
300
290
  return (value: Value) => {
@@ -305,17 +295,14 @@ export const getFieldSelector = (expression: Expression & { kind: "FieldAccess"
305
295
  }
306
296
  const functionClass = getFunctionClass(value);
307
297
  if (functionClass === "tuple") throw createNonIntegerKeyError(field);
308
- // Only TLC's RecordValue names the field it lacks. Any other function, such as a FcnRcdValue
309
- // whose keys are strings, reports an argument outside its domain.
310
298
  return applyFunction(
311
- value,
299
+ value.kind === "LazyFunction" ? toFiniteFunction(value) : value,
312
300
  field,
313
301
  functionClass === "record" ? describeMissing : describeNotInDomain,
314
302
  );
315
303
  };
316
304
  };
317
305
 
318
- // TLC 1.7.4 words what a tuple or a record lacks differently.
319
306
  export const getMissingArgumentDescriber = (version: TlcVersion | undefined) =>
320
307
  version === "1.7.4"
321
308
  ? (functionValue: Value, argument: Value) =>
@@ -338,35 +325,31 @@ export const getSubsetOperator =
338
325
  `Attempted to evaluate an expression of form S \\subseteq T, but S was not enumerable.\n${describeRange(expression)}`,
339
326
  );
340
327
  }
341
- return builtin.evaluate([left, right]);
328
+ return builtin.evaluateBinary
329
+ ? builtin.evaluateBinary(left, right)
330
+ : builtin.evaluate([left, right]);
342
331
  };
343
332
 
344
- // TLC rejects a decimal, or an integer literal too big for it, while it processes the spec.
345
333
  export const createRealNumberError = (expression: DecimalExpression) =>
346
334
  setExitCode(
347
- new TlaEvaluationError(
348
- `TLC can't handle real numbers: ${expression.text} at ${describeLocation(expression)}`,
349
- ),
335
+ new TlaEvaluationError(`TLC can't handle real numbers.\n${expression.text}`),
350
336
  EXIT_STATUS.configParseError,
351
337
  );
352
338
 
353
339
  export const createBigNumberError = (expression: NumberExpression) =>
354
340
  setExitCode(
355
341
  new TlaEvaluationError(
356
- `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}`,
357
343
  ),
358
344
  EXIT_STATUS.error,
359
345
  );
360
346
 
361
- // TLC's Tool#evalAppl fails to look up a variable the state doesn't assign.
362
347
  export const createUnassignedError = (name: string, expression: Expression) =>
363
348
  new TlaUnassignedError(
364
349
  `In evaluation, the identifier ${name} is either undefined or not an operator.\n${describeRange(expression)}`,
365
350
  name,
366
351
  );
367
352
 
368
- // TLC's Tool#enabled reads the subscript of <<A>>_v in the successor as a state of its own, and
369
- // names the fairness condition when A leaves a variable of v unassigned, unlike TLC 1.7.4's.
370
353
  export const toUnspecifiedSubscriptError = (error: unknown, version: TlcVersion | undefined) =>
371
354
  error instanceof TlaUnassignedError && version !== "1.7.4"
372
355
  ? new TlaEvaluationError(
@@ -374,11 +357,6 @@ export const toUnspecifiedSubscriptError = (error: unknown, version: TlcVersion
374
357
  )
375
358
  : error;
376
359
 
377
- export const createPrimeOutsideActionError = (expression: Expression) =>
378
- new TlaEvaluationError(
379
- `A primed expression appears outside an action at ${describeLocation(expression)}`,
380
- );
381
-
382
360
  export const lookupScope = (scope: Scope | undefined, name: string): Binding | undefined => {
383
361
  for (let current = scope; current; current = current.parent) {
384
362
  if (current.name === name) return current.binding;
@@ -392,12 +370,13 @@ export const bindValue = (scope: Scope | undefined, name: string, value: Value):
392
370
  parent: scope,
393
371
  });
394
372
 
395
- const bindPattern = (scope: Scope | undefined, pattern: BoundPattern, value: Value) => {
373
+ export const bindPattern = (scope: Scope | undefined, pattern: BoundPattern, value: Value) => {
396
374
  if (pattern.kind === "Name") return bindValue(scope, pattern.name, value);
397
375
  const elements = getSequenceElements(value);
398
376
  if (!elements || elements.length !== pattern.names.length) {
377
+ const range = pattern.ranges?.[0];
399
378
  throw new TlaEvaluationError(
400
- `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) : ""}`,
401
380
  );
402
381
  }
403
382
  return pattern.names.reduce<Scope | undefined>(
@@ -406,7 +385,6 @@ const bindPattern = (scope: Scope | undefined, pattern: BoundPattern, value: Val
406
385
  );
407
386
  };
408
387
 
409
- // Tool#evalAppl checks that it applies a function before it evaluates the argument.
410
388
  export const expectFunction = (value: Value, application: Expression) => {
411
389
  if (isFunctionValue(value)) return value;
412
390
  throw new TlaEvaluationError(
@@ -442,6 +420,42 @@ export const expectBoolean = (value: Value, description: string) => {
442
420
  return value;
443
421
  };
444
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
+
445
459
  export const getDefinition = (name: string, environment: Environment) =>
446
460
  environment.definitions.get(environment.substitutions.get(name) ?? name);
447
461
 
@@ -461,12 +475,9 @@ const getBoundExplanation = (set: Value, text: string) => {
461
475
  return undefined;
462
476
  };
463
477
 
464
- // TLC enumerates every set except the ones it implements in Java, so any other set fails as its own
465
- // class does.
466
478
  const checkEnumerable = (set: Value, expression: Expression, version: TlcVersion) => {
467
479
  if (!isSetValue(set) || isOverriddenSet(set)) {
468
480
  const text = formatValue(set);
469
- // TLC 1.7.4 doesn't explain why it can't enumerate a set.
470
481
  const explanation = version === "1.7.4" ? undefined : getBoundExplanation(set, text);
471
482
  throw new TlaEvaluationError(
472
483
  explanation === undefined
@@ -482,16 +493,12 @@ const getEnumeratedElements = (set: Value, expression: Expression, version: TlcV
482
493
  return getLazySubsets(set) ?? getNormalizedSetElements(set);
483
494
  };
484
495
 
485
- // The elements Tool.contexts binds to the bound of a quantifier or a set map. TLC 1.7.4 streams a
486
- // lazy set's elements, where later versions normalize the set first.
487
496
  export const getContextElements = (set: Value, expression: Expression, version: TlcVersion) => {
488
497
  if (version !== "1.7.4") return getEnumeratedElements(set, expression, version);
489
498
  checkEnumerable(set, expression, version);
490
499
  return getLazySubsets(set) ?? getStreamedElements(set);
491
500
  };
492
501
 
493
- // Like TLC, a quantifier keeps an interval as an interval, so that it can stop at the first witness
494
- // in a large interval such as 1..2000000000 without listing it.
495
502
  const getKeptInterval = (set: Value) => {
496
503
  if (typeof set !== "object" || set.kind !== "Interval") return undefined;
497
504
  getCardinality(set);
@@ -501,7 +508,6 @@ const getKeptInterval = (set: Value) => {
501
508
  export const getQuantifierElements = (set: Value, expression: Expression, version: TlcVersion) =>
502
509
  getKeptInterval(set) ?? getContextElements(set, expression, version);
503
510
 
504
- // CHOOSE and a function constructor visit the elements of the normalized set.
505
511
  const getNormalizedElements = (set: Value, expression: Expression, version: TlcVersion) =>
506
512
  getKeptInterval(set) ?? getEnumeratedElements(set, expression, version);
507
513
 
@@ -516,16 +522,19 @@ const someElement = (
516
522
  return false;
517
523
  };
518
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
+
519
533
  export const getBoundElements = (bounds: Bound[], context: Context) =>
520
- bounds.map((bound) =>
521
- getQuantifierElements(
522
- evaluate(bound.set, context),
523
- bound.set,
524
- context.environment.runtime.version,
525
- ),
534
+ mapBoundSets(bounds, (set) =>
535
+ getQuantifierElements(evaluate(set, context), set, context.environment.runtime.version),
526
536
  );
527
537
 
528
- // Visits each binding of the bounds to the elements of their sets, until visit returns true.
529
538
  export const forEachBoundElement = (
530
539
  bounds: Bound[],
531
540
  sets: ReturnType<typeof getBoundElements>,
@@ -548,7 +557,7 @@ export const forEachBinding = (
548
557
  ) => forEachBoundElement(bounds, getBoundElements(bounds, context), context.scope, visit);
549
558
 
550
559
  const getBoundsDomain = (bounds: Bound[], context: Context): Value => {
551
- const sets = bounds.map((bound) => evaluate(bound.set, context));
560
+ const sets = mapBoundSets(bounds, (set) => evaluate(set, context));
552
561
  return sets.length === 1 ? sets[0] : { kind: "ProductSet", factors: sets };
553
562
  };
554
563
 
@@ -561,8 +570,6 @@ const bindArgument = (bounds: Bound[], scope: Scope | undefined, argument: Value
561
570
  );
562
571
  };
563
572
 
564
- // The parameters, body and scope of each function a constructor or a definition keeps lazy, whose
565
- // body TLC's getInitStates and getNextStates walk for an argument, as they do a FcnLambdaValue's.
566
573
  interface LazyFunction {
567
574
  value: LazyFunctionValue;
568
575
  bounds: Bound[];
@@ -570,8 +577,7 @@ interface LazyFunction {
570
577
  scope: Scope | undefined;
571
578
  }
572
579
 
573
- // The function keeps its parameters, body and scope itself, since a WeakMap entry for each
574
- // 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.
575
581
  interface KeptLazyFunctionValue extends LazyFunctionValue {
576
582
  lambda: LazyFunction;
577
583
  }
@@ -584,8 +590,6 @@ const keepLambda = (lambda: LazyFunction) => Object.assign(lambda.value, { lambd
584
590
  export const getLazyFunction = (value: Value) =>
585
591
  isKeptLazyFunction(value) ? value.lambda : undefined;
586
592
 
587
- // Tool.getFcnContext: the scope of a lazy function's body for the arguments of an application. It
588
- // ignores arguments beyond the parameters.
589
593
  export const bindLazyArguments = (
590
594
  lambda: LazyFunction,
591
595
  expression: Expression & { kind: "FunctionApplication" },
@@ -610,12 +614,14 @@ export const bindLazyArguments = (
610
614
  typeof value.domain === "object" && value.domain.kind === "ProductSet"
611
615
  ? value.domain.factors
612
616
  : [];
613
- if (elements === undefined || elements.length < bounds.length) {
614
- throw new TlaEvaluationError(
615
- `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`,
616
621
  );
617
- }
622
+ if (elements === undefined) throw createListError();
618
623
  bounds.forEach((bound, index) => {
624
+ if (index >= elements.length) throw createListError();
619
625
  const element = elements[index];
620
626
  const ordinal = `argument number ${index + 1}`;
621
627
  if (!isElementOf(element, domains[index])) {
@@ -636,11 +642,10 @@ export const bindLazyArguments = (
636
642
  );
637
643
  }
638
644
  });
639
- 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);
640
647
  };
641
648
 
642
- // TLC prints a function it can't enumerate as its parameters and the location of its body. It
643
- // prints only the first name of a group such as `m, n \in S`.
644
649
  interface LazyFunctionTemplate {
645
650
  parameters: { index: number; name: string }[];
646
651
  body: string;
@@ -686,22 +691,29 @@ const getLazyFunctionSource = (
686
691
  };
687
692
  };
688
693
 
689
- // TLC's FcnLambdaValue evaluates its body at each application.
690
694
  const createLazyFunction = (
691
695
  domain: Value,
692
696
  compute: (argument: Value, self: LazyFunctionValue) => Value,
693
697
  source: LazyFunctionSource | undefined,
698
+ boundTupleLengths: (number | undefined)[] | undefined,
694
699
  ) => {
695
700
  const self: LazyFunctionValue = {
696
701
  kind: "LazyFunction",
697
702
  domain,
698
703
  source,
704
+ boundTupleLengths,
699
705
  apply: (argument) => compute(argument, self),
700
706
  };
701
707
  return self;
702
708
  };
703
709
 
704
- // 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
+
705
717
  const getDefinitionSource = (definition: FunctionDefinition): Expression => ({
706
718
  kind: "FunctionConstruction",
707
719
  bounds: definition.bounds,
@@ -709,7 +721,10 @@ const getDefinitionSource = (definition: FunctionDefinition): Expression => ({
709
721
  location: definition.location,
710
722
  });
711
723
 
712
- const createRecursiveFunction = (definition: FunctionDefinition, context: Context) => {
724
+ const createRecursiveFunction = (
725
+ definition: FunctionDefinition,
726
+ context: Context,
727
+ ): RebindableLazyFunction => {
713
728
  const domain = getBoundsDomain(definition.bounds, context);
714
729
  const functionValue = createLazyFunction(
715
730
  domain,
@@ -726,6 +741,7 @@ const createRecursiveFunction = (definition: FunctionDefinition, context: Contex
726
741
  definition.bounds,
727
742
  domain,
728
743
  ),
744
+ getBoundTupleLengths(definition.bounds),
729
745
  );
730
746
  keepLambda({
731
747
  value: functionValue,
@@ -733,11 +749,16 @@ const createRecursiveFunction = (definition: FunctionDefinition, context: Contex
733
749
  body: definition.body,
734
750
  scope: bindValue(undefined, definition.name, functionValue),
735
751
  });
736
- 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;
737
760
  };
738
761
 
739
- // TLC computes a constant definition when it starts, without keeping a function it constructs
740
- // lazy, so a function over an interval or an enumerated set is a FcnRcdValue.
741
762
  const toStartupValue = (definition: Definition, value: Value): Value => {
742
763
  if (typeof value !== "object" || getFunctionClass(value) !== "lambda") return value;
743
764
  if (
@@ -752,14 +773,11 @@ const toStartupValue = (definition: Definition, value: Value): Value => {
752
773
  const finite = toFiniteFunction(value);
753
774
  return createSortedFunction(finite.domain, finite.range);
754
775
  } catch (error) {
755
- // TLC leaves a definition it fails to compute to evaluate where the spec uses it.
756
776
  if (error instanceof TlaEvaluationError) return value;
757
777
  throw error;
758
778
  }
759
779
  };
760
780
 
761
- // The code of a definition's body, evaluated as a whole. TLC evaluates a function definition that
762
- // isn't recursive as it does a function constructor.
763
781
  const compileDefinitionBody = (definition: Definition, environment: Environment): Evaluator => {
764
782
  if (definition.kind === "Operator" && definition.params.length > 0) {
765
783
  return () => {
@@ -774,57 +792,79 @@ const compileDefinitionBody = (definition: Definition, environment: Environment)
774
792
  return getEntryEvaluator(getDefinitionSource(definition), environment);
775
793
  };
776
794
 
777
- // The code that evaluates a reference to a definition: the value TLC computed at startup when it
778
- // has one, and the body at the top level otherwise.
779
795
  const getDefinitionEvaluator = (definition: Definition, environment: Environment): Evaluator => {
780
796
  const compiled = environment.definitionEvaluators.get(definition);
781
797
  if (compiled) return compiled;
782
798
  const body = compileDefinitionBody(definition, environment);
783
- const id = environment.facts.ids.get(definition);
799
+ const definitionId = environment.facts.ids.get(definition);
784
800
  const startupValues = environment.startupValues;
785
801
  const evaluator: Evaluator =
786
- id === undefined
802
+ definitionId === undefined
787
803
  ? (context) => body(withScope(context, undefined))
788
- : (context) => startupValues[id] ?? body(withScope(context, undefined));
804
+ : (context) => startupValues[definitionId] ?? body(withScope(context, undefined));
789
805
  environment.definitionEvaluators.set(definition, evaluator);
790
806
  return evaluator;
791
807
  };
792
808
 
793
809
  export const getStartupValue = (definition: Definition, environment: Environment) => {
794
- const id = environment.facts.ids.get(definition);
795
- return id === undefined ? undefined : environment.startupValues[id];
810
+ const definitionId = environment.facts.ids.get(definition);
811
+ return definitionId === undefined ? undefined : environment.startupValues[definitionId];
796
812
  };
797
813
 
798
- // TLC computes each constant definition the configuration doesn't replace when it starts, and
799
- // leaves one it fails to compute to evaluate where the spec uses it.
800
814
  export const evaluateStartupDefinitions = (definitions: Definition[], environment: Environment) =>
801
815
  definitions.forEach((definition) => {
802
816
  if (definition.kind === "Operator" && definition.params.length > 0) return;
803
817
  const name = definition.name;
804
818
  if (environment.constants.has(name) || environment.substitutions.has(name)) return;
805
819
  if (!isConstantLevel(definition, environment)) return;
806
- const id = environment.facts.ids.get(definition);
807
- 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;
808
822
  const context = { environment, scope: undefined, state: undefined, next: undefined };
809
823
  try {
810
824
  const value = environment.runtime.evaluateAtStartup(() =>
811
825
  toStartupValue(definition, compileDefinitionBody(definition, environment)(context)),
812
826
  );
813
827
  markNormalized(value);
814
- environment.startupValues[id] = value;
828
+ environment.startupValues[definitionId] = value;
815
829
  } catch (error) {
816
830
  // TLC swallows whatever the definition throws, a stack overflow included.
817
831
  if (!(error instanceof TlaEvaluationError) && !isStackOverflow(error)) throw error;
818
832
  }
819
833
  });
820
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
+
821
848
  const forceThunk = (thunk: Thunk, context: Context) => {
822
- const isSameState = thunk.state === context.state && thunk.next === context.next;
823
- if (thunk.cache !== undefined && (isSameState || thunk.isReleased)) return thunk.cache;
824
- const value = evaluate(thunk.expression, withScope(context, thunk.scope));
825
- if (isSameState && (!thunk.isStreamed || isSettledValue(value))) thunk.cache = value;
826
- // A value a thunk cached with no state read no variable, so it holds in every state. Releasing
827
- // its scope frees the evaluations the scope's bindings cached, which a long script keeps alive.
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
+ }
828
868
  if (thunk.cache !== undefined && thunk.state === undefined && thunk.next === undefined) {
829
869
  thunk.scope = undefined;
830
870
  thunk.isReleased = true;
@@ -896,6 +936,12 @@ const evaluateOperatorArgument = (expression: Expression, context: Context): Ope
896
936
  };
897
937
 
898
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
+ }
899
945
  if (operator.kind === "Builtin") return operator.evaluate(args, context);
900
946
  if (operator.kind === "Operator") return operator.call(args);
901
947
  const scope = operator.params.reduce<Scope | undefined>(
@@ -913,11 +959,6 @@ const toOperatorValue = (operator: Operator, context: Context): OperatorValue =>
913
959
  name: operator.name,
914
960
  arity: getArity(operator),
915
961
  call: (args) => callOperatorWithValues(operator, args, context),
916
- literalBody:
917
- operator.kind === "Closure" &&
918
- (operator.body.kind === "Number" || operator.body.kind === "String")
919
- ? operator.body.value
920
- : undefined,
921
962
  };
922
963
 
923
964
  const isOperatorArgument = (expression: Expression, context: Context) => {
@@ -969,9 +1010,17 @@ const compileArgumentBinder = (argument: Expression, environment: Environment):
969
1010
  const isLiteral =
970
1011
  argument.kind === "String" || (argument.kind === "Number" && isTlcInteger(argument.value));
971
1012
  if (isLiteral) {
972
- const binding: Binding = { kind: "Value", value: argument.value };
1013
+ const binding: Binding = { kind: "Value", value: argument.value, argument };
973
1014
  return () => binding;
974
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
+ }
975
1024
  if (argument.kind === "Identifier") {
976
1025
  const global = isLocallyResolved(argument)
977
1026
  ? undefined
@@ -980,7 +1029,7 @@ const compileArgumentBinder = (argument: Expression, environment: Environment):
980
1029
  const binding: Binding = { kind: "Value", value: global.value };
981
1030
  return () => binding;
982
1031
  }
983
- if (global === undefined) {
1032
+ if (global === undefined && !environment.callStack) {
984
1033
  return (context) => {
985
1034
  const binding = lookupScope(context.scope, argument.name);
986
1035
  return binding?.kind === "Value" || binding?.kind === "Thunk"
@@ -1028,14 +1077,11 @@ const callOperator = (
1028
1077
  return operator.evaluate(evaluateBuiltinArguments(args, context), context);
1029
1078
  };
1030
1079
 
1031
- // The LET definitions that a reference evaluates again, and those that cache only a settled value.
1032
1080
  interface ReevaluatedDefinitions {
1033
1081
  impure: ReadonlySet<Definition>;
1034
1082
  streamed: ReadonlySet<Definition>;
1035
1083
  }
1036
1084
 
1037
- // A LET's function definition has one function constructor, as in SANY, so its code compiles once
1038
- // however often the LET is evaluated.
1039
1085
  const letFunctionConstructions = new WeakMap<FunctionDefinition, Expression>();
1040
1086
 
1041
1087
  const getLetFunctionConstruction = (definition: FunctionDefinition): Expression => {
@@ -1056,49 +1102,57 @@ export const bindDefinitions = (
1056
1102
  definitions: Definition[],
1057
1103
  context: Context,
1058
1104
  reevaluated?: ReevaluatedDefinitions,
1059
- ): Scope | undefined =>
1060
- definitions.reduce<Scope | undefined>((scope, definition) => {
1061
- const node: Scope = {
1062
- name: definition.name,
1063
- binding: { kind: "Value", value: false },
1064
- parent: scope,
1065
- };
1066
- if (definition.kind === "Function") {
1067
- node.binding = {
1068
- kind: "Thunk",
1069
- expression: getLetFunctionConstruction(definition),
1070
- scope: node,
1071
- state: context.state,
1072
- next: context.next,
1073
- cache: undefined,
1074
- isStreamed: false,
1075
- };
1076
- return node;
1077
- }
1078
- if (definition.params.length > 0 || reevaluated?.impure.has(definition)) {
1079
- node.binding = {
1080
- kind: "Operator",
1081
- operator: {
1082
- kind: "Closure",
1083
- name: definition.name,
1084
- params: definition.params,
1085
- body: definition.body,
1086
- scope: node,
1087
- },
1088
- };
1089
- return node;
1090
- }
1091
- node.binding = {
1092
- kind: "Thunk",
1093
- expression: definition.body,
1094
- scope: node,
1095
- state: context.state,
1096
- next: context.next,
1097
- cache: undefined,
1098
- isStreamed: reevaluated?.streamed.has(definition) ?? false,
1099
- };
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;
1100
1113
  return node;
1101
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
+ };
1102
1156
 
1103
1157
  const evaluateLocalIdentifier = (name: string, expression: Expression, context: Context): Value => {
1104
1158
  const binding = lookupScope(context.scope, name);
@@ -1125,9 +1179,6 @@ const evaluateLocalIdentifier = (name: string, expression: Expression, context:
1125
1179
  throw new TlaEvaluationError(`Unknown identifier ${name} at ${describeLocation(expression)}`);
1126
1180
  };
1127
1181
 
1128
- // TLC's next-state generator does not bind LET definitions to values, so each reference to one
1129
- // evaluates it again: one that calls an impure builtin repeats its effects, and a set one builds
1130
- // with UNION or \cup starts out uncached.
1131
1182
  export const getReevaluatedDefinitions = (
1132
1183
  definitions: Definition[],
1133
1184
  environment: Environment,
@@ -1143,23 +1194,39 @@ export const isImpure = (environment: Environment) =>
1143
1194
  isImpureDefinition(definition, environment),
1144
1195
  );
1145
1196
 
1146
- // Whether evaluating a definition again can show, such as by printing twice.
1147
1197
  export const hasRepeatedEffects = (environment: Environment) =>
1148
1198
  [...environment.facts.ids.keys()].some((definition) =>
1149
1199
  isImpureDefinition(definition, environment, "repeated"),
1150
1200
  );
1151
1201
 
1152
- // A set filter TLC evaluates lazily, with how to rebuild it so that its predicate runs in another
1153
- // environment.
1154
1202
  interface RebindableFilteredSet extends FilteredSetValue {
1155
1203
  rebind: (environment: Environment) => Value;
1156
1204
  }
1157
1205
 
1158
- const isRebindableFilteredSet = (value: Value): value is RebindableFilteredSet =>
1159
- 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
+ };
1160
1229
 
1161
- // TLC's CallStackTool rebinds the lazy values its evaluations return, so their later evaluation
1162
- // records its call stack too.
1163
1230
  const traceEvaluator =
1164
1231
  (
1165
1232
  expression: Expression,
@@ -1177,13 +1244,17 @@ const traceEvaluator =
1177
1244
  setTrace.callStack = callStack;
1178
1245
  try {
1179
1246
  const computed = evaluator(context);
1180
- const value = isRebindableFilteredSet(computed) ? computed.rebind(environment) : computed;
1247
+ const value = isRebindable(computed) ? computed.rebind(environment) : computed;
1181
1248
  callStack.values.set(expression, value);
1182
1249
  if (typeof value === "object" && value.kind !== "FilteredSet" && isSourced(expression)) {
1183
1250
  callStack.sources.set(value, expression);
1184
1251
  }
1185
1252
  return value;
1186
1253
  } catch (error) {
1254
+ if (error instanceof TlaSetBoundError && !callStack.isFrozen) {
1255
+ callStack.expressions.length = 0;
1256
+ callStack.isFrozen = true;
1257
+ }
1187
1258
  const failed = error instanceof Error ? callStack.failures.get(error) : undefined;
1188
1259
  if (error instanceof Error) callStack.failures.set(error, expression);
1189
1260
  const receiver = getReceiver(expression, callStack.values);
@@ -1211,20 +1282,15 @@ const traceEvaluator =
1211
1282
  }
1212
1283
  };
1213
1284
 
1214
- // A method of a value with a source raises a FingerprintException, which each value with a source
1215
- // whose method called it heads in turn. CallStack#freeze adds their sources to the stack, outermost
1216
- // first. The values are those whose methods failed, outermost first.
1217
1285
  export const freezeCallStack = (
1218
1286
  callStack: CallStack,
1219
1287
  values: (Value | undefined)[],
1220
1288
  error: unknown,
1221
1289
  ) => {
1222
- // A set that streams its elements enumerates itself too, so it can appear twice.
1223
1290
  const sources = [...new Set(values)].flatMap((item) => {
1224
1291
  const source = typeof item === "object" ? callStack.sources.get(item) : undefined;
1225
1292
  return source ? [source] : [];
1226
1293
  });
1227
- // A value with a source raises a FingerprintException even when the stack is frozen already.
1228
1294
  if (sources.length > 0 && error instanceof TlaEvaluationError) {
1229
1295
  if (!callStack.isFrozen) callStack.expressions.push(...sources);
1230
1296
  const inner = callStack.fingerprint;
@@ -1236,8 +1302,6 @@ export const freezeCallStack = (
1236
1302
  callStack.isFrozen = true;
1237
1303
  };
1238
1304
 
1239
- // A FingerprintException that a method of a value with a source raises, or that passes through one,
1240
- // takes the value's source as its new head.
1241
1305
  const headFingerprint = (callStack: CallStack, source: Expression, error: unknown) => {
1242
1306
  if (!(error instanceof TlaEvaluationError)) return;
1243
1307
  if (!callStack.isFrozen) callStack.expressions.push(source);
@@ -1249,10 +1313,9 @@ const headFingerprint = (callStack: CallStack, source: Expression, error: unknow
1249
1313
  };
1250
1314
  };
1251
1315
 
1252
- // A copy of the environment that records the call stack of each evaluation, with evaluators of its
1253
- // own since the environment's evaluators record nothing.
1254
1316
  export const createTracingEnvironment = (environment: Environment): Environment => ({
1255
1317
  ...environment,
1318
+ coverage: undefined,
1256
1319
  evaluators: new WeakMap(),
1257
1320
  entryEvaluators: new WeakMap(),
1258
1321
  definitionEvaluators: new WeakMap(),
@@ -1265,20 +1328,60 @@ export const createTracingEnvironment = (environment: Environment): Environment
1265
1328
  },
1266
1329
  });
1267
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
+
1268
1367
  export const getEvaluator = (expression: Expression, environment: Environment): Evaluator => {
1269
1368
  const cached = environment.evaluators.get(expression);
1270
1369
  if (cached) return cached;
1271
1370
  const compiled = compile(expression, environment);
1272
1371
  const callStack = environment.callStack;
1273
- const evaluator = callStack
1372
+ const frames = callStack && substitutionFrames.get(expression);
1373
+ const traced = callStack
1274
1374
  ? traceEvaluator(expression, compiled, environment, callStack)
1275
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;
1276
1379
  environment.evaluators.set(expression, evaluator);
1277
1380
  return evaluator;
1278
1381
  };
1279
1382
 
1280
1383
  export const getEntryEvaluator = (expression: Expression, environment: Environment) => {
1281
- if (environment.callStack) return getEvaluator(expression, environment);
1384
+ if (environment.callStack || environment.coverage) return getEvaluator(expression, environment);
1282
1385
  const compiled = environment.entryEvaluators.get(expression);
1283
1386
  if (compiled) return compiled;
1284
1387
  const evaluator =
@@ -1309,12 +1412,9 @@ const compileIdentifier = (
1309
1412
  return () => value;
1310
1413
  }
1311
1414
  if (global?.kind === "Definition") {
1312
- // The body compiles when the reference is first evaluated, as a recursive definition's body
1313
- // refers back to it.
1314
1415
  const definition = global.definition;
1315
- const compiled = { reference: undefined as Evaluator | undefined };
1316
- return (context) =>
1317
- (compiled.reference ??= getDefinitionEvaluator(definition, environment))(context);
1416
+ let compiled: Evaluator | undefined;
1417
+ return (context) => (compiled ??= getDefinitionEvaluator(definition, environment))(context);
1318
1418
  }
1319
1419
  return (context) => evaluateLocalIdentifier(name, expression, context);
1320
1420
  };
@@ -1394,11 +1494,10 @@ const compileClosureCall = (
1394
1494
  environment: Environment,
1395
1495
  ): Evaluator => {
1396
1496
  const bindArguments = compileArgumentScope(closure, args, environment);
1397
- // The body compiles when the call is first evaluated, as a recursive operator's body calls it.
1398
- const compiled = { body: undefined as Evaluator | undefined };
1497
+ let body: Evaluator | undefined;
1399
1498
  return (context) => {
1400
- compiled.body ??= getEntryEvaluator(closure.body, environment);
1401
- return compiled.body({
1499
+ body ??= getEntryEvaluator(closure.body, environment);
1500
+ return body({
1402
1501
  environment,
1403
1502
  scope: bindArguments(context),
1404
1503
  state: context.state,
@@ -1417,12 +1516,24 @@ const compileApply = (
1417
1516
  const left = getEvaluator(args[0], environment);
1418
1517
  const right = getEvaluator(args[1], environment);
1419
1518
  return (context) =>
1420
- !expectBoolean(left(context), "the left side of =>") ||
1421
- expectBoolean(right(context), "the right side of =>");
1519
+ !expectImplication(left(context), expression, "P") ||
1520
+ expectImplication(right(context), expression, "Q");
1422
1521
  }
1423
- 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 === "-+->") {
1424
1532
  return () => {
1425
- 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
+ );
1426
1537
  };
1427
1538
  }
1428
1539
  const global = isLocallyResolved(expression)
@@ -1434,14 +1545,14 @@ const compileApply = (
1434
1545
  const domain = getDomainOperator(expression);
1435
1546
  return (context) => domain(operand(context));
1436
1547
  }
1437
- // TLC sorts the value of a constant TLCEval argument only where no context binds a name.
1438
1548
  if (global?.kind === "Builtin" && global.name === "TLCEval" && args.length === 1) {
1439
- const operand = getEvaluator(args[0], environment);
1440
- if (contextualApplications.has(expression) || isNonconstant(args[0], environment)) {
1441
- return operand;
1442
- }
1549
+ const isCached =
1550
+ !contextualApplications.has(expression) && !isNonconstant(args[0], environment);
1443
1551
  return (context) =>
1444
- context.scope === undefined ? global.evaluate([operand(context)]) : operand(context);
1552
+ global.evaluate(
1553
+ getLazyArguments(args, context),
1554
+ isCached && context.scope === undefined ? undefined : context,
1555
+ );
1445
1556
  }
1446
1557
  if (global?.kind === "Builtin" && global.name === "\\subseteq" && args.length === 2) {
1447
1558
  const left = getEvaluator(args[0], environment);
@@ -1450,7 +1561,6 @@ const compileApply = (
1450
1561
  return (context) => subset(left(context), right(context));
1451
1562
  }
1452
1563
  if (global?.kind === "Builtin") return compileBuiltinCall(global, args, environment);
1453
- // TLC refuses action composition unless a Java property enables its incomplete implementation.
1454
1564
  if (expression.operator === "\\cdot" && args.length === 2) {
1455
1565
  return () => {
1456
1566
  throw new TlaEvaluationError(
@@ -1479,7 +1589,6 @@ const compileQuantifier = (
1479
1589
  environment: Environment,
1480
1590
  ): Evaluator => {
1481
1591
  const isForall = expression.kind === "Forall";
1482
- const description = isForall ? "the body of \\A" : "the body of \\E";
1483
1592
  const body = getEvaluator(expression.body, environment);
1484
1593
  const bound = expression.bounds[0];
1485
1594
  if (expression.bounds.length === 1 && bound.pattern.kind === "Name") {
@@ -1489,9 +1598,9 @@ const compileQuantifier = (
1489
1598
  const isFound = someElement(
1490
1599
  getQuantifierElements(set(context), bound.set, environment.runtime.version),
1491
1600
  (element) =>
1492
- expectBoolean(
1601
+ expectBooleanBody(
1493
1602
  body(withScope(context, bindValue(context.scope, name, element))),
1494
- description,
1603
+ expression,
1495
1604
  ) !== isForall,
1496
1605
  );
1497
1606
  return isFound ? !isForall : isForall;
@@ -1500,14 +1609,17 @@ const compileQuantifier = (
1500
1609
  const bounds = expression.bounds;
1501
1610
  if (bounds.every((item) => item.pattern.kind === "Name")) {
1502
1611
  const names = bounds.map((item) => (item.pattern.kind === "Name" ? item.pattern.name : ""));
1503
- const sets = bounds.map((item) => getEvaluator(item.set, environment));
1504
1612
  return (context) => {
1505
- const lists = sets.map((set, index) =>
1506
- 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
+ ),
1507
1619
  );
1508
1620
  const visit = (index: number, scope: Scope | undefined): boolean => {
1509
1621
  if (index < 0) {
1510
- return expectBoolean(body(withScope(context, scope)), description) !== isForall;
1622
+ return expectBooleanBody(body(withScope(context, scope)), expression) !== isForall;
1511
1623
  }
1512
1624
  return someElement(lists[index], (element) =>
1513
1625
  visit(index - 1, bindValue(scope, names[index], element)),
@@ -1520,7 +1632,7 @@ const compileQuantifier = (
1520
1632
  const isFound = forEachBinding(
1521
1633
  bounds,
1522
1634
  context,
1523
- (scope) => expectBoolean(body(withScope(context, scope)), description) !== isForall,
1635
+ (scope) => expectBooleanBody(body(withScope(context, scope)), expression) !== isForall,
1524
1636
  );
1525
1637
  return isFound ? !isForall : isForall;
1526
1638
  };
@@ -1539,8 +1651,6 @@ const getBoundValue = (pattern: BoundPattern, scope: Scope | undefined) => {
1539
1651
  return binding?.kind === "Value" ? binding.value : undefined;
1540
1652
  };
1541
1653
 
1542
- // TLC keeps a function constructor lazy when it is the function of an application, or the base of
1543
- // an EXCEPT that is, so it evaluates the body only at the arguments it is applied to.
1544
1654
  const keptLazyExpressions = new WeakSet<Expression>();
1545
1655
 
1546
1656
  export const keepLazy = (expression: Expression) => {
@@ -1549,8 +1659,6 @@ export const keepLazy = (expression: Expression) => {
1549
1659
  }
1550
1660
  };
1551
1661
 
1552
- // The names an expression may look up in its scope, or undefined when a subexpression selector may
1553
- // look up others.
1554
1662
  const scopeNames = new WeakMap<Expression, string[] | undefined>();
1555
1663
 
1556
1664
  const getScopeNames = (expression: Expression) => {
@@ -1568,9 +1676,6 @@ const getScopeNames = (expression: Expression) => {
1568
1676
  return result;
1569
1677
  };
1570
1678
 
1571
- // The bindings of a scope that names look up, so that a lazy function keeps only those alive and
1572
- // not the values its other bindings cached. An unnamed node ends the chain, since a TLCEval in the
1573
- // body sorts its value only where no context binds a name.
1574
1679
  const trimScope = (scope: Scope | undefined, names: string[] | undefined) =>
1575
1680
  names === undefined || scope === undefined
1576
1681
  ? scope
@@ -1582,34 +1687,37 @@ const trimScope = (scope: Scope | undefined, names: string[] | undefined) =>
1582
1687
  { name: "", binding: { kind: "Value", value: false }, parent: undefined },
1583
1688
  );
1584
1689
 
1585
- const compileFunctionConstruction = (
1690
+ export const isKeptLazy = (expression: Expression) => keptLazyExpressions.has(expression);
1691
+
1692
+ export const getFunctionBuilder = (
1586
1693
  expression: Expression & { kind: "FunctionConstruction" },
1587
1694
  environment: Environment,
1588
- ): Evaluator => {
1589
- const isKeptLazy = keptLazyExpressions.has(expression);
1695
+ ) => {
1696
+ const isKeptLazyExpression = isKeptLazy(expression);
1590
1697
  const body = getEvaluator(expression.body, environment);
1591
1698
  const bounds = expression.bounds;
1592
1699
  const bound = bounds[0];
1593
1700
  const isSingleName = bounds.length === 1 && bound.pattern.kind === "Name";
1594
- const set = getEvaluator(bound.set, environment);
1595
1701
  const construct = (domain: Value, context: Context) => {
1596
1702
  if (isSingleName && bound.pattern.kind === "Name") {
1597
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
+ }
1598
1712
  const keys = getFunctionDomain(domain);
1599
- const functionValue = createSortedFunction(
1600
- keys,
1601
- keys.map((key) => body(withScope(context, bindValue(context.scope, name, key)))),
1602
- );
1603
- // FcnLambdaValue#toFcnRcd builds a FcnRcdValue over an interval or an enumerated set.
1604
- 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);
1605
1717
  }
1606
1718
  const pairs: [Value, Value][] = [];
1607
- const sets = bounds.map((item) =>
1608
- getNormalizedElements(
1609
- evaluate(item.set, context),
1610
- item.set,
1611
- context.environment.runtime.version,
1612
- ),
1719
+ const sets = mapBoundSets(bounds, (set) =>
1720
+ getNormalizedElements(evaluate(set, context), set, context.environment.runtime.version),
1613
1721
  );
1614
1722
  forEachBoundElement(bounds, sets, context.scope, (scope) => {
1615
1723
  const key =
@@ -1622,6 +1730,7 @@ const compileFunctionConstruction = (
1622
1730
  return createFunction(pairs);
1623
1731
  };
1624
1732
  const template = getLazyFunctionTemplate(bounds, expression.body);
1733
+ const boundTupleLengths = getBoundTupleLengths(bounds);
1625
1734
  const bodyNames = getScopeNames(expression.body);
1626
1735
  const createLazy = (domain: Value, context: Context) => {
1627
1736
  const scope = trimScope(context.scope, bodyNames);
@@ -1631,6 +1740,7 @@ const compileFunctionConstruction = (
1631
1740
  domain,
1632
1741
  (argument) => body(withScope(lambdaContext, bindArgument(bounds, scope, argument))),
1633
1742
  getLazyFunctionSource(template, bounds, domain),
1743
+ boundTupleLengths,
1634
1744
  ),
1635
1745
  bounds,
1636
1746
  body: expression.body,
@@ -1639,15 +1749,22 @@ const compileFunctionConstruction = (
1639
1749
  return bounds.length === 1 ? markLambdaFunction(functionValue) : functionValue;
1640
1750
  };
1641
1751
  const callStack = environment.callStack;
1642
- return (context) => {
1643
- const domain = isSingleName ? set(context) : getBoundsDomain(bounds, context);
1644
- 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
+ ) {
1645
1759
  return createLazy(domain, context);
1646
1760
  }
1647
- // TLC builds a function over a domain other than a set enumeration or an interval lazily, so
1648
- // its body fails only where TLC forces it, as the replay does. Building it at once is faster
1649
- // otherwise.
1650
- 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) {
1651
1768
  if (callStack) return createLazy(domain, context);
1652
1769
  try {
1653
1770
  return construct(domain, context);
@@ -1657,7 +1774,6 @@ const compileFunctionConstruction = (
1657
1774
  }
1658
1775
  }
1659
1776
  if (!callStack) return construct(domain, context);
1660
- // TLC builds the function in a method of the FcnLambdaValue that CallStackTool gives a source.
1661
1777
  try {
1662
1778
  return construct(domain, context);
1663
1779
  } catch (error) {
@@ -1665,14 +1781,28 @@ const compileFunctionConstruction = (
1665
1781
  throw error;
1666
1782
  }
1667
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);
1668
1798
  };
1669
1799
 
1670
1800
  const compileExcept = (
1671
1801
  expression: Expression & { kind: "Except" },
1672
1802
  environment: Environment,
1673
1803
  ): Evaluator => {
1674
- const isKeptLazy = keptLazyExpressions.has(expression);
1675
- if (isKeptLazy) keepLazy(expression.function);
1804
+ const isKeptLazyExpression = keptLazyExpressions.has(expression);
1805
+ if (isKeptLazyExpression) keepLazy(expression.function);
1676
1806
  const evaluateFunction = getEvaluator(expression.function, environment);
1677
1807
  const updates = expression.updates.map((update) => ({
1678
1808
  path: update.path.map((step): CompiledStep =>
@@ -1705,19 +1835,18 @@ const compileExcept = (
1705
1835
  current,
1706
1836
  getKey(path[depth], context),
1707
1837
  (previous) => update(previous, path, depth + 1, context, value),
1708
- isKeptLazy && depth === 0,
1838
+ isKeptLazyExpression && depth === 0,
1709
1839
  );
1710
1840
  };
1711
1841
  return (context) => {
1712
1842
  let current = evaluateFunction(context);
1713
1843
  for (const item of updates) {
1714
- // TLC leaves the value as it is when an update's path is not in it, and warns.
1715
- const found = { value: false };
1844
+ let isFound = false;
1716
1845
  current = update(current, item.path, 0, context, (inner) => {
1717
- found.value = true;
1846
+ isFound = true;
1718
1847
  return item.value(inner);
1719
1848
  });
1720
- if (!found.value) {
1849
+ if (!isFound) {
1721
1850
  context.environment.runtime.warn(
1722
1851
  MESSAGE_CODE.exceptAppliedToUnknownField,
1723
1852
  `The EXCEPT was applied to non-existing fields of the value at\n${describeRange(expression.function)}`,
@@ -1728,6 +1857,98 @@ const compileExcept = (
1728
1857
  };
1729
1858
  };
1730
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
+
1731
1952
  const compileSetComprehension = (
1732
1953
  expression: Expression & { kind: "SetFilter" | "SetMap" | "Choose" },
1733
1954
  environment: Environment,
@@ -1735,38 +1956,25 @@ const compileSetComprehension = (
1735
1956
  if (expression.kind === "SetFilter") {
1736
1957
  const predicate = getEvaluator(expression.predicate, environment);
1737
1958
  const set = getEvaluator(expression.bound.set, environment);
1959
+ const filterLazily = getLazyFilter(expression, environment);
1738
1960
  const pattern = expression.bound.pattern;
1739
- const range = expression.predicate.location.range;
1740
- const source = range && {
1741
- names: pattern.kind === "Name" ? pattern.name : pattern.names.join(", "),
1742
- predicate: formatRange(range),
1743
- };
1744
- const createTest = (evaluator: Evaluator, context: Context) => (element: Value) =>
1745
- expectBoolean(
1746
- evaluator(withScope(context, bindPattern(context.scope, pattern, element))),
1747
- "a set filter predicate",
1748
- );
1749
- const createFiltered = (
1750
- base: Value,
1751
- context: Context,
1752
- evaluator: Evaluator,
1753
- ): RebindableFilteredSet => ({
1754
- kind: "FilteredSet",
1755
- base,
1756
- test: createTest(evaluator, context),
1757
- source,
1758
- rebind: (tracing) =>
1759
- createFiltered(
1760
- base,
1761
- { ...context, environment: tracing },
1762
- getEvaluator(expression.predicate, tracing),
1763
- ),
1764
- });
1961
+ const coverage = environment.coverage;
1765
1962
  return (context) => {
1766
1963
  const base = set(context);
1767
- // TLC filters any value it can't enumerate lazily, and fails only when it uses the result.
1768
- if (!isReducibleSet(base)) return createFiltered(base, context, predicate);
1769
- 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);
1770
1978
  };
1771
1979
  }
1772
1980
  if (expression.kind === "SetMap") {
@@ -1774,7 +1982,7 @@ const compileSetComprehension = (
1774
1982
  return (context) => {
1775
1983
  const elements: Value[] = [];
1776
1984
  forEachBinding(expression.bounds, context, (scope) => {
1777
- elements.push(mapped(withScope(context, scope)));
1985
+ addBoundedElement(elements, mapped(withScope(context, scope)));
1778
1986
  return false;
1779
1987
  });
1780
1988
  return createEnumeratedSet(elements);
@@ -1784,37 +1992,40 @@ const compileSetComprehension = (
1784
1992
  if (!set) {
1785
1993
  return () => {
1786
1994
  throw new TlaEvaluationError(
1787
- `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)}`,
1788
1996
  );
1789
1997
  };
1790
1998
  }
1791
1999
  const body = getEvaluator(expression.body, environment);
1792
2000
  const evaluateSet = getEvaluator(set, environment);
1793
2001
  return (context) => {
1794
- const base = evaluateSet(context);
1795
- if (!isSetValue(base) || isOverriddenSet(base)) {
1796
- throw new TlaEvaluationError(
1797
- `Attempted to compute the value of an expression of\nform CHOOSE x \\in S: P, but S was not enumerable.\n${describeRange(expression)}`,
1798
- );
1799
- }
1800
- const chosen = { value: undefined as Value | undefined };
1801
- 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;
1802
2010
  someElement(elements, (element) => {
1803
- const scope = bindPattern(context.scope, expression.pattern, element);
1804
- if (!expectBoolean(body(withScope(context, scope)), "the body of CHOOSE")) return false;
1805
- 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);
1806
2022
  return true;
1807
2023
  });
1808
- if (chosen.value === undefined) {
1809
- throw new TlaEvaluationError(
1810
- `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)}`,
1811
- );
1812
- }
1813
- return chosen.value;
2024
+ if (chosen === undefined) throw createNoChoiceError(expression);
2025
+ return chosen;
1814
2026
  };
1815
2027
  };
1816
2028
 
1817
- // TLC orders a record's fields by name.
1818
2029
  export const getSortedFields = (fields: RecordField[]) =>
1819
2030
  [...fields].sort((left, right) => compareValues(left.name, right.name));
1820
2031
 
@@ -1908,26 +2119,10 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1908
2119
  }
1909
2120
  case "Prime": {
1910
2121
  const inner = getChildEvaluator(expression.expression);
1911
- return (context) => {
1912
- if (!context.next) throw createPrimeOutsideActionError(expression);
1913
- return inner({
1914
- environment: context.environment,
1915
- scope: context.scope,
1916
- state: context.next,
1917
- next: undefined,
1918
- isKeepLazy: context.isKeepLazy,
1919
- });
1920
- };
1921
- }
1922
- case "Unchanged": {
1923
- const primed = getChildEvaluator({
1924
- kind: "Prime",
1925
- expression: expression.expression,
1926
- location: expression.location,
1927
- });
1928
- const current = getChildEvaluator(expression.expression);
1929
- return (context) => valuesEqual(primed(context), current(context));
2122
+ return (context) => inner(toNextContext(context));
1930
2123
  }
2124
+ case "Unchanged":
2125
+ return compileUnchanged(getChildEvaluator(expression.expression));
1931
2126
  case "If": {
1932
2127
  const condition = getChildEvaluator(expression.condition);
1933
2128
  const consequent = getChildEvaluator(expression.consequent);
@@ -1971,8 +2166,15 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1971
2166
  return compileQuantifier(expression, environment);
1972
2167
  case "UnboundedQuantifier":
1973
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
+ }
1974
2176
  throw new TlaEvaluationError(
1975
- `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)}`,
1976
2178
  );
1977
2179
  };
1978
2180
  case "Choose":
@@ -2048,16 +2250,18 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
2048
2250
  case "BoxAction":
2049
2251
  case "AngleAction": {
2050
2252
  const action = getChildEvaluator(expression.action);
2051
- const unchanged = getChildEvaluator({
2052
- kind: "Unchanged",
2053
- expression: expression.subscript,
2054
- location: expression.location,
2055
- });
2253
+ const unchanged = compileUnchanged(getChildEvaluator(expression.subscript));
2056
2254
  const isBox = expression.kind === "BoxAction";
2057
- return (context) =>
2058
- isBox
2059
- ? expectBoolean(action(context), "an action") || unchanged(context)
2060
- : 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
+ };
2061
2265
  }
2062
2266
  case "Enabled": {
2063
2267
  const action = expression.expression;
@@ -2076,9 +2280,7 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
2076
2280
  case "WeakFairness":
2077
2281
  case "StrongFairness":
2078
2282
  return () => {
2079
- throw new TlaEvaluationError(
2080
- `TLC cannot evaluate a temporal formula in a state at ${describeLocation(expression)}`,
2081
- );
2283
+ throw createTemporalFormulaError(TEMPORAL_FORMS[expression.kind], expression);
2082
2284
  };
2083
2285
  }
2084
2286
  };