tla-ts 0.0.10-dev.b4a856304 → 0.0.10-dev.c92e6a4ea

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 (586) hide show
  1. package/README.md +2 -1
  2. package/dist/compile.cjs +6 -6
  3. package/dist/compile.js +10 -10
  4. package/dist/deciders.cjs +41 -37
  5. package/dist/deciders.js +57 -53
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +37 -0
  8. package/dist/index.d.ts +37 -0
  9. package/dist/index.js +1 -1
  10. package/dist/parallel-worker.cjs +1 -1
  11. package/dist/parallel-worker.js +1 -1
  12. package/dist/prove.cjs +2683 -427
  13. package/dist/prove.js +2681 -425
  14. package/dist/run.cjs +45 -44
  15. package/dist/run.js +45 -44
  16. package/dist/tlapm.cjs +2 -2
  17. package/dist/tlapm.js +2 -2
  18. package/dist/transfer.cjs +44 -41
  19. package/dist/transfer.js +45 -42
  20. package/dist/worker.cjs +7 -7
  21. package/dist/worker.js +7 -7
  22. package/package.json +1 -1
  23. package/src/ast.ts +41 -41
  24. package/src/bags.ts +2 -5
  25. package/src/builtins.ts +5 -21
  26. package/src/check-failure.ts +116 -0
  27. package/src/check-trace.ts +268 -0
  28. package/src/check.ts +578 -757
  29. package/src/cli/options.ts +6 -31
  30. package/src/cli/run.ts +0 -2
  31. package/src/cli/runtime-invariants.ts +27 -62
  32. package/src/cli/shared.ts +1 -5
  33. package/src/cli/tlapm.ts +433 -70
  34. package/src/cli/tlc-arguments.ts +246 -240
  35. package/src/cli/tlc-output.ts +686 -0
  36. package/src/cli/tlc-usage.ts +3 -5
  37. package/src/cli/tlc.ts +59 -707
  38. package/src/cli/xml-exporter.ts +23 -33
  39. package/src/codegen.ts +5 -10
  40. package/src/coverage.ts +3 -10
  41. package/src/dependencies.ts +30 -14
  42. package/src/dfid.ts +16 -16
  43. package/src/environment-config.ts +315 -0
  44. package/src/environment.ts +73 -338
  45. package/src/errors.ts +33 -5
  46. package/src/evaluate.ts +34 -107
  47. package/src/exit-codes.ts +3 -0
  48. package/src/fingerprints.ts +65 -1
  49. package/src/instances.ts +47 -10
  50. package/src/java-hash.ts +7 -0
  51. package/src/java-overrides.ts +4 -9
  52. package/src/json-reader.ts +1 -2
  53. package/src/json.ts +8 -18
  54. package/src/levels.ts +46 -57
  55. package/src/lexer.ts +76 -85
  56. package/src/liveness-checker.ts +634 -306
  57. package/src/liveness.ts +104 -120
  58. package/src/obligations/action.ts +14 -17
  59. package/src/obligations/anonymize.ts +37 -16
  60. package/src/obligations/enabled-axioms.ts +218 -0
  61. package/src/obligations/equality.ts +1 -3
  62. package/src/obligations/expression.ts +36 -8
  63. package/src/obligations/format.ts +0 -2
  64. package/src/obligations/generate.ts +66 -54
  65. package/src/obligations/index.ts +38 -8
  66. package/src/obligations/levels.ts +24 -11
  67. package/src/obligations/module.ts +28 -41
  68. package/src/obligations/normalize.ts +26 -14
  69. package/src/obligations/operators.ts +0 -2
  70. package/src/obligations/pragma.ts +53 -16
  71. package/src/obligations/printer.ts +43 -13
  72. package/src/obligations/proof.ts +3 -2
  73. package/src/obligations/regroup.ts +0 -2
  74. package/src/obligations/simplify.ts +55 -50
  75. package/src/obligations/source.ts +118 -74
  76. package/src/obligations/subexpression.ts +45 -18
  77. package/src/obligations/substitution.ts +1 -3
  78. package/src/obligations/temporal.ts +5 -7
  79. package/src/obligations/tuples.ts +0 -2
  80. package/src/parallel-worker.ts +17 -31
  81. package/src/parallel.ts +55 -80
  82. package/src/parser.ts +722 -385
  83. package/src/pcal/ast.ts +53 -65
  84. package/src/pcal/parse.ts +144 -191
  85. package/src/pcal/tokenize.ts +91 -115
  86. package/src/pcal/translate.ts +83 -98
  87. package/src/pcal/validate.ts +48 -50
  88. package/src/pretty-print.ts +7 -7
  89. package/src/prover/decide-pool.ts +3 -3
  90. package/src/prover/deciders.ts +12 -9
  91. package/src/prover/isabelle/decide.ts +3 -25
  92. package/src/prover/isabelle/encode.ts +72 -42
  93. package/src/prover/isabelle/isar/attrib.ts +250 -0
  94. package/src/prover/isabelle/isar/context.ts +335 -0
  95. package/src/prover/isabelle/isar/induct.ts +382 -0
  96. package/src/prover/isabelle/isar/inner-syntax.ts +158 -7
  97. package/src/prover/isabelle/isar/method.ts +509 -212
  98. package/src/prover/isabelle/isar/proof.ts +570 -14
  99. package/src/prover/isabelle/isar/rule-cases.ts +224 -0
  100. package/src/prover/isabelle/isar/theory.ts +487 -76
  101. package/src/prover/isabelle/isar/toplevel.ts +331 -0
  102. package/src/prover/isabelle/isar/type-check.ts +89 -14
  103. package/src/prover/isabelle/provers/blast/blast.ts +7 -65
  104. package/src/prover/isabelle/provers/blast/branch.ts +0 -2
  105. package/src/prover/isabelle/provers/blast/prove.ts +0 -2
  106. package/src/prover/isabelle/provers/blast/rules.ts +0 -2
  107. package/src/prover/isabelle/provers/blast/state.ts +0 -2
  108. package/src/prover/isabelle/provers/blast/term.ts +0 -2
  109. package/src/prover/isabelle/provers/clasimp.ts +0 -2
  110. package/src/prover/isabelle/provers/classical.ts +45 -20
  111. package/src/prover/isabelle/provers/hypsubst.ts +17 -28
  112. package/src/prover/isabelle/pure/bicompose.ts +9 -27
  113. package/src/prover/isabelle/pure/consts.ts +0 -2
  114. package/src/prover/isabelle/pure/conv.ts +2 -10
  115. package/src/prover/isabelle/pure/drule.ts +72 -6
  116. package/src/prover/isabelle/pure/envir.ts +0 -2
  117. package/src/prover/isabelle/pure/goal.ts +1 -3
  118. package/src/prover/isabelle/pure/logic.ts +1 -3
  119. package/src/prover/isabelle/pure/name.ts +0 -2
  120. package/src/prover/isabelle/pure/net.ts +0 -2
  121. package/src/prover/isabelle/pure/object-logic.ts +13 -7
  122. package/src/prover/isabelle/pure/pattern.ts +0 -2
  123. package/src/prover/isabelle/pure/raw-simplifier.ts +4 -15
  124. package/src/prover/isabelle/pure/rewriter.ts +6 -17
  125. package/src/prover/isabelle/pure/search.ts +0 -2
  126. package/src/prover/isabelle/pure/seq.ts +0 -2
  127. package/src/prover/isabelle/pure/simplifier.ts +26 -7
  128. package/src/prover/isabelle/pure/table.ts +2 -3
  129. package/src/prover/isabelle/pure/tactic.ts +0 -2
  130. package/src/prover/isabelle/pure/tactical.ts +42 -37
  131. package/src/prover/isabelle/pure/term-ord.ts +0 -2
  132. package/src/prover/isabelle/pure/term.ts +0 -2
  133. package/src/prover/isabelle/pure/thm.ts +14 -13
  134. package/src/prover/isabelle/pure/type.ts +0 -2
  135. package/src/prover/isabelle/pure/unify.ts +0 -2
  136. package/src/prover/isabelle/pure/variable.ts +0 -2
  137. package/src/prover/isabelle/tla/classical-setup.ts +18 -16
  138. package/src/prover/isabelle/tla/context.ts +58 -11
  139. package/src/prover/isabelle/tla/logic-data.ts +1 -1
  140. package/src/prover/isabelle/tla/logic.ts +49 -21
  141. package/src/prover/isabelle/tla/simpdata.ts +1 -12
  142. package/src/prover/isabelle/tools/intuitionistic.ts +28 -12
  143. package/src/prover/ocaml.ts +4 -1
  144. package/src/prover/prep/action.ts +30 -31
  145. package/src/prover/prep/enabled-axioms.ts +11 -2
  146. package/src/prover/prep/fingerprint.ts +2 -5
  147. package/src/prover/prep/methods.ts +181 -51
  148. package/src/prover/prep/normalize.ts +38 -9
  149. package/src/prover/prove.ts +395 -94
  150. package/src/prover/ptl/decide.ts +95 -50
  151. package/src/prover/ptl/encode.ts +2 -3
  152. package/src/prover/ptl/tableau.ts +28 -2
  153. package/src/prover/smt/arithmetic.ts +310 -0
  154. package/src/prover/smt/axioms.ts +12 -8
  155. package/src/prover/smt/context.ts +43 -8
  156. package/src/prover/smt/data.ts +498 -379
  157. package/src/prover/smt/encode.ts +148 -57
  158. package/src/prover/smt/extensionality.ts +5 -3
  159. package/src/prover/smt/flatten.ts +4 -6
  160. package/src/prover/smt/format.ts +28 -4
  161. package/src/prover/smt/instances.ts +7 -1
  162. package/src/prover/smt/layout.ts +91 -0
  163. package/src/prover/smt/rewrite.ts +1021 -618
  164. package/src/prover/smt/simplify.ts +441 -0
  165. package/src/prover/smt/solver/ackermannize-bv-tactic.ts +61 -0
  166. package/src/prover/smt/solver/ackr-helper.ts +179 -0
  167. package/src/prover/smt/solver/ackr-model-converter.ts +105 -0
  168. package/src/prover/smt/solver/act-cache.ts +0 -1
  169. package/src/prover/smt/solver/add-bounds-tactic.ts +59 -0
  170. package/src/prover/smt/solver/aig-tactic.ts +52 -0
  171. package/src/prover/smt/solver/aig.ts +889 -0
  172. package/src/prover/smt/solver/arith-rewriter.ts +613 -6
  173. package/src/prover/smt/solver/arith-terms.ts +121 -0
  174. package/src/prover/smt/solver/array-decl-plugin.ts +175 -0
  175. package/src/prover/smt/solver/array-rewriter.ts +309 -0
  176. package/src/prover/smt/solver/asserted-formulas.ts +87 -16
  177. package/src/prover/smt/solver/ast-lt.ts +166 -12
  178. package/src/prover/smt/solver/ast-util.ts +160 -2
  179. package/src/prover/smt/solver/ast.ts +1427 -41
  180. package/src/prover/smt/solver/auf-solver.ts +2 -6
  181. package/src/prover/smt/solver/bit-blast-tactic.ts +582 -0
  182. package/src/prover/smt/solver/bit-blaster.ts +871 -0
  183. package/src/prover/smt/solver/bound-manager.ts +196 -0
  184. package/src/prover/smt/solver/bound-simplifier.ts +600 -0
  185. package/src/prover/smt/solver/bv-bound-chk.ts +492 -0
  186. package/src/prover/smt/solver/bv-decl-plugin.ts +338 -0
  187. package/src/prover/smt/solver/bv-divrem-bounds.ts +95 -0
  188. package/src/prover/smt/solver/bv-rewriter.ts +1901 -0
  189. package/src/prover/smt/solver/bv1-blast.ts +214 -0
  190. package/src/prover/smt/solver/bv2fpa-converter.ts +174 -0
  191. package/src/prover/smt/solver/bv2int-rewriter.ts +544 -0
  192. package/src/prover/smt/solver/bv2real-rewriter.ts +533 -0
  193. package/src/prover/smt/solver/card2bv.ts +110 -0
  194. package/src/prover/smt/solver/case-split-queue.ts +0 -2
  195. package/src/prover/smt/solver/cg-table.ts +39 -25
  196. package/src/prover/smt/solver/check-logic.ts +330 -0
  197. package/src/prover/smt/solver/clause.ts +0 -1
  198. package/src/prover/smt/solver/cofactor-elim-term-ite.ts +278 -0
  199. package/src/prover/smt/solver/conflict-resolution.ts +78 -2
  200. package/src/prover/smt/solver/context.ts +516 -115
  201. package/src/prover/smt/solver/ctx-simplify.ts +20 -10
  202. package/src/prover/smt/solver/ctx-solver-simplify.ts +122 -0
  203. package/src/prover/smt/solver/datatype-decl-plugin.ts +572 -0
  204. package/src/prover/smt/solver/datatype-rewriter.ts +82 -0
  205. package/src/prover/smt/solver/demodulator.ts +786 -0
  206. package/src/prover/smt/solver/dependent-expr-state.ts +81 -0
  207. package/src/prover/smt/solver/der.ts +38 -10
  208. package/src/prover/smt/solver/diff-neq.ts +206 -0
  209. package/src/prover/smt/solver/distribute-forall.ts +57 -0
  210. package/src/prover/smt/solver/dom-simplify.ts +511 -0
  211. package/src/prover/smt/solver/dt2bv-tactic.ts +260 -0
  212. package/src/prover/smt/solver/dyn-ack.ts +0 -1
  213. package/src/prover/smt/solver/e-matching.ts +7 -8
  214. package/src/prover/smt/solver/elim-small-bv-tactic.ts +129 -0
  215. package/src/prover/smt/solver/elim-uncnstr.ts +545 -0
  216. package/src/prover/smt/solver/enode.ts +100 -3
  217. package/src/prover/smt/solver/eq2bv-tactic.ts +218 -0
  218. package/src/prover/smt/solver/euf/arith-axioms.ts +403 -0
  219. package/src/prover/smt/solver/euf/arith-internalize.ts +653 -0
  220. package/src/prover/smt/solver/euf/arith-solver.ts +889 -0
  221. package/src/prover/smt/solver/euf/array-axioms.ts +527 -0
  222. package/src/prover/smt/solver/euf/array-internalize.ts +428 -0
  223. package/src/prover/smt/solver/euf/array-solver.ts +306 -0
  224. package/src/prover/smt/solver/euf/bv-ackerman.ts +162 -0
  225. package/src/prover/smt/solver/euf/bv-internalize.ts +748 -0
  226. package/src/prover/smt/solver/euf/bv-solver.ts +449 -0
  227. package/src/prover/smt/solver/euf/dt-solver.ts +618 -0
  228. package/src/prover/smt/solver/euf/egraph.ts +908 -0
  229. package/src/prover/smt/solver/euf/euf-solver.ts +1205 -0
  230. package/src/prover/smt/solver/euf/fpa-solver.ts +317 -0
  231. package/src/prover/smt/solver/euf/mam.ts +1050 -0
  232. package/src/prover/smt/solver/euf/q-ematch.ts +830 -0
  233. package/src/prover/smt/solver/euf/q-mbi.ts +587 -0
  234. package/src/prover/smt/solver/euf/q-model-fixer.ts +296 -0
  235. package/src/prover/smt/solver/euf/q-solver.ts +361 -0
  236. package/src/prover/smt/solver/euf/th-solver.ts +335 -0
  237. package/src/prover/smt/solver/euf/th-solvers.ts +30 -0
  238. package/src/prover/smt/solver/expr-ref.ts +0 -1
  239. package/src/prover/smt/solver/expr-safe-replace.ts +26 -2
  240. package/src/prover/smt/solver/expr2polynomial.ts +146 -0
  241. package/src/prover/smt/solver/factor.ts +141 -0
  242. package/src/prover/smt/solver/fd-solver.ts +265 -0
  243. package/src/prover/smt/solver/fingerprints.ts +15 -15
  244. package/src/prover/smt/solver/fix-dl-var.ts +148 -0
  245. package/src/prover/smt/solver/flat-literals.ts +0 -1
  246. package/src/prover/smt/solver/fm-tactic.ts +884 -0
  247. package/src/prover/smt/solver/fpa-decl-plugin.ts +618 -0
  248. package/src/prover/smt/solver/fpa-rewriter.ts +640 -0
  249. package/src/prover/smt/solver/fpa2bv-converter.ts +2249 -0
  250. package/src/prover/smt/solver/fpa2bv-rewriter.ts +348 -0
  251. package/src/prover/smt/solver/fpa2bv-tactic.ts +73 -0
  252. package/src/prover/smt/solver/goal.ts +175 -15
  253. package/src/prover/smt/solver/goal2nlsat.ts +189 -0
  254. package/src/prover/smt/solver/guard-set.ts +219 -0
  255. package/src/prover/smt/solver/hash.ts +0 -1
  256. package/src/prover/smt/solver/hashtable.ts +30 -16
  257. package/src/prover/smt/solver/inf-eps.ts +63 -0
  258. package/src/prover/smt/solver/inj-axiom.ts +101 -0
  259. package/src/prover/smt/solver/internalizer.ts +110 -38
  260. package/src/prover/smt/solver/lackr.ts +381 -0
  261. package/src/prover/smt/solver/lbool.ts +0 -1
  262. package/src/prover/smt/solver/lia2card.ts +268 -0
  263. package/src/prover/smt/solver/lia2pb.ts +154 -0
  264. package/src/prover/smt/solver/literal.ts +0 -1
  265. package/src/prover/smt/solver/logic-tactics.ts +345 -0
  266. package/src/prover/smt/solver/lp/bound-propagator.ts +0 -1
  267. package/src/prover/smt/solver/lp/constraints.ts +0 -1
  268. package/src/prover/smt/solver/lp/containers.ts +7 -2
  269. package/src/prover/smt/solver/lp/core-solver.ts +18 -3
  270. package/src/prover/smt/solver/lp/cross-nested.ts +1 -4
  271. package/src/prover/smt/solver/lp/dep-intervals.ts +0 -3
  272. package/src/prover/smt/solver/lp/dependency.ts +0 -2
  273. package/src/prover/smt/solver/lp/dioph-eq.ts +1 -10
  274. package/src/prover/smt/solver/lp/explanation.ts +0 -1
  275. package/src/prover/smt/solver/lp/gomory.ts +0 -1
  276. package/src/prover/smt/solver/lp/hnf-cutter.ts +1 -2
  277. package/src/prover/smt/solver/lp/hnf.ts +0 -3
  278. package/src/prover/smt/solver/lp/int-cube.ts +3 -4
  279. package/src/prover/smt/solver/lp/int-solver.ts +0 -2
  280. package/src/prover/smt/solver/lp/lar-solver.ts +40 -4
  281. package/src/prover/smt/solver/lp/lar-term.ts +0 -1
  282. package/src/prover/smt/solver/lp/lp-settings.ts +0 -1
  283. package/src/prover/smt/solver/lp/maximize-term.ts +59 -10
  284. package/src/prover/smt/solver/lp/nex-creator.ts +3 -3
  285. package/src/prover/smt/solver/lp/nex.ts +2 -2
  286. package/src/prover/smt/solver/lp/nla-backoff.ts +0 -2
  287. package/src/prover/smt/solver/lp/nla-basics.ts +46 -3
  288. package/src/prover/smt/solver/lp/nla-core.ts +67 -16
  289. package/src/prover/smt/solver/lp/nla-divisions.ts +0 -2
  290. package/src/prover/smt/solver/lp/nla-emonics.ts +0 -1
  291. package/src/prover/smt/solver/lp/nla-factorization.ts +0 -1
  292. package/src/prover/smt/solver/lp/nla-grobner.ts +165 -83
  293. package/src/prover/smt/solver/lp/nla-horner.ts +0 -2
  294. package/src/prover/smt/solver/lp/nla-intervals.ts +0 -1
  295. package/src/prover/smt/solver/lp/nla-monomial-bounds.ts +0 -2
  296. package/src/prover/smt/solver/lp/nla-monotone.ts +0 -1
  297. package/src/prover/smt/solver/lp/nla-order.ts +0 -2
  298. package/src/prover/smt/solver/lp/nla-patcher.ts +0 -1
  299. package/src/prover/smt/solver/lp/nla-powers.ts +220 -0
  300. package/src/prover/smt/solver/lp/nla-tangents.ts +0 -2
  301. package/src/prover/smt/solver/lp/nla-throttle.ts +0 -1
  302. package/src/prover/smt/solver/lp/nla-transcendentals.ts +324 -0
  303. package/src/prover/smt/solver/lp/nla-types.ts +0 -2
  304. package/src/prover/smt/solver/lp/nla-var-eqs.ts +0 -1
  305. package/src/prover/smt/solver/lp/nra-solver.ts +122 -64
  306. package/src/prover/smt/solver/lp/numeric-pair.ts +0 -1
  307. package/src/prover/smt/solver/lp/pdd-interval.ts +6 -3
  308. package/src/prover/smt/solver/lp/pdd-simplifier.ts +60 -21
  309. package/src/prover/smt/solver/lp/pdd-solver.ts +72 -41
  310. package/src/prover/smt/solver/lp/pdd.ts +725 -289
  311. package/src/prover/smt/solver/lp/random-updater.ts +0 -2
  312. package/src/prover/smt/solver/lp/static-matrix.ts +0 -1
  313. package/src/prover/smt/solver/lp/union-find.ts +7 -2
  314. package/src/prover/smt/solver/macro-finder.ts +530 -0
  315. package/src/prover/smt/solver/mam-compiler.ts +122 -90
  316. package/src/prover/smt/solver/mam-interpreter.ts +0 -1
  317. package/src/prover/smt/solver/max-bv-sharing-tactic.ts +17 -0
  318. package/src/prover/smt/solver/max-cliques.ts +105 -0
  319. package/src/prover/smt/solver/maxcore.ts +309 -0
  320. package/src/prover/smt/solver/maximize-ac-sharing.ts +8 -6
  321. package/src/prover/smt/solver/maxlex.ts +115 -0
  322. package/src/prover/smt/solver/maxsmt-base.ts +105 -0
  323. package/src/prover/smt/solver/maxsmt.ts +92 -0
  324. package/src/prover/smt/solver/mbp/mbp-arith.ts +467 -0
  325. package/src/prover/smt/solver/mbp/mbp-basic-tg.ts +101 -0
  326. package/src/prover/smt/solver/mbp/mbp-plugin.ts +287 -0
  327. package/src/prover/smt/solver/mbp/mbp-qel.ts +48 -0
  328. package/src/prover/smt/solver/mbp/mbp-solve-plugin.ts +271 -0
  329. package/src/prover/smt/solver/mbp/mbp-term-graph.ts +606 -0
  330. package/src/prover/smt/solver/model-based-opt.ts +844 -0
  331. package/src/prover/smt/solver/model-checker.ts +18 -27
  332. package/src/prover/smt/solver/model-evaluator.ts +188 -12
  333. package/src/prover/smt/solver/model-finder.ts +12 -18
  334. package/src/prover/smt/solver/model-generator.ts +56 -29
  335. package/src/prover/smt/solver/model-macro-solver.ts +49 -46
  336. package/src/prover/smt/solver/model-printer.ts +214 -0
  337. package/src/prover/smt/solver/mpf.ts +711 -0
  338. package/src/prover/smt/solver/mus.ts +51 -0
  339. package/src/prover/smt/solver/muz/dl-context.ts +404 -0
  340. package/src/prover/smt/solver/muz/dl-mk-bit-blast.ts +97 -0
  341. package/src/prover/smt/solver/muz/dl-mk-coi-filter.ts +167 -0
  342. package/src/prover/smt/solver/muz/dl-mk-elim-term-ite.ts +125 -0
  343. package/src/prover/smt/solver/muz/dl-mk-interp-tail-simplifier.ts +299 -0
  344. package/src/prover/smt/solver/muz/dl-mk-rule-inliner.ts +455 -0
  345. package/src/prover/smt/solver/muz/dl-mk-slice.ts +340 -0
  346. package/src/prover/smt/solver/muz/dl-mk-subsumption-checker.ts +163 -0
  347. package/src/prover/smt/solver/muz/dl-rule-set.ts +273 -0
  348. package/src/prover/smt/solver/muz/dl-rule-transformer.ts +123 -0
  349. package/src/prover/smt/solver/muz/dl-rule.ts +496 -0
  350. package/src/prover/smt/solver/muz/hnf.ts +201 -0
  351. package/src/prover/smt/solver/muz/horn-subsume-model-converter.ts +176 -0
  352. package/src/prover/smt/solver/muz/horn-tactic.ts +201 -0
  353. package/src/prover/smt/solver/muz/rule-properties.ts +337 -0
  354. package/src/prover/smt/solver/muz/spacer-context.ts +1406 -0
  355. package/src/prover/smt/solver/muz/spacer-dl-interface.ts +52 -0
  356. package/src/prover/smt/solver/muz/spacer-generalizers.ts +241 -0
  357. package/src/prover/smt/solver/muz/spacer-manager.ts +127 -0
  358. package/src/prover/smt/solver/muz/spacer-pdr.ts +218 -0
  359. package/src/prover/smt/solver/muz/spacer-prop-solver.ts +333 -0
  360. package/src/prover/smt/solver/muz/spacer-util.ts +282 -0
  361. package/src/prover/smt/solver/muz/substitution.ts +203 -0
  362. package/src/prover/smt/solver/nla2bv-tactic.ts +285 -0
  363. package/src/prover/smt/solver/nlqsat.ts +484 -0
  364. package/src/prover/smt/solver/nlsat/algebraic.ts +125 -12
  365. package/src/prover/smt/solver/nlsat/atoms.ts +20 -6
  366. package/src/prover/smt/solver/nlsat/evaluator.ts +0 -1
  367. package/src/prover/smt/solver/nlsat/explain.ts +63 -23
  368. package/src/prover/smt/solver/nlsat/interval-set.ts +1 -2
  369. package/src/prover/smt/solver/nlsat/levelwise.ts +3 -9
  370. package/src/prover/smt/solver/nlsat/mpbq.ts +45 -1
  371. package/src/prover/smt/solver/nlsat/polynomial.ts +13 -6
  372. package/src/prover/smt/solver/nlsat/solver.ts +236 -45
  373. package/src/prover/smt/solver/nlsat/transcendental-eval.ts +310 -0
  374. package/src/prover/smt/solver/nlsat/transcendentals.ts +367 -0
  375. package/src/prover/smt/solver/nlsat/types.ts +0 -2
  376. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +1 -4
  377. package/src/prover/smt/solver/nlsat/upolynomial.ts +0 -2
  378. package/src/prover/smt/solver/nlsat-tactic.ts +82 -0
  379. package/src/prover/smt/solver/nnf.ts +105 -23
  380. package/src/prover/smt/solver/normalize-bounds.ts +53 -0
  381. package/src/prover/smt/solver/occf.ts +97 -0
  382. package/src/prover/smt/solver/opt-context.ts +787 -0
  383. package/src/prover/smt/solver/opt-nlsat.ts +375 -0
  384. package/src/prover/smt/solver/opt-pareto.ts +282 -0
  385. package/src/prover/smt/solver/opt-preprocess.ts +101 -0
  386. package/src/prover/smt/solver/opt-solver.ts +308 -0
  387. package/src/prover/smt/solver/opt-value.ts +55 -0
  388. package/src/prover/smt/solver/optsmt.ts +692 -0
  389. package/src/prover/smt/solver/parallel-tactic.ts +299 -0
  390. package/src/prover/smt/solver/pattern-inference.ts +19 -11
  391. package/src/prover/smt/solver/pb-rewriter.ts +284 -0
  392. package/src/prover/smt/solver/pb2bv-tactic.ts +540 -0
  393. package/src/prover/smt/solver/poly-rewriter.ts +202 -57
  394. package/src/prover/smt/solver/probes.ts +512 -0
  395. package/src/prover/smt/solver/propagate-values.ts +37 -21
  396. package/src/prover/smt/solver/proto-model.ts +648 -19
  397. package/src/prover/smt/solver/pull-quant.ts +28 -12
  398. package/src/prover/smt/solver/purify-arith.ts +632 -0
  399. package/src/prover/smt/solver/qe-arith-plugin.ts +1098 -0
  400. package/src/prover/smt/solver/qe-lite-der.ts +2 -3
  401. package/src/prover/smt/solver/qe-lite-fm.ts +3 -4
  402. package/src/prover/smt/solver/qe-lite.ts +37 -17
  403. package/src/prover/smt/solver/qe-mbp.ts +270 -0
  404. package/src/prover/smt/solver/qe.ts +1498 -0
  405. package/src/prover/smt/solver/qel.ts +25 -0
  406. package/src/prover/smt/solver/qi-queue.ts +0 -1
  407. package/src/prover/smt/solver/qsat.ts +814 -0
  408. package/src/prover/smt/solver/quant-hoist.ts +196 -0
  409. package/src/prover/smt/solver/quant-tactics.ts +16 -56
  410. package/src/prover/smt/solver/quantifier-analyzer.ts +19 -20
  411. package/src/prover/smt/solver/quantifier-manager.ts +8 -16
  412. package/src/prover/smt/solver/quasi-macros.ts +243 -0
  413. package/src/prover/smt/solver/random-gen.ts +0 -1
  414. package/src/prover/smt/solver/rational.ts +45 -1
  415. package/src/prover/smt/solver/recfun-decl-plugin.ts +261 -0
  416. package/src/prover/smt/solver/recfun-rewriter.ts +107 -0
  417. package/src/prover/smt/solver/reduce-args.ts +225 -0
  418. package/src/prover/smt/solver/reduce-bv-size.ts +119 -0
  419. package/src/prover/smt/solver/ref-vector.ts +0 -1
  420. package/src/prover/smt/solver/relevancy.ts +1 -2
  421. package/src/prover/smt/solver/rewriter-tpl.ts +77 -10
  422. package/src/prover/smt/solver/rewriter.ts +475 -36
  423. package/src/prover/smt/solver/rlimit.ts +38 -2
  424. package/src/prover/smt/solver/sat/asymm-branch.ts +325 -0
  425. package/src/prover/smt/solver/sat/big.ts +177 -0
  426. package/src/prover/smt/solver/sat/clause-use-list.ts +71 -0
  427. package/src/prover/smt/solver/sat/clause.ts +203 -0
  428. package/src/prover/smt/solver/sat/cleaner.ts +94 -0
  429. package/src/prover/smt/solver/sat/config.ts +122 -0
  430. package/src/prover/smt/solver/sat/consequences.ts +203 -0
  431. package/src/prover/smt/solver/sat/elim-eqs.ts +142 -0
  432. package/src/prover/smt/solver/sat/goal2sat.ts +526 -0
  433. package/src/prover/smt/solver/sat/inc-sat-solver.ts +378 -0
  434. package/src/prover/smt/solver/sat/model-converter.ts +136 -0
  435. package/src/prover/smt/solver/sat/pb-constraint.ts +261 -0
  436. package/src/prover/smt/solver/sat/pb-solver.ts +1577 -0
  437. package/src/prover/smt/solver/sat/probing.ts +170 -0
  438. package/src/prover/smt/solver/sat/sat-tactic.ts +43 -0
  439. package/src/prover/smt/solver/sat/sat2goal.ts +165 -0
  440. package/src/prover/smt/solver/sat/scc.ts +142 -0
  441. package/src/prover/smt/solver/sat/simplifier.ts +1618 -0
  442. package/src/prover/smt/solver/sat/solver.ts +2127 -0
  443. package/src/prover/smt/solver/sat/var-queue.ts +117 -0
  444. package/src/prover/smt/solver/sat/watch-list.ts +140 -0
  445. package/src/prover/smt/solver/search-tree.ts +284 -0
  446. package/src/prover/smt/solver/seq-axioms.ts +1010 -0
  447. package/src/prover/smt/solver/seq-decl-plugin.ts +819 -0
  448. package/src/prover/smt/solver/seq-derive.ts +1298 -0
  449. package/src/prover/smt/solver/seq-eq-approx.ts +236 -0
  450. package/src/prover/smt/solver/seq-eq-solver.ts +439 -0
  451. package/src/prover/smt/solver/seq-factory.ts +89 -0
  452. package/src/prover/smt/solver/seq-monadic.ts +728 -0
  453. package/src/prover/smt/solver/seq-range-predicate.ts +235 -0
  454. package/src/prover/smt/solver/seq-re-rewriter.ts +1170 -0
  455. package/src/prover/smt/solver/seq-re-util.ts +758 -0
  456. package/src/prover/smt/solver/seq-regex-bisim.ts +144 -0
  457. package/src/prover/smt/solver/seq-regex-live.ts +200 -0
  458. package/src/prover/smt/solver/seq-rewriter.ts +2402 -0
  459. package/src/prover/smt/solver/seq-skolem.ts +317 -0
  460. package/src/prover/smt/solver/seq-subset.ts +165 -0
  461. package/src/prover/smt/solver/seq-view-witness.ts +353 -0
  462. package/src/prover/smt/solver/smt-consequences.ts +297 -0
  463. package/src/prover/smt/solver/smt-kernel.ts +83 -0
  464. package/src/prover/smt/solver/smt-logics.ts +66 -0
  465. package/src/prover/smt/solver/smt-setup.ts +496 -0
  466. package/src/prover/smt/solver/smt2-printer.ts +765 -0
  467. package/src/prover/smt/solver/smtlib-parser.ts +3126 -316
  468. package/src/prover/smt/solver/smtlib-script.ts +1631 -0
  469. package/src/prover/smt/solver/solve-eqs.ts +929 -0
  470. package/src/prover/smt/solver/solver.ts +113 -22
  471. package/src/prover/smt/solver/static-features.ts +314 -0
  472. package/src/prover/smt/solver/sticky-generations.ts +0 -1
  473. package/src/prover/smt/solver/tactic.ts +1986 -0
  474. package/src/prover/smt/solver/term-enumeration.ts +205 -0
  475. package/src/prover/smt/solver/theory-array.ts +1240 -0
  476. package/src/prover/smt/solver/theory-bv.ts +1200 -0
  477. package/src/prover/smt/solver/theory-char.ts +355 -0
  478. package/src/prover/smt/solver/theory-datatype.ts +598 -0
  479. package/src/prover/smt/solver/theory-finite-set.ts +30 -0
  480. package/src/prover/smt/solver/theory-fpa.ts +389 -0
  481. package/src/prover/smt/solver/theory-lra-axioms.ts +53 -2
  482. package/src/prover/smt/solver/theory-lra-bounds.ts +31 -6
  483. package/src/prover/smt/solver/theory-lra-final-check.ts +56 -70
  484. package/src/prover/smt/solver/theory-lra-internalize.ts +94 -27
  485. package/src/prover/smt/solver/theory-lra-model.ts +20 -35
  486. package/src/prover/smt/solver/theory-lra-propagate.ts +24 -26
  487. package/src/prover/smt/solver/theory-lra-state.ts +6 -22
  488. package/src/prover/smt/solver/theory-lra.ts +188 -1
  489. package/src/prover/smt/solver/theory-pb.ts +934 -0
  490. package/src/prover/smt/solver/theory-polymorphism.ts +58 -0
  491. package/src/prover/smt/solver/theory-recfun.ts +307 -0
  492. package/src/prover/smt/solver/theory-seq-regex.ts +867 -0
  493. package/src/prover/smt/solver/theory-seq-solve.ts +1373 -0
  494. package/src/prover/smt/solver/theory-seq-state.ts +871 -0
  495. package/src/prover/smt/solver/theory-seq.ts +961 -0
  496. package/src/prover/smt/solver/theory.ts +189 -0
  497. package/src/prover/smt/solver/tseitin-cnf.ts +485 -0
  498. package/src/prover/smt/solver/var-subst.ts +36 -14
  499. package/src/prover/smt/table.ts +3 -2
  500. package/src/prover/smt/types.ts +146 -0
  501. package/src/prover/tlapm/cache.ts +50 -19
  502. package/src/prover/tlapm/tlapm.ts +15 -9
  503. package/src/prover/tlapm-library.ts +3208 -0
  504. package/src/prover/verdict.ts +9 -0
  505. package/src/prover/zenon/check/check.ts +1 -2
  506. package/src/prover/zenon/check/records.ts +1 -1
  507. package/src/prover/zenon/check/relations.ts +2 -1
  508. package/src/prover/zenon/check/rewrites.ts +2 -15
  509. package/src/prover/zenon/check/sets.ts +40 -58
  510. package/src/prover/zenon/check/terms.ts +1 -2
  511. package/src/prover/zenon/decide.ts +10 -7
  512. package/src/prover/zenon/encode.ts +0 -2
  513. package/src/prover/zenon/eqrel.ts +2 -2
  514. package/src/prover/zenon/equality-rules.ts +24 -2
  515. package/src/prover/zenon/expr.ts +28 -2
  516. package/src/prover/zenon/index-table.ts +11 -21
  517. package/src/prover/zenon/isar-case.ts +0 -2
  518. package/src/prover/zenon/isar.ts +35 -37
  519. package/src/prover/zenon/llproof.ts +2 -13
  520. package/src/prover/zenon/mltoll.ts +12 -30
  521. package/src/prover/zenon/node.ts +20 -5
  522. package/src/prover/zenon/parse.ts +9 -8
  523. package/src/prover/zenon/phrase.ts +0 -2
  524. package/src/prover/zenon/proof.ts +0 -2
  525. package/src/prover/zenon/propositional-rules.ts +0 -2
  526. package/src/prover/zenon/rules.ts +2 -3
  527. package/src/prover/zenon/search.ts +11 -19
  528. package/src/prover/zenon/tla/functions.ts +2 -4
  529. package/src/prover/zenon/tla/llproof.ts +9 -13
  530. package/src/prover/zenon/tla/records.ts +1 -8
  531. package/src/prover/zenon/tla/rewrites.ts +0 -2
  532. package/src/prover/zenon/tla/sets.ts +22 -22
  533. package/src/prover/zenon/tla/terms.ts +0 -2
  534. package/src/prover/zenon/tla/tla.ts +7 -8
  535. package/src/randomization.ts +1 -4
  536. package/src/resolve.ts +67 -143
  537. package/src/runtime.ts +17 -18
  538. package/src/sany/builtins.ts +1 -3
  539. package/src/sany/generation.ts +394 -0
  540. package/src/sany/generator-def-entries.ts +210 -0
  541. package/src/sany/generator-definitions.ts +686 -0
  542. package/src/sany/generator-expressions.ts +1100 -0
  543. package/src/sany/generator-proofs.ts +662 -0
  544. package/src/sany/generator.ts +160 -2683
  545. package/src/sany/levels.ts +5 -11
  546. package/src/sany/lexer.ts +57 -60
  547. package/src/sany/linter.ts +0 -3
  548. package/src/sany/nodes.ts +6 -13
  549. package/src/sany/report.ts +3 -6
  550. package/src/sany/selectors.ts +35 -38
  551. package/src/sany/xml.ts +23 -55
  552. package/src/search.ts +244 -53
  553. package/src/simulate.ts +202 -184
  554. package/src/spec-description.ts +56 -82
  555. package/src/standard-definitions.ts +4 -3
  556. package/src/standard-modules.ts +17 -44
  557. package/src/state-graph.ts +3 -17
  558. package/src/subexpressions.ts +38 -47
  559. package/src/substitution-levels.ts +5 -4
  560. package/src/successors.ts +20 -43
  561. package/src/symmetry.ts +6 -21
  562. package/src/tableau.ts +2 -2
  563. package/src/tlc/fingerprint.ts +96 -30
  564. package/src/tlc/jar-data.ts +0 -1
  565. package/src/tlc/messages.ts +22 -36
  566. package/src/tlc/order.ts +36 -50
  567. package/src/tlc/random.ts +22 -34
  568. package/src/tlc/replay.ts +21 -48
  569. package/src/tlc/summary.ts +64 -58
  570. package/src/tlc/tlc-operators.ts +6 -17
  571. package/src/tlc/tlcext-operators.ts +70 -29
  572. package/src/tlc/trace-spec.ts +26 -51
  573. package/src/tlc/value-stream.ts +9 -13
  574. package/src/tlc/version.ts +0 -1
  575. package/src/typed-tier.ts +6535 -0
  576. package/src/typescript/actions.ts +2 -4
  577. package/src/typescript/collections.ts +34 -20
  578. package/src/typescript/compile.ts +1 -3
  579. package/src/typescript/formula.ts +5 -3
  580. package/src/typescript/model.ts +4 -5
  581. package/src/typescript/steps.ts +20 -18
  582. package/src/values.ts +136 -338
  583. package/src/prover/isabelle/isar/statement.ts +0 -52
  584. package/src/prover/smt/solver/z3-license.txt +0 -10
  585. package/src/prover/tlaps-module.ts +0 -510
  586. package/src/prover/zenon/LICENSE +0 -32
@@ -1,150 +1,71 @@
1
- import { TEMPORAL_LEVEL } from "../levels";
2
1
  import type { TlcVersion } from "../tlc/version";
3
- import type {
4
- AssumeProve,
5
- Assumption,
6
- Fact,
7
- Bound,
8
- Declaration,
9
- Definition,
10
- Expression,
11
- FunctionDefinition,
12
- Instance,
13
- Module,
14
- OperatorDefinition,
15
- NewSymbol,
16
- Proof,
17
- ProofStep,
18
- SourceLocation,
19
- Theorem,
20
- UseOrHide,
21
- } from "../ast";
22
- import { getChildren } from "../ast";
23
2
  import {
24
- TlaMissingModuleError,
25
- TlaSanyFatalError,
26
- TlaSyntaxError,
27
- TlaUnsupportedError,
28
- } from "../errors";
3
+ type AssumeProve,
4
+ type Expression,
5
+ getChildren,
6
+ type Instance,
7
+ type Module,
8
+ type Proof,
9
+ } from "../ast";
10
+ import { TlaMissingModuleError, TlaSanyFatalError, TlaSyntaxError } from "../errors";
29
11
  import { parseSanyModule } from "../parser";
30
12
  import { isBefore } from "../resolve";
31
- import { BUILTIN_LOCATION, createBuiltins, createLevelFields } from "./builtins";
13
+ import { createBuiltins } from "./builtins";
32
14
  import { getSany174LexicalError } from "./lexer";
33
15
  import { getSanyParseError } from "./parse-error";
34
16
  import {
35
17
  addSanyMessage,
36
- CONSTANT_DECL_KIND,
37
- NEW_CONSTANT_KIND,
38
- VARIABLE_DECL_KIND,
39
18
  addToContext,
19
+ CONSTANT_DECL_KIND,
20
+ type Context,
40
21
  createContext,
41
- getContextModule,
42
22
  formatSanyLocation,
23
+ getContextModule,
43
24
  getContextSymbol,
44
- getSymbolArity,
45
- getDeclarations,
46
- getHashtableValues,
47
- isAbsent,
48
- type AssumeNode,
49
- type AssumeProveNode,
50
- type Context,
51
- type DefStepNode,
52
- type ExprNode,
53
- type ExprOrOpArgNode,
54
- type FactNode,
55
- type FormalParamNode,
56
- type InstanceNode,
57
- type LabelNode,
58
- type LetInNode,
59
- type LeafProofNode,
60
- type LevelNode,
61
25
  type ModuleNode,
62
- type NewSymbNode,
63
- type NonLeafProofNode,
64
- type OpApplNode,
65
- type OpArgNode,
66
- type OpDeclNode,
67
- type OpDefNode,
68
- type ProofStepNode,
69
26
  type SanyLocation,
70
27
  type SanyMessage,
71
- type Subst,
72
- type SubstInNode,
73
28
  type SymbolNode,
74
- type TheoremNode,
75
- type ThmOrAssumpDefNode,
76
- type UseOrHideNode,
29
+ VARIABLE_DECL_KIND,
77
30
  } from "./nodes";
78
- import {
79
- createSelectorResolver,
80
- getSelectorItems,
81
- isGeneralId,
82
- type SelectorItem,
83
- } from "./selectors";
31
+ import { createSelectorResolver } from "./selectors";
84
32
  import {
85
33
  createSourceFile,
86
- findNameTokens,
87
- findToken,
88
- getArgumentSpan,
89
- getExpressionSpan,
90
- getMatchingIndex,
91
- getParenthesizedSpan,
92
34
  getPreComments,
93
- getRangeSpan,
94
- getSpanLocation,
95
35
  getTokenIndex,
96
- getTokenLocation,
97
- getTokenSource,
98
36
  getUnboxedSource,
99
- isBoxToken,
100
- isToken,
101
37
  type SourceFile,
102
- type TokenSpan,
103
38
  } from "./source";
104
- import { SANY_OPERATOR_SYNONYMS } from "../tlc/jar-data";
105
-
106
- const SYNONYMS = new Map(
107
- SANY_OPERATOR_SYNONYMS.flatMap(([canonical, ...synonyms]) =>
108
- synonyms.map((synonym) => [synonym, canonical]),
109
- ),
110
- );
111
-
112
- const resolveSynonym = (name: string) =>
113
- name
114
- .split("!")
115
- .map((part) => SYNONYMS.get(part) ?? (part === "~" ? "\\lnot" : part))
116
- .join("!");
117
-
118
- interface AssumeProveScope {
119
- isDeclaredBefore: boolean[];
120
- hasGoal: boolean;
121
- isSuffices: boolean;
122
- isInProof: boolean;
123
- }
124
-
125
- interface AssumeProveState {
126
- depth: number;
127
- isDeclared: boolean[];
128
- goal: AssumeProveScope | undefined;
129
- goalClause: number;
130
- }
131
-
132
- interface LabelGoal {
133
- scope: AssumeProveScope;
134
- clause: number;
135
- }
136
-
137
- const NEW_SYMBOL_KINDS = {
138
- Constant: { declKind: NEW_CONSTANT_KIND, level: 0 },
139
- Variable: { declKind: 25, level: 1 },
140
- State: { declKind: 26, level: 1 },
141
- Action: { declKind: 27, level: 2 },
142
- Temporal: { declKind: 28, level: 3 },
143
- };
144
-
145
- const isIdentifier = (name: string) => /^[A-Za-z0-9_]+$/.test(name);
146
-
147
- const isSelector = (name: string) => name !== "!!" && name.includes("!");
39
+ import {
40
+ createFormalParam,
41
+ createNullNode,
42
+ createOpAppl,
43
+ createOpArg,
44
+ createOpDef,
45
+ getBuiltin,
46
+ getModule,
47
+ getTopContext,
48
+ getUnitLocation,
49
+ isSameOrigin,
50
+ matchArguments,
51
+ type ModuleGeneration,
52
+ resolveModule,
53
+ resolveSymbol,
54
+ resolveSynonym,
55
+ } from "./generation";
56
+ import {
57
+ checkForUndefinedRecursiveOps,
58
+ checkRecursiveSection,
59
+ createDeclaration,
60
+ createSubstIn,
61
+ generateInstance,
62
+ processFunction,
63
+ processModuleDefinition,
64
+ processOperator,
65
+ processRecursive,
66
+ } from "./generator-definitions";
67
+ import { generateArgument, generateExpression } from "./generator-expressions";
68
+ import { generateUseOrHide, processAssumption, processTheorem } from "./generator-proofs";
148
69
 
149
70
  export interface SanySpecification {
150
71
  root: ModuleNode;
@@ -162,66 +83,15 @@ interface SanyGenerationOptions {
162
83
  rootExtendees?: string[];
163
84
  }
164
85
 
165
- interface SymbolTable {
166
- contexts: Context[];
167
- }
168
-
169
- interface BoundSymbols {
170
- bounded: FormalParamNode[][];
171
- tupleOrs: boolean[];
172
- ranges: ExprNode[];
173
- }
174
-
175
- interface OpApplBinding {
176
- unbounded?: FormalParamNode[];
177
- bounded?: FormalParamNode[][];
178
- tupleOrs?: boolean[];
179
- ranges?: ExprNode[];
180
- }
181
-
182
86
  interface UnresolvedName {
183
87
  name: string;
184
88
  importer: string;
185
89
  namingModule: string;
186
90
  }
187
91
 
188
- const getTopContext = (table: SymbolTable) => table.contexts[table.contexts.length - 1];
189
-
190
- const resolveSymbol = (table: SymbolTable, name: string) => {
191
- for (let index = table.contexts.length - 1; index >= 0; index--) {
192
- const symbol = getContextSymbol(table.contexts[index], name);
193
- if (symbol) return symbol;
194
- }
195
- return undefined;
196
- };
197
-
198
- const getSymbolKind = (symbol: SymbolNode) =>
199
- symbol.kind === "OpDecl"
200
- ? `${symbol.kind}${symbol.declKind}`
201
- : symbol.kind === "OpDef"
202
- ? symbol.defKind
203
- : symbol.kind;
204
-
205
92
  const getKindName = (symbol: SymbolNode) =>
206
93
  symbol.kind === "OpDef" || symbol.kind === "FormalParam" ? "definition" : "declaration";
207
94
 
208
- const isSameOrigin = (symbol: SymbolNode, other: SymbolNode) => {
209
- if (symbol.kind === "OpDef" && other.kind === "OpDef") {
210
- const source = symbol.source ?? symbol;
211
- if (source !== (other.source ?? other)) return false;
212
- return source.module === undefined || isParameterFree(source.module);
213
- }
214
- if (symbol.kind === "ThmOrAssumpDef" && other.kind === "ThmOrAssumpDef") {
215
- const source = symbol.source ?? symbol;
216
- return source === (other.source ?? other) && isParameterFree(source.module);
217
- }
218
- return false;
219
- };
220
-
221
- const isParameterFree = (module: ModuleNode) =>
222
- getDeclarations(module, CONSTANT_DECL_KIND).length === 0 &&
223
- getDeclarations(module, VARIABLE_DECL_KIND).length === 0;
224
-
225
95
  const getLetInstances = (expression: Expression): Instance[] => [
226
96
  ...(expression.kind === "Let" ? (expression.instances ?? []) : []),
227
97
  ...getChildren(expression).flatMap(getLetInstances),
@@ -247,9 +117,6 @@ const getProofInstances = (proof: Proof | undefined): Instance[] =>
247
117
  ...getProofInstances(step.proof),
248
118
  ]);
249
119
 
250
- // SANY resolves a top-level INSTANCE to an inner module only when the module's first top-level
251
- // INSTANCE follows the inner module, and otherwise looks for a file. It looks for a file for an
252
- // INSTANCE in a LET or a proof step too, where tla-ts takes an inner module defined before it.
253
120
  const isInternalInstance = (module: Module, instance: Instance) => {
254
121
  const seen = new Set<string>();
255
122
  for (const unit of module.units) {
@@ -263,26 +130,10 @@ const isInternalInstance = (module: Module, instance: Instance) => {
263
130
  );
264
131
  };
265
132
 
266
- type LetUnit =
267
- | { kind: "Recursive"; declarations: Declaration[] }
268
- | { kind: "Instance"; instance: Instance }
269
- | { kind: "Definition"; definition: Definition };
270
-
271
- const getNumeralDigits = (text: string) =>
272
- BigInt(text.startsWith("\\") ? `0${text.slice(1).replace(/^h/i, "x")}` : text).toString();
273
-
274
- interface LabelScope {
275
- labels: Map<string, LabelNode>;
276
- params: FormalParamNode[][];
277
- }
278
-
279
- // SANY looks at a module's own EXTENDS and INSTANCEs before those of its inner modules.
280
133
  const getDependencies = (module: Module) => {
281
134
  const extendees: string[] = [];
282
135
  const instancees: string[] = [];
283
136
  const importers = new Map<string, string>();
284
- // A module knows the inner modules defined before it in its enclosing modules and those of the
285
- // modules it extends, but not itself.
286
137
  const visit = (current: Module, context: Map<string, Module>) => {
287
138
  const isRoot = current === module;
288
139
  const addImports = (names: string[], imports: string[]) =>
@@ -337,82 +188,6 @@ const getDependencies = (module: Module) => {
337
188
  return { extendees, instancees, importers };
338
189
  };
339
190
 
340
- const OPERATOR_ARGUMENT_KINDS = new Set<Expression["kind"]>([
341
- "Identifier",
342
- "Subexpression",
343
- "OperatorReference",
344
- "Lambda",
345
- ]);
346
-
347
- // A name such as K(1)!C, whose last part takes no arguments, is a GeneralId too.
348
- const isOperatorArgument = (argument: Expression) => {
349
- const items = argument.kind === "Apply" ? getSelectorItems(argument) : undefined;
350
- return OPERATOR_ARGUMENT_KINDS.has(argument.kind) || (items !== undefined && isGeneralId(items));
351
- };
352
-
353
- interface DefEntryParts {
354
- hasChildlessFirstChild: boolean | undefined;
355
- last: TokenSpan;
356
- lastKind: string | undefined;
357
- }
358
-
359
- const SYNTAX_KINDS = new Map<Expression["kind"], string>([
360
- ["Identifier", "N_GeneralId"],
361
- ["Subexpression", "N_GeneralId"],
362
- ["Number", "N_Number"],
363
- ["Decimal", "N_Real"],
364
- ["SetEnumeration", "N_SetEnumerate"],
365
- ["SetFilter", "N_SubsetOf"],
366
- ["SetMap", "N_SetOfAll"],
367
- ["Tuple", "N_Tuple"],
368
- ["FunctionApplication", "N_FcnAppl"],
369
- ["FunctionConstruction", "N_FcnConst"],
370
- ["FunctionSet", "N_SetOfFcns"],
371
- ["Record", "N_RcdConstructor"],
372
- ["RecordSet", "N_SetOfRcds"],
373
- ["FieldAccess", "N_RecordComponent"],
374
- ["Except", "N_Except"],
375
- ["Prime", "N_PostfixExpr"],
376
- ["Always", "N_PrefixExpr"],
377
- ["Eventually", "N_PrefixExpr"],
378
- ["Enabled", "N_PrefixExpr"],
379
- ["Unchanged", "N_PrefixExpr"],
380
- ["Forall", "N_BoundedQuant"],
381
- ["Exists", "N_BoundedQuant"],
382
- ["UnboundedQuantifier", "N_UnboundedQuant"],
383
- ["Choose", "N_UnBoundedOrBoundedChoose"],
384
- ["If", "N_IfThenElse"],
385
- ["Case", "N_Case"],
386
- ["Let", "N_LetIn"],
387
- ["BoxAction", "N_ActionExpr"],
388
- ["AngleAction", "N_ActionExpr"],
389
- ["WeakFairness", "N_FairnessExpr"],
390
- ["StrongFairness", "N_FairnessExpr"],
391
- ]);
392
-
393
- const NESTED_FIRST_CHILD_KINDS = new Set([
394
- "N_GeneralId",
395
- "N_OpApplication",
396
- "N_PrefixExpr",
397
- "N_InfixExpr",
398
- "N_PostfixExpr",
399
- "N_FcnAppl",
400
- "N_RecordComponent",
401
- ]);
402
-
403
- const POSTFIX_OPERATOR_TEXTS = new Set(["'", "^+", "^*", "^#"]);
404
-
405
- // SANY's parser reads a prefix operator other than ~ and -. as a LAMBDA.
406
- const getOperatorNodeKind = (
407
- expression: Expression & { kind: "OperatorReference" | "Lambda" },
408
- text: string,
409
- ) => {
410
- if (POSTFIX_OPERATOR_TEXTS.has(text)) return "N_GenPostfixOp";
411
- return expression.kind === "Lambda" || text === "~" || text === "-."
412
- ? "N_GenNonExpPrefixOp"
413
- : "N_GenInfixOp";
414
- };
415
-
416
191
  export const generateSanySpecification = (
417
192
  rootSource: string,
418
193
  loadModule: (name: string) => string | undefined,
@@ -423,45 +198,11 @@ export const generateSanySpecification = (
423
198
  addSanyMessage(messages, { location, text, isWarning: false });
424
199
  const addWarning = (location: SanyLocation | undefined, text: string) =>
425
200
  addSanyMessage(messages, { location, text, isWarning: true });
426
- // TLC 1.7.4's SANY numbers its first node 0, and the master builds create one before.
427
- const counter = { value: options.version === "1.7.4" ? -1 : 0 };
428
- const getId = () => ++counter.value;
429
- const nullApplication = { id: 0 };
201
+ let lastId = options.version === "1.7.4" ? -1 : 0;
202
+ const getId = () => ++lastId;
203
+ let nullApplicationId = 0;
430
204
 
431
- const addSymbol = (table: SymbolTable, symbol: SymbolNode) => {
432
- const binding = resolveSymbol(table, symbol.name);
433
- if (binding === symbol) return;
434
- if (binding === undefined) {
435
- addToContext(getTopContext(table), symbol);
436
- return;
437
- }
438
- const isConflict =
439
- symbol.kind === "FormalParam" ||
440
- getSymbolKind(binding) !== getSymbolKind(symbol) ||
441
- getSymbolArity(binding) !== getSymbolArity(symbol);
442
- // TLC 1.7.4's SANY reports a conflict before the redefinition of a built-in operator.
443
- const isBuiltIn = binding.kind === "OpDef" && binding.defKind === "BuiltIn";
444
- if (isBuiltIn && !(isConflict && options.version === "1.7.4")) {
445
- addError(
446
- symbol.location,
447
- `Symbol ${symbol.name} is a built-in operator, and cannot be redefined.`,
448
- );
449
- return;
450
- }
451
- if (isConflict) {
452
- addError(
453
- symbol.location,
454
- `Multiply-defined symbol '${symbol.name}': this definition or declaration conflicts \nwith the one at ${formatSanyLocation(binding.location)}.`,
455
- );
456
- } else if (!isSameOrigin(symbol, binding)) {
457
- addWarning(
458
- symbol.location,
459
- `Multiple declarations or definitions for symbol ${symbol.name}. \nThis duplicates the one at ${formatSanyLocation(binding.location)}.`,
460
- );
461
- }
462
- };
463
- // Context's static initializer creates the builtins and SANY.frontEndInitialize creates them
464
- // again; TLC 1.7.4's SANY creates them only once.
205
+ // SANY creates the builtins twice, in Context's static initializer and in frontEndInitialize.
465
206
  if (options.version !== "1.7.4") createBuiltins(getId);
466
207
  const builtins = createBuiltins(getId);
467
208
  getId();
@@ -525,8 +266,6 @@ export const generateSanySpecification = (
525
266
  path.pop();
526
267
  order.push(name);
527
268
  };
528
- // SANY resolves the first unresolved name from the root, every extended module before any
529
- // instantiated one, each in the context of the module that names it.
530
269
  const resolutions = new Set<string>();
531
270
  const isResolved = (importer: string, name: string) => resolutions.has(`${importer} ${name}`);
532
271
  const findUnresolved = (
@@ -564,7 +303,6 @@ export const generateSanySpecification = (
564
303
  }
565
304
  };
566
305
  const rootName = options.rootFileName ?? parseSource("", rootSource).name;
567
- // The post conditions' modules join the root module's own extendees, before its inner modules'.
568
306
  const getModuleDependencies = (name: string, module: Module) => {
569
307
  const dependencies = getDependencies(module);
570
308
  if (name !== rootName || options.rootExtendees === undefined) return dependencies;
@@ -581,49 +319,15 @@ export const generateSanySpecification = (
581
319
  ast: Module,
582
320
  file: SourceFile,
583
321
  parent: ModuleNode | undefined,
584
- symbolTable: SymbolTable,
322
+ contexts: Context[],
585
323
  ): ModuleNode => {
586
- const state = {
587
- curLevel: 0,
588
- unresolvedCount: [0],
589
- unresolvedSum: 0,
590
- recursiveSectionCount: 0,
591
- };
592
- const functions: { name: string; node: OpApplNode }[] = [];
593
- const exceptStack: OpApplNode[] = [];
594
- const exceptSpecStack: OpApplNode[] = [];
595
- const labelScopes: LabelScope[] = [];
596
- const assumeContexts = new WeakSet<Context>();
597
- const pushLabelScope = () => labelScopes.push({ labels: new Map(), params: [] });
598
- const popLabels = () => labelScopes.pop()?.labels ?? new Map<string, LabelNode>();
599
- const assumeProveState: AssumeProveState = {
600
- depth: 0,
601
- isDeclared: [],
602
- goal: undefined,
603
- goalClause: 0,
604
- };
605
- const assumeProveScopes = new WeakMap<AssumeProveNode, AssumeProveScope>();
606
- const labelGoals = new WeakMap<LabelNode, LabelGoal>();
607
- const endProof = (statement: LevelNode) => {
608
- const scope = statement.kind === "AssumeProve" ? assumeProveScopes.get(statement) : undefined;
609
- if (scope) scope.isInProof = false;
610
- };
611
-
612
- const getLocation = (expression: Expression) =>
613
- getSpanLocation(file, getExpressionSpan(file, expression));
614
-
615
- const getUnitSpan = (location: SourceLocation) =>
616
- location.range
617
- ? getRangeSpan(file, location.range)
618
- : { start: getTokenIndex(file, location), end: getTokenIndex(file, location) };
619
-
620
324
  const currentModule: ModuleNode = {
621
325
  kind: "Module",
622
326
  id: getId(),
623
327
  name: ast.name,
624
- location: getSpanLocation(file, getUnitSpan(ast.location)),
328
+ location: getUnitLocation(file, ast.location),
625
329
  extendees: [],
626
- context: getTopContext(symbolTable),
330
+ context: getTopContext(contexts),
627
331
  topLevel: [],
628
332
  definitions: [],
629
333
  opDefsInRecursiveSection: [],
@@ -635,2320 +339,99 @@ export const generateSanySpecification = (
635
339
  records: [],
636
340
  };
637
341
  if (parent) parent.definitions.push(currentModule);
638
-
639
- const resolveModule = (name: string) => {
640
- for (let index = symbolTable.contexts.length - 1; index >= 0; index--) {
641
- const module = getContextModule(symbolTable.contexts[index], name);
642
- if (module?.kind === "Module") return module;
643
- }
644
- return externalModules.get(name);
645
- };
646
-
647
- const getModule = (name: string) => {
648
- const module = resolveModule(name);
649
- if (module === undefined) throw new TlaSyntaxError(`Could not find module ${name}`);
650
- return module;
651
- };
652
-
653
- const withContext = <Result>(context: Context, generate: () => Result) => {
654
- symbolTable.contexts.push(context);
655
- const result = generate();
656
- symbolTable.contexts.pop();
657
- return result;
658
- };
659
-
660
- const createFormalParam = (
661
- name: string,
662
- arity: number,
663
- location: SanyLocation | undefined,
664
- isAdded: boolean,
665
- ): FormalParamNode => {
666
- const param: FormalParamNode = {
667
- ...createLevelFields(getId()),
668
- kind: "FormalParam",
669
- name,
670
- arity,
671
- location,
672
- };
673
- if (isAdded) addSymbol(symbolTable, param);
674
- return param;
675
- };
676
-
677
- const createOpDef = (
678
- fields: Partial<OpDefNode> & Pick<OpDefNode, "name" | "location">,
679
- ): OpDefNode => ({
680
- ...createLevelFields(getId()),
681
- kind: "OpDef",
682
- defKind: "UserDefined",
683
- arity: fields.params?.length ?? 0,
684
- params: [],
685
- body: undefined,
686
- isLocal: false,
687
- module: currentModule,
688
- source: undefined,
689
- preComments: [],
690
- isDefined: true,
691
- inRecursive: false,
692
- inRecursiveSection: false,
693
- recursiveSection: -1,
694
- letInLevel: 0,
695
- weights: (fields.params ?? []).map(() => 0),
696
- isLeibnizArg: (fields.params ?? []).map(() => true),
697
- isLeibniz: true,
698
- opLevelCond: undefined,
699
- maxLevels: (fields.params ?? []).map(() => TEMPORAL_LEVEL),
700
- minMaxLevel: undefined,
701
- labels: new Map(),
702
- step: undefined,
703
- ...fields,
704
- });
705
-
706
- const setRecursionFields = (definition: OpDefNode) => {
707
- definition.letInLevel = state.curLevel;
708
- if (state.unresolvedSum > 0) {
709
- definition.recursiveSection = state.recursiveSectionCount;
710
- definition.inRecursiveSection = state.unresolvedCount[state.curLevel] > 0;
711
- currentModule.opDefsInRecursiveSection.push(definition);
712
- }
713
- };
714
-
715
- const createOpAppl = (
716
- operator: SymbolNode,
717
- operands: (ExprOrOpArgNode | undefined)[],
718
- location: SanyLocation,
719
- binding: OpApplBinding = {},
720
- id = getId(),
721
- ): OpApplNode => ({
722
- ...createLevelFields(id),
723
- kind: "OpAppl",
724
- operator,
725
- operands,
726
- unbounded: binding.unbounded,
727
- bounded: binding.bounded,
728
- tupleOrs: binding.tupleOrs,
729
- ranges: binding.ranges ?? [],
730
- location,
731
- });
732
-
733
- // nullOAN has no syntax tree node, so SANY locates it at the builtins.
734
- const createNullNode = (): OpApplNode => ({
735
- ...createOpAppl(getBuiltin("$Nop"), [], BUILTIN_LOCATION, {}, nullApplication.id),
736
- isNull: true,
737
- });
738
-
739
- const getBuiltin = (name: string) => {
740
- const builtin = builtinsByName.get(name);
741
- if (!builtin) throw new TlaUnsupportedError(`SANY has no builtin operator ${name}`);
742
- return builtin;
743
- };
744
-
745
- const applyBuiltin = (
746
- name: string,
747
- operands: (ExprOrOpArgNode | undefined)[],
748
- location: SanyLocation,
749
- binding: OpApplBinding = {},
750
- ) => createOpAppl(getBuiltin(name), operands, location, binding);
751
-
752
- const createString = (value: string, location: SanyLocation): ExprNode => ({
753
- ...createLevelFields(getId()),
754
- kind: "String",
755
- value,
756
- location,
757
- });
758
-
759
- const createOpArg = (op: SymbolNode, location: SanyLocation): OpArgNode => ({
760
- ...createLevelFields(getId()),
761
- kind: "OpArg",
762
- op,
763
- location,
764
- });
765
-
766
- const resolveName = (name: string, location: SanyLocation) => {
767
- const symbol = resolveSymbol(symbolTable, resolveSynonym(name));
768
- if (symbol === undefined || symbol.kind === "Module") {
769
- throw new TlaSyntaxError(
770
- `Unknown operator: \`${name}' at line ${location.beginLine}, column ${location.beginColumn} of module ${location.file}`,
771
- );
772
- }
773
- return symbol;
774
- };
775
-
776
- // A definition's parameter count differs from its arity only where its RECURSIVE declaration
777
- // gives another.
778
- const matchArguments = (
779
- operator: SymbolNode,
780
- operands: ExprOrOpArgNode[],
781
- location: SanyLocation,
782
- ) => {
783
- if (operator.kind !== "OpDef" || operator.defKind !== "UserDefined") return;
784
- const params = operator.params ?? [];
785
- if (params.length !== operands.length) {
786
- addError(
787
- location,
788
- `Wrong number of arguments (${operands.length}) given to operator '${operator.name}', \nwhich requires ${params.length} arguments.`,
789
- );
790
- return;
791
- }
792
- params.forEach((param, index) => {
793
- const operand = operands[index];
794
- if (param.arity === 0 && operand.kind === "OpArg") {
795
- addError(
796
- location,
797
- `Operator used in argument number ${index + 1} has incorrect number of arguments.`,
798
- );
799
- }
800
- const isMatching =
801
- operand.kind === "OpArg" &&
802
- getSymbolArity(operand.op) === param.arity &&
803
- !(
804
- operand.op.kind === "OpDef" &&
805
- (operand.op.params ?? []).some((parameter) => parameter.arity > 0)
806
- );
807
- if (param.arity > 0 && !isMatching) {
808
- addError(
809
- location,
810
- `Argument number ${index + 1} to operator '${operator.name}' \nshould be a ${param.arity}-parameter operator.`,
811
- );
812
- }
813
- });
814
- };
815
-
816
- const selectorToNode = createSelectorResolver({
342
+ const generation: ModuleGeneration = {
817
343
  version: options.version,
818
- resolveSymbol: (name) => resolveSymbol(symbolTable, name),
819
- resolveSynonym,
820
- generateExpression: (expression) => generateExpression(expression),
821
- generateArgument: (operator, index, argument, location) =>
822
- generateArgument(operator, index, argument, location),
823
- createOpAppl: (operator, operands, location) => {
824
- const node = createOpAppl(operator, operands, location);
825
- matchArguments(operator, operands, location);
826
- return node;
827
- },
828
- createOpArg,
829
- createFormalParam: (name, arity, location) => createFormalParam(name, arity, location, false),
830
- createLambda: (params, body, location) =>
831
- createOpDef({
832
- name: "LAMBDA",
833
- params,
834
- body,
835
- location,
836
- preComments: getPreComments(
837
- file,
838
- getTokenIndex(file, { line: location.beginLine, column: location.beginColumn }),
839
- ),
840
- }),
841
- copySubstIn: (prefix, body) =>
842
- createSubstIn(
843
- "SubstIn",
844
- prefix.substs,
845
- body,
846
- prefix.instantiatedModule,
847
- prefix.location,
848
- prefix.instantiatingModule,
849
- ),
850
- getBuiltin,
851
- addError: (location, text) => {
852
- addError(location, text);
853
- return createNullNode();
854
- },
855
- isOutOfLabelScope: (label) => {
856
- const goal = labelGoals.get(label);
857
- return (
858
- goal !== undefined &&
859
- goal.scope.isDeclaredBefore[goal.clause] &&
860
- goal.scope.isSuffices === goal.scope.isInProof
861
- );
862
- },
863
- isOutOfClauseScope: (assumeProve, position) => {
864
- const scope = assumeProveScopes.get(assumeProve);
865
- return (
866
- scope !== undefined &&
867
- scope.isDeclaredBefore[position - 1] &&
868
- (!scope.hasGoal || scope.isSuffices === scope.isInProof)
869
- );
344
+ addError,
345
+ addWarning,
346
+ getId,
347
+ builtinsByName,
348
+ externalModules,
349
+ nullApplicationId,
350
+ file,
351
+ contexts,
352
+ currentModule,
353
+ curLevel: 0,
354
+ unresolvedCount: [0],
355
+ unresolvedSum: 0,
356
+ recursiveSectionCount: 0,
357
+ functions: [],
358
+ exceptStack: [],
359
+ exceptSpecStack: [],
360
+ labelScopes: [],
361
+ assumeContexts: new WeakSet(),
362
+ assumeProveState: {
363
+ depth: 0,
364
+ isDeclared: [],
365
+ goal: undefined,
366
+ goalClause: 0,
870
367
  },
871
- });
872
-
873
- const locateSelectorItems = (items: SelectorItem[], span: TokenSpan) => {
874
- const cursor = { value: span.start };
875
- return items.map((item): SelectorItem => {
876
- const text = item.op === "Name" ? item.name : item.op === "Null" ? "(" : String(item.op);
877
- const index = findToken(file, cursor.value, span.end, text);
878
- if (index === -1) return item;
879
- if (item.op === "Null") {
880
- const close = getMatchingIndex(file, index);
881
- cursor.value = close + 1;
882
- return { ...item, location: getSpanLocation(file, { start: index, end: close }) };
883
- }
884
- cursor.value = index + 1;
885
- const location = getTokenLocation(file, index);
886
- if (item.args === undefined || !isToken(file, index + 1, "(")) return { ...item, location };
887
- const close = getMatchingIndex(file, index + 1);
888
- cursor.value = close + 1;
889
- return {
890
- ...item,
891
- location,
892
- argsLocation: getSpanLocation(file, { start: index + 1, end: close }),
893
- };
894
- });
895
- };
896
-
897
- const generateSelector = (
898
- expression: Expression,
899
- expectedArity: number,
900
- isFact: boolean,
901
- isDef: boolean,
902
- ) => {
903
- const items = getSelectorItems(expression);
904
- if (items === undefined)
905
- throw new TlaSyntaxError(`Expected a name, found ${expression.kind}`);
906
- return selectorToNode(
907
- locateSelectorItems(items, getExpressionSpan(file, expression)),
908
- expectedArity,
909
- isFact,
910
- isDef,
911
- getLocation(expression),
912
- );
913
- };
914
-
915
- const generateSelectorExpression = (expression: Expression) => {
916
- const node = generateSelector(expression, 0, false, false);
917
- if (node.kind !== "OpAppl") throw new TlaSyntaxError("Expected an expression");
918
- return node;
919
- };
920
-
921
- const checkRecursion = (node: ExprNode) => {
922
- if (node.kind !== "OpAppl") return;
923
- const recursive = functions.find((entry) => entry.name === node.operator.name);
924
- if (recursive) recursive.node.operator = getBuiltin("$RecursiveFcnSpec");
925
- };
926
-
927
- // tla-ts expands \A x, y \in S into a bound per name that shares the set; SANY keeps one group.
928
- const getBoundGroups = (bounds: Bound[]) =>
929
- bounds.reduce<Bound[][]>((groups, bound) => {
930
- const last = groups[groups.length - 1];
931
- const isSameGroup =
932
- last !== undefined &&
933
- last[0].set === bound.set &&
934
- bound.pattern.kind === "Name" &&
935
- last[0].pattern.kind === "Name";
936
- if (isSameGroup) last.push(bound);
937
- else groups.push([bound]);
938
- return groups;
939
- }, []);
940
-
941
- // SANY generates every bounding set before it declares the symbols.
942
- const generateBounds = (bounds: Bound[], searchStart: number) =>
943
- generateBoundsWithRanges(
944
- bounds,
945
- searchStart,
946
- getBoundGroups(bounds).map((group) => generateExpression(group[0].set)),
947
- );
948
-
949
- const generateWithParams = (params: FormalParamNode[], expression: Expression) => {
950
- const scope = labelScopes.at(-1);
951
- scope?.params.push(params);
952
- const node = generateExpression(expression);
953
- scope?.params.pop();
954
- return node;
955
- };
956
-
957
- const generateLambda = (expression: Expression & { kind: "Lambda" }): OpDefNode => {
958
- const span = getExpressionSpan(file, expression);
959
- const nameIndexes = findNameTokens(file, span.start, span.end, expression.params);
960
- return withContext(createContext(), () => {
961
- const params = expression.params.map((name, index) =>
962
- createFormalParam(name, 0, getTokenLocation(file, nameIndexes[index]), true),
963
- );
964
- const body = generateWithParams(params, expression.body);
965
- return createOpDef({
966
- name: "LAMBDA",
967
- params,
968
- body,
969
- location: getSpanLocation(file, span),
970
- preComments: getPreComments(file, span.start),
971
- });
972
- });
973
- };
974
-
975
- // tla-ts desugars an operator symbol argument, such as SUBSET or -., into a LAMBDA naming it.
976
- const getOperatorArgumentName = (argument: Expression) =>
977
- argument.kind === "OperatorReference"
978
- ? argument.operator
979
- : argument.kind === "Lambda" && argument.body.kind === "Apply"
980
- ? argument.body.operator
981
- : file.tokens[getTokenIndex(file, argument.location)].text;
982
-
983
- const generateOperatorArgument = (
984
- argument: Expression,
985
- target: OpDeclNode,
986
- ): OpArgNode | OpApplNode => {
987
- const location = getLocation(argument);
988
- if (argument.kind === "Lambda") {
989
- if (argument.location.range !== undefined && argument.operator === undefined)
990
- return createOpArg(generateLambda(argument), location);
991
- return createOpArg(resolveName(getOperatorArgumentName(argument), location), location);
992
- }
993
- if (!isOperatorArgument(argument)) {
994
- addError(
995
- location,
996
- `Arity ${target.arity} operator (not an expression) is expected \nto substitute for CONSTANT '${target.name}'.`,
997
- );
998
- return createNullNode();
999
- }
1000
- if (argument.kind === "OperatorReference") {
1001
- return createOpArg(resolveName(argument.operator, location), location);
1002
- }
1003
- const node = generateSelector(argument, target.arity, false, false);
1004
- if (node.kind === "OpArg" || (node.kind === "OpAppl" && node.isNull === true)) return node;
1005
- throw new TlaSyntaxError(
1006
- `Expected an operator argument at line ${location.beginLine}, column ${location.beginColumn}`,
1007
- );
1008
- };
1009
-
1010
- const generateArgument = (
1011
- operator: SymbolNode,
1012
- index: number,
1013
- argument: Expression,
1014
- operatorLocation: SanyLocation,
1015
- ): ExprOrOpArgNode => {
1016
- const isDefinition =
1017
- operator.kind === "OpDef" &&
1018
- (operator.defKind === "UserDefined" || operator.defKind === "ModuleInstance");
1019
- const expectedArity = isDefinition ? (operator.params?.[index]?.arity ?? 0) : 0;
1020
- if (expectedArity === 0) return generateExpression(argument);
1021
- const span = getExpressionSpan(file, argument);
1022
- const location = getSpanLocation(file, span);
1023
- const position = `${index + 1} (counting from 1)`;
1024
- const argumentSpan = getArgumentSpan(file, span);
1025
- if (argumentSpan !== span || !isOperatorArgument(argument)) {
1026
- addError(
1027
- getSpanLocation(file, argumentSpan),
1028
- `An expression appears as argument number ${position} to operator '${operator.name}', in a position an operator is required.`,
1029
- );
1030
- return createNullNode();
1031
- }
1032
- if (
1033
- argument.kind === "Identifier" ||
1034
- argument.kind === "Subexpression" ||
1035
- argument.kind === "Apply"
1036
- ) {
1037
- const node = generateSelector(argument, expectedArity, false, false);
1038
- if (node.kind === "OpArg" || node.kind === "OpAppl") return node;
1039
- throw new TlaSyntaxError(
1040
- `Expected an operator argument at ${formatSanyLocation(location)}`,
1041
- );
1042
- }
1043
- if (
1044
- argument.kind === "Lambda" &&
1045
- argument.location.range !== undefined &&
1046
- argument.operator === undefined
1047
- ) {
1048
- const lambda = generateLambda(argument);
1049
- const arity = getSymbolArity(lambda);
1050
- if (arity === expectedArity) return createOpArg(lambda, location);
1051
- addError(
1052
- operatorLocation,
1053
- `Lambda expression with arity ${arity} used as argument ${index + 1} of operator \`${operator.name}', \nbut an operator of arity ${expectedArity} is required.`,
1054
- );
1055
- return createNullNode();
1056
- }
1057
- const name = getOperatorArgumentName(argument);
1058
- const symbol = resolveSymbol(symbolTable, resolveSynonym(name));
1059
- if (symbol === undefined) {
1060
- addError(location, `Could not find declaration or definition of symbol '${name}'.`);
1061
- return createNullNode();
1062
- }
1063
- const arity = getSymbolArity(symbol);
1064
- if (arity === expectedArity) return createOpArg(symbol, location);
1065
- addError(
1066
- operatorLocation,
1067
- `Operator with incorrect arity passed as argument. \nOperator '${symbol.name}' of arity ${arity} is argument number ${position} to operator \`${formatSanyLocation(operator.location)}', \nbut an operator of arity ${expectedArity} was expected.`,
1068
- );
1069
- return createNullNode();
1070
- };
1071
-
1072
- // A /\ B /\ C nests as ((A /\ B) /\ C) in SANY; tla-ts flattens it.
1073
- const generateJunction = (expression: Expression & { kind: "And" | "Or" }) => {
1074
- const location = getLocation(expression);
1075
- if (expression.isBulleted) {
1076
- return applyBuiltin(
1077
- expression.kind === "And" ? "$ConjList" : "$DisjList",
1078
- expression.operands.map(generateExpression),
1079
- location,
1080
- );
1081
- }
1082
- const span = getExpressionSpan(file, expression);
1083
- const name = expression.kind === "And" ? "\\land" : "\\lor";
1084
- const [first, ...rest] = expression.operands;
1085
- return rest.reduce<ExprNode>((left, operand, index) => {
1086
- const operandSpan = getParenthesizedSpan(file, getExpressionSpan(file, operand));
1087
- const end = index === rest.length - 1 ? span.end : operandSpan.end;
1088
- return applyBuiltin(
1089
- name,
1090
- [left, generateExpression(operand)],
1091
- getSpanLocation(file, { start: span.start, end }),
1092
- );
1093
- }, generateExpression(first));
1094
- };
1095
-
1096
- const generateCase = (expression: Expression & { kind: "Case" }) => {
1097
- const span = getExpressionSpan(file, expression);
1098
- const arms = expression.arms.map((arm, index) => {
1099
- const condition = getParenthesizedSpan(file, getExpressionSpan(file, arm.condition));
1100
- const isLast = index === expression.arms.length - 1 && expression.other === undefined;
1101
- const body = getParenthesizedSpan(file, getExpressionSpan(file, arm.body));
1102
- const operands = [generateExpression(arm.condition), generateExpression(arm.body)];
1103
- return applyBuiltin(
1104
- "$Pair",
1105
- operands,
1106
- getSpanLocation(file, { start: condition.start, end: isLast ? span.end : body.end }),
1107
- );
1108
- });
1109
- const other = expression.other;
1110
- if (other) {
1111
- const body = getParenthesizedSpan(file, getExpressionSpan(file, other));
1112
- const otherIndex = findTokenBefore(body.start, "OTHER");
1113
- arms.push(
1114
- applyBuiltin(
1115
- "$Pair",
1116
- [undefined, generateExpression(other)],
1117
- getSpanLocation(file, { start: otherIndex, end: span.end }),
1118
- ),
1119
- );
1120
- }
1121
- return applyBuiltin("$Case", arms, getSpanLocation(file, span));
1122
- };
1123
-
1124
- const findTokenBefore = (index: number, text: string) => {
1125
- for (let current = index; current >= 0; current--) {
1126
- if (isToken(file, current, text)) return current;
1127
- }
1128
- return index;
1129
- };
1130
-
1131
- const generateExcept = (expression: Expression & { kind: "Except" }) => {
1132
- const span = getExpressionSpan(file, expression);
1133
- const location = getSpanLocation(file, span);
1134
- const operands: ExprOrOpArgNode[] = [generateExpression(expression.function)];
1135
- const exceptNode = applyBuiltin("$Except", operands, location);
1136
- const functionSpan = getExpressionSpan(file, expression.function);
1137
- const cursor = { value: findToken(file, functionSpan.end + 1, span.end, "EXCEPT") + 1 };
1138
- expression.updates.forEach((update) => {
1139
- const bang = findToken(file, cursor.value, span.end, "!");
1140
- const valueSpan = getParenthesizedSpan(file, getExpressionSpan(file, update.value));
1141
- const specLocation = getSpanLocation(file, { start: bang, end: valueSpan.end });
1142
- const pathCursor = { value: bang + 1 };
1143
- const components = update.path.map((step): ExprNode => {
1144
- if (step.kind === "Field") {
1145
- const nameIndex = findNameOrKeyword(pathCursor.value, step.name);
1146
- pathCursor.value = nameIndex + 1;
1147
- return createString(step.name, getTokenLocation(file, nameIndex));
1148
- }
1149
- const open = findToken(file, pathCursor.value, span.end, "[");
1150
- const close = getMatchingIndex(file, open);
1151
- pathCursor.value = close + 1;
1152
- if (step.args.length === 1) return generateExpression(step.args[0]);
1153
- return applyBuiltin(
1154
- "$Tuple",
1155
- step.args.map(generateExpression),
1156
- getSpanLocation(file, { start: open, end: close }),
1157
- );
1158
- });
1159
- const sequence = applyBuiltin("$Seq", components, specLocation);
1160
- const pair = applyBuiltin("$Pair", [sequence], specLocation);
1161
- exceptSpecStack.push(pair);
1162
- exceptStack.push(exceptNode);
1163
- pair.operands.push(generateExpression(update.value));
1164
- exceptSpecStack.pop();
1165
- exceptStack.pop();
1166
- operands.push(pair);
1167
- cursor.value = valueSpan.end + 1;
1168
- });
1169
- return exceptNode;
1170
- };
1171
-
1172
- const findNameOrKeyword = (start: number, name: string) => {
1173
- for (let index = start; index < file.tokens.length; index++) {
1174
- if (file.tokens[index].text === name && file.tokens[index].kind !== "String") return index;
1175
- }
1176
- return start;
1177
- };
1178
-
1179
- const generateRecordFields = (
1180
- operator: "$RcdConstructor" | "$SetOfRcds",
1181
- expression: Expression & { kind: "Record" | "RecordSet" },
1182
- ) => {
1183
- const span = getExpressionSpan(file, expression);
1184
- const cursor = { value: span.start + 1 };
1185
- const pairs = expression.fields.map((field, fieldIndex) => {
1186
- const nameIndex = findNameOrKeyword(cursor.value, field.name);
1187
- const valueSpan = getParenthesizedSpan(file, getExpressionSpan(file, field.value));
1188
- cursor.value = valueSpan.end + 1;
1189
- if (expression.fields.slice(0, fieldIndex).some((other) => other.name === field.name)) {
1190
- addError(getTokenLocation(file, nameIndex), "Non-unique fields in constructor.");
1191
- }
1192
- return applyBuiltin(
1193
- "$Pair",
1194
- [
1195
- createString(field.name, getTokenLocation(file, nameIndex)),
1196
- generateExpression(field.value),
1197
- ],
1198
- getSpanLocation(file, { start: nameIndex, end: valueSpan.end }),
1199
- );
1200
- });
1201
- const record = applyBuiltin(operator, pairs, getSpanLocation(file, span));
1202
- currentModule.records.push(record);
1203
- return record;
1204
- };
1205
-
1206
- const getTokenPosition = (index: number) => ({
1207
- line: file.tokens[index].line,
1208
- column: file.tokens[index].column,
1209
- });
1210
-
1211
- // The syntax tree of a LET leaves out its RECURSIVE declarations, so read them from the tokens.
1212
- const getRecursiveDeclarations = (start: number) => {
1213
- const declarations: Declaration[] = [];
1214
- let index = start;
1215
- while (file.tokens[index]?.kind === "Identifier") {
1216
- const end = isToken(file, index + 1, "(") ? getMatchingIndex(file, index + 1) : index;
1217
- const arity = file.tokens
1218
- .slice(index + 1, end)
1219
- .filter((token) => token.text === "_").length;
1220
- declarations.push({
1221
- name: file.tokens[index].text,
1222
- arity,
1223
- location: {
1224
- ...getTokenPosition(index),
1225
- range: {
1226
- module: file.name,
1227
- start: getTokenPosition(index),
1228
- end: getTokenPosition(end),
1229
- },
1230
- },
1231
- });
1232
- if (!isToken(file, end + 1, ",")) break;
1233
- index = end + 2;
1234
- }
1235
- return declarations;
1236
- };
1237
-
1238
- const getLetUnits = (expression: Expression & { kind: "Let" }) => {
1239
- const units = [
1240
- ...expression.definitions.map((definition) => ({
1241
- unit: { kind: "Definition", definition } satisfies LetUnit,
1242
- span: getDefinitionSpan(definition),
1243
- })),
1244
- ...(expression.instances ?? []).map((instance) => ({
1245
- unit: { kind: "Instance", instance } satisfies LetUnit,
1246
- span: getDefinitionSpan(instance),
1247
- })),
1248
- ];
1249
- const letStart = getExpressionSpan(file, expression).start;
1250
- const bodyStart = getParenthesizedSpan(file, getExpressionSpan(file, expression.body)).start;
1251
- const recursives: { unit: LetUnit; span: TokenSpan }[] = [];
1252
- for (let index = letStart + 1; index < bodyStart; index++) {
1253
- const isInUnit = units.some(
1254
- (entry) => entry.span.start <= index && index <= entry.span.end,
1255
- );
1256
- if (isToken(file, index, "RECURSIVE") && !isInUnit) {
1257
- recursives.push({
1258
- unit: { kind: "Recursive", declarations: getRecursiveDeclarations(index + 1) },
1259
- span: { start: index, end: index },
1260
- });
1261
- }
1262
- }
1263
- return [...units, ...recursives]
1264
- .toSorted((first, second) => first.span.start - second.span.start)
1265
- .map((entry) => entry.unit);
1266
- };
1267
-
1268
- const generateLet = (expression: Expression & { kind: "Let" }): LetInNode => {
1269
- const context = createContext();
1270
- return withContext(context, () => {
1271
- state.curLevel++;
1272
- state.unresolvedCount[state.curLevel] = 0;
1273
- const opDefs: (OpDefNode | ThmOrAssumpDefNode)[] = [];
1274
- const instances: InstanceNode[] = [];
1275
- getLetUnits(expression).forEach((unit) => {
1276
- if (unit.kind === "Recursive") processRecursive(unit.declarations);
1277
- else if (unit.kind === "Instance") {
1278
- processModuleDefinition(unit.instance, opDefs, instances);
1279
- } else if (unit.definition.kind === "Function") {
1280
- processFunction(unit.definition, opDefs);
1281
- } else processOperator(unit.definition, opDefs);
1282
- });
1283
- checkForUndefinedRecursiveOps();
1284
- state.curLevel = Math.max(state.curLevel - 1, 0);
1285
- const body = generateExpression(expression.body);
1286
- return {
1287
- ...createLevelFields(getId()),
1288
- kind: "LetIn",
1289
- opDefs,
1290
- instances,
1291
- body,
1292
- context,
1293
- location: getLocation(expression),
1294
- };
1295
- });
1296
- };
1297
-
1298
- const generateChoose = (expression: Expression & { kind: "Choose" }) => {
1299
- const span = getExpressionSpan(file, expression);
1300
- const location = getSpanLocation(file, span);
1301
- return withContext(createContext(), () => {
1302
- const pattern = expression.pattern;
1303
- const names = pattern.kind === "Name" ? [pattern.name] : pattern.names;
1304
- if (expression.set === undefined) {
1305
- const indexes = findNameTokens(file, span.start, span.end, names);
1306
- // SANY locates the symbol of CHOOSE x : P at the CHOOSE keyword.
1307
- const params = names.map((name, index) =>
1308
- createFormalParam(
1309
- name,
1310
- 0,
1311
- getTokenLocation(file, pattern.kind === "Name" ? span.start : indexes[index]),
1312
- true,
1313
- ),
1314
- );
1315
- const body = generateWithParams(params, expression.body);
1316
- return applyBuiltin("$UnboundedChoose", [body], location, { unbounded: params });
1317
- }
1318
- const range = generateExpression(expression.set);
1319
- const setSpan = getExpressionSpan(file, expression.set);
1320
- const indexes = findNameTokens(file, span.start, setSpan.start, names);
1321
- const params = names.map((name, index) =>
1322
- createFormalParam(name, 0, getTokenLocation(file, indexes[index]), true),
1323
- );
1324
- const body = generateWithParams(params, expression.body);
1325
- return applyBuiltin("$BoundedChoose", [body], location, {
1326
- bounded: [params],
1327
- tupleOrs: [pattern.kind === "Tuple"],
1328
- ranges: [range],
1329
- });
1330
- });
1331
- };
1332
-
1333
- const getUnresolvedOperator = (expression: Expression & { kind: "Apply" }) => {
1334
- if (
1335
- isIdentifier(expression.operator) ||
1336
- isSelector(expression.operator) ||
1337
- expression.args.length > 2
1338
- ) {
1339
- return undefined;
1340
- }
1341
- if (resolveSymbol(symbolTable, resolveSynonym(expression.operator)) !== undefined) {
1342
- return undefined;
1343
- }
1344
- const span = getExpressionSpan(file, expression);
1345
- // SANY reports an operator applied like a function, as in op(a, b), as an unknown operator.
1346
- if (
1347
- file.tokens[span.start].text === expression.operator &&
1348
- isToken(file, span.start + 1, "(")
1349
- ) {
1350
- return undefined;
1351
- }
1352
- const firstSpan = getParenthesizedSpan(file, getExpressionSpan(file, expression.args[0]));
1353
- const isPrefix = expression.args.length === 1 && firstSpan.start !== span.start;
1354
- const index = isPrefix ? span.start : firstSpan.end + 1;
1355
- const text = getTokenSource(file, index);
1356
- return {
1357
- index,
1358
- name: isPrefix && text === "-" ? "-." : text,
1359
- fixity: isPrefix ? "prefix" : expression.args.length === 2 ? "infix" : "postfix",
1360
- };
1361
- };
1362
-
1363
- const generateExpression = (expression: Expression): ExprNode => {
1364
- const location = getLocation(expression);
1365
- switch (expression.kind) {
1366
- case "Number":
1367
- return {
1368
- ...createLevelFields(getId()),
1369
- kind: "Numeral",
1370
- value: getNumeralDigits(expression.text ?? String(expression.value)),
1371
- location,
1372
- };
1373
- case "Decimal": {
1374
- const [integralPart, fractionalPart] = expression.text.split(".");
1375
- const mantissa = BigInt(integralPart + fractionalPart);
1376
- const isLong = mantissa <= 9223372036854775807n;
1377
- return {
1378
- ...createLevelFields(getId()),
1379
- kind: "Decimal",
1380
- mantissa: mantissa.toString(),
1381
- exponent: isLong ? String(-fractionalPart.length) : String(fractionalPart.length),
1382
- integralPart,
1383
- fractionalPart,
1384
- location,
1385
- };
1386
- }
1387
- case "String":
1388
- return createString(expression.value, location);
1389
- case "Identifier": {
1390
- const node = generateSelectorExpression(expression);
1391
- checkRecursion(node);
368
+ assumeProveScopes: new WeakMap(),
369
+ labelGoals: new WeakMap(),
370
+ recursiveDeclarations: [],
371
+ selectorToNode: createSelectorResolver({
372
+ version: options.version,
373
+ resolveSymbol: (name) => resolveSymbol(contexts, name),
374
+ resolveSynonym,
375
+ generateExpression: (expression) => generateExpression(generation, expression),
376
+ generateArgument: (operator, index, argument, location) =>
377
+ generateArgument(generation, operator, index, argument, location),
378
+ createOpAppl: (operator, operands, location) => {
379
+ const node = createOpAppl(generation, operator, operands, location);
380
+ matchArguments(generation, operator, operands, location);
1392
381
  return node;
1393
- }
1394
- case "Apply": {
1395
- const unresolved = getUnresolvedOperator(expression);
1396
- if (unresolved !== undefined) {
1397
- addError(
1398
- getTokenLocation(file, unresolved.index),
1399
- `Could not find declaration or definition of symbol '${unresolved.name}'.`,
1400
- );
1401
- addError(
1402
- location,
1403
- `Couldn't resolve ${unresolved.fixity} operator symbol \`${unresolved.name}'.`,
1404
- );
1405
- return { ...createNullNode(), isAbsent: true };
1406
- }
1407
- const node = generateSelectorExpression(expression);
1408
- if (isSelector(expression.operator) || isIdentifier(expression.operator)) {
1409
- checkRecursion(node);
1410
- }
1411
- return node;
1412
- }
1413
- case "Bracket":
1414
- addError(
1415
- getTokenLocation(file, getExpressionSpan(file, expression).start),
1416
- "Unsupported expression type `['.",
1417
- );
1418
- return { ...createNullNode(), isAbsent: true };
1419
- case "OperatorReference":
1420
- case "Lambda": {
1421
- const text = file.tokens[getExpressionSpan(file, expression).start].text;
1422
- addError(
1423
- location,
1424
- text === "LAMBDA"
1425
- ? "LAMBDA expression used where an expression is required."
1426
- : `Unsupported expression type \`${getOperatorNodeKind(expression, text)}'.`,
1427
- );
1428
- return { ...createNullNode(), isAbsent: true };
1429
- }
1430
- case "And":
1431
- case "Or":
1432
- return generateJunction(expression);
1433
- case "Prime":
1434
- return applyBuiltin("'", [generateExpression(expression.expression)], location);
1435
- case "Unchanged":
1436
- return applyBuiltin("UNCHANGED", [generateExpression(expression.expression)], location);
1437
- case "Enabled":
1438
- return applyBuiltin("ENABLED", [generateExpression(expression.expression)], location);
1439
- case "Always":
1440
- return applyBuiltin("[]", [generateExpression(expression.expression)], location);
1441
- case "Eventually":
1442
- return applyBuiltin("<>", [generateExpression(expression.expression)], location);
1443
- case "If":
1444
- return applyBuiltin(
1445
- "$IfThenElse",
1446
- [
1447
- generateExpression(expression.condition),
1448
- generateExpression(expression.consequent),
1449
- generateExpression(expression.alternative),
1450
- ],
1451
- location,
1452
- );
1453
- case "Case":
1454
- return generateCase(expression);
1455
- case "Let":
1456
- return generateLet(expression);
1457
- case "Forall":
1458
- case "Exists": {
1459
- const span = getExpressionSpan(file, expression);
1460
- return withContext(createContext(), () => {
1461
- const bounds = generateBounds(expression.bounds, span.start);
1462
- const body = generateWithParams(bounds.bounded.flat(), expression.body);
1463
- return applyBuiltin(
1464
- expression.kind === "Forall" ? "$BoundedForall" : "$BoundedExists",
1465
- [body],
1466
- location,
1467
- bounds,
1468
- );
1469
- });
1470
- }
1471
- case "UnboundedQuantifier": {
1472
- const span = getExpressionSpan(file, expression);
1473
- const bodySpan = getExpressionSpan(file, expression.body);
1474
- const indexes = findNameTokens(file, span.start, bodySpan.start, expression.names);
1475
- const name = expression.isTemporal
1476
- ? expression.quantifier === "Forall"
1477
- ? "$TemporalForall"
1478
- : "$TemporalExists"
1479
- : expression.quantifier === "Forall"
1480
- ? "$UnboundedForall"
1481
- : "$UnboundedExists";
1482
- return withContext(createContext(), () => {
1483
- const params = expression.names.map((paramName, index) =>
1484
- createFormalParam(paramName, 0, getTokenLocation(file, indexes[index]), true),
1485
- );
1486
- const body = generateWithParams(params, expression.body);
1487
- return applyBuiltin(name, [body], location, { unbounded: params });
1488
- });
1489
- }
1490
- case "Choose":
1491
- return generateChoose(expression);
1492
- case "SetEnumeration":
1493
- return applyBuiltin(
1494
- "$SetEnumerate",
1495
- expression.elements.map(generateExpression),
1496
- location,
1497
- );
1498
- case "Tuple":
1499
- return applyBuiltin("$Tuple", expression.elements.map(generateExpression), location);
1500
- case "SetFilter": {
1501
- const range = generateExpression(expression.bound.set);
1502
- const span = getExpressionSpan(file, expression);
1503
- return withContext(createContext(), () => {
1504
- const bounds = generateBoundsWithRanges([expression.bound], span.start, [range]);
1505
- const body = generateWithParams(bounds.bounded.flat(), expression.predicate);
1506
- return applyBuiltin("$SubsetOf", [body], location, bounds);
1507
- });
1508
- }
1509
- case "SetMap": {
1510
- const expressionSpan = getExpressionSpan(file, expression.expression);
1511
- return withContext(createContext(), () => {
1512
- const bounds = generateBounds(expression.bounds, expressionSpan.end + 1);
1513
- const body = generateWithParams(bounds.bounded.flat(), expression.expression);
1514
- return applyBuiltin("$SetOfAll", [body], location, bounds);
1515
- });
1516
- }
1517
- case "FunctionConstruction": {
1518
- const span = getExpressionSpan(file, expression);
1519
- return withContext(createContext(), () => {
1520
- const bounds = generateBounds(expression.bounds, span.start);
1521
- const body = generateWithParams(bounds.bounded.flat(), expression.body);
1522
- return applyBuiltin("$FcnConstructor", [body], location, bounds);
1523
- });
1524
- }
1525
- case "FunctionSet":
1526
- return applyBuiltin(
1527
- "$SetOfFcns",
1528
- [generateExpression(expression.domain), generateExpression(expression.range)],
1529
- location,
1530
- );
1531
- case "Record":
1532
- return generateRecordFields("$RcdConstructor", expression);
1533
- case "RecordSet":
1534
- return generateRecordFields("$SetOfRcds", expression);
1535
- case "Except":
1536
- return generateExcept(expression);
1537
- case "ExceptAt": {
1538
- const except = exceptStack[exceptStack.length - 1];
1539
- const component = exceptSpecStack[exceptSpecStack.length - 1];
1540
- if (except === undefined || component === undefined) {
1541
- addError(location, "@ used where its meaning is not defined.");
1542
- return createNullNode();
1543
- }
1544
- return {
1545
- ...createLevelFields(getId()),
1546
- kind: "At",
1547
- except,
1548
- component,
1549
- location: component.location,
1550
- };
1551
- }
1552
- case "FunctionApplication": {
1553
- const functionNode = generateExpression(expression.function);
1554
- // SANY leaves the whole application null, without generating its arguments.
1555
- if (isAbsent(functionNode)) return functionNode;
1556
- checkRecursion(functionNode);
1557
- const operator = functionNode.kind === "OpAppl" ? functionNode.operator : undefined;
1558
- const body =
1559
- operator?.kind === "OpDef" && operator.defKind === "UserDefined"
1560
- ? operator.body
1561
- : undefined;
1562
- if (
1563
- body?.kind === "OpAppl" &&
1564
- (body.operator.name === "$NonRecursiveFcnSpec" ||
1565
- body.operator.name === "$RecursiveFcnSpec")
1566
- ) {
1567
- const paramCount = (body.bounded ?? []).reduce(
1568
- (count, params, index) => count + (body.tupleOrs?.[index] ? 1 : params.length),
1569
- 0,
1570
- );
1571
- if (expression.args.length >= 2 && paramCount !== expression.args.length) {
1572
- addError(
1573
- location,
1574
- `Function '${operator?.name}' is defined with ${paramCount} parameters, but is applied to ${expression.args.length} arguments.`,
1575
- );
1576
- return createNullNode();
1577
- }
1578
- }
1579
- const argument =
1580
- expression.args.length === 1
1581
- ? generateExpression(expression.args[0])
1582
- : applyBuiltin("$Tuple", expression.args.map(generateExpression), location);
1583
- return applyBuiltin("$FcnApply", [functionNode, argument], location);
1584
- }
1585
- case "FieldAccess": {
1586
- const record = generateExpression(expression.record);
1587
- const span = getExpressionSpan(file, expression);
1588
- return applyBuiltin(
1589
- "$RcdSelect",
1590
- [record, createString(expression.field, getTokenLocation(file, span.end))],
1591
- location,
1592
- );
1593
- }
1594
- case "Product":
1595
- return applyBuiltin(
1596
- "$CartesianProd",
1597
- expression.factors.map(generateExpression),
1598
- location,
1599
- );
1600
- case "BoxAction":
1601
- case "AngleAction":
1602
- return applyBuiltin(
1603
- expression.kind === "BoxAction" ? "$SquareAct" : "$AngleAct",
1604
- [generateExpression(expression.action), generateExpression(expression.subscript)],
1605
- location,
1606
- );
1607
- case "WeakFairness":
1608
- case "StrongFairness":
1609
- return applyBuiltin(
1610
- expression.kind === "WeakFairness" ? "$WF" : "$SF",
1611
- [generateExpression(expression.subscript), generateExpression(expression.action)],
1612
- location,
1613
- );
1614
- case "Label":
1615
- return generateLabel(expression);
1616
- case "Subexpression":
1617
- return generateSelectorExpression(expression);
1618
- }
1619
- };
1620
-
1621
- const generateBoundsWithRanges = (
1622
- bounds: Bound[],
1623
- searchStart: number,
1624
- ranges: ExprNode[],
1625
- ): BoundSymbols => {
1626
- const groups = getBoundGroups(bounds);
1627
- const cursor = { value: searchStart };
1628
- const bounded = groups.map((group) => {
1629
- const setSpan = getExpressionSpan(file, group[0].set);
1630
- const names = group.flatMap((bound) =>
1631
- bound.pattern.kind === "Name" ? [bound.pattern.name] : bound.pattern.names,
1632
- );
1633
- const indexes = findNameTokens(file, cursor.value, setSpan.start, names);
1634
- cursor.value = setSpan.end + 1;
1635
- return names.map((name, index) =>
1636
- createFormalParam(name, 0, getTokenLocation(file, indexes[index]), true),
1637
- );
1638
- });
1639
- return {
1640
- bounded,
1641
- tupleOrs: groups.map((group) => group[0].pattern.kind === "Tuple"),
1642
- ranges,
1643
- };
1644
- };
1645
-
1646
- const generateLabel = (expression: Expression & { kind: "Label" }): LabelNode | OpApplNode => {
1647
- const location = getLocation(expression);
1648
- const scope = labelScopes.at(-1);
1649
- if (scope === undefined) {
1650
- addError(location, "Label not in definition or proof step.");
1651
- return createNullNode();
1652
- }
1653
- // No label may lie in the scope of a declaration of a nested ASSUME/PROVE.
1654
- if (assumeProveState.isDeclared.slice(2, assumeProveState.depth + 1).some(Boolean)) {
1655
- addError(location, "Label not allowed within scope of declaration in nested ASSUME/PROVE.");
1656
- return createNullNode();
1657
- }
1658
- if (exceptStack.length > 0 && exceptSpecStack.length > 0) {
1659
- addError(location, "Labels inside EXCEPT clauses are not yet implemented.");
1660
- return createNullNode();
1661
- }
1662
- pushLabelScope();
1663
- const body = generateExpression(expression.body);
1664
- const labels = popLabels();
1665
- const paramIndexes = findNameTokens(
1666
- file,
1667
- getExpressionSpan(file, expression).start,
1668
- getExpressionSpan(file, expression.body).start,
1669
- expression.params,
1670
- );
1671
- const params = expression.params.map((name, index) => {
1672
- const symbol = resolveSymbol(symbolTable, name);
1673
- if (symbol?.kind === "FormalParam") return symbol;
1674
- const paramLocation = getTokenLocation(file, paramIndexes[index]);
1675
- addError(paramLocation, `Illegal parameter ${name} of label \`${expression.name}'.`);
1676
- return createFormalParam(name, 0, paramLocation, false);
1677
- });
1678
- const label: LabelNode = {
1679
- ...createLevelFields(getId()),
1680
- kind: "Label",
1681
- name: expression.name,
1682
- params,
1683
- body,
1684
- labels,
1685
- isAssumeProve: false,
1686
- location,
1687
- };
1688
- const named = new Set<FormalParamNode>();
1689
- params.forEach((param) => {
1690
- if (named.has(param)) {
1691
- addError(
1692
- location,
1693
- `Repeated formal parameter ${param.name} \nin label \`${label.name}'.`,
1694
- );
1695
- }
1696
- named.add(param);
1697
- });
1698
- scope.params.flat().forEach((param) => {
1699
- if (!named.delete(param)) {
1700
- addError(location, `Label ${label.name} must contain formal parameter \`${param.name}'.`);
1701
- }
1702
- });
1703
- if (named.size > 0) {
1704
- const extras = [...named].map((param) => `${param.name} `).join("");
1705
- addError(location, `Label ${label.name} declares extra parameter(s) ${extras}`);
1706
- }
1707
- if (scope.labels.has(label.name)) addError(location, `Duplicate label \`${label.name}'.`);
1708
- else scope.labels.set(label.name, label);
1709
- const goal = assumeProveState.goal;
1710
- if (goal) labelGoals.set(label, { scope: goal, clause: assumeProveState.goalClause });
1711
- return label;
1712
- };
1713
-
1714
- const getParams = (
1715
- definition: OperatorDefinition | Instance,
1716
- span: TokenSpan,
1717
- isAdded: boolean,
1718
- ) => {
1719
- const cursor = { value: span.start };
1720
- return definition.params.map((param) => {
1721
- const index = param.location
1722
- ? getTokenIndex(file, param.location)
1723
- : findNameOrKeyword(cursor.value, param.name);
1724
- const paramSpan = getOperatorSpan(index, param.arity);
1725
- cursor.value = paramSpan.end + 1;
1726
- // SANY keeps the spelling of a prefix parameter, so ~ _ does not redefine \lnot.
1727
- const isPrefix = param.arity === 1 && isToken(file, index + 1, "_");
1728
- return createFormalParam(
1729
- isPrefix ? (file.tokens[index].spelling ?? param.name) : resolveSynonym(param.name),
1730
- param.arity,
1731
- getSpanLocation(file, paramSpan),
1732
- isAdded,
1733
- );
1734
- });
1735
- };
1736
-
1737
- const getDefinitionSpan = (definition: { location: SourceLocation; isLocal?: boolean }) => {
1738
- const span = getUnitSpan(definition.location);
1739
- return definition.isLocal &&
1740
- !isToken(file, span.start, "LOCAL") &&
1741
- isToken(file, span.start - 1, "LOCAL")
1742
- ? { start: span.start - 1, end: span.end }
1743
- : span;
1744
- };
1745
-
1746
- const processOperator = (
1747
- definition: OperatorDefinition,
1748
- definitions: (OpDefNode | ThmOrAssumpDefNode)[] | undefined,
1749
- ) => {
1750
- const span = getDefinitionSpan(definition);
1751
- const location = getSpanLocation(file, span);
1752
- const name = resolveSynonym(definition.name);
1753
- const paramsSpan = { start: definition.isLocal ? span.start + 1 : span.start, end: span.end };
1754
- const generated = withContext(createContext(), () => {
1755
- const params = getParams(definition, paramsSpan, true);
1756
- const existing = resolveSymbol(symbolTable, name);
1757
- if (existing?.kind === "OpDef" && existing.inRecursive && !existing.isDefined) {
1758
- const isMatching =
1759
- existing.params?.length === params.length && params.every((param) => param.arity === 0);
1760
- if (existing.letInLevel !== state.curLevel) {
1761
- addError(location, `Recursive operator ${name} defined at wrong LET/IN level.`);
1762
- } else {
1763
- if (!isMatching) {
1764
- addError(
1765
- location,
1766
- `Definition of ${existing.name} has different arity than its RECURSIVE declaration.`,
1767
- );
1768
- }
1769
- // SANY sets the parameters before it analyzes the body.
1770
- existing.params = params;
1771
- }
1772
- } else if (existing !== undefined) {
1773
- addError(location, `Operator ${name} already defined or declared.`);
1774
- }
1775
- pushLabelScope();
1776
- return { params, body: generateExpression(definition.body), existing };
1777
- });
1778
- const labels = popLabels();
1779
- const existing = generated.existing;
1780
- const params = generated.params;
1781
- const preComments = getPreComments(file, span.start);
1782
- if (
1783
- existing?.kind === "OpDef" &&
1784
- existing.inRecursive &&
1785
- !existing.isDefined &&
1786
- existing.letInLevel === state.curLevel
1787
- ) {
1788
- existing.weights = params.map(() => 0);
1789
- existing.maxLevels = params.map(() => TEMPORAL_LEVEL);
1790
- existing.isLeibnizArg = params.map(() => true);
1791
- existing.labels = labels;
1792
- endOpDefNode(existing, generated.body, location, preComments);
1793
- currentModule.definitions.push(existing);
1794
- definitions?.push(existing);
1795
- return;
1796
- }
1797
- const node = createOpDef({
1798
- name,
1799
- params,
1800
- body: generated.body,
1801
- isLocal: definition.isLocal,
1802
- location,
1803
- preComments,
1804
- labels,
1805
- });
1806
- addSymbol(symbolTable, node);
1807
- setRecursionFields(node);
1808
- currentModule.definitions.push(node);
1809
- definitions?.push(node);
1810
- };
1811
-
1812
- const endOpDefNode = (
1813
- node: OpDefNode,
1814
- body: ExprNode,
1815
- location: SanyLocation,
1816
- preComments: string[],
1817
- ) => {
1818
- node.isDefined = true;
1819
- node.body = body;
1820
- node.location = location;
1821
- node.preComments = preComments;
1822
- if (node.inRecursive) {
1823
- state.unresolvedCount[state.curLevel]--;
1824
- state.unresolvedSum--;
1825
- }
1826
- };
1827
-
1828
- const processFunction = (
1829
- definition: FunctionDefinition,
1830
- definitions: (OpDefNode | ThmOrAssumpDefNode)[] | undefined,
1831
- ) => {
1832
- const span = getDefinitionSpan(definition);
1833
- const location = getSpanLocation(file, span);
1834
- const context = createContext();
1835
- const nameIndex = definition.isLocal ? span.start + 1 : span.start;
1836
- const bounds = withContext(context, () => generateBounds(definition.bounds, nameIndex + 1));
1837
- const existing = withContext(context, () => resolveSymbol(symbolTable, definition.name));
1838
- const recursionParam = withContext(context, () =>
1839
- createFormalParam(definition.name, 0, location, existing === undefined),
1840
- );
1841
- const node = applyBuiltin("$NonRecursiveFcnSpec", [], location, {
1842
- unbounded: [recursionParam],
1843
- ...bounds,
1844
- });
1845
- const isPendingRecursive =
1846
- existing?.kind === "OpDef" && existing.inRecursive && !existing.isDefined;
1847
- const isRecursive = isPendingRecursive && existing.letInLevel === state.curLevel;
1848
- if (isRecursive) {
1849
- if (existing.arity !== 0) {
1850
- addError(
1851
- location,
1852
- `Function ${existing.name} has operator arguments in its RECURSIVE declaration.`,
1853
- );
1854
- }
1855
- } else if (isPendingRecursive) {
1856
- addError(location, `Recursive function ${definition.name} defined at wrong LET/IN level.`);
1857
- } else if (existing !== undefined) {
1858
- addError(location, `Function name \`${definition.name}' already defined or declared.`);
1859
- }
1860
- const preComments = getPreComments(file, span.start);
1861
- const definitionNode =
1862
- existing === undefined
1863
- ? createOpDef({
1864
- name: definition.name,
1865
- params: [],
1866
- body: node,
1867
- isLocal: definition.isLocal,
1868
- location,
1869
- preComments,
1870
- })
1871
- : existing.kind === "OpDef" && (isRecursive || !isPendingRecursive)
1872
- ? existing
1873
- : undefined;
1874
- // A function whose RECURSIVE declaration has parameters stays undefined.
1875
- if (isRecursive) {
1876
- if (existing.arity === 0) endOpDefNode(existing, node, location, preComments);
1877
- } else if (existing === undefined && definitionNode !== undefined) {
1878
- addSymbol(symbolTable, definitionNode);
1879
- setRecursionFields(definitionNode);
1880
- }
1881
- if (definitionNode !== undefined) {
1882
- currentModule.definitions.push(definitionNode);
1883
- definitions?.push(definitionNode);
1884
- }
1885
- functions.unshift({ name: definition.name, node });
1886
- pushLabelScope();
1887
- // The bound identifiers are bound in the body only of a function with an OpDefNode.
1888
- const generateBody = () => generateWithParams(bounds.bounded.flat(), definition.body);
1889
- const body =
1890
- definitionNode === undefined ? generateBody() : withContext(context, generateBody);
1891
- const labels = popLabels();
1892
- if (definitionNode !== undefined) definitionNode.labels = labels;
1893
- functions.shift();
1894
- node.operands = [body];
1895
- if (node.operator.name === "$NonRecursiveFcnSpec") node.unbounded = undefined;
1896
- };
1897
-
1898
- const recursiveDeclarations: OpDefNode[] = [];
1899
- const processRecursive = (declarations: Declaration[]) => {
1900
- if (state.unresolvedSum === 0) state.recursiveSectionCount++;
1901
- state.unresolvedCount[state.curLevel] += declarations.length;
1902
- state.unresolvedSum += declarations.length;
1903
- declarations.forEach((declaration) => {
1904
- const span = getDeclarationSpan(declaration);
1905
- // The OpDeclNode buildParameter makes of the declaration to read its name and arity.
1906
- getId();
1907
- const params = Array.from({ length: declaration.arity }, () =>
1908
- createFormalParam("", 0, undefined, false),
1909
- );
1910
- const node = createOpDef({
1911
- name: resolveSynonym(declaration.name),
1912
- params,
1913
- location: getSpanLocation(file, span),
1914
- isDefined: false,
1915
- inRecursive: true,
1916
- inRecursiveSection: true,
1917
- recursiveSection: state.recursiveSectionCount,
1918
- letInLevel: state.curLevel,
1919
- });
1920
- addSymbol(symbolTable, node);
1921
- recursiveDeclarations.push(node);
1922
- currentModule.opDefsInRecursiveSection.push(node);
1923
- });
1924
- };
1925
-
1926
- const checkForUndefinedRecursiveOps = () => {
1927
- if (state.unresolvedCount[state.curLevel] === 0) return;
1928
- recursiveDeclarations
1929
- .filter((node) => node.letInLevel === state.curLevel && !node.isDefined)
1930
- .forEach((node) =>
1931
- addError(
1932
- node.location,
1933
- `Symbol ${node.name} declared in RECURSIVE statement but not defined.`,
1934
- ),
1935
- );
1936
- state.unresolvedSum -= state.unresolvedCount[state.curLevel];
1937
- };
1938
-
1939
- // Implicit substitutions in the order of the instantiated module's Hashtable, then the explicit
1940
- // WITH substitutions.
1941
- const processSubstitutions = (
1942
- instance: Instance,
1943
- instanceeContext: Context,
1944
- location: SanyLocation,
1945
- ) => {
1946
- // The SubstInNode processSubst creates, which only the substitutions' templates use.
1947
- getId();
1948
- const declarations = getHashtableValues(instanceeContext.table).filter(
1949
- (symbol): symbol is OpDeclNode => symbol.kind === "OpDecl",
1950
- );
1951
- const substs: Subst[] = declarations.flatMap((declaration) => {
1952
- const symbol = resolveSymbol(symbolTable, declaration.name);
1953
- if (symbol === undefined) return [];
1954
- const isExpression =
1955
- declaration.declKind === VARIABLE_DECL_KIND ||
1956
- (declaration.declKind === CONSTANT_DECL_KIND && declaration.arity === 0);
1957
- if (isExpression) matchArguments(symbol, [], location);
1958
- return [
1959
- {
1960
- op: declaration,
1961
- expr: isExpression ? createOpAppl(symbol, [], location) : createOpArg(symbol, location),
1962
- isImplicit: true,
1963
- },
1964
- ];
1965
- });
1966
- // SANY locates an arity error at its builtins for the nullOpArg it substitutes after an error.
1967
- const checkArity = (target: OpDeclNode, substitute: ExprOrOpArgNode) => {
1968
- const arity = substitute.kind === "OpArg" ? getSymbolArity(substitute.op) : 0;
1969
- if (arity !== target.arity) {
1970
- addError(
1971
- substitute.location,
1972
- `An operator must be substituted for symbol '${target.name}', and it must have arity ${target.arity}.`,
1973
- );
1974
- }
1975
- };
1976
- const span = getDefinitionSpan(instance);
1977
- const cursor = { value: findToken(file, span.start, span.end, "WITH") + 1 };
1978
- instance.substitutions.forEach((substitution) => {
1979
- const targetIndex = findToken(file, cursor.value, span.end, substitution.name);
1980
- // The next target follows this substitution's expression, which may name it too.
1981
- if (targetIndex !== -1) {
1982
- cursor.value = getExpressionSpan(file, substitution.expression).end + 1;
1983
- }
1984
- const target = getContextSymbol(instanceeContext, resolveSynonym(substitution.name));
1985
- if (target?.kind !== "OpDecl") {
1986
- addError(
1987
- targetIndex === -1 ? location : getTokenLocation(file, targetIndex),
1988
- `Identifier '${targetIndex === -1 ? substitution.name : getTokenSource(file, targetIndex)}' is not a legal target of a substitution. \nA legal target must be a declared CONSTANT or VARIABLE in the module being instantiated. \n(Also, check for warnings about multiple declarations of this same identifier.)`,
1989
- );
1990
- return;
1991
- }
1992
- const substitute =
1993
- target.arity === 0
1994
- ? generateExpression(substitution.expression)
1995
- : generateOperatorArgument(substitution.expression, target);
1996
- checkArity(target, substitute);
1997
- const existing = substs.find((subst) => subst.op.name === target.name);
1998
- if (existing && !existing.isImplicit) {
1999
- addError(
2000
- getLocation(substitution.expression),
2001
- `Multiple substitutions for symbol '${target.name}' in substitution.`,
2002
- );
2003
- } else if (existing) {
2004
- existing.expr = substitute;
2005
- existing.isImplicit = false;
2006
- } else substs.push({ op: target, expr: substitute, isImplicit: false });
2007
- });
2008
- // TLC 1.7.4's SANY checks the arity of only the substitutions that the INSTANCE writes.
2009
- substs
2010
- .filter((subst) => subst.isImplicit && options.version !== "1.7.4")
2011
- .forEach((subst) => checkArity(subst.op, subst.expr));
2012
- declarations
2013
- .filter((declaration) => !substs.some((subst) => subst.op.name === declaration.name))
2014
- .forEach((declaration) =>
2015
- addError(
2016
- location,
2017
- `Substitution missing for symbol ${declaration.name} declared at ${formatSanyLocation(declaration.location)} \nand instantiated in module ${currentModule.name}.`,
2018
- ),
2019
- );
2020
- return substs;
2021
- };
2022
-
2023
- const createSubstIn = (
2024
- kind: "SubstIn" | "APSubstIn",
2025
- substs: Subst[],
2026
- body: LevelNode,
2027
- instantiatedModule: ModuleNode,
2028
- location: SanyLocation,
2029
- instantiatingModule = currentModule,
2030
- ): SubstInNode => {
2031
- if (isAbsent(body)) {
2032
- addError(
2033
- location,
2034
- kind === "SubstIn"
2035
- ? "Substitution error, probably due to error \nin module being instantiated."
2036
- : "Substitution error, probably due to error in module being instantiated.",
2037
- );
2038
- }
2039
- return {
2040
- ...createLevelFields(getId()),
2041
- kind,
2042
- substs,
2043
- body,
2044
- instantiatingModule,
2045
- instantiatedModule,
2046
- location,
2047
- };
2048
- };
2049
-
2050
- const processModuleDefinition = (
2051
- instance: Instance,
2052
- definitions: (OpDefNode | ThmOrAssumpDefNode)[] | undefined,
2053
- instances: InstanceNode[] | undefined,
2054
- ) => {
2055
- const span = getDefinitionSpan(instance);
2056
- const location = getSpanLocation(file, span);
2057
- const preComments = getPreComments(file, span.start);
2058
- const name = instance.name ?? "";
2059
- const parameterContext = createContext();
2060
- const nameIndex = instance.isLocal ? span.start + 1 : span.start;
2061
- if (instance.params.length > 0) symbolTable.contexts.push(parameterContext);
2062
- const args = getParams(
2063
- instance,
2064
- { start: nameIndex, end: span.end },
2065
- instance.params.length > 0,
2066
- );
2067
- const instanceeModule = getModule(instance.module);
2068
- const instanceeContext = instanceeModule.context;
2069
- const substs = processSubstitutions(instance, instanceeContext, location);
2070
- if (instance.params.length > 0) symbolTable.contexts.pop();
2071
- getHashtableValues(instanceeContext.table).forEach((symbol) => {
2072
- if (symbol.kind !== "OpDef" || symbol.isLocal) return;
2073
- if (symbol.defKind !== "UserDefined" && symbol.defKind !== "ModuleInstance") return;
2074
- const params = [...args, ...(symbol.params ?? [])];
2075
- const qualifiedName = `${name}!${symbol.name}`;
2076
- const node =
2077
- symbol.defKind === "UserDefined"
2078
- ? createOpDef({
2079
- name: qualifiedName,
2080
- params,
2081
- body:
2082
- substs.length > 0 && symbol.body
2083
- ? createSubstIn("SubstIn", substs, symbol.body, instanceeModule, location)
2084
- : symbol.body,
2085
- isLocal: instance.isLocal,
2086
- location,
2087
- source: symbol.source ?? symbol,
2088
- preComments,
2089
- labels: symbol.labels,
2090
- })
2091
- : createOpDef({
2092
- defKind: "ModuleInstance",
2093
- name: qualifiedName,
2094
- params,
2095
- isLocal: instance.isLocal,
2096
- location,
2097
- module: symbol.module,
2098
- source: symbol.source ?? symbol,
2099
- preComments,
2100
- });
2101
- addSymbol(symbolTable, node);
2102
- if (symbol.defKind === "UserDefined") setRecursionFields(node);
2103
- (definitions ?? currentModule.definitions).push(node);
2104
- });
2105
- getHashtableValues(instanceeContext.table).forEach((symbol) => {
2106
- if (symbol.kind !== "ThmOrAssumpDef" || symbol.isLocal) return;
2107
- // SANY creates the APSubstInNode before the ThmOrAssumpDefNode that holds it.
2108
- const body =
2109
- substs.length > 0
2110
- ? createSubstIn("APSubstIn", substs, symbol.body, instanceeModule, location)
2111
- : symbol.body;
2112
- const node: ThmOrAssumpDefNode = {
2113
- ...createLevelFields(getId()),
2114
- kind: "ThmOrAssumpDef",
2115
- name: `${name}!${symbol.name}`,
2116
- isTheorem: symbol.isTheorem,
2117
- body,
2118
- params: [...args, ...symbol.params],
2119
- isLocal: instance.isLocal,
2120
- location,
2121
- module: currentModule,
2122
- source: symbol.source ?? symbol,
2123
- labels: symbol.labels,
2124
- isLeibnizArg: [],
2125
- isLeibniz: false,
2126
- opLevelCond: [],
2127
- maxLevels: [],
2128
- minMaxLevel: [],
2129
- };
2130
- addSymbol(symbolTable, node);
2131
- (definitions ?? currentModule.definitions).push(node);
2132
- });
2133
- const instanceNode: InstanceNode = {
2134
- ...createLevelFields(getId()),
2135
- kind: "Instance",
2136
- name,
2137
- isLocal: instance.isLocal,
2138
- params: args,
2139
- module: instanceeModule,
2140
- substs,
2141
- location,
2142
- };
2143
- (instances ?? currentModule.topLevel).push(instanceNode);
2144
- const moduleDefinition = createOpDef({
2145
- defKind: "ModuleInstance",
2146
- name,
2147
- params: args,
2148
- isLocal: instance.isLocal,
2149
- location,
2150
- preComments,
2151
- });
2152
- addSymbol(symbolTable, moduleDefinition);
2153
- // TLC 1.7.4's SANY leaves the definition out of the definitions of a LET.
2154
- if (options.version !== "1.7.4") definitions?.push(moduleDefinition);
2155
- };
2156
-
2157
- // An INSTANCE proof step is located at the step's body and adds no theorem definitions or
2158
- // instance to the module.
2159
- const generateInstance = (
2160
- instance: Instance,
2161
- isTopLevel = true,
2162
- stepLocation?: SanyLocation,
2163
- ) => {
2164
- const span = getDefinitionSpan(instance);
2165
- const location = stepLocation ?? getSpanLocation(file, span);
2166
- const preComments = getPreComments(file, span.start);
2167
- const instanceeModule = getModule(instance.module);
2168
- const instanceeContext = instanceeModule.context;
2169
- const substs = processSubstitutions(instance, instanceeContext, location);
2170
- const isLocal = instance.isLocal;
2171
- const isInstanceeParameterFree = isParameterFree(instanceeModule);
2172
- getHashtableValues(instanceeContext.table).forEach((symbol) => {
2173
- if (symbol.kind !== "OpDef" || symbol.defKind !== "UserDefined" || symbol.isLocal) return;
2174
- const copyFrom = (module: ModuleNode | undefined, body: ExprNode | undefined) => {
2175
- const node = createOpDef({
2176
- name: symbol.name,
2177
- params: symbol.params,
2178
- body,
2179
- isLocal,
2180
- location,
2181
- module,
2182
- source: symbol.source ?? symbol,
2183
- preComments,
2184
- labels: symbol.labels,
2185
- });
2186
- addSymbol(symbolTable, node);
2187
- return node;
2188
- };
2189
- const reuse = () => {
2190
- addSymbol(symbolTable, symbol);
2191
- return symbol;
2192
- };
2193
- const isOriginParameterFree = symbol.module === undefined || isParameterFree(symbol.module);
2194
- const node =
2195
- isInstanceeParameterFree || isOriginParameterFree
2196
- ? isLocal
2197
- ? copyFrom(symbol.module, symbol.body)
2198
- : reuse()
2199
- : copyFrom(
2200
- currentModule,
2201
- symbol.body &&
2202
- createSubstIn("SubstIn", substs, symbol.body, instanceeModule, location),
2203
- );
2204
- currentModule.definitions.push(node);
2205
- setRecursionFields(node);
2206
- });
2207
- // SANY reuses a theorem of a parameter-free module without adding it to the symbol table when
2208
- // the instantiated module has parameters.
2209
- getHashtableValues(instanceeContext.table).forEach((symbol) => {
2210
- if (symbol.kind !== "ThmOrAssumpDef" || symbol.isLocal) return;
2211
- const copyFrom = (module: ModuleNode, body: LevelNode) => {
2212
- const node: ThmOrAssumpDefNode = {
2213
- ...symbol,
2214
- ...createLevelFields(getId()),
382
+ },
383
+ createOpArg: (operator, location) => createOpArg(generation, operator, location),
384
+ createFormalParam: (name, arity, location) =>
385
+ createFormalParam(generation, name, arity, location, false),
386
+ createLambda: (params, body, location) =>
387
+ createOpDef(generation, {
388
+ name: "LAMBDA",
389
+ params,
2215
390
  body,
2216
- isLocal,
2217
391
  location,
2218
- module,
2219
- source: symbol.source ?? symbol,
2220
- };
2221
- addSymbol(symbolTable, node);
2222
- return node;
2223
- };
2224
- const reuse = () => {
2225
- addSymbol(symbolTable, symbol);
2226
- return symbol;
2227
- };
2228
- const node = !isInstanceeParameterFree
2229
- ? isParameterFree(symbol.module)
2230
- ? isLocal
2231
- ? copyFrom(currentModule, symbol.body)
2232
- : symbol
2233
- : copyFrom(
2234
- currentModule,
2235
- createSubstIn("APSubstIn", substs, symbol.body, instanceeModule, location),
2236
- )
2237
- : isLocal
2238
- ? copyFrom(symbol.module, symbol.body)
2239
- : reuse();
2240
- if (isTopLevel) currentModule.definitions.push(node);
2241
- });
2242
- const instanceNode: InstanceNode = {
2243
- ...createLevelFields(getId()),
2244
- kind: "Instance",
2245
- name: undefined,
2246
- isLocal,
2247
- params: [],
2248
- module: instanceeModule,
2249
- substs,
2250
- location,
2251
- };
2252
- if (isTopLevel) currentModule.topLevel.push(instanceNode);
2253
- return instanceNode;
2254
- };
2255
-
2256
- const getFactModules = (fact: Fact & { kind: "ModuleFact" }) => {
2257
- const module =
2258
- resolveModule(fact.name) ?? (fact.name === currentModule.name ? currentModule : undefined);
2259
- if (module !== undefined) return [module];
2260
- addError(
2261
- getTokenLocation(file, getTokenIndex(file, fact.location) + 1),
2262
- `Module \`${fact.name}' used without being extended or instantiated.`,
2263
- );
2264
- return [];
2265
- };
2266
-
2267
- const generateFacts = (facts: Fact[]) =>
2268
- facts.flatMap((fact): FactNode[] => {
2269
- if (fact.kind === "ModuleFact") return getFactModules(fact);
2270
- const items = getSelectorItems(fact);
2271
- if (items === undefined || !isGeneralId(items)) return [generateExpression(fact)];
2272
- const node = generateSelector(fact, 0, true, false);
2273
- if (node.kind === "ThmOrAssumpDef") throw new TlaSyntaxError("Expected a fact");
2274
- return [node];
2275
- });
2276
-
2277
- const isParenthesized = (span: TokenSpan) =>
2278
- isToken(file, span.start, "(") && getMatchingIndex(file, span.start) === span.end;
2279
- const getOperandSpan = (expression: Expression) =>
2280
- getParenthesizedSpan(file, getExpressionSpan(file, expression));
2281
- const getApplicationKind = (expression: Expression & { kind: "Apply" }, span: TokenSpan) => {
2282
- if (getOperandSpan(expression.args[0]).start === span.start) {
2283
- return expression.args.length === 2 ? "N_InfixExpr" : "N_PostfixExpr";
2284
- }
2285
- return file.tokens[span.start].kind === "Identifier" ? "N_OpApplication" : "N_PrefixExpr";
2286
- };
2287
- const getSyntaxKind = (expression: Expression, span: TokenSpan) => {
2288
- if (isParenthesized(span)) return "N_ParenExpr";
2289
- if (expression.kind === "String") return getTokenSource(file, span.start);
2290
- if (expression.kind === "Apply") return getApplicationKind(expression, span);
2291
- return SYNTAX_KINDS.get(expression.kind);
2292
- };
2293
- // Generator.genIdToSelector takes a childless first child for an empty prefix of a name.
2294
- const hasChildlessFirstChild = (expression: Expression, span: TokenSpan) => {
2295
- if (expression.kind === "String" && !isParenthesized(span)) return false;
2296
- if (expression.kind === "Identifier" && !expression.name.includes("!")) return true;
2297
- const kind = getSyntaxKind(expression, span);
2298
- return kind === undefined || NESTED_FIRST_CHILD_KINDS.has(kind) ? undefined : true;
2299
- };
2300
- // Generator.genIdToSelector reads a DEF entry that isn't a name as one: its first child as the
2301
- // prefix and its second as the last part.
2302
- const getDefEntryParts = (
2303
- expression: Expression,
2304
- span: TokenSpan,
2305
- ): DefEntryParts | undefined => {
2306
- const getPart = (operand: Expression, partSpan = getOperandSpan(operand)) => ({
2307
- last: partSpan,
2308
- lastKind: getSyntaxKind(operand, partSpan),
2309
- });
2310
- if (isParenthesized(span)) {
2311
- const inner = { start: span.start + 1, end: span.end - 1 };
2312
- return { hasChildlessFirstChild: false, ...getPart(expression, inner) };
2313
- }
2314
- switch (expression.kind) {
2315
- case "If":
2316
- case "BoxAction":
2317
- case "AngleAction":
2318
- return {
2319
- hasChildlessFirstChild: false,
2320
- ...getPart(expression.kind === "If" ? expression.condition : expression.action),
2321
- };
2322
- case "Tuple":
2323
- case "SetEnumeration": {
2324
- const first = expression.elements[0];
2325
- return first === undefined
2326
- ? {
2327
- hasChildlessFirstChild: false,
2328
- last: { start: span.end, end: span.end },
2329
- lastKind: file.tokens[span.end].text,
2330
- }
2331
- : { hasChildlessFirstChild: false, ...getPart(first) };
2332
- }
2333
- case "Always":
2334
- case "Eventually":
2335
- case "Enabled":
2336
- case "Unchanged":
2337
- return {
2338
- hasChildlessFirstChild: true,
2339
- ...getPart(expression.expression, { start: span.start + 1, end: span.end }),
2340
- };
2341
- case "Prime":
2342
- return {
2343
- hasChildlessFirstChild: hasChildlessFirstChild(
2344
- expression.expression,
2345
- getOperandSpan(expression.expression),
2346
- ),
2347
- last: { start: span.end, end: span.end },
2348
- lastKind: "N_GenPostfixOp",
2349
- };
2350
- case "FunctionApplication":
2351
- case "FieldAccess": {
2352
- const operand =
2353
- expression.kind === "FunctionApplication" ? expression.function : expression.record;
2354
- const operandSpan = getOperandSpan(operand);
2355
- const next = operandSpan.end + 1;
2356
- return {
2357
- hasChildlessFirstChild: hasChildlessFirstChild(operand, operandSpan),
2358
- last: { start: next, end: next },
2359
- lastKind: file.tokens[next].text,
2360
- };
2361
- }
2362
- case "Apply": {
2363
- const kind = getApplicationKind(expression, span);
2364
- if (kind === "N_OpApplication") {
2365
- return expression.operator.includes("!")
2366
- ? undefined
2367
- : {
2368
- hasChildlessFirstChild: true,
2369
- last: { start: span.start + 1, end: span.end },
2370
- lastKind: "N_OpArgs",
2371
- };
2372
- }
2373
- if (kind === "N_PrefixExpr") {
2374
- return {
2375
- hasChildlessFirstChild: true,
2376
- ...getPart(expression.args[0], { start: span.start + 1, end: span.end }),
2377
- };
2378
- }
2379
- const left = getOperandSpan(expression.args[0]);
2380
- const operator = left.end + 1;
2381
- return {
2382
- hasChildlessFirstChild: hasChildlessFirstChild(expression.args[0], left),
2383
- last: { start: operator, end: operator },
2384
- lastKind: kind === "N_InfixExpr" ? "N_GenInfixOp" : "N_GenPostfixOp",
2385
- };
2386
- }
2387
- }
2388
- return undefined;
2389
- };
2390
- // False where SANY's reading of the entry isn't modeled.
2391
- const reportDefEntry = (expression: Expression) => {
2392
- const span = getParenthesizedSpan(file, getExpressionSpan(file, expression));
2393
- const isName =
2394
- expression.kind === "Identifier" ||
2395
- expression.kind === "Subexpression" ||
2396
- expression.kind === "OperatorReference";
2397
- if (isName && !isParenthesized(span)) return false;
2398
- const parts = getDefEntryParts(expression, span);
2399
- if (parts?.hasChildlessFirstChild === undefined || parts.lastKind === undefined) return false;
2400
- const lastLocation = getSpanLocation(file, parts.last);
2401
- if (parts.hasChildlessFirstChild) {
2402
- addError(getSpanLocation(file, span), "Was expecting a GeneralId.");
2403
- }
2404
- if (parts.lastKind === "N_OpArgs") {
2405
- addError(lastLocation, "Selector `!(...)' should not have argument(s).");
2406
- } else {
2407
- addError(lastLocation, "Unexpected token found.");
2408
- addError(lastLocation, `Need name or step number here, not \`${parts.lastKind}'.`);
2409
- }
2410
- addError(getSpanLocation(file, span), "DEF clause entry should describe a defined operator.");
2411
- return true;
2412
- };
2413
-
2414
- const generateDefs = (defs: Fact[]) =>
2415
- defs.flatMap((fact): UseOrHideNode["defs"] => {
2416
- if (fact.kind === "ModuleFact") return getFactModules(fact);
2417
- if (reportDefEntry(fact)) return [];
2418
- const symbol = generateSelector(
2419
- fact.kind === "OperatorReference"
2420
- ? { kind: "Identifier", name: fact.operator, location: fact.location }
2421
- : fact,
2422
- -1,
2423
- false,
2424
- true,
2425
- );
2426
- // SANY rejects a proof step name in a DEF clause and leaves out an entry it rejects.
2427
- // Errors.addMessage drops the message when selectorToNode already reported it.
2428
- const isDefinition =
2429
- symbol.kind === "OpDef" ||
2430
- (symbol.kind === "ThmOrAssumpDef" && !symbol.name.startsWith("<"));
2431
- if (!isDefinition) {
2432
- addError(getLocation(fact), "DEF clause entry should describe a defined operator.");
2433
- return [];
2434
- }
2435
- return [symbol];
2436
- });
2437
-
2438
- // SANY rejects a BY, USE or HIDE with nothing after its keyword before it reads the facts.
2439
- const checkKeywordOnly = (
2440
- statement: UseOrHide | Extract<Proof, { kind: "By" }>,
2441
- location: SanyLocation,
2442
- ) => {
2443
- if (statement.isOnly || statement.facts.length + statement.defs.length > 0) return;
2444
- addError(location, "Empty BY, USE, or HIDE");
2445
- };
2446
-
2447
- const generateUseOrHide = (use: UseOrHide): UseOrHideNode => {
2448
- const location = getSpanLocation(file, getUnitSpan(use.location));
2449
- checkKeywordOnly(use, location);
2450
- const facts = generateFacts(use.facts);
2451
- const defs = generateDefs(use.defs);
2452
- if (facts.length + defs.length === 0) addError(location, "Empty USE or HIDE statement.");
2453
- // A HIDE cites facts by name only.
2454
- if (use.kind === "Hide") {
2455
- facts
2456
- .filter((fact) => fact.kind === "OpAppl" && fact.operator.kind !== "ThmOrAssumpDef")
2457
- .forEach((fact) =>
2458
- addError(
2459
- fact.location,
2460
- "The only expression allowed as a fact in a HIDE is \nthe name of a theorem, assumption, or step.",
392
+ preComments: getPreComments(
393
+ file,
394
+ getTokenIndex(file, { line: location.beginLine, column: location.beginColumn }),
2461
395
  ),
396
+ }),
397
+ copySubstIn: (prefix, body) =>
398
+ createSubstIn(
399
+ generation,
400
+ "SubstIn",
401
+ prefix.substs,
402
+ body,
403
+ prefix.instantiatedModule,
404
+ prefix.location,
405
+ prefix.instantiatingModule,
406
+ ),
407
+ getBuiltin: (name) => getBuiltin(generation, name),
408
+ addError: (location, text) => {
409
+ addError(location, text);
410
+ return createNullNode(generation);
411
+ },
412
+ isOutOfLabelScope: (label) => {
413
+ const goal = generation.labelGoals.get(label);
414
+ return (
415
+ goal !== undefined &&
416
+ goal.scope.isDeclaredBefore[goal.clause] &&
417
+ goal.scope.isSuffices === goal.scope.isInProof
2462
418
  );
2463
- }
2464
- return {
2465
- ...createLevelFields(getId()),
2466
- kind: "UseOrHide",
2467
- facts,
2468
- defs,
2469
- isOnly: use.isOnly,
2470
- isHide: use.kind === "Hide",
2471
- location,
2472
- };
2473
- };
2474
-
2475
- // SANY generates the set before it declares the symbol.
2476
- const generateNewSymbol = (symbol: NewSymbol): NewSymbNode => {
2477
- const span = getUnitSpan(symbol.location);
2478
- const set = symbol.set && generateExpression(symbol.set);
2479
- const nameIndex = findNameOrKeyword(span.start, symbol.name);
2480
- const kind = NEW_SYMBOL_KINDS[symbol.level];
2481
- const declaration: OpDeclNode = {
2482
- ...createLevelFields(getId()),
2483
- levelChecked: 1,
2484
- level: kind.level,
2485
- kind: "OpDecl",
2486
- name: resolveSynonym(symbol.name),
2487
- arity: symbol.arity,
2488
- declKind: kind.declKind,
2489
- location: getSpanLocation(file, getOperatorSpan(nameIndex, symbol.arity)),
2490
- module: currentModule,
2491
- };
2492
- addSymbol(symbolTable, declaration);
2493
- return {
2494
- ...createLevelFields(getId()),
2495
- kind: "NewSymb",
2496
- declaration,
2497
- set,
2498
- location: getSpanLocation(file, span),
2499
- };
2500
- };
2501
-
2502
- const generateAssumeProve = (
2503
- assumeProve: AssumeProve,
2504
- depth: number,
2505
- goal?: { isSuffices: boolean },
2506
- ): AssumeProveNode => {
2507
- const span = getUnitSpan(assumeProve.location);
2508
- const isBoxed = isBoxToken(file, span.start - 1);
2509
- const conclusionStart = getExpressionSpan(file, assumeProve.conclusion).start;
2510
- const proveIndex = file.tokens.findLastIndex(
2511
- (token, index) =>
2512
- index < conclusionStart && token.kind === "Keyword" && token.text === "PROVE",
2513
- );
2514
- const assumeLocation = getSpanLocation(file, {
2515
- start: isBoxed ? span.start - 1 : span.start,
2516
- end: span.start,
2517
- });
2518
- if (isBoxed !== isBoxToken(file, proveIndex - 1)) {
2519
- addError(
2520
- assumeLocation,
2521
- isBoxed
2522
- ? "[]ASSUME matched by PROVE instead of []PROVE"
2523
- : "ASSUME matched by []PROVE instead of PROVE",
2524
- );
2525
- }
2526
- // SANY numbers the AssumeProveNode before it generates its clauses.
2527
- const id = getId();
2528
- if (depth > 1) symbolTable.contexts.push(createContext());
2529
- if (isBoxed && symbolTable.contexts.some((context) => assumeContexts.has(context))) {
2530
- addError(
2531
- assumeLocation,
2532
- "[]ASSUME used within the scope of an ordinary ASSUME's assumptions",
2533
- );
2534
- }
2535
- if (!isBoxed) assumeContexts.add(getTopContext(symbolTable));
2536
- const scope: AssumeProveScope = {
2537
- isDeclaredBefore: [false],
2538
- hasGoal: goal !== undefined,
2539
- isSuffices: goal?.isSuffices ?? false,
2540
- isInProof: true,
2541
- };
2542
- assumeProveState.depth = depth;
2543
- assumeProveState.isDeclared[depth] = false;
2544
- if (depth === 1) {
2545
- assumeProveState.goal = goal && scope;
2546
- assumeProveState.goalClause = 0;
2547
- }
2548
- const assumptions = assumeProve.assumptions.map((assumption, index): LevelNode => {
2549
- const isNew = assumption.kind === "NewSymbol";
2550
- const node =
2551
- assumption.kind === "AssumeProve"
2552
- ? generateAssumeProve(assumption, depth + 1)
2553
- : isNew
2554
- ? generateNewSymbol(assumption)
2555
- : generateExpression(assumption);
2556
- assumeProveState.depth = depth;
2557
- if (isNew) assumeProveState.isDeclared[depth] = true;
2558
- scope.isDeclaredBefore.push(scope.isDeclaredBefore[index] || isNew);
2559
- if (depth === 1) assumeProveState.goalClause++;
2560
- return node;
2561
- });
2562
- const conclusion = generateExpression(assumeProve.conclusion);
2563
- if (depth > 1) symbolTable.contexts.pop();
2564
- assumeProveState.depth = depth - 1;
2565
- if (depth === 1) assumeProveState.goal = undefined;
2566
- const node: AssumeProveNode = {
2567
- ...createLevelFields(id),
2568
- kind: "AssumeProve",
2569
- assumptions,
2570
- goal: conclusion,
2571
- isSuffices: scope.isSuffices,
2572
- isBoxed,
2573
- location: getSpanLocation(file, {
2574
- start: isBoxed ? span.start - 1 : span.start,
2575
- end: span.end,
2576
- }),
2577
- };
2578
- assumeProveScopes.set(node, scope);
2579
- return node;
2580
- };
2581
-
2582
- // SANY numbers the ThmOrAssumpDefNode before it generates what it asserts.
2583
- const createTheoremDefinition = (
2584
- id: number,
2585
- name: string,
2586
- body: LevelNode,
2587
- location: SanyLocation,
2588
- labels: Map<string, LabelNode>,
2589
- isTheorem = true,
2590
- ): ThmOrAssumpDefNode => ({
2591
- ...createLevelFields(id),
2592
- kind: "ThmOrAssumpDef",
2593
- name,
2594
- isTheorem,
2595
- body,
2596
- params: [],
2597
- isLocal: false,
2598
- location,
2599
- module: currentModule,
2600
- source: undefined,
2601
- labels,
2602
- isLeibnizArg: [],
2603
- isLeibniz: false,
2604
- opLevelCond: [],
2605
- maxLevels: [],
2606
- minMaxLevel: [],
2607
- });
2608
-
2609
- const generateLeafProof = (proof: Exclude<Proof, { kind: "Steps" }>): LeafProofNode => {
2610
- const location = getSpanLocation(file, getUnitSpan(proof.location));
2611
- if (proof.kind === "By") checkKeywordOnly(proof, location);
2612
- const facts = proof.kind === "By" ? generateFacts(proof.facts) : [];
2613
- const defs = proof.kind === "By" ? generateDefs(proof.defs) : [];
2614
- // The UseOrHideNode SANY makes of a BY proof's facts and definitions.
2615
- if (proof.kind === "By") getId();
2616
- if (proof.kind === "By" && facts.length + defs.length === 0) addError(location, "Empty BY");
2617
- return {
2618
- ...createLevelFields(getId()),
2619
- kind: "LeafProof",
2620
- facts,
2621
- defs,
2622
- isOmitted: proof.kind === "Omitted",
2623
- isOnly: proof.kind === "By" && proof.isOnly,
2624
- location,
2625
- };
2626
- };
2627
-
2628
- const generateStepBody = (step: ProofStep, bodySpan: TokenSpan) => {
2629
- const body = step.body;
2630
- const bodyLocation = getSpanLocation(file, bodySpan);
2631
- switch (body.kind) {
2632
- case "Have":
2633
- return {
2634
- node: applyBuiltin("$Have", [generateExpression(body.expression)], bodyLocation),
2635
- isPick: false,
2636
- };
2637
- case "Case":
2638
- return {
2639
- node: applyBuiltin("$Pfcase", [generateExpression(body.expression)], bodyLocation),
2640
- isPick: false,
2641
- };
2642
- case "Witness":
2643
- return {
2644
- node: applyBuiltin("$Witness", body.expressions.map(generateExpression), bodyLocation),
2645
- isPick: false,
2646
- };
2647
- case "Qed":
2648
- return { node: applyBuiltin("$Qed", [], bodyLocation), isPick: false };
2649
- case "Take":
2650
- case "Pick": {
2651
- const isPick = body.kind === "Pick";
2652
- const name = isPick ? "$Pick" : "$Take";
2653
- if (isPick) symbolTable.contexts.push(createContext());
2654
- const getOperands = (params: FormalParamNode[]) =>
2655
- body.kind === "Pick" ? [generateWithParams(params, body.body)] : [];
2656
- if (body.bounds.length > 0) {
2657
- const bounds = generateBounds(body.bounds, bodySpan.start);
2658
- const operands = getOperands(bounds.bounded.flat());
2659
- return { node: applyBuiltin(name, operands, bodyLocation, bounds), isPick };
2660
- }
2661
- const indexes = findNameTokens(file, bodySpan.start, bodySpan.end + 1, body.names);
2662
- const unbounded = body.names.map((paramName, index) =>
2663
- createFormalParam(paramName, 0, getTokenLocation(file, indexes[index]), true),
2664
- );
2665
- const operands = getOperands(unbounded);
2666
- return { node: applyBuiltin(name, operands, bodyLocation, { unbounded }), isPick };
2667
- }
2668
- }
2669
- return undefined;
2670
- };
2671
-
2672
- const isInfixExpression = (expression: Expression) => {
2673
- if ((expression.kind === "And" || expression.kind === "Or") && !expression.isBulleted)
2674
- return true;
2675
- if (expression.kind !== "Apply" || expression.args.length !== 2) return false;
2676
- const left = getParenthesizedSpan(file, getExpressionSpan(file, expression.args[0]));
2677
- const start = getExpressionSpan(file, expression).start;
2678
- return left.start === start && !isToken(file, left.end + 1, "(");
2679
- };
2680
-
2681
- const generateProof = (proof: Proof): LeafProofNode | NonLeafProofNode => {
2682
- if (proof.kind !== "Steps") return generateLeafProof(proof);
2683
- const proofContext = createContext();
2684
- symbolTable.contexts.push(proofContext);
2685
- const instances: InstanceNode[] = [];
2686
- const sufficesContexts: Context[] = [];
2687
- // An assertion step @ = e continues the step before it, whose right side the @ stands for.
2688
- const infixStep: { previousRight: ExprOrOpArgNode | undefined } = {
2689
- previousRight: undefined,
2690
- };
2691
- const generateOtherStep = (
2692
- body: ProofStep["body"],
2693
- stepSpan: TokenSpan,
2694
- bodySpan: TokenSpan,
2695
- ): DefStepNode | UseOrHideNode | InstanceNode | undefined => {
2696
- if (body.kind === "Define") {
2697
- const defs = body.definitions.map((definition) => {
2698
- const defined: (OpDefNode | ThmOrAssumpDefNode)[] = [];
2699
- if (definition.kind === "Instance")
2700
- processModuleDefinition(definition, defined, instances);
2701
- else if (definition.kind === "Function") processFunction(definition, defined);
2702
- else processOperator(definition, defined);
2703
- const last = defined[definition.kind === "Instance" ? defined.length - 1 : 0];
2704
- if (last?.kind !== "OpDef")
2705
- throw new TlaSyntaxError("A DEFINE step defines no operator");
2706
- return last;
2707
- });
2708
- return {
2709
- ...createLevelFields(getId()),
2710
- kind: "DefStep",
2711
- defs,
2712
- location: getSpanLocation(file, bodySpan),
2713
- };
2714
- }
2715
- if (body.kind === "Use" || body.kind === "Hide") {
2716
- return { ...generateUseOrHide(body), location: getSpanLocation(file, stepSpan) };
2717
- }
2718
- if (body.kind === "Instance") {
2719
- return generateInstance(body, false, getSpanLocation(file, bodySpan));
2720
- }
2721
- return undefined;
2722
- };
2723
- const steps = proof.steps.map((step): ProofStepNode => {
2724
- const stepSpan = getUnitSpan(step.location);
2725
- const headSpan = getRangeSpan(file, step.head);
2726
- const bodySpan = { start: headSpan.start + 1, end: headSpan.end };
2727
- const body = step.body;
2728
- if (step.name !== undefined && /^<[*+]>/.test(step.token)) {
2729
- addError(
2730
- getTokenLocation(file, stepSpan.start),
2731
- "<*> and <+> cannot be used for a named step.",
419
+ },
420
+ isOutOfClauseScope: (assumeProve, position) => {
421
+ const scope = generation.assumeProveScopes.get(assumeProve);
422
+ return (
423
+ scope !== undefined &&
424
+ scope.isDeclaredBefore[position - 1] &&
425
+ (!scope.hasGoal || scope.isSuffices === scope.isInProof)
2732
426
  );
2733
- }
2734
- if (step.name !== undefined) pushLabelScope();
2735
- const definitionId = step.name === undefined ? undefined : getId();
2736
- if (body.kind !== "Assert") infixStep.previousRight = undefined;
2737
- const otherStep = generateOtherStep(body, stepSpan, bodySpan);
2738
- if (otherStep !== undefined) {
2739
- // SANY puts a definition for a named step that asserts nothing in the symbol table, for a DEF
2740
- // clause to name.
2741
- if (step.name !== undefined) {
2742
- addSymbol(
2743
- symbolTable,
2744
- createOpDef({
2745
- defKind: "NumberedProofStep",
2746
- name: step.name,
2747
- location: getSpanLocation(file, stepSpan),
2748
- labels: popLabels(),
2749
- step: otherStep,
2750
- }),
2751
- );
2752
- }
2753
- return otherStep;
2754
- }
2755
- const isAssumeProve = body.kind === "Assert" && body.statement.kind === "AssumeProve";
2756
- if (isAssumeProve) infixStep.previousRight = undefined;
2757
- const isSuffices = body.kind === "Assert" && body.isSuffices;
2758
- const assumeContext = createContext();
2759
- const generateAssertion = (statement: Expression | AssumeProve): LevelNode => {
2760
- if (statement.kind === "AssumeProve") {
2761
- const node = withContext(assumeContext, () =>
2762
- generateAssumeProve(
2763
- statement,
2764
- 1,
2765
- step.name === undefined ? undefined : { isSuffices },
2766
- ),
2767
- );
2768
- node.isSuffices = isSuffices;
2769
- return node;
2770
- }
2771
- if (isSuffices) {
2772
- const expression = generateExpression(statement);
2773
- return applyBuiltin("$Suffices", [expression], getSpanLocation(file, bodySpan));
2774
- }
2775
- const previousRight = infixStep.previousRight;
2776
- const isAtStep =
2777
- previousRight !== undefined &&
2778
- statement.kind === "Apply" &&
2779
- isInfixExpression(statement) &&
2780
- statement.args[0].kind === "ExceptAt";
2781
- // SANY generates an @ step's right side before the $Nop that stands for its @.
2782
- const atRight = isAtStep ? generateExpression(statement.args[1]) : undefined;
2783
- const expression = isAtStep
2784
- ? createOpAppl(
2785
- resolveName(statement.operator, getLocation(statement)),
2786
- [applyBuiltin("$Nop", [previousRight], getLocation(statement.args[0])), atRight],
2787
- getLocation(statement),
2788
- )
2789
- : generateExpression(statement);
2790
- const right = expression.kind === "OpAppl" ? expression.operands[1] : undefined;
2791
- infixStep.previousRight = isInfixExpression(statement) ? right : undefined;
2792
- return expression;
2793
- };
2794
- const generated =
2795
- body.kind === "Assert"
2796
- ? { node: generateAssertion(body.statement), isPick: false }
2797
- : generateStepBody(step, bodySpan);
2798
- if (generated === undefined) throw new TlaSyntaxError(`Unexpected proof step ${body.kind}`);
2799
- const pickContext = generated.isPick ? symbolTable.contexts.pop() : undefined;
2800
- const definition =
2801
- step.name === undefined || definitionId === undefined
2802
- ? undefined
2803
- : createTheoremDefinition(
2804
- definitionId,
2805
- step.name,
2806
- generated.node,
2807
- getTokenLocation(file, getTokenIndex(file, step.location)),
2808
- popLabels(),
2809
- );
2810
- if (definition) addSymbol(symbolTable, definition);
2811
- const isScoped = isAssumeProve && !isSuffices;
2812
- if (isScoped) symbolTable.contexts.push(assumeContext);
2813
- const stepProof = step.proof && generateProof(step.proof);
2814
- if (isScoped) symbolTable.contexts.pop();
2815
- endProof(generated.node);
2816
- if (isAssumeProve && isSuffices) {
2817
- sufficesContexts.push(assumeContext);
2818
- symbolTable.contexts.push(assumeContext);
2819
- }
2820
- pickContext?.symbols.forEach((symbol) => addSymbol(symbolTable, symbol));
2821
- return {
2822
- ...createLevelFields(getId()),
2823
- kind: "Theorem",
2824
- definition,
2825
- body: generated.node,
2826
- proof: stepProof,
2827
- isSuffices,
2828
- location: getSpanLocation(file, stepSpan),
2829
- };
2830
- });
2831
- sufficesContexts.forEach(() => {
2832
- symbolTable.contexts.pop()?.symbols.forEach((symbol) => addToContext(proofContext, symbol));
2833
- });
2834
- symbolTable.contexts.pop();
2835
- return {
2836
- ...createLevelFields(getId()),
2837
- kind: "NonLeafProof",
2838
- steps,
2839
- instances,
2840
- proofLevel: proof.level,
2841
- location: getSpanLocation(file, getUnitSpan(proof.location)),
2842
- };
427
+ },
428
+ }),
2843
429
  };
2844
430
 
2845
- const processTheorem = (theorem: Theorem) => {
2846
- const location = getSpanLocation(file, getUnitSpan(theorem.location));
2847
- const statement = theorem.statement;
2848
- const assumeContext = createContext();
2849
- if (theorem.name !== undefined) pushLabelScope();
2850
- const definitionId = theorem.name === undefined ? undefined : getId();
2851
- if (statement.kind === "AssumeProve") symbolTable.contexts.push(assumeContext);
2852
- const body =
2853
- statement.kind === "AssumeProve"
2854
- ? generateAssumeProve(
2855
- statement,
2856
- 1,
2857
- theorem.name === undefined ? undefined : { isSuffices: false },
2858
- )
2859
- : generateExpression(statement);
2860
- const definition =
2861
- theorem.name === undefined || definitionId === undefined
2862
- ? undefined
2863
- : createTheoremDefinition(definitionId, theorem.name, body, location, popLabels());
2864
- if (definition) {
2865
- if (statement.kind === "AssumeProve") symbolTable.contexts.pop();
2866
- addSymbol(symbolTable, definition);
2867
- currentModule.definitions.push(definition);
2868
- if (statement.kind === "AssumeProve") symbolTable.contexts.push(assumeContext);
2869
- }
2870
- const proof = theorem.proof && generateProof(theorem.proof);
2871
- if (statement.kind === "AssumeProve") symbolTable.contexts.pop();
2872
- endProof(body);
2873
- const node: TheoremNode = {
2874
- ...createLevelFields(getId()),
2875
- kind: "Theorem",
2876
- definition,
2877
- body,
2878
- proof,
2879
- isSuffices: false,
2880
- location,
2881
- };
2882
- currentModule.topLevel.push(node);
2883
- };
2884
-
2885
- const processAssumption = (assumption: Assumption) => {
2886
- const span = getUnitSpan(assumption.location);
2887
- const location = getSpanLocation(file, span);
2888
- if (assumption.name !== undefined) pushLabelScope();
2889
- const body = generateExpression(assumption.expression);
2890
- const definition =
2891
- assumption.name === undefined
2892
- ? undefined
2893
- : createTheoremDefinition(getId(), assumption.name, body, location, popLabels(), false);
2894
- if (definition) {
2895
- addSymbol(symbolTable, definition);
2896
- currentModule.definitions.push(definition);
2897
- }
2898
- const node: AssumeNode = {
2899
- ...createLevelFields(getId()),
2900
- kind: "Assume",
2901
- definition,
2902
- body,
2903
- location,
2904
- };
2905
- currentModule.topLevel.push(node);
2906
- };
2907
-
2908
- const getOperatorSpan = (start: number, arity: number) => {
2909
- if (arity === 0) return { start, end: start };
2910
- if (isToken(file, start, "_")) {
2911
- return { start, end: isToken(file, start + 2, "_") ? start + 2 : start + 1 };
2912
- }
2913
- if (isToken(file, start + 1, "(")) return { start, end: getMatchingIndex(file, start + 1) };
2914
- return { start, end: isToken(file, start + 1, "_") ? start + 1 : start };
2915
- };
2916
-
2917
- const getDeclarationSpan = (declaration: Declaration) =>
2918
- getOperatorSpan(getUnitSpan(declaration.location).start, declaration.arity);
2919
-
2920
- const createDeclaration = (declaration: Declaration, declKind: number): OpDeclNode => {
2921
- const span = getDeclarationSpan(declaration);
2922
- // Generator.processParameters makes this check of a constant too, of its syntax node's name,
2923
- // which is never @.
2924
- if (declaration.name === "@" && declKind === VARIABLE_DECL_KIND) {
2925
- addError(getSpanLocation(file, span), "Attempted to declare '@' as a variable.");
2926
- }
2927
- const node: OpDeclNode = {
2928
- ...createLevelFields(getId()),
2929
- levelChecked: 1,
2930
- level: declKind === VARIABLE_DECL_KIND ? 1 : 0,
2931
- kind: "OpDecl",
2932
- name: resolveSynonym(declaration.name),
2933
- arity: declaration.arity,
2934
- declKind,
2935
- location: getSpanLocation(file, span),
2936
- module: currentModule,
2937
- };
2938
- if (declKind === CONSTANT_DECL_KIND) {
2939
- node.levelParams.add(node);
2940
- node.allParams.add(node);
2941
- }
2942
- addSymbol(symbolTable, node);
2943
- return node;
2944
- };
2945
-
2946
- // The extended module's symbols join in the order they joined it, apart from LOCAL ones and
2947
- // those already present.
2948
431
  ast.extends.forEach((name) => {
2949
- const extendee = getModule(name);
432
+ const extendee = getModule(generation, name);
2950
433
  currentModule.extendees.push(extendee);
2951
- const context = getTopContext(symbolTable);
434
+ const context = getTopContext(contexts);
2952
435
  extendee.context.symbols.forEach((symbol) => {
2953
436
  if (
2954
437
  symbol.kind !== "Module" &&
@@ -2979,57 +462,52 @@ export const generateSanySpecification = (
2979
462
  currentModule.topLevel.push(...extendee.topLevel);
2980
463
  });
2981
464
 
2982
- const checkRecursiveSection = (location: SourceLocation, type: string) => {
2983
- if (state.unresolvedSum === 0) return;
2984
- addError(
2985
- getSpanLocation(file, getUnitSpan(location)),
2986
- `${type} may not appear within a recursive definition section.`,
2987
- );
2988
- };
2989
-
2990
465
  ast.units.forEach((unit) => {
2991
466
  switch (unit.kind) {
2992
467
  case "Variables":
2993
- checkRecursiveSection(unit.location, "A VARIABLE declaration");
468
+ checkRecursiveSection(generation, unit.location, "A VARIABLE declaration");
2994
469
  unit.declarations.forEach((declaration) =>
2995
- createDeclaration(declaration, VARIABLE_DECL_KIND),
470
+ createDeclaration(generation, declaration, VARIABLE_DECL_KIND),
2996
471
  );
2997
472
  break;
2998
473
  case "Constants":
2999
- checkRecursiveSection(unit.location, "A declaration");
474
+ checkRecursiveSection(generation, unit.location, "A declaration");
3000
475
  unit.declarations.forEach((declaration) =>
3001
- createDeclaration(declaration, CONSTANT_DECL_KIND),
476
+ createDeclaration(generation, declaration, CONSTANT_DECL_KIND),
3002
477
  );
3003
478
  break;
3004
479
  case "Recursive":
3005
- processRecursive(unit.declarations);
480
+ processRecursive(generation, unit.declarations);
3006
481
  break;
3007
482
  case "Definition":
3008
- if (unit.definition.kind === "Function") processFunction(unit.definition, undefined);
3009
- else processOperator(unit.definition, undefined);
483
+ if (unit.definition.kind === "Function")
484
+ processFunction(generation, unit.definition, undefined);
485
+ else processOperator(generation, unit.definition, undefined);
3010
486
  break;
3011
487
  case "Instance":
3012
- if (unit.instance.name === undefined) generateInstance(unit.instance);
3013
- else processModuleDefinition(unit.instance, undefined, undefined);
488
+ if (unit.instance.name === undefined) generateInstance(generation, unit.instance);
489
+ else processModuleDefinition(generation, unit.instance, undefined, undefined);
3014
490
  break;
3015
491
  case "Assumption":
3016
- checkRecursiveSection(unit.assumption.location, "An ASSUME");
3017
- processAssumption(unit.assumption);
492
+ checkRecursiveSection(generation, unit.assumption.location, "An ASSUME");
493
+ processAssumption(generation, unit.assumption);
3018
494
  break;
3019
495
  case "Theorem":
3020
- checkRecursiveSection(unit.theorem.location, "A THEOREM");
3021
- processTheorem(unit.theorem);
496
+ checkRecursiveSection(generation, unit.theorem.location, "A THEOREM");
497
+ processTheorem(generation, unit.theorem);
3022
498
  break;
3023
499
  case "Use":
3024
- checkRecursiveSection(unit.use.location, "A USE or HIDE");
3025
- currentModule.topLevel.push(generateUseOrHide(unit.use));
500
+ checkRecursiveSection(generation, unit.use.location, "A USE or HIDE");
501
+ currentModule.topLevel.push(generateUseOrHide(generation, unit.use));
3026
502
  break;
3027
503
  case "Module": {
3028
- checkRecursiveSection(unit.module.location, "A MODULE ");
3029
- const innerTable = { contexts: [...symbolTable.contexts, createContext()] };
3030
- const inner = generateModule(unit.module, file, currentModule, innerTable);
3031
- const binding = resolveModule(inner.name);
3032
- if (binding === undefined) addToContext(getTopContext(symbolTable), inner);
504
+ checkRecursiveSection(generation, unit.module.location, "A MODULE ");
505
+ const inner = generateModule(unit.module, file, currentModule, [
506
+ ...contexts,
507
+ createContext(),
508
+ ]);
509
+ const binding = resolveModule(generation, inner.name);
510
+ if (binding === undefined) addToContext(getTopContext(contexts), inner);
3033
511
  else if (binding !== inner) {
3034
512
  addError(
3035
513
  inner.location,
@@ -3040,21 +518,20 @@ export const generateSanySpecification = (
3040
518
  }
3041
519
  }
3042
520
  });
3043
- checkForUndefinedRecursiveOps();
521
+
522
+ checkForUndefinedRecursiveOps(generation);
523
+
3044
524
  return currentModule;
3045
525
  };
3046
526
 
3047
527
  const modules = order.map((name) => {
3048
528
  options.onAnalyze?.(name);
3049
529
  // Each module's Generator creates its nullODN, nullOAN, nullOpArg and nullLabelNode.
3050
- nullApplication.id = Array.from({ length: 4 }, getId)[1];
530
+ nullApplicationId = Array.from({ length: 4 }, getId)[1];
3051
531
  const entry = getSource(name, undefined);
3052
532
  const context = createContext();
3053
- // SANY's global context lists its builtins from the last to the first.
3054
533
  builtins.toReversed().forEach((builtin) => addToContext(context, builtin));
3055
- const module = generateModule(entry.module, entry.file, undefined, {
3056
- contexts: [context],
3057
- });
534
+ const module = generateModule(entry.module, entry.file, undefined, [context]);
3058
535
  externalModules.set(name, module);
3059
536
  options.onModule?.(module, messages);
3060
537
  return module;