tla-ts 0.0.9 → 0.0.10-dev.63a6693bd

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