tla-ts 0.0.3 → 0.0.4-dev.2a873ee

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