tla-ts 0.0.3 → 0.0.4-dev.1a3acf6

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 (381) hide show
  1. package/README.md +46 -115
  2. package/dist/cli.cjs +1 -1
  3. package/dist/cli.js +1 -1
  4. package/dist/deciders.cjs +366 -0
  5. package/dist/deciders.js +366 -0
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +194 -8
  8. package/dist/index.d.ts +194 -8
  9. package/dist/index.js +1 -1
  10. package/dist/parallel-worker.cjs +1 -4
  11. package/dist/parallel-worker.js +1 -4
  12. package/dist/prove-worker.cjs +9 -0
  13. package/dist/prove-worker.d.cts +9 -0
  14. package/dist/prove-worker.d.ts +9 -0
  15. package/dist/prove-worker.js +9 -0
  16. package/dist/prove.cjs +1006 -0
  17. package/dist/prove.js +1006 -0
  18. package/dist/run.cjs +45 -0
  19. package/dist/run.js +45 -0
  20. package/dist/tlapm.cjs +10 -0
  21. package/dist/tlapm.js +10 -0
  22. package/dist/transfer.cjs +1377 -18
  23. package/dist/transfer.js +1377 -18
  24. package/dist/worker.cjs +21 -0
  25. package/dist/worker.js +21 -0
  26. package/package.json +24 -11
  27. package/src/ast.ts +149 -8
  28. package/src/bags.ts +26 -30
  29. package/src/builtins.ts +45 -19
  30. package/src/bundled-modules.ts +3 -3
  31. package/src/check.ts +1182 -900
  32. package/src/cli/options.ts +109 -0
  33. package/src/cli/run.ts +63 -0
  34. package/src/cli/shared.ts +106 -0
  35. package/src/cli/tlapm.ts +374 -0
  36. package/src/cli/tlc.ts +941 -0
  37. package/src/cli/xml-exporter.ts +221 -0
  38. package/src/cli.ts +9 -2
  39. package/src/codegen.ts +112 -51
  40. package/src/config.ts +254 -181
  41. package/src/dependencies.ts +5 -7
  42. package/src/environment.ts +579 -184
  43. package/src/errors.ts +287 -4
  44. package/src/evaluate.ts +1095 -365
  45. package/src/exit-codes.ts +22 -43
  46. package/src/fingerprints.ts +49 -14
  47. package/src/index.ts +11 -0
  48. package/src/instances.ts +73 -60
  49. package/src/java-overrides.ts +183 -66
  50. package/src/json.ts +31 -36
  51. package/src/levels.ts +197 -54
  52. package/src/lexer.ts +127 -30
  53. package/src/liveness-checker.ts +894 -0
  54. package/src/liveness.ts +246 -596
  55. package/src/{obligation-action.ts → obligations/action.ts} +248 -74
  56. package/src/{obligation-anon.ts → obligations/anonymize.ts} +55 -57
  57. package/src/obligations/equality.ts +260 -0
  58. package/src/obligations/expression.ts +618 -0
  59. package/src/{obligation-format.ts → obligations/format.ts} +7 -8
  60. package/src/obligations/generate.ts +457 -0
  61. package/src/{obligations.ts → obligations/index.ts} +46 -32
  62. package/src/{obligation-levels.ts → obligations/levels.ts} +44 -40
  63. package/src/obligations/module.ts +445 -0
  64. package/src/obligations/normalize.ts +554 -0
  65. package/src/obligations/operators.ts +176 -0
  66. package/src/obligations/pragma.ts +195 -0
  67. package/src/{obligation-printer.ts → obligations/printer.ts} +65 -230
  68. package/src/{obligation-proof.ts → obligations/proof.ts} +7 -2
  69. package/src/obligations/regroup.ts +100 -0
  70. package/src/{obligation-generate.ts → obligations/simplify.ts} +130 -536
  71. package/src/{obligation-source.ts → obligations/source.ts} +174 -216
  72. package/src/{obligation-deref.ts → obligations/subexpression.ts} +84 -115
  73. package/src/obligations/substitution.ts +261 -0
  74. package/src/obligations/temporal.ts +321 -0
  75. package/src/{obligation-tuples.ts → obligations/tuples.ts} +38 -54
  76. package/src/parallel-worker.ts +184 -235
  77. package/src/parallel.ts +156 -91
  78. package/src/parser.ts +490 -188
  79. package/src/pcal/ast.ts +755 -0
  80. package/src/pcal/parse.ts +1487 -0
  81. package/src/pcal/tokenize.ts +487 -0
  82. package/src/pcal/translate.ts +1151 -0
  83. package/src/pcal/validate.ts +444 -0
  84. package/src/prover/decide-pool.ts +95 -0
  85. package/src/prover/deciders.ts +33 -0
  86. package/src/prover/first-order.ts +175 -0
  87. package/src/prover/isabelle/LICENSE +36 -0
  88. package/src/prover/isabelle/LICENSE-tlapm +26 -0
  89. package/src/prover/isabelle/decide.ts +44 -0
  90. package/src/prover/isabelle/encode.ts +445 -0
  91. package/src/prover/isabelle/isar/inner-syntax.ts +579 -0
  92. package/src/prover/isabelle/isar/method.ts +367 -0
  93. package/src/prover/isabelle/isar/proof.ts +28 -0
  94. package/src/prover/isabelle/isar/statement.ts +57 -0
  95. package/src/prover/isabelle/isar/theory.ts +192 -0
  96. package/src/prover/isabelle/isar/type-check.ts +278 -0
  97. package/src/prover/isabelle/provers/blast/blast.ts +258 -0
  98. package/src/prover/isabelle/provers/blast/branch.ts +322 -0
  99. package/src/prover/isabelle/provers/blast/prove.ts +347 -0
  100. package/src/prover/isabelle/provers/blast/rules.ts +330 -0
  101. package/src/prover/isabelle/provers/blast/state.ts +180 -0
  102. package/src/prover/isabelle/provers/blast/term.ts +546 -0
  103. package/src/prover/isabelle/provers/clasimp.ts +150 -0
  104. package/src/prover/isabelle/provers/classical.ts +389 -0
  105. package/src/prover/isabelle/provers/hypsubst.ts +433 -0
  106. package/src/prover/isabelle/pure/bicompose.ts +174 -0
  107. package/src/prover/isabelle/pure/consts.ts +32 -0
  108. package/src/prover/isabelle/pure/conv.ts +79 -0
  109. package/src/prover/isabelle/pure/drule.ts +264 -0
  110. package/src/prover/isabelle/pure/envir.ts +331 -0
  111. package/src/prover/isabelle/pure/goal.ts +53 -0
  112. package/src/prover/isabelle/pure/interrupt.ts +16 -0
  113. package/src/prover/isabelle/pure/list.ts +12 -0
  114. package/src/prover/isabelle/pure/logic.ts +330 -0
  115. package/src/prover/isabelle/pure/name.ts +98 -0
  116. package/src/prover/isabelle/pure/net.ts +215 -0
  117. package/src/prover/isabelle/pure/object-logic.ts +41 -0
  118. package/src/prover/isabelle/pure/pattern.ts +631 -0
  119. package/src/prover/isabelle/pure/raw-simplifier.ts +338 -0
  120. package/src/prover/isabelle/pure/rewriter.ts +602 -0
  121. package/src/prover/isabelle/pure/search.ts +68 -0
  122. package/src/prover/isabelle/pure/seq.ts +133 -0
  123. package/src/prover/isabelle/pure/simplifier.ts +106 -0
  124. package/src/prover/isabelle/pure/table.ts +201 -0
  125. package/src/prover/isabelle/pure/tactic.ts +168 -0
  126. package/src/prover/isabelle/pure/tactical.ts +264 -0
  127. package/src/prover/isabelle/pure/term-ord.ts +105 -0
  128. package/src/prover/isabelle/pure/term.ts +688 -0
  129. package/src/prover/isabelle/pure/thm.ts +783 -0
  130. package/src/prover/isabelle/pure/type.ts +121 -0
  131. package/src/prover/isabelle/pure/unify.ts +753 -0
  132. package/src/prover/isabelle/pure/variable.ts +25 -0
  133. package/src/prover/isabelle/tla/classical-setup.ts +101 -0
  134. package/src/prover/isabelle/tla/context.ts +74 -0
  135. package/src/prover/isabelle/tla/logic-data.ts +5 -0
  136. package/src/prover/isabelle/tla/logic.ts +215 -0
  137. package/src/prover/isabelle/tla/simpdata.ts +241 -0
  138. package/src/prover/isabelle/tools/intuitionistic.ts +132 -0
  139. package/src/prover/ocaml.ts +22 -0
  140. package/src/prover/prep/action.ts +508 -0
  141. package/src/prover/prep/enabled-axioms.ts +189 -0
  142. package/src/prover/prep/fingerprint.ts +388 -0
  143. package/src/prover/prep/level-comparison.ts +529 -0
  144. package/src/prover/prep/md5.ts +60 -0
  145. package/src/prover/prep/methods.ts +221 -0
  146. package/src/prover/prep/normalize.ts +309 -0
  147. package/src/prover/prove-worker.ts +22 -0
  148. package/src/prover/prove.ts +492 -0
  149. package/src/prover/ptl/decide.ts +68 -0
  150. package/src/prover/ptl/encode.ts +244 -0
  151. package/src/prover/ptl/sat.ts +151 -0
  152. package/src/prover/ptl/tableau.ts +276 -0
  153. package/src/prover/smt/axioms.ts +209 -0
  154. package/src/prover/smt/context.ts +108 -0
  155. package/src/prover/smt/data.ts +636 -0
  156. package/src/prover/smt/encode.ts +275 -0
  157. package/src/prover/smt/extensionality.ts +65 -0
  158. package/src/prover/smt/flatten.ts +112 -0
  159. package/src/prover/smt/format.ts +154 -0
  160. package/src/prover/smt/instances.ts +181 -0
  161. package/src/prover/smt/rewrite.ts +766 -0
  162. package/src/prover/smt/solver/act-cache.ts +265 -0
  163. package/src/prover/smt/solver/arith-rewriter.ts +962 -0
  164. package/src/prover/smt/solver/array.ts +22 -0
  165. package/src/prover/smt/solver/asserted-formulas.ts +469 -0
  166. package/src/prover/smt/solver/ast-lt.ts +157 -0
  167. package/src/prover/smt/solver/ast-util.ts +91 -0
  168. package/src/prover/smt/solver/ast.ts +1315 -0
  169. package/src/prover/smt/solver/auf-solver.ts +572 -0
  170. package/src/prover/smt/solver/case-split-queue.ts +178 -0
  171. package/src/prover/smt/solver/cg-table.ts +175 -0
  172. package/src/prover/smt/solver/clause.ts +276 -0
  173. package/src/prover/smt/solver/conflict-resolution.ts +343 -0
  174. package/src/prover/smt/solver/context.ts +1292 -0
  175. package/src/prover/smt/solver/ctx-simplify.ts +334 -0
  176. package/src/prover/smt/solver/der.ts +224 -0
  177. package/src/prover/smt/solver/dyn-ack.ts +141 -0
  178. package/src/prover/smt/solver/e-matching.ts +659 -0
  179. package/src/prover/smt/solver/enode.ts +259 -0
  180. package/src/prover/smt/solver/expr-ref.ts +21 -0
  181. package/src/prover/smt/solver/expr-safe-replace.ts +172 -0
  182. package/src/prover/smt/solver/fingerprints.ts +92 -0
  183. package/src/prover/smt/solver/flat-literals.ts +51 -0
  184. package/src/prover/smt/solver/goal.ts +138 -0
  185. package/src/prover/smt/solver/hash.ts +173 -0
  186. package/src/prover/smt/solver/hashtable.ts +166 -0
  187. package/src/prover/smt/solver/internalizer.ts +1381 -0
  188. package/src/prover/smt/solver/lbool.ts +5 -0
  189. package/src/prover/smt/solver/literal.ts +24 -0
  190. package/src/prover/smt/solver/lp/bound-propagator.ts +391 -0
  191. package/src/prover/smt/solver/lp/constraints.ts +78 -0
  192. package/src/prover/smt/solver/lp/containers.ts +296 -0
  193. package/src/prover/smt/solver/lp/core-solver.ts +504 -0
  194. package/src/prover/smt/solver/lp/cross-nested.ts +224 -0
  195. package/src/prover/smt/solver/lp/dep-intervals.ts +642 -0
  196. package/src/prover/smt/solver/lp/dependency.ts +51 -0
  197. package/src/prover/smt/solver/lp/dioph-eq.ts +1181 -0
  198. package/src/prover/smt/solver/lp/explanation.ts +46 -0
  199. package/src/prover/smt/solver/lp/gomory.ts +255 -0
  200. package/src/prover/smt/solver/lp/hnf-cutter.ts +125 -0
  201. package/src/prover/smt/solver/lp/hnf.ts +281 -0
  202. package/src/prover/smt/solver/lp/int-cube.ts +295 -0
  203. package/src/prover/smt/solver/lp/int-solver.ts +514 -0
  204. package/src/prover/smt/solver/lp/lar-solver.ts +816 -0
  205. package/src/prover/smt/solver/lp/lar-term.ts +62 -0
  206. package/src/prover/smt/solver/lp/lp-settings.ts +91 -0
  207. package/src/prover/smt/solver/lp/maximize-term.ts +347 -0
  208. package/src/prover/smt/solver/lp/nex-creator.ts +381 -0
  209. package/src/prover/smt/solver/lp/nex.ts +120 -0
  210. package/src/prover/smt/solver/lp/nla-backoff.ts +43 -0
  211. package/src/prover/smt/solver/lp/nla-basics.ts +398 -0
  212. package/src/prover/smt/solver/lp/nla-core.ts +968 -0
  213. package/src/prover/smt/solver/lp/nla-divisions.ts +332 -0
  214. package/src/prover/smt/solver/lp/nla-emonics.ts +373 -0
  215. package/src/prover/smt/solver/lp/nla-factorization.ts +30 -0
  216. package/src/prover/smt/solver/lp/nla-grobner.ts +904 -0
  217. package/src/prover/smt/solver/lp/nla-horner.ts +126 -0
  218. package/src/prover/smt/solver/lp/nla-intervals.ts +265 -0
  219. package/src/prover/smt/solver/lp/nla-monomial-bounds.ts +715 -0
  220. package/src/prover/smt/solver/lp/nla-monotone.ts +59 -0
  221. package/src/prover/smt/solver/lp/nla-order.ts +307 -0
  222. package/src/prover/smt/solver/lp/nla-patcher.ts +112 -0
  223. package/src/prover/smt/solver/lp/nla-tangents.ts +251 -0
  224. package/src/prover/smt/solver/lp/nla-throttle.ts +85 -0
  225. package/src/prover/smt/solver/lp/nla-types.ts +124 -0
  226. package/src/prover/smt/solver/lp/nla-var-eqs.ts +141 -0
  227. package/src/prover/smt/solver/lp/nra-solver.ts +440 -0
  228. package/src/prover/smt/solver/lp/numeric-pair.ts +65 -0
  229. package/src/prover/smt/solver/lp/pdd-interval.ts +31 -0
  230. package/src/prover/smt/solver/lp/pdd-simplifier.ts +184 -0
  231. package/src/prover/smt/solver/lp/pdd-solver.ts +408 -0
  232. package/src/prover/smt/solver/lp/pdd.ts +971 -0
  233. package/src/prover/smt/solver/lp/random-updater.ts +138 -0
  234. package/src/prover/smt/solver/lp/static-matrix.ts +246 -0
  235. package/src/prover/smt/solver/lp/union-find.ts +96 -0
  236. package/src/prover/smt/solver/mam-compiler.ts +847 -0
  237. package/src/prover/smt/solver/mam-interpreter.ts +400 -0
  238. package/src/prover/smt/solver/maximize-ac-sharing.ts +118 -0
  239. package/src/prover/smt/solver/model-checker.ts +347 -0
  240. package/src/prover/smt/solver/model-evaluator.ts +262 -0
  241. package/src/prover/smt/solver/model-finder.ts +155 -0
  242. package/src/prover/smt/solver/model-generator.ts +97 -0
  243. package/src/prover/smt/solver/model-macro-solver.ts +728 -0
  244. package/src/prover/smt/solver/nlsat/algebraic.ts +1161 -0
  245. package/src/prover/smt/solver/nlsat/atoms.ts +238 -0
  246. package/src/prover/smt/solver/nlsat/evaluator.ts +303 -0
  247. package/src/prover/smt/solver/nlsat/explain.ts +607 -0
  248. package/src/prover/smt/solver/nlsat/interval-set.ts +351 -0
  249. package/src/prover/smt/solver/nlsat/levelwise.ts +737 -0
  250. package/src/prover/smt/solver/nlsat/mpbq.ts +161 -0
  251. package/src/prover/smt/solver/nlsat/polynomial.ts +1722 -0
  252. package/src/prover/smt/solver/nlsat/solver.ts +911 -0
  253. package/src/prover/smt/solver/nlsat/types.ts +43 -0
  254. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +648 -0
  255. package/src/prover/smt/solver/nlsat/upolynomial.ts +996 -0
  256. package/src/prover/smt/solver/nnf.ts +469 -0
  257. package/src/prover/smt/solver/pattern-inference.ts +351 -0
  258. package/src/prover/smt/solver/poly-rewriter.ts +477 -0
  259. package/src/prover/smt/solver/propagate-values.ts +83 -0
  260. package/src/prover/smt/solver/proto-model.ts +551 -0
  261. package/src/prover/smt/solver/pull-quant.ts +139 -0
  262. package/src/prover/smt/solver/qe-lite-der.ts +526 -0
  263. package/src/prover/smt/solver/qe-lite-fm.ts +576 -0
  264. package/src/prover/smt/solver/qe-lite.ts +381 -0
  265. package/src/prover/smt/solver/qi-queue.ts +362 -0
  266. package/src/prover/smt/solver/quant-tactics.ts +117 -0
  267. package/src/prover/smt/solver/quantifier-analyzer.ts +562 -0
  268. package/src/prover/smt/solver/quantifier-manager.ts +186 -0
  269. package/src/prover/smt/solver/random-gen.ts +10 -0
  270. package/src/prover/smt/solver/rational.ts +165 -0
  271. package/src/prover/smt/solver/ref-vector.ts +62 -0
  272. package/src/prover/smt/solver/relevancy.ts +247 -0
  273. package/src/prover/smt/solver/rewriter-tpl.ts +1159 -0
  274. package/src/prover/smt/solver/rewriter.ts +843 -0
  275. package/src/prover/smt/solver/rlimit.ts +79 -0
  276. package/src/prover/smt/solver/smtlib-parser.ts +526 -0
  277. package/src/prover/smt/solver/solver.ts +71 -0
  278. package/src/prover/smt/solver/sort.ts +35 -0
  279. package/src/prover/smt/solver/sticky-generations.ts +69 -0
  280. package/src/prover/smt/solver/theory-lra-axioms.ts +340 -0
  281. package/src/prover/smt/solver/theory-lra-bounds.ts +226 -0
  282. package/src/prover/smt/solver/theory-lra-final-check.ts +252 -0
  283. package/src/prover/smt/solver/theory-lra-internalize.ts +476 -0
  284. package/src/prover/smt/solver/theory-lra-model.ts +243 -0
  285. package/src/prover/smt/solver/theory-lra-propagate.ts +405 -0
  286. package/src/prover/smt/solver/theory-lra-state.ts +43 -0
  287. package/src/prover/smt/solver/theory-lra.ts +56 -0
  288. package/src/prover/smt/solver/var-subst.ts +258 -0
  289. package/src/prover/smt/solver/z3-license.txt +10 -0
  290. package/src/prover/smt/table.ts +170 -0
  291. package/src/prover/tlapm/cache.ts +236 -0
  292. package/src/prover/tlapm/ocaml-marshal.ts +166 -0
  293. package/src/prover/tlapm/tlapm.ts +96 -0
  294. package/src/prover/tlaps-module.ts +510 -0
  295. package/src/prover/verdict.ts +13 -0
  296. package/src/prover/zenon/LICENSE +32 -0
  297. package/src/prover/zenon/check/check.ts +105 -0
  298. package/src/prover/zenon/check/definitions.ts +144 -0
  299. package/src/prover/zenon/check/equality.ts +182 -0
  300. package/src/prover/zenon/check/functions.ts +62 -0
  301. package/src/prover/zenon/check/keys.ts +125 -0
  302. package/src/prover/zenon/check/propositional.ts +104 -0
  303. package/src/prover/zenon/check/records.ts +188 -0
  304. package/src/prover/zenon/check/relations.ts +121 -0
  305. package/src/prover/zenon/check/rewrites.ts +224 -0
  306. package/src/prover/zenon/check/sets.ts +302 -0
  307. package/src/prover/zenon/check/terms.ts +127 -0
  308. package/src/prover/zenon/check/tla.ts +126 -0
  309. package/src/prover/zenon/decide.ts +107 -0
  310. package/src/prover/zenon/encode.ts +378 -0
  311. package/src/prover/zenon/eqrel.ts +300 -0
  312. package/src/prover/zenon/equality-rules.ts +435 -0
  313. package/src/prover/zenon/expr.ts +551 -0
  314. package/src/prover/zenon/index-table.ts +350 -0
  315. package/src/prover/zenon/isar-case.ts +513 -0
  316. package/src/prover/zenon/isar.ts +1249 -0
  317. package/src/prover/zenon/limits.ts +15 -0
  318. package/src/prover/zenon/llproof.ts +173 -0
  319. package/src/prover/zenon/mltoll.ts +1566 -0
  320. package/src/prover/zenon/node.ts +297 -0
  321. package/src/prover/zenon/ocaml.ts +169 -0
  322. package/src/prover/zenon/parse.ts +247 -0
  323. package/src/prover/zenon/phrase.ts +191 -0
  324. package/src/prover/zenon/proof.ts +198 -0
  325. package/src/prover/zenon/propositional-rules.ts +387 -0
  326. package/src/prover/zenon/rules.ts +94 -0
  327. package/src/prover/zenon/search.ts +288 -0
  328. package/src/prover/zenon/tla/functions.ts +151 -0
  329. package/src/prover/zenon/tla/llproof.ts +480 -0
  330. package/src/prover/zenon/tla/records.ts +225 -0
  331. package/src/prover/zenon/tla/rewrites.ts +447 -0
  332. package/src/prover/zenon/tla/sets.ts +304 -0
  333. package/src/prover/zenon/tla/terms.ts +162 -0
  334. package/src/prover/zenon/tla/tla.ts +506 -0
  335. package/src/randomization.ts +39 -27
  336. package/src/resolve.ts +1474 -426
  337. package/src/runtime.ts +25 -7
  338. package/src/sany/builtins.ts +147 -0
  339. package/src/sany/generator.ts +3111 -0
  340. package/src/sany/levels.ts +1205 -0
  341. package/src/sany/lexer.ts +544 -0
  342. package/src/sany/linter.ts +122 -0
  343. package/src/sany/modules.ts +1398 -0
  344. package/src/sany/nodes.ts +463 -0
  345. package/src/sany/parse-error.ts +2161 -0
  346. package/src/sany/report.ts +355 -0
  347. package/src/sany/selectors.ts +736 -0
  348. package/src/sany/source.ts +247 -0
  349. package/src/sany/xml.ts +1016 -0
  350. package/src/search.ts +969 -0
  351. package/src/spec-description.ts +66 -29
  352. package/src/{standard-levels.ts → standard-definitions.ts} +118 -2
  353. package/src/standard-modules.ts +215 -164
  354. package/src/state-graph.ts +181 -0
  355. package/src/subexpressions.ts +231 -171
  356. package/src/substitution-levels.ts +40 -19
  357. package/src/successors.ts +253 -125
  358. package/src/symmetry.ts +194 -54
  359. package/src/tableau.ts +60 -32
  360. package/src/tlc/fingerprint.ts +214 -0
  361. package/src/{tlc-modules.ts → tlc/jar-data.ts} +4 -0
  362. package/src/tlc/messages.ts +441 -0
  363. package/src/{tlc-order.ts → tlc/order.ts} +84 -16
  364. package/src/{tlc-random.ts → tlc/random.ts} +30 -189
  365. package/src/tlc/replay.ts +659 -0
  366. package/src/{tlc-summary.ts → tlc/summary.ts} +20 -5
  367. package/src/{tlc-module.ts → tlc/tlc-operators.ts} +59 -50
  368. package/src/{tlc-ext.ts → tlc/tlcext-operators.ts} +63 -45
  369. package/src/tlc/version.ts +19 -0
  370. package/src/transfer.ts +44 -32
  371. package/src/values.ts +843 -241
  372. package/src/worker.ts +62 -0
  373. package/dist/parallel.cjs +0 -12
  374. package/dist/parallel.js +0 -12
  375. package/dist/run-cli.cjs +0 -28
  376. package/dist/run-cli.js +0 -28
  377. package/src/canonical.ts +0 -39
  378. package/src/cli-options.ts +0 -58
  379. package/src/obligation-expression.ts +0 -1060
  380. package/src/obligation-module.ts +0 -1042
  381. package/src/run-cli.ts +0 -478
package/src/evaluate.ts CHANGED
@@ -1,54 +1,74 @@
1
- import type {
2
- Bound,
3
- BoundPattern,
4
- DecimalExpression,
5
- Definition,
6
- Expression,
7
- FunctionDefinition,
8
- NumberExpression,
9
- OperatorParam,
10
- RecordField,
11
- SourceRange,
1
+ import {
2
+ getChildren,
3
+ isLocallyResolved,
4
+ type Bound,
5
+ type BoundPattern,
6
+ type DecimalExpression,
7
+ type Definition,
8
+ type Expression,
9
+ type FunctionDefinition,
10
+ type NumberExpression,
11
+ type OperatorParam,
12
+ type RecordField,
13
+ type SourceRange,
12
14
  } from "./ast";
13
15
  import { getKindString } from "./builtins";
14
- import { TlaEvaluationError } from "./errors";
16
+ import { isStackOverflow, TlaEvaluationError, TlaUnassignedError } from "./errors";
15
17
  import { EXIT_STATUS, setExitCode } from "./exit-codes";
16
18
  import { generateEvaluator } from "./codegen";
19
+ import { MESSAGE_CODE } from "./tlc/messages";
17
20
  import type { CheckerRuntime } from "./runtime";
18
21
  import { getReadVariables } from "./dependencies";
19
22
  import { contextualApplications, mapChildren, substitutedExpressions } from "./instances";
20
- import { isEnabled } from "./successors";
23
+ import { prettyPrint } from "./pretty-print";
24
+ import { getReadLocals, isEnabled } from "./successors";
21
25
  import {
22
26
  applyFunction,
27
+ describeMissingArgument,
23
28
  combineHash,
24
29
  compareValues,
25
30
  createFunction,
31
+ createNonIntegerKeyError,
32
+ createRecord,
26
33
  createEnumeratedSet,
27
34
  createSortedFunction,
35
+ createSortedRecord,
28
36
  createSortedSet,
29
37
  createWrittenRecord,
30
38
  createTuple,
31
39
  formatValue,
40
+ getCardinality,
32
41
  getDomain,
33
42
  getFunctionDomain,
34
43
  getIntervalElements,
44
+ getLazySubsets,
45
+ getStreamedElements,
46
+ getFunctionClass,
35
47
  getSequenceElements,
36
48
  getValueHash,
49
+ isElementOf,
37
50
  isEnumerable,
38
51
  isFunctionValue,
39
52
  isOverriddenSet,
40
53
  isSameValue,
41
54
  markLambdaFunction,
55
+ isReducibleSet,
42
56
  isSetValue,
43
- MAXIMUM_INTEGER,
44
- MINIMUM_INTEGER,
57
+ isSettledValue,
58
+ isTlcInteger,
59
+ toFiniteFunction,
45
60
  toFiniteSet,
46
61
  updateFunction,
47
62
  valuesEqual,
63
+ type FilteredSetValue,
48
64
  type LazyFunctionSource,
49
65
  type LazyFunctionValue,
66
+ type ObjectValue,
50
67
  type Value,
68
+ markNormalized,
69
+ setTrace,
51
70
  } from "./values";
71
+ import type { TlcVersion } from "./tlc/version";
52
72
 
53
73
  export type State = (Value | undefined)[];
54
74
 
@@ -71,6 +91,8 @@ export interface Builtin {
71
91
  evaluateUnary: ((value: Value) => Value) | undefined;
72
92
  evaluateBinary: ((left: Value, right: Value) => Value) | undefined;
73
93
  isStateLevel?: boolean;
94
+ // Whether TLC takes an application for a constant one although its value depends on the state.
95
+ isLevelConstant?: boolean;
74
96
  isLazy?: boolean;
75
97
  }
76
98
 
@@ -91,6 +113,9 @@ export interface Thunk {
91
113
  state: State | undefined;
92
114
  next: State | undefined;
93
115
  cache: Value | undefined;
116
+ // Whether the expression may build a set that streams until TLC caches it, so that the thunk
117
+ // caches only a settled value.
118
+ isStreamed: boolean;
94
119
  }
95
120
 
96
121
  type Binding = { kind: "Value"; value: Value } | Thunk | { kind: "Operator"; operator: Operator };
@@ -107,18 +132,89 @@ export interface Environment {
107
132
  builtins: Map<string, Builtin>;
108
133
  constants: Map<string, Value>;
109
134
  substitutions: Map<string, string>;
135
+ // The name SANY gives each definition that a named instance such as `M == INSTANCE Module`
136
+ // copies, such as M!Op, by the key of the copy.
137
+ instanceNames: Map<string, string>;
110
138
  variables: string[];
111
139
  variableIndex: Map<string, number>;
112
140
  definitionValues: Map<Definition, Value>;
113
141
  constantLevels: Map<Definition, boolean>;
142
+ // The definitions an INSTANCE copies from a module that declares constants or variables. SANY
143
+ // wraps the body of each in its substitutions.
144
+ substitutedDefinitions: Set<Definition>;
114
145
  evaluators: WeakMap<Expression, Evaluator>;
146
+ // The expressions being evaluated, outermost first, when the environment replays an error to
147
+ // find where it occurred, as TLC's CallStackTool does.
148
+ callStack?: CallStack;
149
+ }
150
+
151
+ export interface CallStack {
152
+ expressions: Expression[];
153
+ // TLC stops popping the stack once an evaluation fails, so it keeps where the failure occurred.
154
+ isFrozen: boolean;
155
+ // The expression that built each value of the replay that TLC's CallStackTool gives a source.
156
+ sources: WeakMap<ObjectValue, Expression>;
157
+ // The value each expression of the replay last evaluated to.
158
+ values: WeakMap<Expression, Value>;
159
+ // The expression each failure last left, which tells a failure of an operand from one of the
160
+ // method that computes the operator.
161
+ failures: WeakMap<Error, Expression>;
162
+ // The failure of a value with a source, which TLC raises as a FingerprintException.
163
+ fingerprint?: FingerprintFailure;
115
164
  }
116
165
 
166
+ export interface FingerprintFailure {
167
+ // The sources of the values whose methods failed, outermost first.
168
+ sources: Expression[];
169
+ // The message of the error the innermost one raised.
170
+ reason: string;
171
+ }
172
+
173
+ // The operators of Tool#evalAppl whose value TLC's CallStackTool gives a source.
174
+ const SOURCED_OPERATORS = new Set(["SUBSET", "UNION", "DOMAIN", "\\cup", "\\cap", "\\"]);
175
+
176
+ // CallStackTool copies the SetPredValue, FcnLambdaValue and OpLambdaValue that an evaluation
177
+ // returns without their source, and a function TLC builds from a FcnLambdaValue has none.
178
+ const SOURCED_KINDS = new Set<Expression["kind"]>([
179
+ "SetEnumeration",
180
+ "SetFilter",
181
+ "SetMap",
182
+ "Tuple",
183
+ "FunctionSet",
184
+ "Record",
185
+ "RecordSet",
186
+ "Product",
187
+ ]);
188
+
189
+ const isSourced = (expression: Expression) =>
190
+ SOURCED_KINDS.has(expression.kind) ||
191
+ (expression.kind === "Apply" && SOURCED_OPERATORS.has(expression.operator));
192
+
193
+ // The argument whose method Tool#evalAppl calls to compute an operator, as with S.member(e) for
194
+ // 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.
195
+ const getReceiver = (expression: Expression, values: CallStack["values"]) => {
196
+ if (expression.kind === "FunctionApplication" || expression.kind === "Except") {
197
+ return expression.function;
198
+ }
199
+ if (expression.kind !== "Apply" || expression.args.length !== 2) return undefined;
200
+ if (["\\subseteq", "=", "#", "\\"].includes(expression.operator)) return expression.args[0];
201
+ if (expression.operator === "\\cap" || expression.operator === "\\cup") {
202
+ const left = values.get(expression.args[0]);
203
+ return left !== undefined && isReducibleSet(left) ? expression.args[0] : expression.args[1];
204
+ }
205
+ return expression.operator === "\\in" || expression.operator === "\\notin"
206
+ ? expression.args[1]
207
+ : undefined;
208
+ };
209
+
117
210
  export interface Context {
118
211
  environment: Environment;
119
212
  scope: Scope | undefined;
120
213
  state: State | undefined;
121
214
  next: State | undefined;
215
+ // EvalControl.KeepLazy, which Tool#evalAppl sets to evaluate the function it applies and which
216
+ // the evaluation passes on, so that a function constructor within builds a FcnLambdaValue.
217
+ isKeepLazy?: boolean;
122
218
  }
123
219
 
124
220
  export type Evaluator = (context: Context) => Value;
@@ -149,14 +245,20 @@ export const describeRange = (expression: Expression) => {
149
245
  return range ? formatRange(range) : describeLocation(expression);
150
246
  };
151
247
 
152
- export const getConditionError = (expression: Expression, value: Value) =>
248
+ // SANY prints a numeral as written and any other expression by its location.
249
+ export const describeNode = (expression: Expression) =>
250
+ expression.kind === "Number"
251
+ ? (expression.text ?? String(expression.value))
252
+ : describeRange(expression);
253
+
254
+ export const createConditionError = (expression: Expression, value: Value) =>
153
255
  new TlaEvaluationError(
154
256
  `A non-boolean expression (${getKindString(value)}) was used as the condition of an IF.\n${describeRange(expression)}`,
155
257
  );
156
258
 
157
- // TLC parses an infix chain of /\ as nested binary conjunctions and a bulleted list as one
158
- // conjunction list, and it words the error differently for each.
159
- export const getConjunctError = (
259
+ // TLC parses an infix chain of /\ or \/ as nested binary junctions and a bulleted list as one
260
+ // junction list, and it words the error differently for each.
261
+ export const createJunctionError = (
160
262
  expression: Expression & { kind: "And" | "Or" },
161
263
  index: number,
162
264
  value: Value,
@@ -166,22 +268,48 @@ export const getConjunctError = (
166
268
  range?.start.line === expression.location.line &&
167
269
  range.start.column === expression.location.column;
168
270
  if (isBulleted || !range) {
169
- const operand = expression.operands[index];
170
- // SANY prints a numeral as its value instead of its location.
171
- const description = operand.kind === "Number" ? String(operand.value) : describeRange(operand);
172
271
  return new TlaEvaluationError(
173
- `A non-boolean expression (${getKindString(value)}) was used as a formula in a conjunction.\n${description}`,
272
+ `A non-boolean expression (${getKindString(value)}) was used as a formula in a ${expression.kind === "And" ? "conjunction" : "disjunction"}.\n${describeNode(expression.operands[index])}`,
174
273
  );
175
274
  }
176
- const end = expression.operands[Math.max(index, 1)].location.range?.end ?? range.end;
275
+ const end = expression.prefixEnds?.[Math.max(index, 1) - 1] ?? range.end;
177
276
  return new TlaEvaluationError(
178
- `Attempted to evaluate an expression of form P /\\ Q when ${index === 0 ? "P" : "Q"} was\n${getKindString(value)}.\n${describeRange({ ...expression, location: { ...expression.location, range: { ...range, end } } })}`,
277
+ `Attempted to evaluate an expression of form P ${expression.kind === "And" ? "/\\" : "\\/"} Q when ${index === 0 ? "P" : "Q"} was\n${getKindString(value)}.\n${describeRange({ ...expression, location: { ...expression.location, range: { ...range, end } } })}`,
179
278
  );
180
279
  };
181
280
 
182
- export const getFieldError =
183
- (expression: Expression & { kind: "FieldAccess" }) => (record: Value) =>
184
- `Attempted to select nonexistent field "${expression.field}" from the record\n${formatValue(record)}\n${describeRange(expression)}`;
281
+ // TLC selects a field of a record, and of another function from the function it converts it to,
282
+ // which for a tuple keeps its domain as an interval.
283
+ export const getFieldSelector = (expression: Expression & { kind: "FieldAccess" }) => {
284
+ const field = expression.field;
285
+ const describeMissing = (record: Value) =>
286
+ `Attempted to select nonexistent field "${field}" from the record\n${formatValue(record)}\n${describeRange(expression)}`;
287
+ const describeNotInDomain = (functionValue: Value) =>
288
+ `Attempted to apply function:\n${prettyPrint(formatValue(functionValue))}\nto argument "${field}", which is not in the domain of the function.`;
289
+ return (value: Value) => {
290
+ if (!isFunctionValue(value)) {
291
+ throw new TlaEvaluationError(
292
+ `Attempted to select field "${field}" from a non-record value ${prettyPrint(formatValue(value))}\n${describeRange(expression)}`,
293
+ );
294
+ }
295
+ const functionClass = getFunctionClass(value);
296
+ if (functionClass === "tuple") throw createNonIntegerKeyError(field);
297
+ // Only TLC's RecordValue names the field it lacks. Any other function, such as a FcnRcdValue
298
+ // whose keys are strings, reports an argument outside its domain.
299
+ return applyFunction(
300
+ value,
301
+ field,
302
+ functionClass === "record" ? describeMissing : describeNotInDomain,
303
+ );
304
+ };
305
+ };
306
+
307
+ // TLC 1.7.4 words what a tuple or a record lacks differently.
308
+ export const getMissingArgumentDescriber = (version: TlcVersion | undefined) =>
309
+ version === "1.7.4"
310
+ ? (functionValue: Value, argument: Value) =>
311
+ describeMissingArgument(functionValue, argument, version)
312
+ : undefined;
185
313
 
186
314
  export const getDomainOperator = (expression: Expression) => (value: Value) => {
187
315
  if (!isFunctionValue(value)) {
@@ -219,6 +347,27 @@ export const createBigNumberError = (expression: NumberExpression) =>
219
347
  EXIT_STATUS.error,
220
348
  );
221
349
 
350
+ // TLC's Tool#evalAppl fails to look up a variable the state doesn't assign.
351
+ export const createUnassignedError = (name: string, expression: Expression) =>
352
+ new TlaUnassignedError(
353
+ `In evaluation, the identifier ${name} is either undefined or not an operator.\n${describeRange(expression)}`,
354
+ name,
355
+ );
356
+
357
+ // TLC's Tool#enabled reads the subscript of <<A>>_v in the successor as a state of its own, and
358
+ // names the fairness condition when A leaves a variable of v unassigned, unlike TLC 1.7.4's.
359
+ export const toUnspecifiedSubscriptError = (error: unknown, version: TlcVersion | undefined) =>
360
+ error instanceof TlaUnassignedError && version !== "1.7.4"
361
+ ? new TlaEvaluationError(
362
+ `The action formula A appearing in a WF_v(A) or SF_v(A) operator does not specify the primed value of the variable ${error.variable} occurring in the state formula v.\n`,
363
+ )
364
+ : error;
365
+
366
+ export const createPrimeOutsideActionError = (expression: Expression) =>
367
+ new TlaEvaluationError(
368
+ `A primed expression appears outside an action at ${describeLocation(expression)}`,
369
+ );
370
+
222
371
  export const lookupScope = (scope: Scope | undefined, name: string): Binding | undefined => {
223
372
  for (let current = scope; current; current = current.parent) {
224
373
  if (current.name === name) return current.binding;
@@ -246,11 +395,31 @@ const bindPattern = (scope: Scope | undefined, pattern: BoundPattern, value: Val
246
395
  );
247
396
  };
248
397
 
398
+ // Tool#evalAppl checks that it applies a function before it evaluates the argument.
399
+ export const expectFunction = (value: Value, application: Expression) => {
400
+ if (isFunctionValue(value)) return value;
401
+ throw new TlaEvaluationError(
402
+ `A non-function (${getKindString(value)}) was applied as a function.\n${describeRange(application)}`,
403
+ );
404
+ };
405
+
406
+ export const toKeepLazyContext = (context: Context): Context =>
407
+ context.isKeepLazy
408
+ ? context
409
+ : {
410
+ environment: context.environment,
411
+ scope: context.scope,
412
+ state: context.state,
413
+ next: context.next,
414
+ isKeepLazy: true,
415
+ };
416
+
249
417
  const withScope = (context: Context, scope: Scope | undefined): Context => ({
250
418
  environment: context.environment,
251
419
  scope,
252
420
  state: context.state,
253
421
  next: context.next,
422
+ isKeepLazy: context.isKeepLazy,
254
423
  });
255
424
 
256
425
  export const expectBoolean = (value: Value, description: string) => {
@@ -262,104 +431,29 @@ export const expectBoolean = (value: Value, description: string) => {
262
431
  return value;
263
432
  };
264
433
 
265
- export const getChildren = (expression: Expression): Expression[] => {
266
- switch (expression.kind) {
267
- case "Number":
268
- case "Decimal":
269
- case "String":
270
- case "Identifier":
271
- case "OperatorReference":
272
- case "ExceptAt":
273
- return [];
274
- case "Apply":
275
- return expression.args;
276
- case "Lambda":
277
- return [expression.body];
278
- case "And":
279
- case "Or":
280
- return expression.operands;
281
- case "Prime":
282
- case "Unchanged":
283
- case "Enabled":
284
- case "Always":
285
- case "Eventually":
286
- return [expression.expression];
287
- case "If":
288
- return [expression.condition, expression.consequent, expression.alternative];
289
- case "Case":
290
- return [
291
- ...expression.arms.flatMap((arm) => [arm.condition, arm.body]),
292
- ...(expression.other ? [expression.other] : []),
293
- ];
294
- case "Let":
295
- return [
296
- ...expression.definitions.flatMap((definition) =>
297
- definition.kind === "Function"
298
- ? [...definition.bounds.map((bound) => bound.set), definition.body]
299
- : [definition.body],
300
- ),
301
- expression.body,
302
- ];
303
- case "Forall":
304
- case "Exists":
305
- return [...expression.bounds.map((bound) => bound.set), expression.body];
306
- case "UnboundedQuantifier":
307
- return [expression.body];
308
- case "Choose":
309
- return [...(expression.set ? [expression.set] : []), expression.body];
310
- case "SetEnumeration":
311
- case "Tuple":
312
- return expression.elements;
313
- case "SetFilter":
314
- return [expression.bound.set, expression.predicate];
315
- case "SetMap":
316
- return [expression.expression, ...expression.bounds.map((bound) => bound.set)];
317
- case "FunctionConstruction":
318
- return [...expression.bounds.map((bound) => bound.set), expression.body];
319
- case "FunctionSet":
320
- return [expression.domain, expression.range];
321
- case "Record":
322
- case "RecordSet":
323
- return expression.fields.map((field) => field.value);
324
- case "Except":
325
- return [
326
- expression.function,
327
- ...expression.updates.flatMap((update) => [
328
- ...update.path.flatMap((step) => (step.kind === "Index" ? step.args : [])),
329
- update.value,
330
- ]),
331
- ];
332
- case "FunctionApplication":
333
- return [expression.function, ...expression.args];
334
- case "FieldAccess":
335
- return [expression.record];
336
- case "Product":
337
- return expression.factors;
338
- case "BoxAction":
339
- case "AngleAction":
340
- return [expression.action, expression.subscript];
341
- case "WeakFairness":
342
- case "StrongFairness":
343
- return [expression.subscript, expression.action];
344
- case "Label":
345
- return [expression.body];
346
- case "Subexpression":
347
- return expression.selectors.flatMap((selector) => ("args" in selector ? selector.args : []));
348
- }
349
- };
350
-
351
- export const isLocallyResolved = (expression: Expression) =>
352
- (expression.kind === "Identifier" || expression.kind === "Apply") &&
353
- expression.resolution?.kind === "Local";
354
-
355
434
  export const getDefinition = (name: string, environment: Environment) =>
356
435
  environment.definitions.get(environment.substitutions.get(name) ?? name);
357
436
 
358
- const isStateDependent = (expression: Expression, environment: Environment): boolean => {
437
+ // TLC bounds the level of every action and temporal operator above constant, whatever its operands.
438
+ const NONCONSTANT_KINDS = new Set<Expression["kind"]>([
439
+ "Prime",
440
+ "Unchanged",
441
+ "Enabled",
442
+ "BoxAction",
443
+ "AngleAction",
444
+ "Always",
445
+ "Eventually",
446
+ "WeakFairness",
447
+ "StrongFairness",
448
+ ]);
449
+
450
+ const NONCONSTANT_OPERATORS = new Set(["~>", "-+->", "\\cdot"]);
451
+
452
+ const isNonconstant = (expression: Expression, environment: Environment): boolean => {
359
453
  if (
360
- expression.kind === "Prime" ||
361
- expression.kind === "Unchanged" ||
362
- expression.kind === "Enabled"
454
+ NONCONSTANT_KINDS.has(expression.kind) ||
455
+ (expression.kind === "UnboundedQuantifier" && expression.isTemporal === true) ||
456
+ (expression.kind === "Apply" && NONCONSTANT_OPERATORS.has(expression.operator))
363
457
  ) {
364
458
  return true;
365
459
  }
@@ -376,7 +470,7 @@ const isStateDependent = (expression: Expression, environment: Environment): boo
376
470
  if (definition && !environment.constants.has(name) && !isConstantLevel(definition, environment))
377
471
  return true;
378
472
  }
379
- return getChildren(expression).some((child) => isStateDependent(child, environment));
473
+ return getChildren(expression).some((child) => isNonconstant(child, environment));
380
474
  };
381
475
 
382
476
  export const isConstantLevel = (definition: Definition, environment: Environment): boolean => {
@@ -384,9 +478,9 @@ export const isConstantLevel = (definition: Definition, environment: Environment
384
478
  if (cached !== undefined) return cached;
385
479
  environment.constantLevels.set(definition, true);
386
480
  const isConstant =
387
- !isStateDependent(definition.body, environment) &&
481
+ !isNonconstant(definition.body, environment) &&
388
482
  (definition.kind === "Operator" ||
389
- !definition.bounds.some((bound) => isStateDependent(bound.set, environment)));
483
+ !definition.bounds.some((bound) => isNonconstant(bound.set, environment)));
390
484
  environment.constantLevels.set(definition, isConstant);
391
485
  return isConstant;
392
486
  };
@@ -409,44 +503,96 @@ const getBoundExplanation = (set: Value, text: string) => {
409
503
 
410
504
  // TLC enumerates every set except the ones it implements in Java, so any other set fails as its own
411
505
  // class does.
412
- export const getEnumeratedElements = (set: Value, expression: Expression) => {
506
+ const checkEnumerable = (set: Value, expression: Expression, version: TlcVersion) => {
413
507
  if (!isSetValue(set) || isOverriddenSet(set)) {
414
508
  const text = formatValue(set);
415
- const explanation = getBoundExplanation(set, text);
509
+ // TLC 1.7.4 doesn't explain why it can't enumerate a set.
510
+ const explanation = version === "1.7.4" ? undefined : getBoundExplanation(set, text);
416
511
  throw new TlaEvaluationError(
417
512
  explanation === undefined
418
- ? `TLC encountered a non-enumerable quantifier bound\n${text}.\n${describeRange(expression)}`
419
- : `TLC encountered the non-enumerable quantifier bound\n${text}\n${describeRange(expression)}\n${explanation}`,
513
+ ? `TLC encountered a non-enumerable quantifier bound\n${text}.\n${describeNode(expression)}`
514
+ : `TLC encountered the non-enumerable quantifier bound\n${text}\n${describeNode(expression)}\n${explanation}`,
420
515
  );
421
516
  }
422
- return typeof set === "object" && set.kind === "Interval"
423
- ? getIntervalElements(set)
424
- : toFiniteSet(set).elements;
425
517
  };
426
518
 
427
- export const forEachBinding = (
519
+ const getEnumeratedElements = (set: Value, expression: Expression, version: TlcVersion) => {
520
+ checkEnumerable(set, expression, version);
521
+ if (typeof set === "object" && set.kind === "Interval") return getIntervalElements(set);
522
+ return getLazySubsets(set) ?? toFiniteSet(set).elements;
523
+ };
524
+
525
+ // The elements Tool.contexts binds to the bound of a quantifier or a set map. TLC 1.7.4 streams a
526
+ // lazy set's elements, where later versions normalize the set first.
527
+ export const getContextElements = (set: Value, expression: Expression, version: TlcVersion) => {
528
+ if (version !== "1.7.4") return getEnumeratedElements(set, expression, version);
529
+ checkEnumerable(set, expression, version);
530
+ return getLazySubsets(set) ?? getStreamedElements(set);
531
+ };
532
+
533
+ // Like TLC, a quantifier keeps an interval as an interval, so that it can stop at the first witness
534
+ // in a large interval such as 1..2000000000 without listing it.
535
+ const getKeptInterval = (set: Value) => {
536
+ if (typeof set !== "object" || set.kind !== "Interval") return undefined;
537
+ getCardinality(set);
538
+ return set;
539
+ };
540
+
541
+ export const getQuantifierElements = (set: Value, expression: Expression, version: TlcVersion) =>
542
+ getKeptInterval(set) ?? getContextElements(set, expression, version);
543
+
544
+ // CHOOSE and a function constructor visit the elements of the normalized set.
545
+ const getNormalizedElements = (set: Value, expression: Expression, version: TlcVersion) =>
546
+ getKeptInterval(set) ?? getEnumeratedElements(set, expression, version);
547
+
548
+ const someElement = (
549
+ elements: ReturnType<typeof getQuantifierElements>,
550
+ visit: (element: Value) => boolean,
551
+ ) => {
552
+ if (Array.isArray(elements)) return elements.some(visit);
553
+ for (let element = elements.low; element <= elements.high; element++) {
554
+ if (visit(element)) return true;
555
+ }
556
+ return false;
557
+ };
558
+
559
+ export const getBoundElements = (bounds: Bound[], context: Context) =>
560
+ bounds.map((bound) =>
561
+ getQuantifierElements(
562
+ evaluate(bound.set, context),
563
+ bound.set,
564
+ context.environment.runtime.version,
565
+ ),
566
+ );
567
+
568
+ // Visits each binding of the bounds to the elements of their sets, until visit returns true.
569
+ export const forEachBoundElement = (
428
570
  bounds: Bound[],
429
- context: Context,
571
+ sets: ReturnType<typeof getBoundElements>,
572
+ scope: Scope | undefined,
430
573
  visit: (scope: Scope | undefined) => boolean,
431
574
  ): boolean => {
432
- const sets = bounds.map((bound) =>
433
- getEnumeratedElements(evaluate(bound.set, context), bound.set),
434
- );
435
- const visitBound = (index: number, scope: Scope | undefined): boolean => {
436
- if (index < 0) return visit(scope);
437
- return sets[index].some((element) =>
438
- visitBound(index - 1, bindPattern(scope, bounds[index].pattern, element)),
575
+ const visitBound = (index: number, bound: Scope | undefined): boolean => {
576
+ if (index < 0) return visit(bound);
577
+ return someElement(sets[index], (element) =>
578
+ visitBound(index - 1, bindPattern(bound, bounds[index].pattern, element)),
439
579
  );
440
580
  };
441
- return visitBound(bounds.length - 1, context.scope);
581
+ return visitBound(bounds.length - 1, scope);
442
582
  };
443
583
 
444
- export const getBoundsDomain = (bounds: Bound[], context: Context): Value => {
584
+ export const forEachBinding = (
585
+ bounds: Bound[],
586
+ context: Context,
587
+ visit: (scope: Scope | undefined) => boolean,
588
+ ) => forEachBoundElement(bounds, getBoundElements(bounds, context), context.scope, visit);
589
+
590
+ const getBoundsDomain = (bounds: Bound[], context: Context): Value => {
445
591
  const sets = bounds.map((bound) => evaluate(bound.set, context));
446
592
  return sets.length === 1 ? sets[0] : { kind: "ProductSet", factors: sets };
447
593
  };
448
594
 
449
- export const bindArgument = (bounds: Bound[], scope: Scope | undefined, argument: Value) => {
595
+ const bindArgument = (bounds: Bound[], scope: Scope | undefined, argument: Value) => {
450
596
  if (bounds.length === 1) return bindPattern(scope, bounds[0].pattern, argument);
451
597
  const components = getSequenceElements(argument) ?? [];
452
598
  return bounds.reduce<Scope | undefined>(
@@ -455,6 +601,84 @@ export const bindArgument = (bounds: Bound[], scope: Scope | undefined, argument
455
601
  );
456
602
  };
457
603
 
604
+ // The parameters, body and scope of each function a constructor or a definition keeps lazy, whose
605
+ // body TLC's getInitStates and getNextStates walk for an argument, as they do a FcnLambdaValue's.
606
+ interface LazyFunction {
607
+ value: LazyFunctionValue;
608
+ bounds: Bound[];
609
+ body: Expression;
610
+ scope: Scope | undefined;
611
+ }
612
+
613
+ // The function keeps its parameters, body and scope itself, since a WeakMap entry for each
614
+ // short-lived function makes every garbage collection slower.
615
+ interface KeptLazyFunctionValue extends LazyFunctionValue {
616
+ lambda: LazyFunction;
617
+ }
618
+
619
+ const isKeptLazyFunction = (value: Value): value is KeptLazyFunctionValue =>
620
+ typeof value === "object" && value.kind === "LazyFunction" && "lambda" in value;
621
+
622
+ const keepLambda = (lambda: LazyFunction) => Object.assign(lambda.value, { lambda });
623
+
624
+ export const getLazyFunction = (value: Value) =>
625
+ isKeptLazyFunction(value) ? value.lambda : undefined;
626
+
627
+ // Tool.getFcnContext: the scope of a lazy function's body for the arguments of an application. It
628
+ // ignores arguments beyond the parameters.
629
+ export const bindLazyArguments = (
630
+ lambda: LazyFunction,
631
+ expression: Expression & { kind: "FunctionApplication" },
632
+ context: Context,
633
+ ) => {
634
+ const value = lambda.value;
635
+ const args = expression.args.map((arg) => evaluate(arg, context));
636
+ const argument = args.length === 1 ? args[0] : createTuple(args);
637
+ const describeArgument = (ordinal: string, element: Value, problem: string) =>
638
+ `In applying the function\n${prettyPrint(formatValue(value))},\nthe ${ordinal} is:\n${prettyPrint(formatValue(element))}${problem}.\n${describeRange(expression.function)}`;
639
+ const bounds = lambda.bounds;
640
+ if (bounds.length === 1) {
641
+ if (!isElementOf(argument, value.domain)) {
642
+ throw new TlaEvaluationError(
643
+ describeArgument("first argument", argument, "which is not in its domain"),
644
+ );
645
+ }
646
+ return bindArgument(bounds, lambda.scope, argument);
647
+ }
648
+ const elements = getSequenceElements(argument);
649
+ const domains =
650
+ typeof value.domain === "object" && value.domain.kind === "ProductSet"
651
+ ? value.domain.factors
652
+ : [];
653
+ if (elements === undefined || elements.length < bounds.length) {
654
+ throw new TlaEvaluationError(
655
+ `Attempted to apply a function to an argument not in its domain.\n${describeRange(expression.function)}`,
656
+ );
657
+ }
658
+ bounds.forEach((bound, index) => {
659
+ const element = elements[index];
660
+ const ordinal = `argument number ${index + 1}`;
661
+ if (!isElementOf(element, domains[index])) {
662
+ throw new TlaEvaluationError(
663
+ describeArgument(
664
+ ordinal,
665
+ element,
666
+ `${bound.pattern.kind === "Name" ? "" : "\n"}which is not in its domain`,
667
+ ),
668
+ );
669
+ }
670
+ if (
671
+ bound.pattern.kind === "Tuple" &&
672
+ getSequenceElements(element)?.length !== bound.pattern.names.length
673
+ ) {
674
+ throw new TlaEvaluationError(
675
+ describeArgument(ordinal, element, "which does not match its formal parameter"),
676
+ );
677
+ }
678
+ });
679
+ return bindArgument(bounds, lambda.scope, createTuple(elements.slice(0, bounds.length)));
680
+ };
681
+
458
682
  // TLC prints a function it can't enumerate as its parameters and the location of its body. It
459
683
  // prints only the first name of a group such as `m, n \in S`.
460
684
  interface LazyFunctionTemplate {
@@ -533,6 +757,22 @@ const createLazyFunction = (
533
757
  return self;
534
758
  };
535
759
 
760
+ const definitionSources = new WeakMap<FunctionDefinition, Expression>();
761
+
762
+ // The function constructor of a definition, which SANY locates at the whole definition.
763
+ const getDefinitionSource = (definition: FunctionDefinition) => {
764
+ const cached = definitionSources.get(definition);
765
+ if (cached) return cached;
766
+ const source: Expression = {
767
+ kind: "FunctionConstruction",
768
+ bounds: definition.bounds,
769
+ body: definition.body,
770
+ location: definition.location,
771
+ };
772
+ definitionSources.set(definition, source);
773
+ return source;
774
+ };
775
+
536
776
  const createRecursiveFunction = (definition: FunctionDefinition, context: Context) => {
537
777
  const domain = getBoundsDomain(definition.bounds, context);
538
778
  const functionValue = createLazyFunction(
@@ -547,13 +787,44 @@ const createRecursiveFunction = (definition: FunctionDefinition, context: Contex
547
787
  ),
548
788
  getLazyFunctionSource(definition.bounds, definition.body, domain),
549
789
  );
790
+ keepLambda({
791
+ value: functionValue,
792
+ bounds: definition.bounds,
793
+ body: definition.body,
794
+ scope: bindValue(undefined, definition.name, functionValue),
795
+ });
550
796
  return definition.bounds.length === 1 ? markLambdaFunction(functionValue) : functionValue;
551
797
  };
552
798
 
553
- const evaluateDefinitionBody = (definition: Definition, context: Context) =>
554
- definition.kind === "Function"
799
+ // TLC computes a constant definition when it starts, without keeping a function it constructs
800
+ // lazy, so a function over an interval or an enumerated set is a FcnRcdValue.
801
+ const toStartupValue = (definition: Definition, value: Value): Value => {
802
+ if (typeof value !== "object" || getFunctionClass(value) !== "lambda") return value;
803
+ if (
804
+ definition.kind === "Operator" ||
805
+ definition.isSelfReferential ||
806
+ value.kind !== "LazyFunction" ||
807
+ !isReducibleSet(value.domain)
808
+ ) {
809
+ return value;
810
+ }
811
+ try {
812
+ const finite = toFiniteFunction(value);
813
+ return createSortedFunction(finite.domain, finite.range);
814
+ } catch (error) {
815
+ // TLC leaves a definition it fails to compute to evaluate where the spec uses it.
816
+ if (error instanceof TlaEvaluationError) return value;
817
+ throw error;
818
+ }
819
+ };
820
+
821
+ // TLC evaluates a function definition that isn't recursive as it does a function constructor.
822
+ const evaluateDefinitionBody = (definition: Definition, context: Context) => {
823
+ if (definition.kind !== "Function") return evaluate(definition.body, context);
824
+ return definition.isSelfReferential
555
825
  ? createRecursiveFunction(definition, context)
556
- : evaluate(definition.body, context);
826
+ : evaluate(getDefinitionSource(definition), context);
827
+ };
557
828
 
558
829
  const evaluateDefinitionValue = (definition: Definition, context: Context) => {
559
830
  const isConstant = isConstantLevel(definition, context.environment);
@@ -567,17 +838,40 @@ const evaluateDefinitionValue = (definition: Definition, context: Context) => {
567
838
  const topLevel = withScope(context, undefined);
568
839
  if (!isConstant) return evaluateDefinitionBody(definition, topLevel);
569
840
  const value = context.environment.runtime.evaluateAtStartup(() =>
570
- evaluateDefinitionBody(definition, topLevel),
841
+ toStartupValue(definition, evaluateDefinitionBody(definition, topLevel)),
571
842
  );
572
843
  context.environment.definitionValues.set(definition, value);
573
844
  return value;
574
845
  };
575
846
 
847
+ // TLC computes each constant definition the configuration doesn't replace when it starts, and
848
+ // leaves one it fails to compute to evaluate where the spec uses it.
849
+ export const evaluateStartupDefinitions = (definitions: Definition[], environment: Environment) =>
850
+ definitions.forEach((definition) => {
851
+ if (definition.kind === "Operator" && definition.params.length > 0) return;
852
+ const name = definition.name;
853
+ if (environment.constants.has(name) || environment.substitutions.has(name)) return;
854
+ if (!isConstantLevel(definition, environment)) return;
855
+ try {
856
+ markNormalized(
857
+ evaluateDefinitionValue(definition, {
858
+ environment,
859
+ scope: undefined,
860
+ state: undefined,
861
+ next: undefined,
862
+ }),
863
+ );
864
+ } catch (error) {
865
+ // TLC swallows whatever the definition throws, a stack overflow included.
866
+ if (!(error instanceof TlaEvaluationError) && !isStackOverflow(error)) throw error;
867
+ }
868
+ });
869
+
576
870
  const forceThunk = (thunk: Thunk, context: Context) => {
577
871
  const isSameState = thunk.state === context.state && thunk.next === context.next;
578
872
  if (isSameState && thunk.cache !== undefined) return thunk.cache;
579
873
  const value = evaluate(thunk.expression, withScope(context, thunk.scope));
580
- if (isSameState) thunk.cache = value;
874
+ if (isSameState && (!thunk.isStreamed || isSettledValue(value))) thunk.cache = value;
581
875
  return value;
582
876
  };
583
877
 
@@ -691,6 +985,18 @@ const isOperatorArgument = (expression: Expression, context: Context) => {
691
985
  return operator !== undefined && getArity(operator) > 0;
692
986
  };
693
987
 
988
+ const evaluateBuiltinArguments = (args: Expression[], context: Context) =>
989
+ args.map((arg) =>
990
+ isOperatorArgument(arg, context)
991
+ ? toOperatorValue(evaluateOperatorArgument(arg, context), context)
992
+ : evaluate(arg, context),
993
+ );
994
+
995
+ const createArityError = (closure: Closure, count: number) =>
996
+ new TlaEvaluationError(
997
+ `Operator ${closure.name} expects ${closure.params.length} arguments but received ${count}`,
998
+ );
999
+
694
1000
  const createThunk = (expression: Expression, context: Context): Thunk => ({
695
1001
  kind: "Thunk",
696
1002
  expression,
@@ -698,6 +1004,7 @@ const createThunk = (expression: Expression, context: Context): Thunk => ({
698
1004
  state: context.state,
699
1005
  next: context.next,
700
1006
  cache: undefined,
1007
+ isStreamed: false,
701
1008
  });
702
1009
 
703
1010
  export const findGlobalName = (name: string, environment: Environment): GlobalName | undefined => {
@@ -757,47 +1064,61 @@ export const bindOperatorArguments = (
757
1064
  closure: Closure,
758
1065
  args: Expression[],
759
1066
  context: Context,
1067
+ binders?: ArgumentBinder[],
760
1068
  ): Scope | undefined => {
761
- if (args.length !== closure.params.length) {
762
- throw new TlaEvaluationError(
763
- `Operator ${closure.name} expects ${closure.params.length} arguments but received ${args.length}`,
764
- );
765
- }
1069
+ if (args.length !== closure.params.length) throw createArityError(closure, args.length);
766
1070
  let scope = closure.scope;
767
1071
  for (let index = 0; index < args.length; index++) {
768
1072
  const param = closure.params[index];
769
1073
  const binding: Binding =
770
1074
  param.arity > 0
771
1075
  ? { kind: "Operator", operator: evaluateOperatorArgument(args[index], context) }
772
- : getArgumentBinder(args[index], context.environment)(context);
1076
+ : (binders?.[index] ?? getArgumentBinder(args[index], context.environment))(context);
773
1077
  scope = { name: param.name, binding, parent: scope };
774
1078
  }
775
1079
  return scope;
776
1080
  };
777
1081
 
778
- const callOperator = (operator: Operator, args: Expression[], context: Context) => {
1082
+ // The body a call site last called and its evaluator, as a site mostly calls one closure.
1083
+ interface CalledBody {
1084
+ body: Expression;
1085
+ evaluator: Evaluator;
1086
+ }
1087
+
1088
+ const callOperator = (
1089
+ operator: Operator,
1090
+ args: Expression[],
1091
+ context: Context,
1092
+ called: { entry: CalledBody | undefined },
1093
+ binders: ArgumentBinder[],
1094
+ ) => {
779
1095
  if (operator.kind === "Closure") {
780
- return evaluate(
781
- operator.body,
782
- withScope(context, bindOperatorArguments(operator, args, context)),
783
- );
1096
+ const bodyContext = withScope(context, bindOperatorArguments(operator, args, context, binders));
1097
+ if (context.environment.callStack) return evaluate(operator.body, bodyContext);
1098
+ const entry =
1099
+ called.entry?.body === operator.body
1100
+ ? called.entry
1101
+ : (called.entry = {
1102
+ body: operator.body,
1103
+ evaluator: getEntryEvaluator(operator.body, context.environment),
1104
+ });
1105
+ return entry.evaluator(bodyContext);
784
1106
  }
785
1107
  if (operator.kind === "Operator") return operator.call(args.map((arg) => evaluate(arg, context)));
786
1108
  if (operator.isLazy) return operator.evaluate(getLazyArguments(args, context), context);
787
- return operator.evaluate(
788
- args.map((arg) =>
789
- isOperatorArgument(arg, context)
790
- ? toOperatorValue(evaluateOperatorArgument(arg, context), context)
791
- : evaluate(arg, context),
792
- ),
793
- context,
794
- );
1109
+ return operator.evaluate(evaluateBuiltinArguments(args, context), context);
795
1110
  };
796
1111
 
1112
+ // The LET definitions that a reference evaluates again, and those that cache only a settled value.
1113
+ interface ReevaluatedDefinitions {
1114
+ impure: ReadonlySet<Definition>;
1115
+ streamed: ReadonlySet<Definition>;
1116
+ }
1117
+
797
1118
  export const bindDefinitions = (
798
1119
  definitions: Definition[],
799
1120
  context: Context,
800
- reevaluated?: ReadonlySet<Definition>,
1121
+ reevaluated?: ReevaluatedDefinitions,
801
1122
  ): Scope | undefined =>
802
1123
  definitions.reduce<Scope | undefined>((scope, definition) => {
803
1124
  const node: Scope = {
@@ -819,10 +1140,11 @@ export const bindDefinitions = (
819
1140
  state: context.state,
820
1141
  next: context.next,
821
1142
  cache: undefined,
1143
+ isStreamed: false,
822
1144
  };
823
1145
  return node;
824
1146
  }
825
- if (definition.params.length > 0 || reevaluated?.has(definition)) {
1147
+ if (definition.params.length > 0 || reevaluated?.impure.has(definition)) {
826
1148
  node.binding = {
827
1149
  kind: "Operator",
828
1150
  operator: {
@@ -842,6 +1164,7 @@ export const bindDefinitions = (
842
1164
  state: context.state,
843
1165
  next: context.next,
844
1166
  cache: undefined,
1167
+ isStreamed: reevaluated?.streamed.has(definition) ?? false,
845
1168
  };
846
1169
  return node;
847
1170
  }, context.scope);
@@ -859,11 +1182,7 @@ const evaluateLocalIdentifier = (name: string, expression: Expression, context:
859
1182
  const global = findGlobalName(name, context.environment);
860
1183
  if (global?.kind === "Variable") {
861
1184
  const value = context.state?.[global.index];
862
- if (value === undefined) {
863
- throw new TlaEvaluationError(
864
- `The variable ${name} is not assigned at ${describeLocation(expression)}`,
865
- );
866
- }
1185
+ if (value === undefined) throw createUnassignedError(name, expression);
867
1186
  return value;
868
1187
  }
869
1188
  if (global?.kind === "Value") return global.value;
@@ -873,9 +1192,6 @@ const evaluateLocalIdentifier = (name: string, expression: Expression, context:
873
1192
  throw new TlaEvaluationError(`Unknown identifier ${name} at ${describeLocation(expression)}`);
874
1193
  };
875
1194
 
876
- export const isTlcInteger = (value: number) =>
877
- Number.isInteger(value) && value <= MAXIMUM_INTEGER && value >= MINIMUM_INTEGER;
878
-
879
1195
  const IMPURE_BUILTINS = new Set([
880
1196
  "Print",
881
1197
  "PrintT",
@@ -889,14 +1205,29 @@ const IMPURE_BUILTINS = new Set([
889
1205
  export const isImpureBuiltin = (name: string, environment: Environment) =>
890
1206
  IMPURE_BUILTINS.has(name) || environment.builtins.get(name)?.isStateLevel === true;
891
1207
 
892
- const impureDefinitions = new WeakMap<Definition, boolean>();
1208
+ interface Impurity {
1209
+ builtins: Set<string>;
1210
+ definitions: WeakMap<Definition, boolean>;
1211
+ }
1212
+
1213
+ const ANY_EFFECT: Impurity = { builtins: IMPURE_BUILTINS, definitions: new WeakMap() };
1214
+
1215
+ // An Assert that held holds again, so evaluating it twice looks the same as evaluating it once.
1216
+ const REPEATED_EFFECT: Impurity = {
1217
+ builtins: new Set([...IMPURE_BUILTINS].filter((name) => name !== "Assert")),
1218
+ definitions: new WeakMap(),
1219
+ };
893
1220
 
894
1221
  const isEvaluatedOnce = (definition: Definition, environment: Environment) =>
895
1222
  definition.kind === "Operator" &&
896
1223
  definition.params.length === 0 &&
897
1224
  isConstantLevel(definition, environment);
898
1225
 
899
- const callsImpureBuiltin = (expression: Expression, environment: Environment): boolean => {
1226
+ const callsImpureBuiltin = (
1227
+ expression: Expression,
1228
+ environment: Environment,
1229
+ impurity: Impurity,
1230
+ ): boolean => {
900
1231
  const name =
901
1232
  expression.kind === "Identifier"
902
1233
  ? expression.name
@@ -905,42 +1236,69 @@ const callsImpureBuiltin = (expression: Expression, environment: Environment): b
905
1236
  : undefined;
906
1237
  if (name !== undefined && !isLocallyResolved(expression)) {
907
1238
  const definition = getDefinition(name, environment);
908
- if (!definition && isImpureBuiltin(name, environment)) return true;
1239
+ const isImpureCall =
1240
+ impurity.builtins.has(name) || environment.builtins.get(name)?.isStateLevel === true;
1241
+ if (!definition && isImpureCall) return true;
909
1242
  if (
910
1243
  definition &&
911
1244
  !isEvaluatedOnce(definition, environment) &&
912
- isImpureDefinition(definition, environment)
1245
+ isImpureDefinition(definition, environment, impurity)
913
1246
  ) {
914
1247
  return true;
915
1248
  }
916
1249
  }
917
- return getChildren(expression).some((child) => callsImpureBuiltin(child, environment));
1250
+ return getChildren(expression).some((child) => callsImpureBuiltin(child, environment, impurity));
918
1251
  };
919
1252
 
920
1253
  // TLC evaluates a constant definition without parameters once, so only other definitions pass
921
1254
  // on the side effects and random choices of the builtins they call.
922
- const isImpureDefinition = (definition: Definition, environment: Environment): boolean => {
923
- const cached = impureDefinitions.get(definition);
1255
+ const isImpureDefinition = (
1256
+ definition: Definition,
1257
+ environment: Environment,
1258
+ impurity = ANY_EFFECT,
1259
+ ): boolean => {
1260
+ const cached = impurity.definitions.get(definition);
924
1261
  if (cached !== undefined) return cached;
925
- impureDefinitions.set(definition, false);
1262
+ impurity.definitions.set(definition, false);
926
1263
  const isImpure =
927
- callsImpureBuiltin(definition.body, environment) ||
1264
+ callsImpureBuiltin(definition.body, environment, impurity) ||
928
1265
  (definition.kind === "Function" &&
929
- definition.bounds.some((bound) => callsImpureBuiltin(bound.set, environment)));
930
- impureDefinitions.set(definition, isImpure);
1266
+ definition.bounds.some((bound) => callsImpureBuiltin(bound.set, environment, impurity)));
1267
+ impurity.definitions.set(definition, isImpure);
931
1268
  return isImpure;
932
1269
  };
933
1270
 
1271
+ // UNION and \cup build sets that stream the sets they combine until TLC caches them, and TLC
1272
+ // builds a new one at each evaluation.
1273
+ const STREAMED_SET: Impurity = {
1274
+ builtins: new Set(["UNION", "\\cup"]),
1275
+ definitions: new WeakMap(),
1276
+ };
1277
+
934
1278
  // TLC's next-state generator does not bind LET definitions to values, so each reference to one
935
- // that calls an impure builtin evaluates it again.
936
- export const getReevaluatedDefinitions = (definitions: Definition[], environment: Environment) =>
937
- new Set(definitions.filter((definition) => isImpureDefinition(definition, environment)));
1279
+ // evaluates it again: one that calls an impure builtin repeats its effects, and a set one builds
1280
+ // with UNION or \cup starts out uncached.
1281
+ export const getReevaluatedDefinitions = (
1282
+ definitions: Definition[],
1283
+ environment: Environment,
1284
+ ): ReevaluatedDefinitions => ({
1285
+ impure: new Set(definitions.filter((definition) => isImpureDefinition(definition, environment))),
1286
+ streamed: new Set(
1287
+ definitions.filter((definition) => isImpureDefinition(definition, environment, STREAMED_SET)),
1288
+ ),
1289
+ });
938
1290
 
939
1291
  export const isImpure = (environment: Environment) =>
940
1292
  [...environment.definitions.values()].some((definition) =>
941
1293
  isImpureDefinition(definition, environment),
942
1294
  );
943
1295
 
1296
+ // Whether evaluating a definition again can show, such as by printing twice.
1297
+ export const hasRepeatedEffects = (environment: Environment) =>
1298
+ [...environment.definitions.values()].some((definition) =>
1299
+ isImpureDefinition(definition, environment, REPEATED_EFFECT),
1300
+ );
1301
+
944
1302
  const closedConstants = new WeakMap<Expression, boolean>();
945
1303
 
946
1304
  export const isClosedConstant = (expression: Expression, environment: Environment): boolean => {
@@ -1004,7 +1362,11 @@ const computeIsClosedConstant = (
1004
1362
  return global?.kind === "Definition" && isEvaluatedOnce(global.definition, environment);
1005
1363
  }
1006
1364
  if (expression.kind === "Apply") {
1007
- if (isImpureBuiltin(expression.operator, environment) || expression.operator === "~>") {
1365
+ if (
1366
+ isImpureBuiltin(expression.operator, environment) ||
1367
+ STREAMED_SET.builtins.has(expression.operator) ||
1368
+ expression.operator === "~>"
1369
+ ) {
1008
1370
  return false;
1009
1371
  }
1010
1372
  const operator = resolveGlobalOperator(expression.operator, environment);
@@ -1076,12 +1438,128 @@ const isStateCached = (expression: Expression, environment: Environment) =>
1076
1438
  getReadVariables(expression, environment) !== undefined &&
1077
1439
  !hasFreeLocals(expression, NO_BOUND_NAMES);
1078
1440
 
1441
+ // A set filter TLC evaluates lazily, with how to rebuild it so that its predicate runs in another
1442
+ // environment.
1443
+ interface RebindableFilteredSet extends FilteredSetValue {
1444
+ rebind: (environment: Environment) => Value;
1445
+ }
1446
+
1447
+ const isRebindableFilteredSet = (value: Value): value is RebindableFilteredSet =>
1448
+ typeof value === "object" && value.kind === "FilteredSet" && "rebind" in value;
1449
+
1450
+ // TLC's CallStackTool rebinds the lazy values its evaluations return, so their later evaluation
1451
+ // records its call stack too.
1452
+ const traceEvaluator =
1453
+ (
1454
+ expression: Expression,
1455
+ evaluator: Evaluator,
1456
+ environment: Environment,
1457
+ callStack: CallStack,
1458
+ ): Evaluator =>
1459
+ (context) => {
1460
+ callStack.expressions.push(expression);
1461
+ const outerSets = setTrace.sets;
1462
+ const outerCallStack = setTrace.callStack;
1463
+ const sets = outerSets ?? [];
1464
+ const depth = sets.length;
1465
+ setTrace.sets = sets;
1466
+ setTrace.callStack = callStack;
1467
+ try {
1468
+ const computed = evaluator(context);
1469
+ const value = isRebindableFilteredSet(computed) ? computed.rebind(environment) : computed;
1470
+ callStack.values.set(expression, value);
1471
+ if (typeof value === "object" && value.kind !== "FilteredSet" && isSourced(expression)) {
1472
+ callStack.sources.set(value, expression);
1473
+ }
1474
+ return value;
1475
+ } catch (error) {
1476
+ const failed = error instanceof Error ? callStack.failures.get(error) : undefined;
1477
+ if (error instanceof Error) callStack.failures.set(error, expression);
1478
+ const receiver = getReceiver(expression, callStack.values);
1479
+ const received =
1480
+ receiver && !getChildren(expression).some((child) => child === failed)
1481
+ ? callStack.values.get(receiver)
1482
+ : undefined;
1483
+ const value =
1484
+ expression.kind === "FunctionApplication" &&
1485
+ received !== undefined &&
1486
+ !isFunctionValue(received)
1487
+ ? undefined
1488
+ : received;
1489
+ freezeCallStack(
1490
+ callStack,
1491
+ [value, ...sets.slice(depth).filter((set) => set !== value)],
1492
+ error,
1493
+ );
1494
+ throw error;
1495
+ } finally {
1496
+ if (!callStack.isFrozen) callStack.expressions.pop();
1497
+ sets.length = depth;
1498
+ setTrace.sets = outerSets;
1499
+ setTrace.callStack = outerCallStack;
1500
+ }
1501
+ };
1502
+
1503
+ // A method of a value with a source raises a FingerprintException, which each value with a source
1504
+ // whose method called it heads in turn. CallStack#freeze adds their sources to the stack, outermost
1505
+ // first. The values are those whose methods failed, outermost first.
1506
+ export const freezeCallStack = (
1507
+ callStack: CallStack,
1508
+ values: (Value | undefined)[],
1509
+ error: unknown,
1510
+ ) => {
1511
+ // A set that streams its elements enumerates itself too, so it can appear twice.
1512
+ const sources = [...new Set(values)].flatMap((item) => {
1513
+ const source = typeof item === "object" ? callStack.sources.get(item) : undefined;
1514
+ return source ? [source] : [];
1515
+ });
1516
+ // A value with a source raises a FingerprintException even when the stack is frozen already.
1517
+ if (sources.length > 0 && error instanceof TlaEvaluationError) {
1518
+ if (!callStack.isFrozen) callStack.expressions.push(...sources);
1519
+ const inner = callStack.fingerprint;
1520
+ callStack.fingerprint = {
1521
+ sources: [...sources, ...(inner?.sources ?? [])],
1522
+ reason: inner?.reason ?? error.message,
1523
+ };
1524
+ }
1525
+ callStack.isFrozen = true;
1526
+ };
1527
+
1528
+ // A FingerprintException that a method of a value with a source raises, or that passes through one,
1529
+ // takes the value's source as its new head.
1530
+ const headFingerprint = (callStack: CallStack, source: Expression, error: unknown) => {
1531
+ if (!(error instanceof TlaEvaluationError)) return;
1532
+ if (!callStack.isFrozen) callStack.expressions.push(source);
1533
+ callStack.isFrozen = true;
1534
+ const inner = callStack.fingerprint;
1535
+ callStack.fingerprint = {
1536
+ sources: [source, ...(inner?.sources ?? [])],
1537
+ reason: inner?.reason ?? error.message,
1538
+ };
1539
+ };
1540
+
1541
+ // A copy of the environment that records the call stack of each evaluation, with evaluators of its
1542
+ // own since the environment's evaluators record nothing.
1543
+ export const createTracingEnvironment = (environment: Environment): Environment => ({
1544
+ ...environment,
1545
+ evaluators: new WeakMap(),
1546
+ callStack: {
1547
+ expressions: [],
1548
+ isFrozen: false,
1549
+ sources: new WeakMap(),
1550
+ values: new WeakMap(),
1551
+ failures: new WeakMap(),
1552
+ },
1553
+ });
1554
+
1079
1555
  export const getEvaluator = (expression: Expression, environment: Environment): Evaluator => {
1080
1556
  const cached = environment.evaluators.get(expression);
1081
1557
  if (cached) return cached;
1082
1558
  const compiled = compile(expression, environment);
1083
- const evaluator =
1084
- isWorthCaching(expression) && isClosedConstant(expression, environment)
1559
+ const callStack = environment.callStack;
1560
+ const evaluator = callStack
1561
+ ? traceEvaluator(expression, compiled, environment, callStack)
1562
+ : isWorthCaching(expression) && isClosedConstant(expression, environment)
1085
1563
  ? cacheFirstValue(compiled)
1086
1564
  : isStateCached(expression, environment)
1087
1565
  ? cacheStateValue(compiled)
@@ -1092,7 +1570,8 @@ export const getEvaluator = (expression: Expression, environment: Environment):
1092
1570
 
1093
1571
  const entryEvaluators = new WeakMap<Expression, Evaluator>();
1094
1572
 
1095
- const getEntryEvaluator = (expression: Expression, environment: Environment) => {
1573
+ export const getEntryEvaluator = (expression: Expression, environment: Environment) => {
1574
+ if (environment.callStack) return getEvaluator(expression, environment);
1096
1575
  const cached = entryEvaluators.get(expression);
1097
1576
  if (cached) return cached;
1098
1577
  const evaluator =
@@ -1116,11 +1595,7 @@ const compileIdentifier = (
1116
1595
  const index = global.index;
1117
1596
  return (context) => {
1118
1597
  const value = context.state?.[index];
1119
- if (value === undefined) {
1120
- throw new TlaEvaluationError(
1121
- `The variable ${name} is not assigned at ${describeLocation(expression)}`,
1122
- );
1123
- }
1598
+ if (value === undefined) throw createUnassignedError(name, expression);
1124
1599
  return value;
1125
1600
  };
1126
1601
  }
@@ -1182,20 +1657,13 @@ const cacheStateValue = (evaluator: Evaluator): Evaluator => {
1182
1657
  };
1183
1658
  };
1184
1659
 
1185
- const isOperatorName = (name: string, environment: Environment) => {
1186
- const operator = resolveGlobalOperator(name, environment);
1187
- return operator !== undefined && getArity(operator) > 0;
1660
+ export const isValueArgument = (argument: Expression, environment: Environment) => {
1661
+ if (argument.kind === "Lambda" || argument.kind === "OperatorReference") return false;
1662
+ if (argument.kind !== "Identifier" || isLocallyResolved(argument)) return true;
1663
+ const operator = resolveGlobalOperator(argument.name, environment);
1664
+ return operator === undefined || getArity(operator) === 0;
1188
1665
  };
1189
1666
 
1190
- export const isValueArgument = (argument: Expression, environment: Environment) =>
1191
- argument.kind !== "Lambda" &&
1192
- argument.kind !== "OperatorReference" &&
1193
- !(
1194
- argument.kind === "Identifier" &&
1195
- !isLocallyResolved(argument) &&
1196
- isOperatorName(argument.name, environment)
1197
- );
1198
-
1199
1667
  const getLazyArguments = (args: Expression[], context: Context): OperatorValue[] =>
1200
1668
  args.map((arg) => ({
1201
1669
  kind: "Operator",
@@ -1228,15 +1696,7 @@ const compileBuiltinCall = (
1228
1696
  const right = getEvaluator(args[1], environment);
1229
1697
  return (context) => binary(left(context), right(context));
1230
1698
  }
1231
- return (context) =>
1232
- builtin.evaluate(
1233
- args.map((arg) =>
1234
- isOperatorArgument(arg, context)
1235
- ? toOperatorValue(evaluateOperatorArgument(arg, context), context)
1236
- : evaluate(arg, context),
1237
- ),
1238
- context,
1239
- );
1699
+ return (context) => builtin.evaluate(evaluateBuiltinArguments(args, context), context);
1240
1700
  };
1241
1701
 
1242
1702
  export const compileArgumentScope = (
@@ -1246,9 +1706,7 @@ export const compileArgumentScope = (
1246
1706
  ): ((context: Context) => Scope | undefined) => {
1247
1707
  if (args.length !== closure.params.length) {
1248
1708
  return () => {
1249
- throw new TlaEvaluationError(
1250
- `Operator ${closure.name} expects ${closure.params.length} arguments but received ${args.length}`,
1251
- );
1709
+ throw createArityError(closure, args.length);
1252
1710
  };
1253
1711
  }
1254
1712
  const params = closure.params;
@@ -1269,75 +1727,236 @@ export const compileArgumentScope = (
1269
1727
  };
1270
1728
 
1271
1729
  interface MemoizedCall {
1730
+ sources: (Expression | undefined)[];
1272
1731
  args: Value[];
1273
1732
  value: Value;
1274
1733
  }
1275
1734
 
1276
1735
  const MEMOIZED_CALL_LIMIT = 1 << 16;
1277
1736
 
1278
- const callMemos = new WeakMap<Closure, { calls: Map<number, MemoizedCall[]>; size: number }>();
1737
+ // A call site that finds fewer than half its calls in a state's memo after this many new ones
1738
+ // stops paying for the lookups.
1739
+ const MEMOIZED_TRIAL_CALLS = 1 << 10;
1740
+
1741
+ interface CallMemo {
1742
+ calls: Map<number, MemoizedCall[]>;
1743
+ size: number;
1744
+ state: Context["state"];
1745
+ }
1746
+
1747
+ interface CallMemos {
1748
+ constant: CallMemo;
1749
+ state: CallMemo;
1750
+ }
1751
+
1752
+ const createCallMemo = (): CallMemo => ({ calls: new Map(), size: 0, state: undefined });
1279
1753
 
1280
- const getCallMemo = (closure: Closure) => {
1754
+ const callMemos = new WeakMap<Closure, CallMemos>();
1755
+
1756
+ const getCallMemos = (closure: Closure) => {
1281
1757
  const cached = callMemos.get(closure);
1282
1758
  if (cached) return cached;
1283
- const memo = { calls: new Map<number, MemoizedCall[]>(), size: 0 };
1284
- callMemos.set(closure, memo);
1285
- return memo;
1759
+ const memos = { constant: createCallMemo(), state: createCallMemo() };
1760
+ callMemos.set(closure, memos);
1761
+ return memos;
1762
+ };
1763
+
1764
+ const readsExceptAt = (expression: Expression): boolean =>
1765
+ expression.kind === "ExceptAt" || getChildren(expression).some(readsExceptAt);
1766
+
1767
+ // The locals an argument expression reads, when the state and their values decide its value. An @
1768
+ // reads the value its EXCEPT binds.
1769
+ const argumentLocals = new WeakMap<Expression, string[] | false>();
1770
+
1771
+ const getArgumentLocals = (expression: Expression, environment: Environment) => {
1772
+ const cached = argumentLocals.get(expression);
1773
+ if (cached !== undefined) return cached;
1774
+ const locals =
1775
+ getReadVariables(expression, environment) !== undefined &&
1776
+ getReadLocals(expression, NO_BOUND_NAMES);
1777
+ const unique = locals && [
1778
+ ...new Set(readsExceptAt(expression) ? [...locals, EXCEPT_AT] : locals),
1779
+ ];
1780
+ argumentLocals.set(expression, unique ?? false);
1781
+ return unique ?? false;
1782
+ };
1783
+
1784
+ // Hashing a lazy set or function would enumerate it, which TLC does only when it has to.
1785
+ const isEagerValue = (value: Value) =>
1786
+ typeof value !== "object" ||
1787
+ value.kind === "ModelValue" ||
1788
+ value.kind === "Set" ||
1789
+ value.kind === "Function" ||
1790
+ value.kind === "Interval";
1791
+
1792
+ // The key of the call being looked up, copied into the memo only when the call is new. Counts
1793
+ // mark its ends, since shortening an array is slow.
1794
+ const callKey = {
1795
+ sources: [] as (Expression | undefined)[],
1796
+ sourceCount: 0,
1797
+ args: [] as Value[],
1798
+ argCount: 0,
1799
+ hash: 0,
1800
+ isStateKeyed: false,
1801
+ };
1802
+
1803
+ // A model value's rank tells it apart without hashing its name.
1804
+ const getKeyHash = (value: Value) =>
1805
+ typeof value === "object" && value.kind === "ModelValue" ? value.rank : getValueHash(value);
1806
+
1807
+ const pushKeyValue = (value: Value) => {
1808
+ if (!isEagerValue(value)) return false;
1809
+ callKey.sources[callKey.sourceCount++] = undefined;
1810
+ callKey.args[callKey.argCount++] = value;
1811
+ callKey.hash = combineHash(callKey.hash, getKeyHash(value));
1812
+ return true;
1813
+ };
1814
+
1815
+ // An argument TLC has not evaluated yet stands for its expression and the values of the locals it
1816
+ // reads, so a call keeps the laziness of its arguments.
1817
+ const pushKeyExpression = (
1818
+ expression: Expression,
1819
+ locals: string[] | false,
1820
+ scope: Scope | undefined,
1821
+ ) => {
1822
+ if (!locals) return false;
1823
+ callKey.sources[callKey.sourceCount++] = expression;
1824
+ callKey.isStateKeyed = true;
1825
+ for (let index = 0; index < locals.length; index++) {
1826
+ const local = lookupScope(scope, locals[index]);
1827
+ if (local?.kind !== "Value" || !isEagerValue(local.value)) return false;
1828
+ callKey.args[callKey.argCount++] = local.value;
1829
+ callKey.hash = combineHash(callKey.hash, getKeyHash(local.value));
1830
+ }
1831
+ return true;
1832
+ };
1833
+
1834
+ // Each argument adds to the key what compileArgumentBinder would bind its parameter to.
1835
+ const compileArgumentKey = (
1836
+ argument: Expression,
1837
+ environment: Environment,
1838
+ ): ((context: Context) => boolean) => {
1839
+ const isLiteral =
1840
+ argument.kind === "String" || (argument.kind === "Number" && isTlcInteger(argument.value));
1841
+ if (isLiteral) return () => pushKeyValue(argument.value);
1842
+ if (argument.kind === "Identifier") {
1843
+ const global = isLocallyResolved(argument)
1844
+ ? undefined
1845
+ : findGlobalName(argument.name, environment);
1846
+ if (global?.kind === "Value") return () => pushKeyValue(global.value);
1847
+ if (global === undefined) {
1848
+ return (context) => {
1849
+ const binding = lookupScope(context.scope, argument.name);
1850
+ if (binding?.kind === "Value") return pushKeyValue(binding.value);
1851
+ if (binding?.kind !== "Thunk" || binding.state !== context.state) return false;
1852
+ return pushKeyExpression(
1853
+ binding.expression,
1854
+ getArgumentLocals(binding.expression, environment),
1855
+ binding.scope,
1856
+ );
1857
+ };
1858
+ }
1859
+ }
1860
+ const locals = getArgumentLocals(argument, environment);
1861
+ return (context) => pushKeyExpression(argument, locals, context.scope);
1286
1862
  };
1287
1863
 
1288
- const getArgumentValues = (scope: Scope | undefined, arity: number) => {
1289
- const values: Value[] = [];
1290
- for (let current = scope; values.length < arity; current = current?.parent) {
1291
- if (current?.binding.kind !== "Value") return undefined;
1292
- values.push(current.binding.value);
1864
+ const isKnownCall = (call: MemoizedCall) => {
1865
+ if (call.args.length !== callKey.argCount || call.sources.length !== callKey.sourceCount) {
1866
+ return false;
1293
1867
  }
1294
- return values;
1868
+ for (let index = 0; index < callKey.sourceCount; index++) {
1869
+ if (call.sources[index] !== callKey.sources[index]) return false;
1870
+ }
1871
+ for (let index = 0; index < callKey.argCount; index++) {
1872
+ if (!isSameValue(call.args[index], callKey.args[index])) return false;
1873
+ }
1874
+ return true;
1295
1875
  };
1296
1876
 
1297
- const isSameArguments = (left: Value[], right: Value[]) =>
1298
- left.every((value, index) => isSameValue(value, right[index]));
1877
+ const findCall = (bucket: MemoizedCall[] | undefined) => {
1878
+ if (bucket === undefined) return undefined;
1879
+ for (let index = 0; index < bucket.length; index++) {
1880
+ if (isKnownCall(bucket[index])) return bucket[index];
1881
+ }
1882
+ return undefined;
1883
+ };
1299
1884
 
1300
- // A constant-level operator without side effects yields the same value for the same arguments,
1301
- // so its calls with evaluated arguments share one result.
1302
- const isMemoizable = (expression: Expression & { kind: "Apply" }, environment: Environment) => {
1885
+ // An operator without side effects yields the same value for the same arguments, a state-level one
1886
+ // in the same state, so its calls share one result.
1887
+ const getMemoizedLevel = (expression: Expression & { kind: "Apply" }, environment: Environment) => {
1303
1888
  const definition = getDefinition(expression.operator, environment);
1304
- return (
1889
+ const isMemoizable =
1305
1890
  definition?.kind === "Operator" &&
1306
1891
  definition.params.length > 0 &&
1307
1892
  definition.params.every((param) => param.arity === 0) &&
1308
- isConstantLevel(definition, environment) &&
1309
- !isImpureDefinition(definition, environment)
1310
- );
1893
+ !isImpureDefinition(definition, environment);
1894
+ if (!isMemoizable) return undefined;
1895
+ if (isConstantLevel(definition, environment)) return "constant";
1896
+ return isStatePure(definition, environment) ? "state" : undefined;
1311
1897
  };
1312
1898
 
1313
1899
  const compileClosureCall = (
1314
1900
  closure: Closure,
1315
1901
  args: Expression[],
1316
1902
  environment: Environment,
1317
- isMemoized: boolean,
1903
+ memoizedLevel: "constant" | "state" | undefined,
1318
1904
  ): Evaluator => {
1319
1905
  const bindArguments = compileArgumentScope(closure, args, environment);
1320
1906
  const compiled = { body: undefined as Evaluator | undefined };
1321
1907
  const evaluateBody = (scope: Scope | undefined, context: Context) => {
1322
1908
  compiled.body ??= getEntryEvaluator(closure.body, environment);
1323
- return compiled.body({ environment, scope, state: context.state, next: context.next });
1909
+ return compiled.body({
1910
+ environment,
1911
+ scope,
1912
+ state: context.state,
1913
+ next: context.next,
1914
+ isKeepLazy: context.isKeepLazy,
1915
+ });
1324
1916
  };
1325
- if (!isMemoized) return (context) => evaluateBody(bindArguments(context), context);
1326
- const memo = getCallMemo(closure);
1917
+ if (!memoizedLevel || args.length !== closure.params.length) {
1918
+ return (context) => evaluateBody(bindArguments(context), context);
1919
+ }
1920
+ const memos = getCallMemos(closure);
1921
+ const keys = args.map((arg) => compileArgumentKey(arg, environment));
1922
+ const usage = { hits: 0, misses: 0 };
1327
1923
  return (context) => {
1328
- const scope = bindArguments(context);
1329
- const values = getArgumentValues(scope, args.length);
1330
- if (!values) return evaluateBody(scope, context);
1331
- let hash = values.length;
1332
- for (const value of values) hash = combineHash(hash, getValueHash(value));
1924
+ // A call TLC evaluates with EvalControl.KeepLazy builds what a memoized one wouldn't.
1925
+ if (context.isKeepLazy) return evaluateBody(bindArguments(context), context);
1926
+ callKey.sourceCount = 0;
1927
+ callKey.argCount = 0;
1928
+ callKey.hash = args.length;
1929
+ callKey.isStateKeyed = false;
1930
+ for (let index = 0; index < keys.length; index++) {
1931
+ if (!keys[index](context)) return evaluateBody(bindArguments(context), context);
1932
+ }
1933
+ const isStateKeyed = memoizedLevel === "state" || callKey.isStateKeyed;
1934
+ if (isStateKeyed && usage.misses > MEMOIZED_TRIAL_CALLS && usage.hits < usage.misses) {
1935
+ return evaluateBody(bindArguments(context), context);
1936
+ }
1937
+ const memo = isStateKeyed ? memos.state : memos.constant;
1938
+ if (isStateKeyed && memo.state !== context.state) {
1939
+ memo.state = context.state;
1940
+ memo.calls.clear();
1941
+ memo.size = 0;
1942
+ }
1943
+ // A small integer key keeps the Map from boxing it.
1944
+ const hash = callKey.hash & 0x3fffffff;
1333
1945
  const bucket = memo.calls.get(hash);
1334
- const known = bucket?.find((call) => isSameArguments(call.args, values));
1335
- if (known) return known.value;
1336
- const value = evaluateBody(scope, context);
1946
+ const known = findCall(bucket);
1947
+ if (known) {
1948
+ if (isStateKeyed) usage.hits++;
1949
+ return known.value;
1950
+ }
1951
+ if (isStateKeyed) usage.misses++;
1952
+ const sources = callKey.sources.slice(0, callKey.sourceCount);
1953
+ const keyArgs = callKey.args.slice(0, callKey.argCount);
1954
+ const value = evaluateBody(bindArguments(context), context);
1337
1955
  if (memo.size < MEMOIZED_CALL_LIMIT) {
1338
1956
  memo.size++;
1339
- if (bucket) bucket.push({ args: values, value });
1340
- else memo.calls.set(hash, [{ args: values, value }]);
1957
+ const call = { sources, args: keyArgs, value };
1958
+ if (bucket) bucket.push(call);
1959
+ else memo.calls.set(hash, [call]);
1341
1960
  }
1342
1961
  return value;
1343
1962
  };
@@ -1364,7 +1983,11 @@ const compileApply = (
1364
1983
  ? undefined
1365
1984
  : resolveGlobalOperator(expression.operator, environment);
1366
1985
  if (global?.kind === "Closure") {
1367
- return compileClosureCall(global, args, environment, isMemoizable(expression, environment));
1986
+ // The replay records the evaluation of each call, which TLC repeats.
1987
+ const memoizedLevel = environment.callStack
1988
+ ? undefined
1989
+ : getMemoizedLevel(expression, environment);
1990
+ return compileClosureCall(global, args, environment, memoizedLevel);
1368
1991
  }
1369
1992
  if (global?.kind === "Builtin" && global.name === "DOMAIN") {
1370
1993
  const operand = getEvaluator(args[0], environment);
@@ -1374,7 +1997,7 @@ const compileApply = (
1374
1997
  // TLC sorts the value of a constant TLCEval argument only where no context binds a name.
1375
1998
  if (global?.kind === "Builtin" && global.name === "TLCEval" && args.length === 1) {
1376
1999
  const operand = getEvaluator(args[0], environment);
1377
- if (contextualApplications.has(expression) || isStateDependent(args[0], environment)) {
2000
+ if (contextualApplications.has(expression) || isNonconstant(args[0], environment)) {
1378
2001
  return operand;
1379
2002
  }
1380
2003
  return (context) =>
@@ -1387,9 +2010,21 @@ const compileApply = (
1387
2010
  return (context) => subset(left(context), right(context));
1388
2011
  }
1389
2012
  if (global?.kind === "Builtin") return compileBuiltinCall(global, args, environment);
2013
+ // TLC refuses action composition unless a Java property enables its incomplete implementation.
2014
+ if (expression.operator === "\\cdot" && args.length === 2) {
2015
+ return () => {
2016
+ throw new TlaEvaluationError(
2017
+ environment.runtime.version === "1.7.4"
2018
+ ? "The current version of TLC does not support action composition."
2019
+ : "The current version of TLC does not support action composition. An incomplete implementation can be enabled via the tlc2.tool.impl.Tool.cdot=true java property.",
2020
+ );
2021
+ };
2022
+ }
2023
+ const called = { entry: undefined as CalledBody | undefined };
2024
+ const binders = args.map((arg) => getArgumentBinder(arg, environment));
1390
2025
  return (context) => {
1391
2026
  const operator = resolveOperator(expression.operator, context);
1392
- if (operator) return callOperator(operator, args, context);
2027
+ if (operator) return callOperator(operator, args, context, called, binders);
1393
2028
  const definition = environment.definitions.get(expression.operator);
1394
2029
  if (definition?.kind === "Function") {
1395
2030
  throw new TlaEvaluationError(`${expression.operator} is a function; apply it with brackets`);
@@ -1412,15 +2047,15 @@ const compileQuantifier = (
1412
2047
  const name = bound.pattern.name;
1413
2048
  const set = getEvaluator(bound.set, environment);
1414
2049
  return (context) => {
1415
- const elements = getEnumeratedElements(set(context), bound.set);
1416
- for (let index = 0; index < elements.length; index++) {
1417
- const result = expectBoolean(
1418
- body(withScope(context, bindValue(context.scope, name, elements[index]))),
1419
- description,
1420
- );
1421
- if (result !== isForall) return result;
1422
- }
1423
- return isForall;
2050
+ const isFound = someElement(
2051
+ getQuantifierElements(set(context), bound.set, environment.runtime.version),
2052
+ (element) =>
2053
+ expectBoolean(
2054
+ body(withScope(context, bindValue(context.scope, name, element))),
2055
+ description,
2056
+ ) !== isForall,
2057
+ );
2058
+ return isFound ? !isForall : isForall;
1424
2059
  };
1425
2060
  }
1426
2061
  const bounds = expression.bounds;
@@ -1429,17 +2064,15 @@ const compileQuantifier = (
1429
2064
  const sets = bounds.map((item) => getEvaluator(item.set, environment));
1430
2065
  return (context) => {
1431
2066
  const lists = sets.map((set, index) =>
1432
- getEnumeratedElements(set(context), bounds[index].set),
2067
+ getQuantifierElements(set(context), bounds[index].set, environment.runtime.version),
1433
2068
  );
1434
2069
  const visit = (index: number, scope: Scope | undefined): boolean => {
1435
2070
  if (index < 0) {
1436
2071
  return expectBoolean(body(withScope(context, scope)), description) !== isForall;
1437
2072
  }
1438
- const list = lists[index];
1439
- for (let position = 0; position < list.length; position++) {
1440
- if (visit(index - 1, bindValue(scope, names[index], list[position]))) return true;
1441
- }
1442
- return false;
2073
+ return someElement(lists[index], (element) =>
2074
+ visit(index - 1, bindValue(scope, names[index], element)),
2075
+ );
1443
2076
  };
1444
2077
  return visit(bounds.length - 1, context.scope) ? !isForall : isForall;
1445
2078
  };
@@ -1454,7 +2087,7 @@ const compileQuantifier = (
1454
2087
  };
1455
2088
  };
1456
2089
 
1457
- const lookupKey = (pattern: BoundPattern, scope: Scope | undefined) => {
2090
+ const getBoundValue = (pattern: BoundPattern, scope: Scope | undefined) => {
1458
2091
  if (pattern.kind === "Tuple") {
1459
2092
  return createTuple(
1460
2093
  pattern.names.map((name) => {
@@ -1487,37 +2120,75 @@ const compileFunctionConstruction = (
1487
2120
  const bound = bounds[0];
1488
2121
  const isSingleName = bounds.length === 1 && bound.pattern.kind === "Name";
1489
2122
  const set = getEvaluator(bound.set, environment);
1490
- return (context) => {
1491
- const domain = isSingleName ? set(context) : getBoundsDomain(bounds, context);
1492
- if (expression.isRecursive || isKeptLazy || !isEnumerable(domain)) {
1493
- const functionValue = createLazyFunction(
1494
- domain,
1495
- (argument) => body(withScope(context, bindArgument(bounds, context.scope, argument))),
1496
- getLazyFunctionSource(bounds, expression.body, domain),
1497
- );
1498
- return bounds.length === 1 ? markLambdaFunction(functionValue) : functionValue;
1499
- }
2123
+ const construct = (domain: Value, context: Context) => {
1500
2124
  if (isSingleName && bound.pattern.kind === "Name") {
1501
2125
  const name = bound.pattern.name;
1502
2126
  const keys = getFunctionDomain(domain);
1503
- return markLambdaFunction(
1504
- createSortedFunction(
1505
- keys,
1506
- keys.map((key) => body(withScope(context, bindValue(context.scope, name, key)))),
1507
- ),
2127
+ const functionValue = createSortedFunction(
2128
+ keys,
2129
+ keys.map((key) => body(withScope(context, bindValue(context.scope, name, key)))),
1508
2130
  );
2131
+ // FcnLambdaValue#toFcnRcd builds a FcnRcdValue over an interval or an enumerated set.
2132
+ return isReducibleSet(domain) ? functionValue : markLambdaFunction(functionValue);
1509
2133
  }
1510
2134
  const pairs: [Value, Value][] = [];
1511
- forEachBinding(bounds, context, (scope) => {
2135
+ const sets = bounds.map((item) =>
2136
+ getNormalizedElements(
2137
+ evaluate(item.set, context),
2138
+ item.set,
2139
+ context.environment.runtime.version,
2140
+ ),
2141
+ );
2142
+ forEachBoundElement(bounds, sets, context.scope, (scope) => {
1512
2143
  const key =
1513
2144
  bounds.length === 1
1514
- ? (lookupKey(bound.pattern, scope) ?? false)
1515
- : createTuple(bounds.map((item) => lookupKey(item.pattern, scope) ?? false));
2145
+ ? (getBoundValue(bound.pattern, scope) ?? false)
2146
+ : createTuple(bounds.map((item) => getBoundValue(item.pattern, scope) ?? false));
1516
2147
  pairs.push([key, body(withScope(context, scope))]);
1517
2148
  return false;
1518
2149
  });
1519
2150
  return createFunction(pairs);
1520
2151
  };
2152
+ const createLazy = (domain: Value, context: Context) => {
2153
+ const functionValue = keepLambda({
2154
+ value: createLazyFunction(
2155
+ domain,
2156
+ (argument) => body(withScope(context, bindArgument(bounds, context.scope, argument))),
2157
+ getLazyFunctionSource(bounds, expression.body, domain),
2158
+ ),
2159
+ bounds,
2160
+ body: expression.body,
2161
+ scope: context.scope,
2162
+ });
2163
+ return bounds.length === 1 ? markLambdaFunction(functionValue) : functionValue;
2164
+ };
2165
+ const callStack = environment.callStack;
2166
+ return (context) => {
2167
+ const domain = isSingleName ? set(context) : getBoundsDomain(bounds, context);
2168
+ if (expression.isRecursive || isKeptLazy || context.isKeepLazy || !isEnumerable(domain)) {
2169
+ return createLazy(domain, context);
2170
+ }
2171
+ // TLC builds a function over a domain other than a set enumeration or an interval lazily, so
2172
+ // its body fails only where TLC forces it, as the replay does. Building it at once is faster
2173
+ // otherwise.
2174
+ if (!isReducibleSet(domain)) {
2175
+ if (callStack) return createLazy(domain, context);
2176
+ try {
2177
+ return construct(domain, context);
2178
+ } catch (error) {
2179
+ if (!(error instanceof TlaEvaluationError)) throw error;
2180
+ return createLazy(domain, context);
2181
+ }
2182
+ }
2183
+ if (!callStack) return construct(domain, context);
2184
+ // TLC builds the function in a method of the FcnLambdaValue that CallStackTool gives a source.
2185
+ try {
2186
+ return construct(domain, context);
2187
+ } catch (error) {
2188
+ headFingerprint(callStack, expression, error);
2189
+ throw error;
2190
+ }
2191
+ };
1521
2192
  };
1522
2193
 
1523
2194
  const compileExcept = (
@@ -1563,7 +2234,20 @@ const compileExcept = (
1563
2234
  };
1564
2235
  return (context) => {
1565
2236
  let current = evaluateFunction(context);
1566
- for (const item of updates) current = update(current, item.path, 0, context, item.value);
2237
+ for (const item of updates) {
2238
+ // TLC leaves the value as it is when an update's path is not in it, and warns.
2239
+ const found = { value: false };
2240
+ current = update(current, item.path, 0, context, (inner) => {
2241
+ found.value = true;
2242
+ return item.value(inner);
2243
+ });
2244
+ if (!found.value) {
2245
+ context.environment.runtime.warn(
2246
+ MESSAGE_CODE.exceptAppliedToUnknownField,
2247
+ `The EXCEPT was applied to non-existing fields of the value at\n${describeRange(expression.function)}`,
2248
+ );
2249
+ }
2250
+ }
1567
2251
  return current;
1568
2252
  };
1569
2253
  };
@@ -1576,23 +2260,37 @@ const compileSetComprehension = (
1576
2260
  const predicate = getEvaluator(expression.predicate, environment);
1577
2261
  const set = getEvaluator(expression.bound.set, environment);
1578
2262
  const pattern = expression.bound.pattern;
2263
+ const range = expression.predicate.location.range;
2264
+ const source = range && {
2265
+ names: pattern.kind === "Name" ? pattern.name : pattern.names.join(", "),
2266
+ predicate: formatRange(range),
2267
+ };
2268
+ const createTest = (evaluator: Evaluator, context: Context) => (element: Value) =>
2269
+ expectBoolean(
2270
+ evaluator(withScope(context, bindPattern(context.scope, pattern, element))),
2271
+ "a set filter predicate",
2272
+ );
2273
+ const createFiltered = (
2274
+ base: Value,
2275
+ context: Context,
2276
+ evaluator: Evaluator,
2277
+ ): RebindableFilteredSet => ({
2278
+ kind: "FilteredSet",
2279
+ base,
2280
+ test: createTest(evaluator, context),
2281
+ source,
2282
+ rebind: (tracing) =>
2283
+ createFiltered(
2284
+ base,
2285
+ { ...context, environment: tracing },
2286
+ getEvaluator(expression.predicate, tracing),
2287
+ ),
2288
+ });
1579
2289
  return (context) => {
1580
2290
  const base = set(context);
1581
- const test = (element: Value) =>
1582
- expectBoolean(
1583
- predicate(withScope(context, bindPattern(context.scope, pattern, element))),
1584
- "a set filter predicate",
1585
- );
1586
- const isReducible =
1587
- typeof base === "object" &&
1588
- (base.kind === "Set" || base.kind === "MixedSet" || base.kind === "Interval");
1589
- if (!isReducible) {
1590
- if (isSetValue(base)) return { kind: "FilteredSet", base, test };
1591
- throw new TlaEvaluationError(
1592
- `TLC encountered a non-enumerable quantifier bound ${formatValue(base)} at ${describeLocation(expression.bound.set)}`,
1593
- );
1594
- }
1595
- return createSortedSet(toFiniteSet(base).elements.filter(test));
2291
+ // TLC filters any value it can't enumerate lazily, and fails only when it uses the result.
2292
+ if (!isReducibleSet(base)) return createFiltered(base, context, predicate);
2293
+ return createSortedSet(toFiniteSet(base).elements.filter(createTest(predicate, context)));
1596
2294
  };
1597
2295
  }
1598
2296
  if (expression.kind === "SetMap") {
@@ -1615,12 +2313,20 @@ const compileSetComprehension = (
1615
2313
  };
1616
2314
  }
1617
2315
  const body = getEvaluator(expression.body, environment);
1618
- const bound = { pattern: expression.pattern, set };
2316
+ const evaluateSet = getEvaluator(set, environment);
1619
2317
  return (context) => {
2318
+ const base = evaluateSet(context);
2319
+ if (!isSetValue(base) || isOverriddenSet(base)) {
2320
+ throw new TlaEvaluationError(
2321
+ `Attempted to compute the value of an expression of\nform CHOOSE x \\in S: P, but S was not enumerable.\n${describeRange(expression)}`,
2322
+ );
2323
+ }
1620
2324
  const chosen = { value: undefined as Value | undefined };
1621
- forEachBinding([bound], context, (scope) => {
2325
+ const elements = getNormalizedElements(base, set, context.environment.runtime.version);
2326
+ someElement(elements, (element) => {
2327
+ const scope = bindPattern(context.scope, expression.pattern, element);
1622
2328
  if (!expectBoolean(body(withScope(context, scope)), "the body of CHOOSE")) return false;
1623
- chosen.value = lookupKey(expression.pattern, scope);
2329
+ chosen.value = getBoundValue(expression.pattern, scope);
1624
2330
  return true;
1625
2331
  });
1626
2332
  if (chosen.value === undefined) {
@@ -1632,16 +2338,21 @@ const compileSetComprehension = (
1632
2338
  };
1633
2339
  };
1634
2340
 
2341
+ // TLC orders a record's fields by name.
2342
+ export const getSortedFields = (fields: RecordField[]) =>
2343
+ [...fields].sort((left, right) => compareValues(left.name, right.name));
2344
+
2345
+ export const hasDuplicateFields = (sortedFields: RecordField[]) =>
2346
+ sortedFields.some((field, index) => index > 0 && sortedFields[index - 1].name === field.name);
2347
+
1635
2348
  const compileRecord = (recordFields: RecordField[], environment: Environment): Evaluator => {
1636
- const fields = [...recordFields].sort((left, right) => compareValues(left.name, right.name));
1637
- const hasDuplicates = fields.some(
1638
- (field, index) => index > 0 && fields[index - 1].name === field.name,
1639
- );
2349
+ const fields = getSortedFields(recordFields);
2350
+ const hasDuplicates = hasDuplicateFields(fields);
1640
2351
  const values = fields.map((field) => getEvaluator(field.value, environment));
1641
2352
  if (hasDuplicates) {
1642
2353
  return (context) =>
1643
- createFunction(
1644
- fields.map((field, index): [Value, Value] => [field.name, values[index](context)]),
2354
+ createRecord(
2355
+ fields.map((field, index): [string, Value] => [field.name, values[index](context)]),
1645
2356
  );
1646
2357
  }
1647
2358
  const names = fields.map((field) => field.name);
@@ -1655,14 +2366,14 @@ const compileRecord = (recordFields: RecordField[], environment: Environment): E
1655
2366
  );
1656
2367
  }
1657
2368
  return (context) =>
1658
- createSortedFunction(
2369
+ createSortedRecord(
1659
2370
  names,
1660
2371
  values.map((value) => value(context)),
1661
2372
  );
1662
2373
  };
1663
2374
 
1664
2375
  const compile = (expression: Expression, environment: Environment): Evaluator => {
1665
- const child = (node: Expression) => getEvaluator(node, environment);
2376
+ const getChildEvaluator = (node: Expression) => getEvaluator(node, environment);
1666
2377
  switch (expression.kind) {
1667
2378
  case "Number": {
1668
2379
  const value = expression.value;
@@ -1684,6 +2395,12 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1684
2395
  return compileIdentifier(expression, environment);
1685
2396
  case "Apply":
1686
2397
  return compileApply(expression, environment);
2398
+ case "Bracket":
2399
+ return () => {
2400
+ throw new TlaEvaluationError(
2401
+ `A bracket without a function or subscript is not an expression at ${describeLocation(expression)}`,
2402
+ );
2403
+ };
1687
2404
  case "OperatorReference":
1688
2405
  case "Lambda":
1689
2406
  return () => {
@@ -1692,76 +2409,84 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1692
2409
  );
1693
2410
  };
1694
2411
  case "And": {
1695
- const operands = expression.operands.map(child);
2412
+ const operands = expression.operands.map(getChildEvaluator);
1696
2413
  return (context) => {
1697
2414
  for (let index = 0; index < operands.length; index++) {
1698
2415
  const value = operands[index](context);
1699
- if (typeof value !== "boolean") throw getConjunctError(expression, index, value);
2416
+ if (typeof value !== "boolean") throw createJunctionError(expression, index, value);
1700
2417
  if (!value) return false;
1701
2418
  }
1702
2419
  return true;
1703
2420
  };
1704
2421
  }
1705
2422
  case "Or": {
1706
- const operands = expression.operands.map(child);
2423
+ const operands = expression.operands.map(getChildEvaluator);
1707
2424
  return (context) => {
1708
2425
  for (let index = 0; index < operands.length; index++) {
1709
- if (expectBoolean(operands[index](context), "a disjunct")) return true;
2426
+ const value = operands[index](context);
2427
+ if (typeof value !== "boolean") throw createJunctionError(expression, index, value);
2428
+ if (value) return true;
1710
2429
  }
1711
2430
  return false;
1712
2431
  };
1713
2432
  }
1714
2433
  case "Prime": {
1715
- const inner = child(expression.expression);
2434
+ const inner = getChildEvaluator(expression.expression);
1716
2435
  return (context) => {
1717
- if (!context.next) {
1718
- throw new TlaEvaluationError(
1719
- `A primed expression appears outside an action at ${describeLocation(expression)}`,
1720
- );
1721
- }
2436
+ if (!context.next) throw createPrimeOutsideActionError(expression);
1722
2437
  return inner({
1723
2438
  environment: context.environment,
1724
2439
  scope: context.scope,
1725
2440
  state: context.next,
1726
2441
  next: undefined,
2442
+ isKeepLazy: context.isKeepLazy,
1727
2443
  });
1728
2444
  };
1729
2445
  }
1730
2446
  case "Unchanged": {
1731
- const primed = child({
2447
+ const primed = getChildEvaluator({
1732
2448
  kind: "Prime",
1733
2449
  expression: expression.expression,
1734
2450
  location: expression.location,
1735
2451
  });
1736
- const current = child(expression.expression);
2452
+ const current = getChildEvaluator(expression.expression);
1737
2453
  return (context) => valuesEqual(primed(context), current(context));
1738
2454
  }
1739
2455
  case "If": {
1740
- const condition = child(expression.condition);
1741
- const consequent = child(expression.consequent);
1742
- const alternative = child(expression.alternative);
2456
+ const condition = getChildEvaluator(expression.condition);
2457
+ const consequent = getChildEvaluator(expression.consequent);
2458
+ const alternative = getChildEvaluator(expression.alternative);
1743
2459
  return (context) => {
1744
2460
  const value = condition(context);
1745
- if (typeof value !== "boolean") throw getConditionError(expression, value);
2461
+ if (typeof value !== "boolean") throw createConditionError(expression, value);
1746
2462
  return value ? consequent(context) : alternative(context);
1747
2463
  };
1748
2464
  }
1749
2465
  case "Case": {
1750
2466
  const arms = expression.arms.map((arm) => ({
1751
- condition: child(arm.condition),
1752
- body: child(arm.body),
2467
+ source: arm.condition,
2468
+ condition: getChildEvaluator(arm.condition),
2469
+ body: getChildEvaluator(arm.body),
1753
2470
  }));
1754
- const other = expression.other ? child(expression.other) : undefined;
2471
+ const other = expression.other ? getChildEvaluator(expression.other) : undefined;
1755
2472
  return (context) => {
1756
2473
  for (const arm of arms) {
1757
- if (expectBoolean(arm.condition(context), "a CASE guard")) return arm.body(context);
2474
+ const value = arm.condition(context);
2475
+ if (typeof value !== "boolean") {
2476
+ throw new TlaEvaluationError(
2477
+ `A non-boolean expression (${getKindString(value)}) was used as a condition of a CASE. ${describeNode(arm.source)}`,
2478
+ );
2479
+ }
2480
+ if (value) return arm.body(context);
1758
2481
  }
1759
2482
  if (other) return other(context);
1760
- throw new TlaEvaluationError(`No CASE guard is true at ${describeLocation(expression)}`);
2483
+ throw new TlaEvaluationError(
2484
+ `Attempted to evaluate a CASE with no conditions true.\n${describeRange(expression)}`,
2485
+ );
1761
2486
  };
1762
2487
  }
1763
2488
  case "Let": {
1764
- const body = child(expression.body);
2489
+ const body = getChildEvaluator(expression.body);
1765
2490
  return (context) =>
1766
2491
  body(withScope(context, bindDefinitions(expression.definitions, context)));
1767
2492
  }
@@ -1779,28 +2504,26 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1779
2504
  case "SetMap":
1780
2505
  return compileSetComprehension(expression, environment);
1781
2506
  case "SetEnumeration": {
1782
- const elements = expression.elements.map(child);
2507
+ const elements = expression.elements.map(getChildEvaluator);
1783
2508
  return (context) => createEnumeratedSet(elements.map((element) => element(context)));
1784
2509
  }
1785
2510
  case "Tuple": {
1786
- const elements = expression.elements.map(child);
2511
+ const elements = expression.elements.map(getChildEvaluator);
1787
2512
  return (context) => createTuple(elements.map((element) => element(context)));
1788
2513
  }
1789
2514
  case "FunctionConstruction":
1790
2515
  return compileFunctionConstruction(expression, environment);
1791
2516
  case "FunctionSet": {
1792
- const domain = child(expression.domain);
1793
- const range = child(expression.range);
2517
+ const domain = getChildEvaluator(expression.domain);
2518
+ const range = getChildEvaluator(expression.range);
1794
2519
  return (context) => ({ kind: "FunctionSet", domain: domain(context), range: range(context) });
1795
2520
  }
1796
2521
  case "Record":
1797
2522
  return compileRecord(expression.fields, environment);
1798
2523
  case "RecordSet": {
1799
- const fields = [...expression.fields].sort((left, right) =>
1800
- compareValues(left.name, right.name),
1801
- );
2524
+ const fields = getSortedFields(expression.fields);
1802
2525
  const names = fields.map((field) => field.name);
1803
- const sets = fields.map((field) => child(field.value));
2526
+ const sets = fields.map((field) => getChildEvaluator(field.value));
1804
2527
  return (context) => ({ kind: "RecordSet", names, sets: sets.map((set) => set(context)) });
1805
2528
  }
1806
2529
  case "Except":
@@ -1817,23 +2540,30 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1817
2540
  };
1818
2541
  case "FunctionApplication": {
1819
2542
  keepLazy(expression.function);
1820
- const evaluateFunction = child(expression.function);
1821
- const args = expression.args.map(child);
2543
+ const evaluated = getChildEvaluator(expression.function);
2544
+ const evaluateFunction = (context: Context) =>
2545
+ expectFunction(evaluated(toKeepLazyContext(context)), expression);
2546
+ const args = expression.args.map(getChildEvaluator);
2547
+ const describeMissing = getMissingArgumentDescriber(environment.runtime.version);
1822
2548
  if (args.length === 1) {
1823
2549
  const argument = args[0];
1824
- return (context) => applyFunction(evaluateFunction(context), argument(context));
2550
+ return (context) =>
2551
+ applyFunction(evaluateFunction(context), argument(context), describeMissing);
1825
2552
  }
1826
2553
  return (context) =>
1827
- applyFunction(evaluateFunction(context), createTuple(args.map((arg) => arg(context))));
2554
+ applyFunction(
2555
+ evaluateFunction(context),
2556
+ createTuple(args.map((arg) => arg(context))),
2557
+ describeMissing,
2558
+ );
1828
2559
  }
1829
2560
  case "FieldAccess": {
1830
- const record = child(expression.record);
1831
- const field = expression.field;
1832
- const describeMissing = getFieldError(expression);
1833
- return (context) => applyFunction(record(context), field, describeMissing);
2561
+ const record = getChildEvaluator(expression.record);
2562
+ const select = getFieldSelector(expression);
2563
+ return (context) => select(record(context));
1834
2564
  }
1835
2565
  case "Product": {
1836
- const factors = expression.factors.map(child);
2566
+ const factors = expression.factors.map(getChildEvaluator);
1837
2567
  return (context) => ({
1838
2568
  kind: "ProductSet",
1839
2569
  factors: factors.map((factor) => factor(context)),
@@ -1841,8 +2571,8 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1841
2571
  }
1842
2572
  case "BoxAction":
1843
2573
  case "AngleAction": {
1844
- const action = child(expression.action);
1845
- const unchanged = child({
2574
+ const action = getChildEvaluator(expression.action);
2575
+ const unchanged = getChildEvaluator({
1846
2576
  kind: "Unchanged",
1847
2577
  expression: expression.subscript,
1848
2578
  location: expression.location,
@@ -1858,7 +2588,7 @@ const compile = (expression: Expression, environment: Environment): Evaluator =>
1858
2588
  return (context) => isEnabled(action, context);
1859
2589
  }
1860
2590
  case "Label":
1861
- return child(expression.body);
2591
+ return getChildEvaluator(expression.body);
1862
2592
  case "Subexpression":
1863
2593
  return () => {
1864
2594
  throw new TlaEvaluationError(