tla-ts 0.0.10-dev.28c823e4b → 0.0.10-dev.37a75eb5b

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