tla-ts 0.0.10-dev.f16792fed → 0.0.10-dev.fdc173479

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 (587) 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 +41 -37
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +21 -4
  8. package/dist/index.d.ts +21 -4
  9. package/dist/index.js +1 -1
  10. package/dist/parallel-worker.cjs +1 -1
  11. package/dist/parallel-worker.js +1 -1
  12. package/dist/prove-worker.cjs +1 -1
  13. package/dist/prove-worker.js +1 -1
  14. package/dist/prove.cjs +2681 -425
  15. package/dist/prove.js +2681 -425
  16. package/dist/run.cjs +41 -42
  17. package/dist/run.js +41 -42
  18. package/dist/tlapm.cjs +2 -2
  19. package/dist/tlapm.js +2 -2
  20. package/dist/transfer.cjs +97 -89
  21. package/dist/transfer.js +97 -89
  22. package/dist/worker.cjs +7 -7
  23. package/dist/worker.js +7 -7
  24. package/package.json +1 -1
  25. package/src/ast.ts +72 -39
  26. package/src/bags.ts +50 -29
  27. package/src/builtins.ts +8 -16
  28. package/src/check-failure.ts +118 -0
  29. package/src/check-trace.ts +321 -0
  30. package/src/check.ts +828 -770
  31. package/src/cli/options.ts +6 -31
  32. package/src/cli/runtime-invariants.ts +20 -56
  33. package/src/cli/shared.ts +1 -1
  34. package/src/cli/tlapm.ts +433 -70
  35. package/src/cli/tlc-arguments.ts +224 -212
  36. package/src/cli/tlc-output.ts +701 -0
  37. package/src/cli/tlc-usage.ts +1 -2
  38. package/src/cli/tlc.ts +65 -712
  39. package/src/cli/xml-exporter.ts +23 -33
  40. package/src/codegen.ts +28 -20
  41. package/src/coverage.ts +255 -20
  42. package/src/dependencies.ts +96 -27
  43. package/src/dfid.ts +115 -50
  44. package/src/environment-config.ts +315 -0
  45. package/src/environment.ts +175 -373
  46. package/src/errors.ts +40 -5
  47. package/src/evaluate.ts +429 -139
  48. package/src/exit-codes.ts +28 -12
  49. package/src/fingerprints.ts +65 -1
  50. package/src/instances.ts +178 -17
  51. package/src/java-hash.ts +14 -0
  52. package/src/java-overrides.ts +2 -2
  53. package/src/json.ts +4 -7
  54. package/src/levels.ts +708 -272
  55. package/src/lexer.ts +17 -5
  56. package/src/liveness-checker.ts +707 -249
  57. package/src/liveness.ts +148 -95
  58. package/src/obligations/action.ts +14 -17
  59. package/src/obligations/anonymize.ts +37 -16
  60. package/src/obligations/enabled-axioms.ts +218 -0
  61. package/src/obligations/equality.ts +1 -3
  62. package/src/obligations/expression.ts +36 -8
  63. package/src/obligations/format.ts +0 -2
  64. package/src/obligations/generate.ts +66 -54
  65. package/src/obligations/index.ts +39 -9
  66. package/src/obligations/levels.ts +24 -11
  67. package/src/obligations/module.ts +28 -41
  68. package/src/obligations/normalize.ts +27 -18
  69. package/src/obligations/operators.ts +0 -2
  70. package/src/obligations/pragma.ts +53 -16
  71. package/src/obligations/printer.ts +48 -18
  72. package/src/obligations/proof.ts +3 -2
  73. package/src/obligations/regroup.ts +0 -2
  74. package/src/obligations/simplify.ts +55 -50
  75. package/src/obligations/source.ts +120 -74
  76. package/src/obligations/subexpression.ts +45 -18
  77. package/src/obligations/substitution.ts +1 -3
  78. package/src/obligations/temporal.ts +5 -7
  79. package/src/obligations/tuples.ts +0 -2
  80. package/src/parallel-worker.ts +17 -31
  81. package/src/parallel.ts +29 -47
  82. package/src/parser.ts +757 -326
  83. package/src/pretty-print.ts +1 -1
  84. package/src/prover/decide-pool.ts +3 -3
  85. package/src/prover/deciders.ts +12 -9
  86. package/src/prover/isabelle/decide.ts +3 -25
  87. package/src/prover/isabelle/encode.ts +72 -42
  88. package/src/prover/isabelle/isar/attrib.ts +250 -0
  89. package/src/prover/isabelle/isar/context.ts +335 -0
  90. package/src/prover/isabelle/isar/induct.ts +382 -0
  91. package/src/prover/isabelle/isar/inner-syntax.ts +158 -7
  92. package/src/prover/isabelle/isar/method.ts +509 -212
  93. package/src/prover/isabelle/isar/proof.ts +570 -14
  94. package/src/prover/isabelle/isar/rule-cases.ts +226 -0
  95. package/src/prover/isabelle/isar/theory.ts +487 -76
  96. package/src/prover/isabelle/isar/toplevel.ts +331 -0
  97. package/src/prover/isabelle/isar/type-check.ts +89 -14
  98. package/src/prover/isabelle/provers/blast/blast.ts +7 -65
  99. package/src/prover/isabelle/provers/blast/branch.ts +0 -2
  100. package/src/prover/isabelle/provers/blast/prove.ts +0 -2
  101. package/src/prover/isabelle/provers/blast/rules.ts +0 -2
  102. package/src/prover/isabelle/provers/blast/state.ts +0 -2
  103. package/src/prover/isabelle/provers/blast/term.ts +0 -2
  104. package/src/prover/isabelle/provers/clasimp.ts +1 -3
  105. package/src/prover/isabelle/provers/classical.ts +45 -20
  106. package/src/prover/isabelle/provers/hypsubst.ts +19 -30
  107. package/src/prover/isabelle/pure/bicompose.ts +9 -27
  108. package/src/prover/isabelle/pure/consts.ts +0 -2
  109. package/src/prover/isabelle/pure/conv.ts +2 -10
  110. package/src/prover/isabelle/pure/drule.ts +72 -6
  111. package/src/prover/isabelle/pure/envir.ts +0 -2
  112. package/src/prover/isabelle/pure/goal.ts +1 -3
  113. package/src/prover/isabelle/pure/logic.ts +1 -3
  114. package/src/prover/isabelle/pure/name.ts +0 -2
  115. package/src/prover/isabelle/pure/net.ts +0 -2
  116. package/src/prover/isabelle/pure/object-logic.ts +13 -7
  117. package/src/prover/isabelle/pure/pattern.ts +0 -2
  118. package/src/prover/isabelle/pure/raw-simplifier.ts +4 -15
  119. package/src/prover/isabelle/pure/rewriter.ts +9 -20
  120. package/src/prover/isabelle/pure/search.ts +0 -2
  121. package/src/prover/isabelle/pure/seq.ts +0 -2
  122. package/src/prover/isabelle/pure/simplifier.ts +26 -7
  123. package/src/prover/isabelle/pure/table.ts +2 -3
  124. package/src/prover/isabelle/pure/tactic.ts +0 -2
  125. package/src/prover/isabelle/pure/tactical.ts +42 -37
  126. package/src/prover/isabelle/pure/term-ord.ts +0 -2
  127. package/src/prover/isabelle/pure/term.ts +3 -5
  128. package/src/prover/isabelle/pure/thm.ts +14 -13
  129. package/src/prover/isabelle/pure/type.ts +0 -2
  130. package/src/prover/isabelle/pure/unify.ts +0 -2
  131. package/src/prover/isabelle/pure/variable.ts +0 -2
  132. package/src/prover/isabelle/tla/classical-setup.ts +18 -16
  133. package/src/prover/isabelle/tla/context.ts +58 -11
  134. package/src/prover/isabelle/tla/logic-data.ts +1 -1
  135. package/src/prover/isabelle/tla/logic.ts +49 -21
  136. package/src/prover/isabelle/tla/simpdata.ts +1 -12
  137. package/src/prover/isabelle/tools/intuitionistic.ts +28 -12
  138. package/src/prover/ocaml.ts +4 -1
  139. package/src/prover/prep/action.ts +30 -31
  140. package/src/prover/prep/enabled-axioms.ts +11 -2
  141. package/src/prover/prep/fingerprint.ts +2 -5
  142. package/src/prover/prep/md5.ts +26 -29
  143. package/src/prover/prep/methods.ts +181 -51
  144. package/src/prover/prep/normalize.ts +38 -9
  145. package/src/prover/prove.ts +395 -94
  146. package/src/prover/ptl/decide.ts +95 -50
  147. package/src/prover/ptl/encode.ts +2 -3
  148. package/src/prover/ptl/tableau.ts +28 -2
  149. package/src/prover/smt/arithmetic.ts +310 -0
  150. package/src/prover/smt/axioms.ts +12 -8
  151. package/src/prover/smt/context.ts +43 -8
  152. package/src/prover/smt/data.ts +498 -379
  153. package/src/prover/smt/encode.ts +148 -57
  154. package/src/prover/smt/extensionality.ts +5 -3
  155. package/src/prover/smt/flatten.ts +4 -6
  156. package/src/prover/smt/format.ts +28 -4
  157. package/src/prover/smt/instances.ts +7 -1
  158. package/src/prover/smt/layout.ts +91 -0
  159. package/src/prover/smt/rewrite.ts +1016 -618
  160. package/src/prover/smt/simplify.ts +441 -0
  161. package/src/prover/smt/solver/ackermannize-bv-tactic.ts +62 -0
  162. package/src/prover/smt/solver/ackr-helper.ts +179 -0
  163. package/src/prover/smt/solver/ackr-model-converter.ts +105 -0
  164. package/src/prover/smt/solver/act-cache.ts +0 -1
  165. package/src/prover/smt/solver/add-bounds-tactic.ts +59 -0
  166. package/src/prover/smt/solver/aig-tactic.ts +52 -0
  167. package/src/prover/smt/solver/aig.ts +889 -0
  168. package/src/prover/smt/solver/arith-rewriter.ts +624 -9
  169. package/src/prover/smt/solver/arith-terms.ts +121 -0
  170. package/src/prover/smt/solver/array-decl-plugin.ts +175 -0
  171. package/src/prover/smt/solver/array-rewriter.ts +319 -0
  172. package/src/prover/smt/solver/asserted-formulas.ts +240 -56
  173. package/src/prover/smt/solver/ast-lt.ts +165 -11
  174. package/src/prover/smt/solver/ast-util.ts +160 -2
  175. package/src/prover/smt/solver/ast.ts +1483 -45
  176. package/src/prover/smt/solver/auf-solver.ts +25 -18
  177. package/src/prover/smt/solver/bit-blast-tactic.ts +608 -0
  178. package/src/prover/smt/solver/bit-blaster.ts +871 -0
  179. package/src/prover/smt/solver/blast-term-ite.ts +47 -0
  180. package/src/prover/smt/solver/bound-manager.ts +196 -0
  181. package/src/prover/smt/solver/bound-simplifier.ts +598 -0
  182. package/src/prover/smt/solver/bv-bound-chk.ts +492 -0
  183. package/src/prover/smt/solver/bv-decl-plugin.ts +341 -0
  184. package/src/prover/smt/solver/bv-divrem-bounds.ts +95 -0
  185. package/src/prover/smt/solver/bv-rewriter.ts +1901 -0
  186. package/src/prover/smt/solver/bv1-blast.ts +214 -0
  187. package/src/prover/smt/solver/bv2fpa-converter.ts +174 -0
  188. package/src/prover/smt/solver/bv2int-rewriter.ts +544 -0
  189. package/src/prover/smt/solver/bv2real-rewriter.ts +533 -0
  190. package/src/prover/smt/solver/card2bv.ts +127 -0
  191. package/src/prover/smt/solver/case-split-queue.ts +0 -2
  192. package/src/prover/smt/solver/cg-table.ts +39 -25
  193. package/src/prover/smt/solver/check-logic.ts +330 -0
  194. package/src/prover/smt/solver/clause.ts +0 -1
  195. package/src/prover/smt/solver/cofactor-elim-term-ite.ts +293 -0
  196. package/src/prover/smt/solver/conflict-resolution.ts +78 -2
  197. package/src/prover/smt/solver/context.ts +598 -128
  198. package/src/prover/smt/solver/ctx-simplify.ts +29 -14
  199. package/src/prover/smt/solver/ctx-solver-simplify.ts +122 -0
  200. package/src/prover/smt/solver/datatype-decl-plugin.ts +580 -0
  201. package/src/prover/smt/solver/datatype-rewriter.ts +82 -0
  202. package/src/prover/smt/solver/demodulator.ts +786 -0
  203. package/src/prover/smt/solver/dependent-expr-state.ts +93 -0
  204. package/src/prover/smt/solver/der.ts +38 -10
  205. package/src/prover/smt/solver/diff-neq.ts +207 -0
  206. package/src/prover/smt/solver/distribute-forall.ts +57 -0
  207. package/src/prover/smt/solver/dom-simplify.ts +511 -0
  208. package/src/prover/smt/solver/dt2bv-tactic.ts +298 -0
  209. package/src/prover/smt/solver/dyn-ack.ts +0 -1
  210. package/src/prover/smt/solver/e-matching.ts +7 -8
  211. package/src/prover/smt/solver/elim-bounds.ts +89 -0
  212. package/src/prover/smt/solver/elim-small-bv-tactic.ts +129 -0
  213. package/src/prover/smt/solver/elim-term-ite-tactic.ts +48 -0
  214. package/src/prover/smt/solver/elim-uncnstr.ts +548 -0
  215. package/src/prover/smt/solver/enode.ts +100 -3
  216. package/src/prover/smt/solver/eq2bv-tactic.ts +227 -0
  217. package/src/prover/smt/solver/euf/arith-axioms.ts +403 -0
  218. package/src/prover/smt/solver/euf/arith-internalize.ts +653 -0
  219. package/src/prover/smt/solver/euf/arith-solver.ts +889 -0
  220. package/src/prover/smt/solver/euf/array-axioms.ts +527 -0
  221. package/src/prover/smt/solver/euf/array-internalize.ts +428 -0
  222. package/src/prover/smt/solver/euf/array-solver.ts +306 -0
  223. package/src/prover/smt/solver/euf/bv-ackerman.ts +162 -0
  224. package/src/prover/smt/solver/euf/bv-internalize.ts +748 -0
  225. package/src/prover/smt/solver/euf/bv-solver.ts +449 -0
  226. package/src/prover/smt/solver/euf/dt-solver.ts +618 -0
  227. package/src/prover/smt/solver/euf/egraph.ts +901 -0
  228. package/src/prover/smt/solver/euf/euf-solver.ts +1204 -0
  229. package/src/prover/smt/solver/euf/fpa-solver.ts +317 -0
  230. package/src/prover/smt/solver/euf/mam.ts +1046 -0
  231. package/src/prover/smt/solver/euf/q-ematch.ts +829 -0
  232. package/src/prover/smt/solver/euf/q-mbi.ts +587 -0
  233. package/src/prover/smt/solver/euf/q-model-fixer.ts +296 -0
  234. package/src/prover/smt/solver/euf/q-solver.ts +361 -0
  235. package/src/prover/smt/solver/euf/th-solver.ts +328 -0
  236. package/src/prover/smt/solver/euf/th-solvers.ts +30 -0
  237. package/src/prover/smt/solver/expr-ref.ts +0 -1
  238. package/src/prover/smt/solver/expr-safe-replace.ts +26 -2
  239. package/src/prover/smt/solver/expr2polynomial.ts +271 -0
  240. package/src/prover/smt/solver/factor.ts +163 -0
  241. package/src/prover/smt/solver/fd-solver.ts +734 -0
  242. package/src/prover/smt/solver/fingerprints.ts +15 -15
  243. package/src/prover/smt/solver/fix-dl-var.ts +147 -0
  244. package/src/prover/smt/solver/flat-literals.ts +0 -1
  245. package/src/prover/smt/solver/fm-tactic.ts +886 -0
  246. package/src/prover/smt/solver/fpa-decl-plugin.ts +618 -0
  247. package/src/prover/smt/solver/fpa-rewriter.ts +639 -0
  248. package/src/prover/smt/solver/fpa2bv-converter.ts +2251 -0
  249. package/src/prover/smt/solver/fpa2bv-rewriter.ts +349 -0
  250. package/src/prover/smt/solver/fpa2bv-tactic.ts +73 -0
  251. package/src/prover/smt/solver/goal.ts +178 -15
  252. package/src/prover/smt/solver/goal2nlsat.ts +216 -0
  253. package/src/prover/smt/solver/guard-set.ts +219 -0
  254. package/src/prover/smt/solver/hash.ts +0 -1
  255. package/src/prover/smt/solver/hashtable.ts +34 -16
  256. package/src/prover/smt/solver/inf-eps.ts +63 -0
  257. package/src/prover/smt/solver/inj-axiom.ts +101 -0
  258. package/src/prover/smt/solver/internalizer.ts +111 -39
  259. package/src/prover/smt/solver/lackr.ts +381 -0
  260. package/src/prover/smt/solver/lbool.ts +0 -1
  261. package/src/prover/smt/solver/lia2card.ts +268 -0
  262. package/src/prover/smt/solver/lia2pb.ts +154 -0
  263. package/src/prover/smt/solver/literal.ts +0 -1
  264. package/src/prover/smt/solver/logic-tactics.ts +355 -0
  265. package/src/prover/smt/solver/lp/bound-propagator.ts +0 -1
  266. package/src/prover/smt/solver/lp/constraints.ts +0 -1
  267. package/src/prover/smt/solver/lp/containers.ts +7 -2
  268. package/src/prover/smt/solver/lp/core-solver.ts +30 -11
  269. package/src/prover/smt/solver/lp/cross-nested.ts +1 -4
  270. package/src/prover/smt/solver/lp/dep-intervals.ts +0 -3
  271. package/src/prover/smt/solver/lp/dependency.ts +0 -2
  272. package/src/prover/smt/solver/lp/dioph-eq.ts +1 -10
  273. package/src/prover/smt/solver/lp/explanation.ts +0 -1
  274. package/src/prover/smt/solver/lp/gomory.ts +0 -1
  275. package/src/prover/smt/solver/lp/hnf-cutter.ts +1 -2
  276. package/src/prover/smt/solver/lp/hnf.ts +0 -3
  277. package/src/prover/smt/solver/lp/int-cube.ts +3 -4
  278. package/src/prover/smt/solver/lp/int-solver.ts +0 -2
  279. package/src/prover/smt/solver/lp/lar-solver.ts +41 -5
  280. package/src/prover/smt/solver/lp/lar-term.ts +0 -1
  281. package/src/prover/smt/solver/lp/lp-settings.ts +6 -3
  282. package/src/prover/smt/solver/lp/maximize-term.ts +59 -10
  283. package/src/prover/smt/solver/lp/nex-creator.ts +3 -3
  284. package/src/prover/smt/solver/lp/nex.ts +2 -2
  285. package/src/prover/smt/solver/lp/nla-backoff.ts +0 -2
  286. package/src/prover/smt/solver/lp/nla-basics.ts +46 -3
  287. package/src/prover/smt/solver/lp/nla-core.ts +68 -17
  288. package/src/prover/smt/solver/lp/nla-divisions.ts +0 -2
  289. package/src/prover/smt/solver/lp/nla-emonics.ts +0 -1
  290. package/src/prover/smt/solver/lp/nla-factorization.ts +0 -1
  291. package/src/prover/smt/solver/lp/nla-grobner.ts +167 -85
  292. package/src/prover/smt/solver/lp/nla-horner.ts +0 -2
  293. package/src/prover/smt/solver/lp/nla-intervals.ts +0 -1
  294. package/src/prover/smt/solver/lp/nla-monomial-bounds.ts +0 -2
  295. package/src/prover/smt/solver/lp/nla-monotone.ts +0 -1
  296. package/src/prover/smt/solver/lp/nla-order.ts +0 -2
  297. package/src/prover/smt/solver/lp/nla-patcher.ts +0 -1
  298. package/src/prover/smt/solver/lp/nla-powers.ts +220 -0
  299. package/src/prover/smt/solver/lp/nla-tangents.ts +0 -2
  300. package/src/prover/smt/solver/lp/nla-throttle.ts +0 -1
  301. package/src/prover/smt/solver/lp/nla-transcendentals.ts +324 -0
  302. package/src/prover/smt/solver/lp/nla-types.ts +0 -2
  303. package/src/prover/smt/solver/lp/nla-var-eqs.ts +0 -1
  304. package/src/prover/smt/solver/lp/nra-solver.ts +163 -99
  305. package/src/prover/smt/solver/lp/numeric-pair.ts +0 -1
  306. package/src/prover/smt/solver/lp/pdd-interval.ts +6 -3
  307. package/src/prover/smt/solver/lp/pdd-simplifier.ts +60 -21
  308. package/src/prover/smt/solver/lp/pdd-solver.ts +72 -41
  309. package/src/prover/smt/solver/lp/pdd.ts +725 -290
  310. package/src/prover/smt/solver/lp/random-updater.ts +0 -2
  311. package/src/prover/smt/solver/lp/static-matrix.ts +0 -1
  312. package/src/prover/smt/solver/lp/union-find.ts +7 -2
  313. package/src/prover/smt/solver/macro-finder.ts +530 -0
  314. package/src/prover/smt/solver/mam-compiler.ts +122 -90
  315. package/src/prover/smt/solver/mam-interpreter.ts +0 -1
  316. package/src/prover/smt/solver/max-bv-sharing-tactic.ts +17 -0
  317. package/src/prover/smt/solver/max-cliques.ts +105 -0
  318. package/src/prover/smt/solver/maxcore.ts +310 -0
  319. package/src/prover/smt/solver/maximize-ac-sharing.ts +8 -6
  320. package/src/prover/smt/solver/maxlex.ts +115 -0
  321. package/src/prover/smt/solver/maxsmt-base.ts +106 -0
  322. package/src/prover/smt/solver/maxsmt.ts +92 -0
  323. package/src/prover/smt/solver/mbp/mbp-arith.ts +467 -0
  324. package/src/prover/smt/solver/mbp/mbp-basic-tg.ts +101 -0
  325. package/src/prover/smt/solver/mbp/mbp-plugin.ts +287 -0
  326. package/src/prover/smt/solver/mbp/mbp-qel.ts +48 -0
  327. package/src/prover/smt/solver/mbp/mbp-solve-plugin.ts +271 -0
  328. package/src/prover/smt/solver/mbp/mbp-term-graph.ts +606 -0
  329. package/src/prover/smt/solver/model-based-opt.ts +844 -0
  330. package/src/prover/smt/solver/model-checker.ts +19 -28
  331. package/src/prover/smt/solver/model-evaluator.ts +190 -12
  332. package/src/prover/smt/solver/model-finder.ts +12 -18
  333. package/src/prover/smt/solver/model-generator.ts +104 -35
  334. package/src/prover/smt/solver/model-macro-solver.ts +49 -46
  335. package/src/prover/smt/solver/model-printer.ts +214 -0
  336. package/src/prover/smt/solver/mpf.ts +709 -0
  337. package/src/prover/smt/solver/mus.ts +50 -0
  338. package/src/prover/smt/solver/muz/dl-context.ts +382 -0
  339. package/src/prover/smt/solver/muz/dl-mk-bit-blast.ts +97 -0
  340. package/src/prover/smt/solver/muz/dl-mk-coi-filter.ts +167 -0
  341. package/src/prover/smt/solver/muz/dl-mk-elim-term-ite.ts +125 -0
  342. package/src/prover/smt/solver/muz/dl-mk-interp-tail-simplifier.ts +299 -0
  343. package/src/prover/smt/solver/muz/dl-mk-rule-inliner.ts +455 -0
  344. package/src/prover/smt/solver/muz/dl-mk-slice.ts +340 -0
  345. package/src/prover/smt/solver/muz/dl-mk-subsumption-checker.ts +163 -0
  346. package/src/prover/smt/solver/muz/dl-rule-set.ts +273 -0
  347. package/src/prover/smt/solver/muz/dl-rule-transformer.ts +123 -0
  348. package/src/prover/smt/solver/muz/dl-rule.ts +495 -0
  349. package/src/prover/smt/solver/muz/hnf.ts +201 -0
  350. package/src/prover/smt/solver/muz/horn-subsume-model-converter.ts +176 -0
  351. package/src/prover/smt/solver/muz/horn-tactic.ts +214 -0
  352. package/src/prover/smt/solver/muz/rule-properties.ts +359 -0
  353. package/src/prover/smt/solver/muz/spacer-context.ts +1404 -0
  354. package/src/prover/smt/solver/muz/spacer-dl-interface.ts +52 -0
  355. package/src/prover/smt/solver/muz/spacer-generalizers.ts +241 -0
  356. package/src/prover/smt/solver/muz/spacer-manager.ts +127 -0
  357. package/src/prover/smt/solver/muz/spacer-pdr.ts +219 -0
  358. package/src/prover/smt/solver/muz/spacer-prop-solver.ts +333 -0
  359. package/src/prover/smt/solver/muz/spacer-util.ts +282 -0
  360. package/src/prover/smt/solver/muz/substitution.ts +203 -0
  361. package/src/prover/smt/solver/nla2bv-tactic.ts +285 -0
  362. package/src/prover/smt/solver/nlqsat.ts +485 -0
  363. package/src/prover/smt/solver/nlsat/algebraic.ts +315 -98
  364. package/src/prover/smt/solver/nlsat/atoms.ts +71 -38
  365. package/src/prover/smt/solver/nlsat/evaluator.ts +0 -1
  366. package/src/prover/smt/solver/nlsat/explain.ts +427 -229
  367. package/src/prover/smt/solver/nlsat/interval-set.ts +1 -2
  368. package/src/prover/smt/solver/nlsat/levelwise.ts +460 -246
  369. package/src/prover/smt/solver/nlsat/mpbq.ts +45 -1
  370. package/src/prover/smt/solver/nlsat/polynomial.ts +2376 -684
  371. package/src/prover/smt/solver/nlsat/solver.ts +293 -92
  372. package/src/prover/smt/solver/nlsat/transcendental-eval.ts +310 -0
  373. package/src/prover/smt/solver/nlsat/transcendentals.ts +391 -0
  374. package/src/prover/smt/solver/nlsat/types.ts +0 -2
  375. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +9 -8
  376. package/src/prover/smt/solver/nlsat/upolynomial.ts +41 -20
  377. package/src/prover/smt/solver/nlsat-tactic.ts +82 -0
  378. package/src/prover/smt/solver/nnf.ts +110 -24
  379. package/src/prover/smt/solver/normalize-bounds.ts +53 -0
  380. package/src/prover/smt/solver/occf.ts +97 -0
  381. package/src/prover/smt/solver/opt-context.ts +801 -0
  382. package/src/prover/smt/solver/opt-nlsat.ts +386 -0
  383. package/src/prover/smt/solver/opt-pareto.ts +301 -0
  384. package/src/prover/smt/solver/opt-preprocess.ts +101 -0
  385. package/src/prover/smt/solver/opt-solver.ts +312 -0
  386. package/src/prover/smt/solver/opt-value.ts +55 -0
  387. package/src/prover/smt/solver/optsmt.ts +692 -0
  388. package/src/prover/smt/solver/parallel-tactic.ts +299 -0
  389. package/src/prover/smt/solver/pattern-inference.ts +19 -11
  390. package/src/prover/smt/solver/pb-rewriter.ts +281 -0
  391. package/src/prover/smt/solver/pb2bv-tactic.ts +546 -0
  392. package/src/prover/smt/solver/poly-rewriter.ts +259 -57
  393. package/src/prover/smt/solver/probes.ts +577 -0
  394. package/src/prover/smt/solver/propagate-values.ts +37 -21
  395. package/src/prover/smt/solver/proto-model.ts +648 -19
  396. package/src/prover/smt/solver/pull-quant.ts +28 -12
  397. package/src/prover/smt/solver/purify-arith.ts +634 -0
  398. package/src/prover/smt/solver/push-app-ite.ts +37 -0
  399. package/src/prover/smt/solver/qe-arith-plugin.ts +1096 -0
  400. package/src/prover/smt/solver/qe-lite-der.ts +2 -3
  401. package/src/prover/smt/solver/qe-lite-fm.ts +3 -4
  402. package/src/prover/smt/solver/qe-lite.ts +39 -19
  403. package/src/prover/smt/solver/qe-mbp.ts +270 -0
  404. package/src/prover/smt/solver/qe.ts +1499 -0
  405. package/src/prover/smt/solver/qel.ts +25 -0
  406. package/src/prover/smt/solver/qi-queue.ts +0 -1
  407. package/src/prover/smt/solver/qsat.ts +829 -0
  408. package/src/prover/smt/solver/quant-hoist.ts +196 -0
  409. package/src/prover/smt/solver/quant-tactics.ts +16 -56
  410. package/src/prover/smt/solver/quantifier-analyzer.ts +19 -20
  411. package/src/prover/smt/solver/quantifier-manager.ts +22 -25
  412. package/src/prover/smt/solver/quasi-macros.ts +243 -0
  413. package/src/prover/smt/solver/random-gen.ts +0 -1
  414. package/src/prover/smt/solver/rational.ts +45 -1
  415. package/src/prover/smt/solver/recfun-decl-plugin.ts +262 -0
  416. package/src/prover/smt/solver/recfun-rewriter.ts +107 -0
  417. package/src/prover/smt/solver/reduce-args.ts +225 -0
  418. package/src/prover/smt/solver/reduce-bv-size.ts +119 -0
  419. package/src/prover/smt/solver/ref-vector.ts +0 -1
  420. package/src/prover/smt/solver/relevancy.ts +1 -2
  421. package/src/prover/smt/solver/rewriter-tpl.ts +82 -14
  422. package/src/prover/smt/solver/rewriter.ts +505 -60
  423. package/src/prover/smt/solver/rlimit.ts +45 -5
  424. package/src/prover/smt/solver/sat/asymm-branch.ts +325 -0
  425. package/src/prover/smt/solver/sat/big.ts +177 -0
  426. package/src/prover/smt/solver/sat/clause-use-list.ts +71 -0
  427. package/src/prover/smt/solver/sat/clause.ts +203 -0
  428. package/src/prover/smt/solver/sat/cleaner.ts +94 -0
  429. package/src/prover/smt/solver/sat/config.ts +122 -0
  430. package/src/prover/smt/solver/sat/consequences.ts +203 -0
  431. package/src/prover/smt/solver/sat/elim-eqs.ts +142 -0
  432. package/src/prover/smt/solver/sat/goal2sat.ts +589 -0
  433. package/src/prover/smt/solver/sat/inc-sat-solver.ts +480 -0
  434. package/src/prover/smt/solver/sat/model-converter.ts +136 -0
  435. package/src/prover/smt/solver/sat/pb-constraint.ts +268 -0
  436. package/src/prover/smt/solver/sat/pb-solver.ts +1596 -0
  437. package/src/prover/smt/solver/sat/probing.ts +170 -0
  438. package/src/prover/smt/solver/sat/sat-tactic.ts +72 -0
  439. package/src/prover/smt/solver/sat/sat2goal.ts +190 -0
  440. package/src/prover/smt/solver/sat/scc.ts +142 -0
  441. package/src/prover/smt/solver/sat/simplifier.ts +1618 -0
  442. package/src/prover/smt/solver/sat/solver.ts +2107 -0
  443. package/src/prover/smt/solver/sat/var-queue.ts +117 -0
  444. package/src/prover/smt/solver/sat/watch-list.ts +140 -0
  445. package/src/prover/smt/solver/search-tree.ts +284 -0
  446. package/src/prover/smt/solver/seq-axioms.ts +995 -0
  447. package/src/prover/smt/solver/seq-decl-plugin.ts +819 -0
  448. package/src/prover/smt/solver/seq-derive.ts +1298 -0
  449. package/src/prover/smt/solver/seq-eq-approx.ts +236 -0
  450. package/src/prover/smt/solver/seq-eq-solver.ts +439 -0
  451. package/src/prover/smt/solver/seq-factory.ts +89 -0
  452. package/src/prover/smt/solver/seq-monadic.ts +730 -0
  453. package/src/prover/smt/solver/seq-range-predicate.ts +235 -0
  454. package/src/prover/smt/solver/seq-re-rewriter.ts +1171 -0
  455. package/src/prover/smt/solver/seq-re-util.ts +758 -0
  456. package/src/prover/smt/solver/seq-regex-bisim.ts +144 -0
  457. package/src/prover/smt/solver/seq-regex-live.ts +200 -0
  458. package/src/prover/smt/solver/seq-rewriter.ts +2404 -0
  459. package/src/prover/smt/solver/seq-skolem.ts +294 -0
  460. package/src/prover/smt/solver/seq-subset.ts +165 -0
  461. package/src/prover/smt/solver/seq-view-witness.ts +353 -0
  462. package/src/prover/smt/solver/smt-consequences.ts +297 -0
  463. package/src/prover/smt/solver/smt-kernel.ts +124 -0
  464. package/src/prover/smt/solver/smt-logics.ts +66 -0
  465. package/src/prover/smt/solver/smt-setup.ts +589 -0
  466. package/src/prover/smt/solver/smt2-printer.ts +765 -0
  467. package/src/prover/smt/solver/smtlib-parser.ts +3535 -360
  468. package/src/prover/smt/solver/smtlib-script.ts +2136 -0
  469. package/src/prover/smt/solver/solve-eqs.ts +928 -0
  470. package/src/prover/smt/solver/solver.ts +128 -23
  471. package/src/prover/smt/solver/static-features.ts +314 -0
  472. package/src/prover/smt/solver/sticky-generations.ts +0 -1
  473. package/src/prover/smt/solver/tactic.ts +2176 -0
  474. package/src/prover/smt/solver/term-enumeration.ts +205 -0
  475. package/src/prover/smt/solver/theory-array.ts +1240 -0
  476. package/src/prover/smt/solver/theory-bv.ts +1210 -0
  477. package/src/prover/smt/solver/theory-char.ts +355 -0
  478. package/src/prover/smt/solver/theory-datatype.ts +598 -0
  479. package/src/prover/smt/solver/theory-finite-set.ts +30 -0
  480. package/src/prover/smt/solver/theory-fpa.ts +389 -0
  481. package/src/prover/smt/solver/theory-lra-axioms.ts +53 -2
  482. package/src/prover/smt/solver/theory-lra-bounds.ts +31 -6
  483. package/src/prover/smt/solver/theory-lra-final-check.ts +57 -70
  484. package/src/prover/smt/solver/theory-lra-internalize.ts +96 -27
  485. package/src/prover/smt/solver/theory-lra-model.ts +20 -35
  486. package/src/prover/smt/solver/theory-lra-propagate.ts +35 -28
  487. package/src/prover/smt/solver/theory-lra-state.ts +7 -23
  488. package/src/prover/smt/solver/theory-lra.ts +189 -2
  489. package/src/prover/smt/solver/theory-pb.ts +951 -0
  490. package/src/prover/smt/solver/theory-polymorphism.ts +58 -0
  491. package/src/prover/smt/solver/theory-recfun.ts +307 -0
  492. package/src/prover/smt/solver/theory-seq-regex.ts +867 -0
  493. package/src/prover/smt/solver/theory-seq-solve.ts +1373 -0
  494. package/src/prover/smt/solver/theory-seq-state.ts +852 -0
  495. package/src/prover/smt/solver/theory-seq.ts +961 -0
  496. package/src/prover/smt/solver/theory-without-terms.ts +24 -0
  497. package/src/prover/smt/solver/theory.ts +189 -0
  498. package/src/prover/smt/solver/tseitin-cnf.ts +495 -0
  499. package/src/prover/smt/solver/var-subst.ts +36 -14
  500. package/src/prover/smt/table.ts +3 -2
  501. package/src/prover/smt/types.ts +146 -0
  502. package/src/prover/tlapm/cache.ts +57 -26
  503. package/src/prover/tlapm/tlapm.ts +15 -9
  504. package/src/prover/tlapm-library.ts +3208 -0
  505. package/src/prover/verdict.ts +9 -0
  506. package/src/prover/zenon/check/check.ts +1 -2
  507. package/src/prover/zenon/check/records.ts +1 -1
  508. package/src/prover/zenon/check/relations.ts +2 -1
  509. package/src/prover/zenon/check/rewrites.ts +2 -15
  510. package/src/prover/zenon/check/sets.ts +40 -58
  511. package/src/prover/zenon/check/terms.ts +1 -2
  512. package/src/prover/zenon/decide.ts +10 -7
  513. package/src/prover/zenon/encode.ts +0 -2
  514. package/src/prover/zenon/eqrel.ts +2 -2
  515. package/src/prover/zenon/equality-rules.ts +24 -2
  516. package/src/prover/zenon/expr.ts +28 -2
  517. package/src/prover/zenon/index-table.ts +16 -23
  518. package/src/prover/zenon/isar-case.ts +1 -3
  519. package/src/prover/zenon/isar.ts +37 -39
  520. package/src/prover/zenon/llproof.ts +2 -13
  521. package/src/prover/zenon/mltoll.ts +12 -30
  522. package/src/prover/zenon/node.ts +20 -5
  523. package/src/prover/zenon/parse.ts +9 -8
  524. package/src/prover/zenon/phrase.ts +1 -3
  525. package/src/prover/zenon/proof.ts +0 -2
  526. package/src/prover/zenon/propositional-rules.ts +0 -2
  527. package/src/prover/zenon/rules.ts +2 -3
  528. package/src/prover/zenon/search.ts +11 -19
  529. package/src/prover/zenon/tla/functions.ts +2 -4
  530. package/src/prover/zenon/tla/llproof.ts +9 -13
  531. package/src/prover/zenon/tla/records.ts +1 -8
  532. package/src/prover/zenon/tla/rewrites.ts +0 -2
  533. package/src/prover/zenon/tla/sets.ts +22 -22
  534. package/src/prover/zenon/tla/terms.ts +0 -2
  535. package/src/prover/zenon/tla/tla.ts +7 -8
  536. package/src/resolve.ts +1327 -328
  537. package/src/runtime.ts +25 -2
  538. package/src/sany/builtins.ts +10 -10
  539. package/src/sany/generation.ts +384 -0
  540. package/src/sany/generator-def-entries.ts +297 -0
  541. package/src/sany/generator-definitions.ts +688 -0
  542. package/src/sany/generator-expressions.ts +1123 -0
  543. package/src/sany/generator-proofs.ts +668 -0
  544. package/src/sany/generator.ts +161 -2625
  545. package/src/sany/levels.ts +0 -2
  546. package/src/sany/lexer.ts +32 -23
  547. package/src/sany/linter.ts +0 -2
  548. package/src/sany/modules.ts +4 -2
  549. package/src/sany/nodes.ts +3 -4
  550. package/src/sany/report.ts +3 -6
  551. package/src/sany/selectors.ts +46 -44
  552. package/src/sany/xml.ts +25 -58
  553. package/src/search.ts +513 -165
  554. package/src/simulate.ts +340 -251
  555. package/src/spec-description.ts +48 -55
  556. package/src/standard-definitions.ts +5 -0
  557. package/src/standard-modules.ts +72 -54
  558. package/src/state-graph.ts +0 -2
  559. package/src/subexpressions.ts +564 -138
  560. package/src/substitution-levels.ts +5 -4
  561. package/src/successors.ts +56 -28
  562. package/src/symmetry.ts +4 -3
  563. package/src/tableau.ts +2 -2
  564. package/src/tlc/fingerprint.ts +81 -9
  565. package/src/tlc/jar-data.ts +10 -0
  566. package/src/tlc/messages.ts +23 -18
  567. package/src/tlc/order.ts +14 -3
  568. package/src/tlc/random.ts +6 -5
  569. package/src/tlc/replay.ts +152 -58
  570. package/src/tlc/summary.ts +29 -14
  571. package/src/tlc/tlc-operators.ts +12 -11
  572. package/src/tlc/tlcext-operators.ts +87 -26
  573. package/src/tlc/trace-spec.ts +27 -60
  574. package/src/trace-liveness.ts +529 -0
  575. package/src/typed-tier.ts +6556 -0
  576. package/src/typescript/actions.ts +2 -4
  577. package/src/typescript/collections.ts +34 -20
  578. package/src/typescript/compile.ts +1 -3
  579. package/src/typescript/formula.ts +5 -3
  580. package/src/typescript/model.ts +4 -5
  581. package/src/typescript/steps.ts +20 -18
  582. package/src/typescript/types.ts +2 -2
  583. package/src/values.ts +208 -227
  584. package/src/prover/isabelle/isar/statement.ts +0 -52
  585. package/src/prover/smt/solver/z3-license.txt +0 -10
  586. package/src/prover/tlaps-module.ts +0 -510
  587. package/src/prover/zenon/LICENSE +0 -32
package/src/resolve.ts CHANGED
@@ -18,9 +18,14 @@ import {
18
18
  type Selector,
19
19
  type SourceLocation,
20
20
  type SourceRange,
21
+ type StepBody,
21
22
  type Theorem,
23
+ type UseOrHide,
22
24
  } from "./ast";
23
25
  import { formatRange, TlaSyntaxError, type SanyError } from "./errors";
26
+ import { defEntryErrors, getDefEntryBinder, parenthesizedRanges } from "./parser";
27
+ import { formatSanyLocation } from "./sany/nodes";
28
+ import { resolveSynonym } from "./tlc/jar-data";
24
29
 
25
30
  export type SymbolKind =
26
31
  | "Builtin"
@@ -37,6 +42,7 @@ interface Binding {
37
42
  arity: number;
38
43
  params?: number[];
39
44
  range?: SourceRange;
45
+ functionArity?: number;
40
46
  }
41
47
 
42
48
  export interface ModuleSymbol extends Binding {
@@ -49,6 +55,7 @@ interface Goal {
49
55
  statement: Expression | AssumeProve;
50
56
  isSuffices: boolean;
51
57
  isInProof: boolean;
58
+ keyword: string | undefined;
52
59
  }
53
60
 
54
61
  interface LocalName extends Binding {
@@ -56,7 +63,7 @@ interface LocalName extends Binding {
56
63
  parent: LocalName | undefined;
57
64
  goal?: Goal;
58
65
  isPending?: boolean;
59
- isNonFact?: boolean;
66
+ nonFactStep?: "Use" | "Hide" | "Instance" | "Define";
60
67
  }
61
68
 
62
69
  interface ModuleBinding extends Binding {
@@ -69,6 +76,7 @@ interface Unit {
69
76
  getInstance: (instance: Instance) => InstancedModule;
70
77
  definitions: Map<string, Definition>;
71
78
  getKey: (definition: Definition) => string;
79
+ isModuleKnown: (name: string, location: SourceLocation) => boolean;
72
80
  location: SourceLocation;
73
81
  self: Definition | undefined;
74
82
  facts: Set<string>;
@@ -84,8 +92,16 @@ interface Unit {
84
92
  isGenerated: boolean;
85
93
  }
86
94
 
87
- interface SelectionError {
95
+ export interface SelectionArguments {
96
+ operator: string;
97
+ range: SourceRange | undefined;
88
98
  args: Expression[];
99
+ params: number[];
100
+ }
101
+
102
+ interface SelectionError {
103
+ applications: SelectionArguments[];
104
+ nulls: NullSelection[];
89
105
  error: SanyError;
90
106
  }
91
107
 
@@ -99,8 +115,43 @@ type Reference = Expression & { kind: "Identifier" | "Apply" | "Subexpression" }
99
115
 
100
116
  export const LOCAL_RESOLUTION = { kind: "Local" } as const;
101
117
 
102
- export const selections = new WeakSet<Expression>();
118
+ export const SELECTION_NAME = "$subexpression";
119
+
120
+ export interface NullSelection {
121
+ node: Expression;
122
+ error: SanyError;
123
+ isEmpty: boolean;
124
+ applications: SelectionArguments[];
125
+ }
126
+
127
+ interface SelectionArgument {
128
+ operator: string;
129
+ index: number;
130
+ range: SourceRange | undefined;
131
+ }
132
+
133
+ export const selections = new WeakMap<Expression, Expression>();
103
134
  export const selectionErrors = new WeakMap<Expression, SelectionError>();
135
+ export const operatorSelectionErrors = new WeakMap<Expression, SanyError>();
136
+ export const factReferences = new WeakMap<Fact[], Fact[]>();
137
+ export const selectionArguments = new WeakMap<Expression, SelectionArgument>();
138
+ export const nullSelections = new WeakMap<Expression, NullSelection[]>();
139
+ export const generatedArgumentCounts = new WeakMap<Expression, number>();
140
+ const unresolvedExpressions = new WeakSet<Expression>();
141
+ const emptyExpressions = new WeakSet<Expression>();
142
+
143
+ // SANY's failed selection is an operator application with no operands.
144
+ const isEmptyExpression = (expression: Expression): boolean =>
145
+ emptyExpressions.has(expression) || findNullError(nullSelections.get(expression)) !== undefined;
146
+
147
+ const findNullSelection = (nulls: NullSelection[] | undefined) =>
148
+ nulls?.find((selection) =>
149
+ selection.isEmpty
150
+ ? isEmptyExpression(selection.node)
151
+ : unresolvedExpressions.has(selection.node),
152
+ );
153
+
154
+ const findNullError = (nulls: NullSelection[] | undefined) => findNullSelection(nulls)?.error;
104
155
 
105
156
  const renamedArities = new WeakMap<Expression, number>();
106
157
 
@@ -111,13 +162,20 @@ const isKey = (name: string) => {
111
162
  return index > 0 && index < name.length - 1;
112
163
  };
113
164
 
114
- const CORE_SYMBOLS: Symbols = new Map(
115
- ["~>", "-+->", "\\cdot"].map((name) => [name, { key: name, arity: 2, kind: "Builtin" }]),
116
- );
165
+ const CORE_SYMBOLS: Symbols = new Map([
166
+ ...["~>", "-+->", "\\cdot", "\\X"].map((name): [string, ModuleSymbol] => [
167
+ name,
168
+ { key: name, arity: 2, kind: "Builtin" },
169
+ ]),
170
+ ["'", { key: "'", arity: 1, kind: "Builtin" }],
171
+ ]);
117
172
 
118
173
  export const isBefore = (left: SourceLocation, right: SourceLocation) =>
119
174
  left.line < right.line || (left.line === right.line && left.column < right.column);
120
175
 
176
+ export const compareLocations = (left: SourceLocation, right: SourceLocation) =>
177
+ isBefore(left, right) ? -1 : isBefore(right, left) ? 1 : 0;
178
+
121
179
  export const getArity = (definition: Definition) =>
122
180
  definition.kind === "Operator" ? definition.params.length : 0;
123
181
 
@@ -126,6 +184,11 @@ export const getParamArities = (definition: Definition) =>
126
184
 
127
185
  const isInstantiated = (definition: Definition) => definition.name.includes("!");
128
186
 
187
+ export const getFunctionArity = (definition: Definition) =>
188
+ definition.kind === "Function" && !isInstantiated(definition)
189
+ ? definition.bounds.length
190
+ : undefined;
191
+
129
192
  const lookupLocal = (scope: LocalName | undefined, name: string) => {
130
193
  for (let current = scope; current; current = current.parent) {
131
194
  if (current.name === name) return current;
@@ -157,7 +220,7 @@ const isBindable = (name: string, current: Binding | undefined, added: Binding,
157
220
  if (current.kind === "Builtin") {
158
221
  unit.errors.push({
159
222
  location,
160
- message: `Symbol ${name} is a built-in operator, and cannot be redefined.`,
223
+ message: `Symbol ${resolveSynonym(name)} is a built-in operator, and cannot be redefined.`,
161
224
  });
162
225
  } else if (
163
226
  added.kind === "Parameter" ||
@@ -166,12 +229,12 @@ const isBindable = (name: string, current: Binding | undefined, added: Binding,
166
229
  ) {
167
230
  unit.errors.push({
168
231
  location,
169
- message: `Multiply-defined symbol '${name}': this definition or declaration conflicts \nwith the one at ${existing}.`,
232
+ message: `Multiply-defined symbol '${resolveSynonym(name)}': this definition or declaration conflicts \nwith the one at ${existing}.`,
170
233
  });
171
234
  } else {
172
235
  unit.warnings.push({
173
236
  location,
174
- message: `Multiple declarations or definitions for symbol ${name}. \nThis duplicates the one at ${existing}.`,
237
+ message: `Multiple declarations or definitions for symbol ${resolveSynonym(name)}. \nThis duplicates the one at ${existing}.`,
175
238
  });
176
239
  }
177
240
  return false;
@@ -230,26 +293,44 @@ export const getBoundNames = (bounds: Bound[]) =>
230
293
 
231
294
  const getVisibleDefinition = (name: string, unit: Unit) => {
232
295
  const definition = unit.definitions.get(name);
296
+ const binding = getModuleBinding(name, unit, undefined);
233
297
  const isVisible =
234
298
  definition !== undefined &&
235
299
  (definition === unit.self
236
- ? definition.kind === "Function" || definition.isRecursive
237
- : definition.isRecursive || isBefore(definition.location, unit.location));
300
+ ? definition.isRecursive
301
+ : definition.isRecursive
302
+ ? binding !== undefined
303
+ : isBefore(definition.location, unit.location) &&
304
+ (binding === undefined || !isBefore(binding.position, definition.location)));
238
305
  return isVisible ? definition : undefined;
239
306
  };
240
307
 
241
308
  const findSymbol = (name: string, unit: Unit): ModuleSymbol | undefined => {
242
309
  const definition = getVisibleDefinition(name, unit);
243
- return definition
244
- ? {
245
- key: unit.getKey(definition),
246
- arity: getArity(definition),
247
- params: getParamArities(definition),
248
- kind: "Definition",
249
- }
250
- : unit.imported.get(name);
310
+ if (definition) {
311
+ const declared = definition.isRecursive ? unit.bindings.get(name) : undefined;
312
+ return {
313
+ key: unit.getKey(definition),
314
+ arity: declared?.arity ?? getArity(definition),
315
+ params: declared?.params ?? getParamArities(definition),
316
+ kind: "Definition",
317
+ range: definition.location.range,
318
+ functionArity: getFunctionArity(definition),
319
+ };
320
+ }
321
+ const binding = getModuleBinding(name, unit, undefined);
322
+ if (binding?.isPending) {
323
+ return { key: name, arity: binding.arity, params: binding.params, kind: binding.kind };
324
+ }
325
+ return binding ? unit.imported.get(name) : undefined;
251
326
  };
252
327
 
328
+ const isFact = (name: string, unit: Unit) =>
329
+ unit.facts.has(name) || unit.bindings.get(name)?.kind === "Theorem";
330
+
331
+ const getGoal = (name: string, unit: Unit) =>
332
+ unit.bindings.get(name)?.kind === "Theorem" ? unit.goals.get(name) : undefined;
333
+
253
334
  const findBinding = (name: string, scope: LocalName | undefined, unit: Unit): Binding | undefined =>
254
335
  lookupLocal(scope, name) ?? findSymbol(name, unit);
255
336
 
@@ -271,12 +352,22 @@ const getSpelledNameRange = (
271
352
  };
272
353
 
273
354
  const getFixity = (expression: Expression) => {
274
- if (expression.kind !== "Apply") return undefined;
355
+ if (expression.kind !== "Apply" || expression.argumentsRange) return undefined;
275
356
  if (expression.args.length === 2) return "infix";
276
357
  if (expression.args.length !== 1) return undefined;
277
- return isBefore(expression.location, expression.args[0].location) ? "prefix" : "postfix";
358
+ return expression.operator === "-." ? "prefix" : "postfix";
278
359
  };
279
360
 
361
+ const BUILTIN_LOCATION = "In module --TLA+ BUILTINS--";
362
+
363
+ const SELECTABLE_KINDS = new Set<SymbolKind>(["Definition", "Instance", "Theorem"]);
364
+
365
+ const reportUnselectable = (name: string, range: SourceRange, unit: Unit) =>
366
+ unit.errors.push({
367
+ location: formatRange(range),
368
+ message: `Cannot take subexpression of \`${resolveSynonym(name)}'.`,
369
+ });
370
+
280
371
  const isOperatorSymbol = (name: string) => !/^[\p{L}\d_]/u.test(name);
281
372
 
282
373
  const isStepName = (name: string) =>
@@ -388,6 +479,7 @@ export const getOperands = (expression: Expression): Expression[] | undefined =>
388
479
  case "Enabled":
389
480
  case "Always":
390
481
  case "Eventually":
482
+ case "Selection":
391
483
  return [expression.expression];
392
484
  case "BoxAction":
393
485
  case "AngleAction":
@@ -416,12 +508,19 @@ const isInScopeOfDeclaration = (assumeProve: AssumeProve, clause: number) =>
416
508
 
417
509
  const findLabel = (expression: Expression, name: string): LabelExpression | undefined => {
418
510
  if (expression.kind === "Label") return expression.name === name ? expression : undefined;
419
- if (expression.kind === "Lambda") return undefined;
511
+ if (expression.kind === "Lambda" || expression.kind === "Selection") return undefined;
420
512
  if (expression.kind === "Let") return findLabel(expression.body, name);
421
- return getChildren(expression).reduce<LabelExpression | undefined>(
422
- (found, child) => found ?? findLabel(child, name),
423
- undefined,
424
- );
513
+ const generated = generatedArgumentCounts.get(expression);
514
+ if (expression.kind === "Apply" && generated === undefined && isEmptyExpression(expression))
515
+ return undefined;
516
+ if (expression.kind === "FunctionApplication" && isEmptyExpression(expression))
517
+ return findLabel(expression.function, name);
518
+ return getChildren(expression)
519
+ .slice(0, generated)
520
+ .reduce<LabelExpression | undefined>(
521
+ (found, child) => found ?? findLabel(child, name),
522
+ undefined,
523
+ );
425
524
  };
426
525
 
427
526
  const findClauseLabel = (
@@ -453,7 +552,6 @@ const checkSelection = (
453
552
  reference: Reference,
454
553
  selectors: Selector[],
455
554
  goal: Goal,
456
- scope: LocalName | undefined,
457
555
  unit: Unit,
458
556
  isFact: boolean,
459
557
  ) => {
@@ -462,6 +560,7 @@ const checkSelection = (
462
560
  (index === undefined ? undefined : reference.selectorRanges?.[index]) ??
463
561
  reference.location.range;
464
562
  if (range) unit.errors.push({ location: formatRange(range), message });
563
+ return undefined;
465
564
  };
466
565
  const isOutOfScope = goal.isSuffices === goal.isInProof;
467
566
  const statement = goal.statement;
@@ -470,6 +569,8 @@ const checkSelection = (
470
569
  isGoal: true,
471
570
  isSufficesOpen: goal.isSuffices,
472
571
  };
572
+ let params = 0;
573
+ let args = 0;
473
574
  for (const [offset, selector] of selectors.slice(1).entries()) {
474
575
  const index = offset + 1;
475
576
  const node = state.node;
@@ -479,9 +580,7 @@ const checkSelection = (
479
580
  node.kind !== "NewSymbol" &&
480
581
  node.kind !== "AssumeProve" &&
481
582
  getLabelBody(node).kind === "Let";
482
- return isLet
483
- ? undefined
484
- : report(index - 1, "A name selector here must be from a LET clause.");
583
+ return isLet ? node : report(index - 1, "A name selector here must be from a LET clause.");
485
584
  }
486
585
  const clauses =
487
586
  statement.kind === "AssumeProve"
@@ -519,10 +618,30 @@ const checkSelection = (
519
618
  state.isSufficesOpen = false;
520
619
  continue;
521
620
  }
522
- if (selector.kind !== "Operand") return;
523
- const operand = getOperandName(selector.operand);
621
+ if (selector.kind === "Colon") {
622
+ if (selectors[index - 1].kind !== "Name") {
623
+ return report(index - 1, "!: should not follow an operand selector.");
624
+ }
625
+ const next = selectors[index + 1];
626
+ if (next === undefined ? index !== 1 : next.kind !== "Name") {
627
+ return report(
628
+ index,
629
+ "`!:' can be used only after a name and either at the end after an\noperator name or before an operator name.",
630
+ );
631
+ }
632
+ continue;
633
+ }
634
+ const operand =
635
+ selector.kind === "Operand"
636
+ ? getOperandName(selector.operand)
637
+ : selector.kind === "At"
638
+ ? "@"
639
+ : "!(...)";
640
+ const getPosition = (count: number) =>
641
+ selector.kind === "Operand" ? getOperandIndex(selector.operand, count) : -1;
642
+ const unexpectedNull = `An unexpected null node specified by '${operand}'.\nThis is probably due to a previous error.`;
524
643
  if (state.isSufficesOpen) {
525
- if (getOperandIndex(selector.operand, 1) !== 0) {
644
+ if (getPosition(1) !== 0) {
526
645
  return report(
527
646
  index,
528
647
  node.kind === "AssumeProve"
@@ -533,20 +652,37 @@ const checkSelection = (
533
652
  state.isSufficesOpen = false;
534
653
  continue;
535
654
  }
536
- if (node.kind === "NewSymbol") return;
655
+ if (node.kind === "NewSymbol") return node;
537
656
  if (node.kind !== "AssumeProve") {
538
657
  const expression = getLabelBody(node);
658
+ if (unresolvedExpressions.has(expression)) {
659
+ return report(
660
+ index,
661
+ "Subexpression selection failed, probably due to an error in the selected expression.",
662
+ );
663
+ }
539
664
  if (["Number", "Decimal", "String"].includes(expression.kind)) {
540
665
  return report(index, "Selecting subexpression of expression that has none.");
541
666
  }
542
- const kind =
543
- expression.kind === "Identifier"
544
- ? findBinding(expression.name, scope, unit)?.kind
545
- : undefined;
546
- if (kind === "Variable" || kind?.startsWith("New")) {
667
+ if (isEmptyExpression(expression)) {
547
668
  return report(index, `Choosing operand \`${operand}' of subexpression with no operands.`);
548
669
  }
549
- const sets = getBinder(expression)?.sets;
670
+ const binder = getBinder(expression);
671
+ if (binder && selector.kind !== "Operand") {
672
+ const count = selector.kind === "Bound" ? selector.args.length : 0;
673
+ if (selector.kind === "Bound" && count !== binder.names.length) {
674
+ return report(
675
+ index,
676
+ `Selector with ${count} argument(s) used for quantifier with ${binder.names.length} bound identifier(s).`,
677
+ );
678
+ }
679
+ params += binder.names.length;
680
+ args += count;
681
+ state.node = binder.body;
682
+ state.isGoal = false;
683
+ continue;
684
+ }
685
+ const sets = binder?.sets;
550
686
  const operands =
551
687
  expression.kind === "Identifier"
552
688
  ? []
@@ -554,18 +690,21 @@ const checkSelection = (
554
690
  ? sets.length > 0
555
691
  ? sets
556
692
  : undefined
557
- : expression.kind === "Except"
558
- ? undefined
559
- : getOperands(expression);
560
- if (!operands) return;
561
- const position = getOperandIndex(selector.operand, operands.length);
693
+ : getOperands(expression);
694
+ if (!operands) return node;
695
+ const isExcept = expression.kind === "Except";
696
+ const position = getPosition(isExcept ? expression.updates.length + 1 : operands.length);
562
697
  if (position === -1) return report(index, `Nonexistent operand specified by \`${operand}'.`);
698
+ if (isExcept && position > 0) {
699
+ return report(index, "Selecting subexpression of an EXCEPT not yet implemented.");
700
+ }
563
701
  state.node = operands[position];
564
702
  state.isGoal = false;
703
+ if (unresolvedExpressions.has(state.node)) return report(index, unexpectedNull);
565
704
  continue;
566
705
  }
567
706
  const clauses = [...node.assumptions, node.conclusion];
568
- const position = getOperandIndex(selector.operand, clauses.length);
707
+ const position = getPosition(clauses.length);
569
708
  if (position === -1) return report(index, `Nonexistent operand specified by \`${operand}'.`);
570
709
  if (isInScopeOfDeclaration(node, position) && (!state.isGoal || isOutOfScope)) {
571
710
  return report(index, `Accessing ASSUME/PROVE clause ${SCOPE_MESSAGE}`);
@@ -576,14 +715,24 @@ const checkSelection = (
576
715
  }
577
716
  state.node = clause;
578
717
  state.isGoal = false;
718
+ if (
719
+ clause.kind !== "NewSymbol" &&
720
+ clause.kind !== "AssumeProve" &&
721
+ unresolvedExpressions.has(clause)
722
+ ) {
723
+ return report(index, unexpectedNull);
724
+ }
579
725
  }
580
- if (isFact) return;
581
726
  if (state.node.kind === "AssumeProve") {
582
- report(undefined, "Selected ASSUME/PROVE instead of expression.");
727
+ return isFact ? state.node : report(undefined, "Selected ASSUME/PROVE instead of expression.");
583
728
  }
584
729
  if (state.node.kind === "NewSymbol") {
585
- report(undefined, "Selected a NEW declaration as an expression or operator.");
730
+ return isFact
731
+ ? state.node
732
+ : report(undefined, "Selected a NEW declaration as an expression or operator.");
586
733
  }
734
+ if (params !== args) return report(undefined, `Expected ${params} arguments but found ${args}.`);
735
+ return state.node;
587
736
  };
588
737
 
589
738
  const isLabelReported = (label: LabelExpression, unit: Unit) => {
@@ -659,10 +808,18 @@ const checkReference = (
659
808
  const first = selectors[0];
660
809
  const goal =
661
810
  selectors.length > 1 && first.kind === "Name"
662
- ? (lookupLocal(scope, first.name)?.goal ?? unit.goals.get(first.name))
811
+ ? (lookupLocal(scope, first.name)?.goal ?? getGoal(first.name, unit))
663
812
  : undefined;
664
- if (goal) checkSelection(expression, selectors, goal, scope, unit, isFact);
665
- return goal !== undefined;
813
+ return goal && { node: checkSelection(expression, selectors, goal, unit, isFact) };
814
+ };
815
+
816
+ const isInstanceName = (name: string, scope: LocalName | undefined, unit: Unit) => {
817
+ const binding = lookupLocal(scope, name) ?? getModuleBinding(name, unit, undefined);
818
+ if (binding) return binding.kind === "Instance";
819
+ return (
820
+ findInstance(name, scope, unit) !== undefined &&
821
+ [...unit.bindings.keys()].some((key) => key.startsWith(`${name}!`))
822
+ );
666
823
  };
667
824
 
668
825
  const getSymbolArity = (
@@ -677,18 +834,53 @@ const getSymbolArity = (
677
834
  if (renamed !== undefined) return renamed;
678
835
  if (isKey(name)) return expression.kind === "Apply" ? expression.args.length : 0;
679
836
  const local = lookupLocal(scope, name);
680
- if (local?.isNonFact) {
837
+ if (local?.nonFactStep) {
681
838
  unit.errors.push({
682
839
  location: formatRange(getSpelledNameRange(expression, name)),
683
840
  message: "Step number of non-expression step used as an expression.",
684
841
  });
685
842
  return undefined;
686
843
  }
844
+ const keyword = local?.goal?.keyword;
845
+ if (keyword) {
846
+ unit.errors.push({
847
+ location: formatRange(getSpelledNameRange(expression, name)),
848
+ message: `${keyword} proof step selected instead of expression.`,
849
+ });
850
+ return undefined;
851
+ }
687
852
  if (checkReference(expression, scope, unit, false) || (isStepName(name) && local)) {
688
853
  return expression.kind === "Apply" ? expression.args.length : 0;
689
854
  }
855
+ if (isInstanceName(name, scope, unit)) {
856
+ const instance = lookupLocal(scope, name) ?? getModuleBinding(name, unit, undefined);
857
+ const count = expression.kind === "Apply" ? expression.args.length : 0;
858
+ if (instance?.kind === "Instance" && instance.arity !== count) {
859
+ unit.errors.push({
860
+ location: formatRange(
861
+ (expression.kind === "Apply" && expression.argumentsRange) ||
862
+ getSpelledNameRange(expression, name),
863
+ ),
864
+ message: `The operator ${name} requires ${instance.arity} arguments.`,
865
+ });
866
+ return undefined;
867
+ }
868
+ const range = getSpelledNameRange(expression, name);
869
+ unit.errors.push({
870
+ location: formatRange({
871
+ ...range,
872
+ start: {
873
+ line: range.end.line,
874
+ column: range.end.column - name.slice(name.lastIndexOf("!") + 1).length + 1,
875
+ },
876
+ }),
877
+ message: `Operator name ${name} is incomplete.`,
878
+ });
879
+ return undefined;
880
+ }
690
881
  if (local && expression.kind !== "OperatorReference") expression.resolution = LOCAL_RESOLUTION;
691
882
  if (local) return local.arity;
883
+ if (getGoal(name, unit)?.statement.kind === "AssumeProve") return 0;
692
884
  const symbol = findSymbol(name, unit);
693
885
  if (symbol) {
694
886
  if (expression.kind === "Identifier") expression.name = symbol.key;
@@ -697,29 +889,58 @@ const getSymbolArity = (
697
889
  return symbol.arity;
698
890
  }
699
891
  const prefix = name.includes("!") ? name.slice(0, name.indexOf("!")) : "";
700
- const isSelected =
892
+ const selected =
893
+ prefix === "" ? undefined : (lookupLocal(scope, prefix) ?? findSymbol(prefix, unit));
894
+ if (
895
+ selected &&
896
+ (!SELECTABLE_KINDS.has(selected.kind) || lookupLocal(scope, prefix)?.nonFactStep)
897
+ ) {
898
+ reportUnselectable(
899
+ prefix,
900
+ (expression.kind !== "OperatorReference" && expression.selectorRanges?.[0]) ||
901
+ getSpelledNameRange(expression, name),
902
+ unit,
903
+ );
904
+ return undefined;
905
+ }
906
+ if (
907
+ expression.kind !== "OperatorReference" &&
701
908
  prefix !== "" &&
702
- (lookupLocal(scope, prefix) !== undefined ||
703
- findSymbol(prefix, unit) !== undefined ||
704
- unit.facts.has(prefix));
705
- if (isSelected) {
909
+ isPendingSelectionReported(
910
+ prefix,
911
+ expression.kind === "Apply" && expression.argumentCounts
912
+ ? expression.args.slice(0, expression.argumentCounts[0])
913
+ : [],
914
+ expression.selectorRanges?.[0],
915
+ (expression.kind === "Apply" ? expression.argumentRanges?.[0] : undefined) ?? location.range,
916
+ scope,
917
+ unit,
918
+ )
919
+ ) {
920
+ return undefined;
921
+ }
922
+ if (selected || (prefix !== "" && isFact(prefix, unit))) {
706
923
  return expression.kind === "Apply" ? expression.args.length : 0;
707
924
  }
708
- const spelling = (expression.kind === "Identifier" ? undefined : expression.spelling) ?? name;
709
- const range = formatRange(
710
- expression.kind === "Apply" && spelling === "-."
711
- ? getNameRange(location, "-")
712
- : getSpelledNameRange(expression, name),
713
- );
714
- if (!isOperatorSymbol(name) || isStepName(name)) {
715
- unit.errors.push({ location: range, message: `Unknown operator: \`${name}'.` });
925
+ const fixity = getFixity(expression);
926
+ const isOperatorApplication = expression.kind === "OperatorReference" || fixity !== undefined;
927
+ if (!isOperatorSymbol(name) || isStepName(name) || !isOperatorApplication) {
928
+ unit.errors.push({
929
+ location: formatRange(getSpelledNameRange(expression, name)),
930
+ message: `Unknown operator: \`${resolveSynonym(name)}'.`,
931
+ });
716
932
  return undefined;
717
933
  }
934
+ const spelling = expression.spelling ?? name;
718
935
  unit.errors.push({
719
- location: range,
936
+ location: formatRange(
937
+ fixity === "prefix" && spelling === "-."
938
+ ? getNameRange(location, "-")
939
+ : getSpelledNameRange(expression, name),
940
+ ),
720
941
  message: `Could not find declaration or definition of symbol '${spelling}'.`,
721
942
  });
722
- const fixity = getFixity(expression);
943
+ if (fixity) unresolvedExpressions.add(expression);
723
944
  if (fixity && location.range) {
724
945
  unit.errors.push({
725
946
  location: formatRange(location.range),
@@ -774,15 +995,30 @@ const resolveDefinition = (
774
995
  const isDeclared = current?.isPending === true && recursive.has(current);
775
996
  if (current?.isPending && !isDeclared) {
776
997
  report(
777
- `Recursive ${definition.kind === "Function" ? "function" : "operator"} ${name} defined at wrong LET/IN level.`,
998
+ `Recursive ${definition.kind === "Function" ? "function" : "operator"} ${resolveSynonym(name)} defined at wrong LET/IN level.`,
778
999
  );
779
1000
  } else if (current && !isDeclared) {
780
1001
  report(
781
1002
  definition.kind === "Function"
782
1003
  ? `Function name \`${name}' already defined or declared.`
783
- : `Operator ${name} already defined or declared.`,
1004
+ : `Operator ${resolveSynonym(name)} already defined or declared.`,
1005
+ );
1006
+ } else if (current && definition.kind === "Function" && current.arity > 0) {
1007
+ report(`Function ${resolveSynonym(name)} has operator arguments in its RECURSIVE declaration.`);
1008
+ } else if (
1009
+ current &&
1010
+ definition.kind === "Operator" &&
1011
+ // Deviation from SANY: Generator#processOperator compares only the last parameter's arity with the RECURSIVE declaration's.
1012
+ (current.arity !== definition.params.length ||
1013
+ definition.params.some((param) => param.arity > 0))
1014
+ ) {
1015
+ report(
1016
+ `Definition of ${resolveSynonym(name)} has different arity than its RECURSIVE declaration.`,
784
1017
  );
785
1018
  }
1019
+ if (current && isDeclared && definition.kind === "Operator") {
1020
+ current.params = getParamArities(definition);
1021
+ }
786
1022
  if (definition.kind === "Function") {
787
1023
  resolveExpression(
788
1024
  definition.body,
@@ -793,8 +1029,10 @@ const resolveDefinition = (
793
1029
  definition.isSelfReferential = isReferenced(definition.body, name);
794
1030
  } else resolveExpression(definition.body, inner, unit);
795
1031
  if (current && isDeclared) {
796
- current.isPending = false;
797
- current.range = range;
1032
+ if (definition.kind === "Operator" || current.arity === 0) {
1033
+ current.isPending = false;
1034
+ current.range = range;
1035
+ }
798
1036
  return false;
799
1037
  }
800
1038
  return definition.kind === "Function"
@@ -812,10 +1050,15 @@ const resolveDefinitions = (
812
1050
  scope: LocalName | undefined,
813
1051
  unit: Unit,
814
1052
  instances: Instance[] = [],
1053
+ declarations: Declaration[] = [],
815
1054
  ) => {
816
1055
  const recursive = new Set<Binding>();
817
1056
  const declared = definitions
818
- .filter((definition) => definition.isRecursive)
1057
+ .filter(
1058
+ (definition) =>
1059
+ definition.isRecursive &&
1060
+ declarations.every((declaration) => declaration.name !== definition.name),
1061
+ )
819
1062
  .reduce<LocalName | undefined>((parent, definition) => {
820
1063
  if (lookupLocal(parent, definition.name)?.isPending) return parent;
821
1064
  const local: LocalName = {
@@ -829,28 +1072,62 @@ const resolveDefinitions = (
829
1072
  recursive.add(local);
830
1073
  return local;
831
1074
  }, scope);
832
- const pending = unit.isGenerated ? [] : [...instances];
833
- const resolveInstances = (
1075
+ const declaredLocals = new Map<Declaration, LocalName | undefined>();
1076
+ const bindDeclaration = (parent: LocalName | undefined, declaration: Declaration) => {
1077
+ const binding: Binding = {
1078
+ kind: "Definition",
1079
+ arity: declaration.arity,
1080
+ params: Array(declaration.arity).fill(0),
1081
+ range: declaration.location.range,
1082
+ };
1083
+ const local: LocalName | undefined = isBindable(
1084
+ declaration.name,
1085
+ lookupLocal(parent, declaration.name) ??
1086
+ getModuleBinding(declaration.name, unit, binding.range),
1087
+ binding,
1088
+ unit,
1089
+ )
1090
+ ? { ...binding, name: declaration.name, parent, isPending: true }
1091
+ : undefined;
1092
+ if (local) recursive.add(local);
1093
+ declaredLocals.set(declaration, local);
1094
+ return local ?? parent;
1095
+ };
1096
+ const pending = [...(unit.isGenerated ? [] : instances), ...declarations].toSorted(
1097
+ (left, right) => compareLocations(left.location, right.location),
1098
+ );
1099
+ const resolvePending = (
834
1100
  current: LocalName | undefined,
835
- isDue: (instance: Instance) => boolean,
1101
+ isDue: (item: Instance | Declaration) => boolean,
836
1102
  ) => {
837
- const count = pending.findIndex((instance) => !isDue(instance));
1103
+ const count = pending.findIndex((item) => !isDue(item));
838
1104
  return pending
839
1105
  .splice(0, count === -1 ? pending.length : count)
840
- .reduce((parent, instance) => resolveLocalInstance(instance, parent, unit), current);
1106
+ .reduce(
1107
+ (parent, item) =>
1108
+ "kind" in item ? resolveLocalInstance(item, parent, unit) : bindDeclaration(parent, item),
1109
+ current,
1110
+ );
841
1111
  };
842
1112
  const resolved = definitions.reduce<LocalName | undefined>((previous, definition) => {
843
1113
  const current = isKey(definition.name)
844
1114
  ? previous
845
- : resolveInstances(previous, (instance) => !isBefore(definition.location, instance.location));
1115
+ : resolvePending(previous, (item) => !isBefore(definition.location, item.location));
846
1116
  const local: LocalName = {
847
1117
  name: definition.name,
848
1118
  arity: getArity(definition),
849
1119
  kind: "Definition",
850
1120
  range: definition.location.range,
851
1121
  parent: current,
1122
+ functionArity: getFunctionArity(definition),
852
1123
  };
853
- if (isInstantiated(definition)) return local;
1124
+ if (isInstantiated(definition)) {
1125
+ return {
1126
+ ...local,
1127
+ params: getParamArities(definition),
1128
+ functionArity: lookupLocal(current, definition.name)?.functionArity,
1129
+ };
1130
+ }
854
1131
  const isInstanced = instances.some((instance) => instance.location === definition.location);
855
1132
  const isGenerated = unit.isGenerated || definition.isLocal || isKey(definition.name);
856
1133
  const inner = isInstanced
@@ -862,7 +1139,17 @@ const resolveDefinitions = (
862
1139
  ? { ...local, params: getParamArities(definition) }
863
1140
  : current;
864
1141
  }, declared);
865
- return resolveInstances(resolved, () => true);
1142
+ const resolvedScope = resolvePending(resolved, () => true);
1143
+ declaredLocals.forEach((local, declaration) => {
1144
+ const range = declaration.location.range;
1145
+ if (range && !unit.isGenerated && (!local || local.isPending)) {
1146
+ unit.errors.push({
1147
+ location: formatRange(range),
1148
+ message: `Symbol ${resolveSynonym(declaration.name)} declared in RECURSIVE statement but not defined.`,
1149
+ });
1150
+ }
1151
+ });
1152
+ return resolvedScope;
866
1153
  };
867
1154
 
868
1155
  const findInstance = (name: string, scope: LocalName | undefined, unit: Unit) => {
@@ -871,7 +1158,9 @@ const findInstance = (name: string, scope: LocalName | undefined, unit: Unit) =>
871
1158
  prefix === name
872
1159
  ? undefined
873
1160
  : (lookupLocal(scope, prefix) ?? getModuleBinding(prefix, unit, undefined));
874
- return binding?.kind === "Instance" ? { name: prefix, arity: binding.arity } : undefined;
1161
+ return binding?.kind === "Instance"
1162
+ ? { name: prefix, arity: binding.arity, range: binding.range }
1163
+ : undefined;
875
1164
  };
876
1165
 
877
1166
  const isInstanceArityReported = (
@@ -879,16 +1168,22 @@ const isInstanceArityReported = (
879
1168
  scope: LocalName | undefined,
880
1169
  unit: Unit,
881
1170
  ) => {
882
- if (expression.kind !== "Identifier" && expression.kind !== "Apply") return false;
1171
+ if (!isReference(expression)) return false;
1172
+ const selectors = getSelectors(expression);
1173
+ const nameCount = selectors.findIndex((selector) => selector.kind !== "Name");
883
1174
  const instance = findInstance(
884
- expression.kind === "Identifier" ? expression.name : expression.operator,
1175
+ selectors
1176
+ .slice(0, nameCount === -1 ? selectors.length : nameCount)
1177
+ .flatMap((selector) => (selector.kind === "Name" ? [selector.name] : []))
1178
+ .join("!"),
885
1179
  scope,
886
1180
  unit,
887
1181
  );
888
- const count = expression.kind === "Apply" ? (expression.argumentCounts?.[0] ?? 0) : 0;
1182
+ const first = selectors[0];
1183
+ const count = first.kind === "Name" ? first.args.length : 0;
889
1184
  if (!instance || count === instance.arity) return false;
890
1185
  const range =
891
- (expression.kind === "Apply" ? expression.argumentRanges?.[0] : undefined) ??
1186
+ (expression.kind === "Identifier" ? undefined : expression.argumentRanges?.[0]) ??
892
1187
  expression.location.range;
893
1188
  if (range) {
894
1189
  unit.errors.push({
@@ -899,104 +1194,215 @@ const isInstanceArityReported = (
899
1194
  return true;
900
1195
  };
901
1196
 
902
- // Deviation from SANY: an operator whose parameters tla-ts does not know takes any argument.
1197
+ const isArgumentCountReported = (
1198
+ callee: Binding | undefined,
1199
+ name: string,
1200
+ count: number,
1201
+ range: SourceRange | undefined,
1202
+ unit: Unit,
1203
+ ) => {
1204
+ const params = callee?.kind === "Definition" ? callee.params : undefined;
1205
+ if (!callee || !params || params.length === callee.arity) return false;
1206
+ if (range && !unit.isGenerated) {
1207
+ unit.errors.push({
1208
+ location: formatRange(range),
1209
+ message: `Wrong number of arguments (${count}) given to operator '${resolveSynonym(name)}', \nwhich requires ${params.length} arguments.`,
1210
+ });
1211
+ }
1212
+ return true;
1213
+ };
1214
+
1215
+ const resolveExpressionArgument = (arg: Expression, scope: LocalName | undefined, unit: Unit) => {
1216
+ const range = arg.location.range;
1217
+ const report = (message: string) => {
1218
+ if (range) unit.errors.push({ location: formatRange(range), message });
1219
+ };
1220
+ const selectionError = operatorSelectionErrors.get(arg);
1221
+ // Deviation from SANY: SANY names its internal node kind here, where tla-ts words it as for a name.
1222
+ if (arg.kind === "Lambda" && arg.operator !== undefined) {
1223
+ report(`The operator ${resolveSynonym(arg.operator)} requires 1 arguments.`);
1224
+ } else if (selectionError) {
1225
+ unit.errors.push(selectionError);
1226
+ } else if (arg.kind === "Lambda" && range) {
1227
+ unresolvedExpressions.add(arg);
1228
+ report("LAMBDA expression used where an expression is required.");
1229
+ } else if (arg.kind === "OperatorReference") {
1230
+ const argArity = getSymbolArity(arg, arg.operator, scope, unit);
1231
+ if (argArity !== undefined) {
1232
+ report(`The operator ${resolveSynonym(arg.operator)} requires ${argArity} arguments.`);
1233
+ }
1234
+ } else resolveExpression(arg, scope, unit);
1235
+ };
1236
+
1237
+ const getSelectorArgumentError = (reference: Expression) => {
1238
+ // SANY reads a reference that ends in arguments as an application, not as a selector's arguments.
1239
+ const selectors =
1240
+ reference.kind === "Subexpression" ||
1241
+ (reference.kind === "Apply" && reference.argumentCounts?.at(-1) === 0)
1242
+ ? getSelectors(reference)
1243
+ : [];
1244
+ const index = selectors.findIndex((selector) => "args" in selector && selector.args.length > 0);
1245
+ if (index === -1 || !isReference(reference)) return undefined;
1246
+ const selector = selectors[index];
1247
+ return {
1248
+ index,
1249
+ range: reference.selectorRanges?.[index],
1250
+ message: `Selector \`${selector.kind === "Name" ? selector.name : "!(...)"}' should not have argument(s).`,
1251
+ };
1252
+ };
1253
+
1254
+ const matchArgument = (
1255
+ arg: Expression,
1256
+ expected: number,
1257
+ index: number,
1258
+ operator: string,
1259
+ operatorRange: SourceRange | undefined,
1260
+ scope: LocalName | undefined,
1261
+ unit: Unit,
1262
+ ) => {
1263
+ const report = (range: SourceRange | undefined, message: string) => {
1264
+ if (range) unit.errors.push({ location: formatRange(range), message });
1265
+ };
1266
+ const reportOperatorArity = (name: string, arity: number) => {
1267
+ const definition =
1268
+ findInstance(operator, scope, unit)?.range ?? findBinding(operator, scope, unit)?.range;
1269
+ if (!definition) return;
1270
+ report(
1271
+ operatorRange,
1272
+ `Operator with incorrect arity passed as argument. \nOperator '${resolveSynonym(name)}' of arity ${arity} is argument number ${index + 1} (counting from 1) to operator \`${formatRange(definition)}', \nbut an operator of arity ${expected} was expected.`,
1273
+ );
1274
+ };
1275
+ const range = arg.location.range;
1276
+ if (expected === 0) {
1277
+ resolveExpressionArgument(arg, scope, unit);
1278
+ return true;
1279
+ }
1280
+ const parenthesized = parenthesizedRanges.get(arg);
1281
+ if (parenthesized) {
1282
+ report(
1283
+ parenthesized,
1284
+ `An expression appears as argument number ${index + 1} (counting from 1) to operator '${operator}', in a position an operator is required.`,
1285
+ );
1286
+ return false;
1287
+ }
1288
+ const reference = selections.get(arg) ?? arg;
1289
+ const argumentError = getSelectorArgumentError(reference);
1290
+ if (argumentError) {
1291
+ report(argumentError.range, argumentError.message);
1292
+ return false;
1293
+ }
1294
+ if (arg.kind === "Lambda") {
1295
+ if (selections.has(arg)) resolveExpression(arg, scope, unit);
1296
+ else resolveLambda(arg, scope, unit);
1297
+ if (findNullError(nullSelections.get(arg))) return false;
1298
+ const isMatched = arg.params.length === expected;
1299
+ if (!isMatched && selections.has(arg)) {
1300
+ report(range, `Expected arity ${expected} but found operator of arity ${arg.params.length}.`);
1301
+ } else if (!isMatched && range && arg.operator === undefined) {
1302
+ report(
1303
+ operatorRange,
1304
+ `Lambda expression with arity ${arg.params.length} used as argument ${index + 1} of operator \`${operator}', \nbut an operator of arity ${expected} is required.`,
1305
+ );
1306
+ } else if (!isMatched && arg.operator !== undefined) {
1307
+ reportOperatorArity(arg.operator, arg.params.length);
1308
+ }
1309
+ return isMatched;
1310
+ }
1311
+ if (reference !== arg) {
1312
+ const failed = findNullError(nullSelections.get(arg));
1313
+ if (failed) unit.errors.push(failed);
1314
+ if (!failed) {
1315
+ report(reference.location.range, `Expected arity ${expected} but found operator of arity 0.`);
1316
+ }
1317
+ return false;
1318
+ }
1319
+ if (arg.kind === "Subexpression") {
1320
+ resolveExpression(arg, scope, unit);
1321
+ return false;
1322
+ }
1323
+ if (arg.kind !== "Identifier" && arg.kind !== "OperatorReference") {
1324
+ report(
1325
+ range,
1326
+ `An expression appears as argument number ${index + 1} (counting from 1) to operator '${operator}', in a position an operator is required.`,
1327
+ );
1328
+ return false;
1329
+ }
1330
+ const name = arg.kind === "Identifier" ? arg.name : arg.operator;
1331
+ const argParams = findBinding(name, scope, unit)?.params ?? [];
1332
+ const argArity = getSymbolArity(arg, name, scope, unit);
1333
+ if (arg.kind === "Identifier" && argArity !== undefined && argArity !== expected) {
1334
+ report(
1335
+ getSpelledNameRange(arg, name),
1336
+ `Expected arity ${expected} but found operator of arity ${argArity}.`,
1337
+ );
1338
+ }
1339
+ if (arg.kind === "OperatorReference" && argArity !== undefined && argArity !== expected) {
1340
+ reportOperatorArity(name, argArity);
1341
+ }
1342
+ // Deviation from SANY: OpDefNode#matchingOpArgOperand reads as many parameters as a RECURSIVE declaration gives and crashes when the definition has fewer.
1343
+ return argArity === expected && argParams.every((param) => param === 0);
1344
+ };
1345
+
903
1346
  const resolveApply = (
904
1347
  expression: Expression & { kind: "Apply" },
905
1348
  scope: LocalName | undefined,
906
1349
  unit: Unit,
907
1350
  ) => {
908
- if (isInstanceArityReported(expression, scope, unit)) return;
909
1351
  const operator = expression.operator;
910
1352
  const callee = findBinding(operator, scope, unit);
911
- const arity = getSymbolArity(expression, operator, scope, unit);
912
- if (arity === undefined) return;
913
- if (arity !== expression.args.length) {
1353
+ const arity = isInstanceArityReported(expression, scope, unit)
1354
+ ? undefined
1355
+ : getSymbolArity(expression, operator, scope, unit);
1356
+ if (arity !== undefined && arity !== expression.args.length) {
914
1357
  unit.errors.push({
915
1358
  location: formatRange(expression.argumentsRange ?? getSpelledNameRange(expression, operator)),
916
- message: `The operator ${operator} requires ${arity - (findInstance(operator, scope, unit)?.arity ?? 0)} arguments.`,
1359
+ message: `The operator ${resolveSynonym(operator)} requires ${arity - (findInstance(operator, scope, unit)?.arity ?? 0)} arguments.`,
917
1360
  });
1361
+ }
1362
+ if (arity !== expression.args.length) {
1363
+ emptyExpressions.add(expression);
918
1364
  return;
919
1365
  }
920
- const params = callee && (callee.kind === "Definition" ? callee.params : []);
1366
+ const params =
1367
+ callee && (callee.kind === "Definition" ? callee.params : expression.args.map(() => 0));
921
1368
  if (params === undefined) {
922
1369
  expression.args.forEach((arg) => resolveArgument(arg, scope, unit));
923
1370
  return;
924
1371
  }
925
- const report = (range: SourceRange | undefined, message: string) => {
926
- if (range) unit.errors.push({ location: formatRange(range), message });
927
- };
928
- expression.args
929
- .map((arg, index) => {
930
- const expected = params[index] ?? 0;
931
- const range = arg.location.range;
932
- if (expected === 0) {
933
- // Deviation from SANY: SANY fails here with an internal error; tla-ts words it as for a name.
934
- if (arg.kind === "Lambda" && arg.operator !== undefined) {
935
- report(range, `The operator ${arg.operator} requires 1 arguments.`);
936
- } else if (arg.kind === "Lambda" && range) {
937
- report(range, "LAMBDA expression used where an expression is required.");
938
- } else if (arg.kind === "OperatorReference") {
939
- const argArity = getSymbolArity(arg, arg.operator, scope, unit);
940
- if (argArity !== undefined) {
941
- report(range, `The operator ${arg.operator} requires ${argArity} arguments.`);
942
- }
943
- } else resolveExpression(arg, scope, unit);
944
- return true;
945
- }
946
- if (arg.kind === "Lambda") {
947
- resolveExpression(arg, scope, unit);
948
- const isMatched = arg.params.length === expected;
949
- if (!isMatched && selections.has(arg)) {
950
- report(
951
- range,
952
- `Expected arity ${expected} but found operator of arity ${arg.params.length}.`,
953
- );
954
- } else if (!isMatched && range && arg.operator === undefined) {
955
- report(
956
- expression.selectorRanges?.at(-1) ?? getSpelledNameRange(expression, operator),
957
- `Lambda expression with arity ${arg.params.length} used as argument ${index + 1} of operator \`${operator}', \nbut an operator of arity ${expected} is required.`,
958
- );
959
- }
960
- return isMatched;
961
- }
962
- if (arg.kind === "Subexpression") {
963
- resolveExpression(arg, scope, unit);
964
- return true;
965
- }
966
- if (arg.kind === "Apply" && arg.argumentCounts?.at(-1) === 0) {
967
- const selectorIndex = arg.argumentCounts.findIndex((count) => count > 0);
968
- report(
969
- arg.selectorRanges?.[selectorIndex],
970
- `Selector \`${arg.operator.split("!")[selectorIndex]}' should not have argument(s).`,
971
- );
972
- return false;
973
- }
974
- if (arg.kind !== "Identifier" && arg.kind !== "OperatorReference") {
975
- report(
976
- range,
977
- `An expression appears as argument number ${index + 1} (counting from 1) to operator '${operator}', in a position an operator is required.`,
978
- );
979
- return false;
980
- }
981
- const name = arg.kind === "Identifier" ? arg.name : arg.operator;
982
- const argParams = findBinding(name, scope, unit)?.params ?? [];
983
- const argArity = getSymbolArity(arg, name, scope, unit);
984
- if (arg.kind === "Identifier" && argArity !== undefined && argArity !== expected) {
985
- report(
986
- getSpelledNameRange(arg, name),
987
- `Expected arity ${expected} but found operator of arity ${argArity}.`,
988
- );
989
- }
990
- return argArity === expected && argParams.every((param) => param === 0);
991
- })
992
- .forEach((isMatched, index) => {
993
- if (!isMatched) {
994
- report(
995
- expression.location.range,
996
- `Argument number ${index + 1} to operator '${operator}' \nshould be a ${params[index]}-parameter operator.`,
997
- );
998
- }
999
- });
1372
+ const operatorRange =
1373
+ expression.selectorRanges?.at(-1) ?? getSpelledNameRange(expression, operator);
1374
+ const isSelection = operator === SELECTION_NAME;
1375
+ const matches = expression.args.slice(0, params.length).map((arg, index) => {
1376
+ const source = isSelection ? selectionArguments.get(arg) : undefined;
1377
+ return matchArgument(
1378
+ arg,
1379
+ params[index],
1380
+ source?.index ?? index,
1381
+ source?.operator ?? operator,
1382
+ source?.range ?? operatorRange,
1383
+ scope,
1384
+ isSelection ? { ...unit, isGenerated: false } : unit,
1385
+ );
1386
+ });
1387
+ if (
1388
+ isArgumentCountReported(
1389
+ callee,
1390
+ operator,
1391
+ expression.args.length,
1392
+ expression.location.range,
1393
+ unit,
1394
+ )
1395
+ ) {
1396
+ return;
1397
+ }
1398
+ matches.forEach((isMatched, index) => {
1399
+ if (!isMatched && expression.location.range) {
1400
+ unit.errors.push({
1401
+ location: formatRange(expression.location.range),
1402
+ message: `Argument number ${index + 1} to operator '${isSelection ? "LAMBDA" : operator}' \nshould be a ${params[index]}-parameter operator.`,
1403
+ });
1404
+ }
1405
+ });
1000
1406
  };
1001
1407
 
1002
1408
  const resolveArgument = (arg: Expression, scope: LocalName | undefined, unit: Unit) => {
@@ -1004,20 +1410,61 @@ const resolveArgument = (arg: Expression, scope: LocalName | undefined, unit: Un
1004
1410
  else resolveExpression(arg, scope, unit);
1005
1411
  };
1006
1412
 
1413
+ const matchApplications = (
1414
+ applications: SelectionArguments[],
1415
+ scope: LocalName | undefined,
1416
+ unit: Unit,
1417
+ ) =>
1418
+ applications.forEach((application) =>
1419
+ application.args
1420
+ .slice(0, application.params.length)
1421
+ .forEach((arg, index) =>
1422
+ matchArgument(
1423
+ arg,
1424
+ application.params[index],
1425
+ index,
1426
+ application.operator,
1427
+ application.range,
1428
+ scope,
1429
+ unit,
1430
+ ),
1431
+ ),
1432
+ );
1433
+
1007
1434
  const isSelectionReported = (expression: Expression, scope: LocalName | undefined, unit: Unit) => {
1008
1435
  const failed = selectionErrors.get(expression);
1009
1436
  if (!failed) return false;
1010
- failed.args.forEach((arg) => resolveArgument(arg, scope, unit));
1011
- unit.errors.push(failed.error);
1437
+ matchApplications(failed.applications, scope, unit);
1438
+ unit.errors.push(findNullError(failed.nulls) ?? failed.error);
1012
1439
  return true;
1013
1440
  };
1014
1441
 
1442
+ const resolveLambda = (
1443
+ expression: Expression & { kind: "Lambda" },
1444
+ scope: LocalName | undefined,
1445
+ unit: Unit,
1446
+ ) =>
1447
+ resolveExpression(
1448
+ expression.body,
1449
+ bindNames(scope, expression.params, expression.paramRanges, unit),
1450
+ {
1451
+ ...unit,
1452
+ labelParams: [...unit.labelParams, ...expression.params],
1453
+ },
1454
+ );
1455
+
1015
1456
  const resolveExpression = (
1016
1457
  expression: Expression,
1017
1458
  scope: LocalName | undefined,
1018
1459
  unit: Unit,
1019
1460
  ): void => {
1020
1461
  if (selections.has(expression) && !unit.isGenerated) {
1462
+ const failed = findNullSelection(nullSelections.get(expression));
1463
+ if (failed) {
1464
+ matchApplications(failed.applications, scope, unit);
1465
+ unit.errors.push(failed.error);
1466
+ return;
1467
+ }
1021
1468
  resolveExpression(expression, scope, { ...unit, isGenerated: true });
1022
1469
  return;
1023
1470
  }
@@ -1031,18 +1478,51 @@ const resolveExpression = (
1031
1478
  case "Number":
1032
1479
  case "Decimal":
1033
1480
  case "String":
1481
+ return;
1034
1482
  case "ExceptAt":
1483
+ if (!unit.isInExcept && expression.location.range) {
1484
+ emptyExpressions.add(expression);
1485
+ unit.errors.push({
1486
+ location: formatRange(expression.location.range),
1487
+ message: "@ used where its meaning is not defined.",
1488
+ });
1489
+ }
1035
1490
  return;
1036
1491
  case "Identifier": {
1037
- if (isInstanceArityReported(expression, scope, unit)) return;
1038
1492
  const name = expression.name;
1039
- const arity = getSymbolArity(expression, name, scope, unit);
1040
- if (arity !== undefined && arity > 0) {
1493
+ const arity = isInstanceArityReported(expression, scope, unit)
1494
+ ? undefined
1495
+ : getSymbolArity(expression, name, scope, unit);
1496
+ if (arity === 0) {
1497
+ const binding = findBinding(name, scope, unit);
1498
+ const kind = binding?.kind;
1499
+ // SANY's selector chooses no operand of a variable, theorem, step or NEW symbol, unlike of a constant or definition.
1500
+ if (
1501
+ kind === "Variable" ||
1502
+ kind === "Theorem" ||
1503
+ kind?.startsWith("New") ||
1504
+ isFact(name, unit)
1505
+ ) {
1506
+ emptyExpressions.add(expression);
1507
+ }
1508
+ const local = lookupLocal(scope, name);
1509
+ if ((local ? local.goal : getGoal(name, unit))?.statement.kind === "AssumeProve") {
1510
+ unit.errors.push({
1511
+ location: formatRange(getSpelledNameRange(expression, name)),
1512
+ message: "ASSUME/PROVE used where an expression is required.",
1513
+ });
1514
+ return;
1515
+ }
1516
+ isArgumentCountReported(binding, name, 0, getSpelledNameRange(expression, name), unit);
1517
+ return;
1518
+ }
1519
+ if (arity !== undefined) {
1041
1520
  unit.errors.push({
1042
1521
  location: formatRange(getSpelledNameRange(expression, name)),
1043
- message: `The operator ${name} requires ${arity} arguments.`,
1522
+ message: `The operator ${resolveSynonym(name)} requires ${arity} arguments.`,
1044
1523
  });
1045
1524
  }
1525
+ emptyExpressions.add(expression);
1046
1526
  return;
1047
1527
  }
1048
1528
  case "OperatorReference":
@@ -1052,11 +1532,14 @@ const resolveExpression = (
1052
1532
  resolveApply(expression, scope, unit);
1053
1533
  return;
1054
1534
  case "Lambda":
1055
- resolveExpression(
1056
- expression.body,
1057
- bindNames(scope, expression.params, expression.paramRanges, unit),
1058
- bindLabelParams(expression.params),
1059
- );
1535
+ if (selections.has(expression)) resolveLambda(expression, scope, unit);
1536
+ else if (expression.location.range) {
1537
+ unresolvedExpressions.add(expression);
1538
+ unit.errors.push({
1539
+ location: formatRange(expression.location.range),
1540
+ message: "LAMBDA expression used where an expression is required.",
1541
+ });
1542
+ }
1060
1543
  return;
1061
1544
  case "And":
1062
1545
  case "Or":
@@ -1079,7 +1562,13 @@ const resolveExpression = (
1079
1562
  case "Let":
1080
1563
  resolveExpression(
1081
1564
  expression.body,
1082
- resolveDefinitions(expression.definitions, scope, unit, expression.instances),
1565
+ resolveDefinitions(
1566
+ expression.definitions,
1567
+ scope,
1568
+ unit,
1569
+ expression.instances,
1570
+ expression.recursive,
1571
+ ),
1083
1572
  unit,
1084
1573
  );
1085
1574
  return;
@@ -1147,9 +1636,30 @@ const resolveExpression = (
1147
1636
  resolveExpression(update.value, scope, { ...unit, isInExcept: true });
1148
1637
  });
1149
1638
  return;
1150
- case "FunctionApplication":
1151
- resolveAll([expression.function, ...expression.args]);
1639
+ case "FunctionApplication": {
1640
+ const applied = expression.function;
1641
+ const name =
1642
+ applied.kind === "Identifier"
1643
+ ? applied.name
1644
+ : applied.kind === "Apply"
1645
+ ? applied.operator
1646
+ : undefined;
1647
+ const arity = name === undefined ? undefined : findBinding(name, scope, unit)?.functionArity;
1648
+ resolveExpression(applied, scope, unit);
1649
+ const count = expression.args.length;
1650
+ if (arity === undefined || count < 2 || arity === count || isEmptyExpression(applied)) {
1651
+ resolveAll(expression.args);
1652
+ return;
1653
+ }
1654
+ emptyExpressions.add(expression);
1655
+ if (expression.location.range) {
1656
+ unit.errors.push({
1657
+ location: formatRange(expression.location.range),
1658
+ message: `Function '${name}' is defined with ${arity} parameters, but is applied to ${count} arguments.`,
1659
+ });
1660
+ }
1152
1661
  return;
1662
+ }
1153
1663
  case "FieldAccess":
1154
1664
  resolveExpression(expression.record, scope, unit);
1155
1665
  return;
@@ -1169,34 +1679,365 @@ const resolveExpression = (
1169
1679
  resolveExpression(expression.body, scope, { ...unit, labelParams: [], labels: new Set() });
1170
1680
  checkLabel(expression, scope, unit);
1171
1681
  return;
1172
- case "Subexpression": {
1173
- if (isSelectionReported(expression, scope, unit)) return;
1174
- expression.selectors
1175
- .flatMap((selector) => ("args" in selector ? selector.args : []))
1176
- .forEach((arg) => resolveArgument(arg, scope, unit));
1177
- checkReference(expression, scope, unit, false);
1682
+ case "Subexpression":
1683
+ if (isSubexpressionReported(expression, scope, unit)) emptyExpressions.add(expression);
1684
+ return;
1685
+ case "Selection":
1686
+ return;
1687
+ }
1688
+ };
1689
+
1690
+ const isPendingSelectionReported = (
1691
+ name: string,
1692
+ args: Expression[],
1693
+ selectorRange: SourceRange | undefined,
1694
+ argumentsRange: SourceRange | undefined,
1695
+ scope: LocalName | undefined,
1696
+ unit: Unit,
1697
+ ) => {
1698
+ const pending = lookupLocal(scope, name) ?? getModuleBinding(name, unit, undefined);
1699
+ if (!pending?.isPending || !selectorRange || !argumentsRange) return false;
1700
+ if (args.length !== pending.arity) {
1701
+ unit.errors.push({
1702
+ location: formatRange(argumentsRange),
1703
+ message: `The operator ${name} requires ${pending.arity} arguments.`,
1704
+ });
1705
+ return true;
1706
+ }
1707
+ args.forEach((arg) => resolveExpression(arg, scope, unit));
1708
+ unit.errors.push({
1709
+ location: formatRange(selectorRange),
1710
+ message: `Subexpression of \`${name}' used inside the operator's definition.`,
1711
+ });
1712
+ return true;
1713
+ };
1714
+
1715
+ const isSubexpressionReported = (
1716
+ expression: Expression & { kind: "Subexpression" },
1717
+ scope: LocalName | undefined,
1718
+ unit: Unit,
1719
+ ) => {
1720
+ if (
1721
+ isInstanceArityReported(expression, scope, unit) ||
1722
+ isSelectionReported(expression, scope, unit)
1723
+ ) {
1724
+ return true;
1725
+ }
1726
+ const head = expression.selectors[0];
1727
+ const range = expression.selectorRanges?.[0];
1728
+ const nameCount = expression.selectors.findIndex((selector) => selector.kind !== "Name");
1729
+ const names = expression.selectors
1730
+ .slice(0, nameCount)
1731
+ .flatMap((selector) => (selector.kind === "Name" ? [selector.name] : []));
1732
+ const symbolIndex = names.findIndex(
1733
+ (_name, index) =>
1734
+ index > 0 &&
1735
+ (findSymbol(names.slice(0, index + 1).join("!"), unit)?.kind ?? "Instance") !== "Instance",
1736
+ );
1737
+ const isInstance =
1738
+ names.length > 1 &&
1739
+ (lookupLocal(scope, names[0]) ?? getModuleBinding(names[0], unit, undefined))?.kind ===
1740
+ "Instance";
1741
+ const lastRange = expression.selectorRanges?.[nameCount - 1];
1742
+ if (isInstance && symbolIndex === -1 && range && lastRange) {
1743
+ unit.errors.push({
1744
+ location: formatRange({ module: range.module, start: range.start, end: lastRange.end }),
1745
+ message: `Unknown operator: \`${resolveSynonym(names.join("!"))}'.`,
1746
+ });
1747
+ return true;
1748
+ }
1749
+ const name = names.slice(0, symbolIndex + 1).join("!");
1750
+ const symbol = symbolIndex > 0 ? findSymbol(name, unit) : undefined;
1751
+ const argumentCount = expression.selectors
1752
+ .slice(0, symbolIndex + 1)
1753
+ .flatMap((selector) => ("args" in selector ? selector.args : [])).length;
1754
+ const argumentRange = expression.argumentRanges?.[symbolIndex] ?? expression.location.range;
1755
+ if (symbol && symbol.arity !== argumentCount && argumentRange) {
1756
+ unit.errors.push({
1757
+ location: formatRange(argumentRange),
1758
+ message: `The operator ${resolveSynonym(name)} requires ${symbol.arity} arguments.`,
1759
+ });
1760
+ return true;
1761
+ }
1762
+ if (head.kind === "Name" && expression.selectors[1].kind !== "Name" && range) {
1763
+ const local = lookupLocal(scope, head.name);
1764
+ const binding = local ?? findSymbol(head.name, unit);
1765
+ if ((binding === undefined && !isFact(head.name, unit)) || binding?.kind === "Instance") {
1766
+ unit.errors.push({
1767
+ location: formatRange(range),
1768
+ message: `Unknown operator: \`${resolveSynonym(head.name)}'.`,
1769
+ });
1770
+ return true;
1178
1771
  }
1772
+ if (binding && (!SELECTABLE_KINDS.has(binding.kind) || local?.nonFactStep)) {
1773
+ reportUnselectable(head.name, range, unit);
1774
+ return true;
1775
+ }
1776
+ }
1777
+ if (
1778
+ head.kind === "Name" &&
1779
+ isPendingSelectionReported(
1780
+ head.name,
1781
+ head.args,
1782
+ range,
1783
+ expression.argumentRanges?.[0] ?? expression.location.range,
1784
+ scope,
1785
+ unit,
1786
+ )
1787
+ ) {
1788
+ return true;
1179
1789
  }
1790
+ expression.selectors
1791
+ .flatMap((selector) => ("args" in selector ? selector.args : []))
1792
+ .forEach((arg) => resolveArgument(arg, scope, unit));
1793
+ const selected = checkReference(expression, scope, unit, false);
1794
+ return selected ? selected.node === undefined : false;
1180
1795
  };
1181
1796
 
1182
- const checkFacts = (facts: Fact[], scope: LocalName | undefined, unit: Unit) =>
1183
- facts.forEach((fact) => {
1184
- if (
1185
- fact.kind === "ModuleFact" ||
1186
- isInstanceArityReported(fact, scope, unit) ||
1187
- checkReference(fact, scope, unit, true)
1188
- ) {
1189
- return;
1797
+ const reportUnknownModule = (fact: Fact & { kind: "ModuleFact" }, unit: Unit) => {
1798
+ const range = fact.location.range;
1799
+ if (unit.isModuleKnown(fact.name, fact.location) || !range) return;
1800
+ unit.errors.push({
1801
+ location: formatRange({
1802
+ ...range,
1803
+ start: { line: range.end.line, column: range.end.column - fact.name.length + 1 },
1804
+ }),
1805
+ message: `Module \`${fact.name}' used without being extended or instantiated.`,
1806
+ });
1807
+ };
1808
+
1809
+ const checkFact = (fact: Fact, reference: Fact, scope: LocalName | undefined, unit: Unit) => {
1810
+ if (fact.kind === "ModuleFact") {
1811
+ reportUnknownModule(fact, unit);
1812
+ return undefined;
1813
+ }
1814
+ if (fact.kind === "ExceptAt" && fact.location.range) {
1815
+ unit.errors.push({
1816
+ location: formatRange(fact.location.range),
1817
+ message: "Unknown operator: `@'.",
1818
+ });
1819
+ return BUILTIN_LOCATION;
1820
+ }
1821
+ const hidden = getHiddenExpressionLocation(fact, reference, scope, unit);
1822
+ if (selections.has(fact)) {
1823
+ resolveExpression(fact, scope, unit);
1824
+ return hidden;
1825
+ }
1826
+ if (isInstanceArityReported(fact, scope, unit)) return hidden;
1827
+ const selected = checkReference(fact, scope, unit, true);
1828
+ if (selected) {
1829
+ const kind = selected.node?.kind;
1830
+ if (kind === undefined) return BUILTIN_LOCATION;
1831
+ return kind === "AssumeProve" || kind === "NewSymbol"
1832
+ ? undefined
1833
+ : fact.location.range && formatRange(fact.location.range);
1834
+ }
1835
+ if (fact.kind === "Subexpression") {
1836
+ return isSubexpressionReported(fact, scope, unit) ? BUILTIN_LOCATION : hidden;
1837
+ }
1838
+ const name = fact.kind === "Identifier" ? fact.name : fact.kind === "Apply" ? fact.operator : "";
1839
+ if (fact.kind === "Identifier" && lookupLocal(scope, name)?.nonFactStep) {
1840
+ unit.errors.push({
1841
+ location: formatRange(getSpelledNameRange(fact, name)),
1842
+ message: "Step number of non-fact used as a fact",
1843
+ });
1844
+ return BUILTIN_LOCATION;
1845
+ }
1846
+ if (
1847
+ !isFact(name, unit) &&
1848
+ !lookupLocal(scope, name)?.goal &&
1849
+ !(fact.kind === "Identifier" && isInstanceName(name, scope, unit))
1850
+ ) {
1851
+ resolveExpression(fact, scope, unit);
1852
+ }
1853
+ return hidden;
1854
+ };
1855
+
1856
+ const isDefinitionEntry = (def: Fact, scope: LocalName | undefined, unit: Unit) => {
1857
+ if (def.kind === "ModuleFact") {
1858
+ reportUnknownModule(def, unit);
1859
+ return unit.isModuleKnown(def.name, def.location);
1860
+ }
1861
+ const entryErrors = defEntryErrors.get(def) ?? [];
1862
+ unit.errors.push(
1863
+ ...entryErrors.map((error) => ({
1864
+ location: formatSanyLocation(error.location),
1865
+ message: error.message,
1866
+ })),
1867
+ );
1868
+ if (entryErrors.length > 0) return false;
1869
+ const binder = getDefEntryBinder(def);
1870
+ const reference = binder ?? selections.get(def) ?? def;
1871
+ const range = reference.location.range;
1872
+ if (!range) return true;
1873
+ const name =
1874
+ reference.kind === "Identifier"
1875
+ ? reference.name
1876
+ : reference.kind === "Apply" || reference.kind === "OperatorReference"
1877
+ ? reference.operator
1878
+ : "";
1879
+ const local = lookupLocal(scope, name);
1880
+ const binding = local ?? findSymbol(name, unit) ?? getModuleBinding(name, unit, range);
1881
+ if (binding === undefined && isFact(name, unit)) return true;
1882
+ const isDefined =
1883
+ isReference(reference) &&
1884
+ getSelectors(reference).length > 1 &&
1885
+ (binding === undefined || getSelectorArgumentError(reference))
1886
+ ? isDefinitionSelected(def, reference, scope, unit)
1887
+ : name === "" || isDefinitionName(name, local, binding, range, unit);
1888
+ if (isDefined) return true;
1889
+ unit.errors.push({
1890
+ location: formatRange((binder ? def : reference).location.range ?? range),
1891
+ message: "DEF clause entry should describe a defined operator.",
1892
+ });
1893
+ return false;
1894
+ };
1895
+
1896
+ const isDefinitionName = (
1897
+ name: string,
1898
+ local: LocalName | undefined,
1899
+ binding: Binding | undefined,
1900
+ range: SourceRange,
1901
+ unit: Unit,
1902
+ ) => {
1903
+ if (binding === undefined) {
1904
+ unit.errors.push({
1905
+ location: formatRange(range),
1906
+ message: `Unknown operator: \`${resolveSynonym(name)}'.`,
1907
+ });
1908
+ }
1909
+ if (local?.nonFactStep === "Define") return true;
1910
+ if (local?.nonFactStep) {
1911
+ unit.errors.push({
1912
+ location: formatRange(range),
1913
+ message: "DEF clause entry refers to a non-definition step.",
1914
+ });
1915
+ }
1916
+ return binding !== undefined && SELECTABLE_KINDS.has(binding.kind) && !isStepName(name);
1917
+ };
1918
+
1919
+ const isDefinitionSelected = (
1920
+ def: Expression,
1921
+ reference: Reference,
1922
+ scope: LocalName | undefined,
1923
+ unit: Unit,
1924
+ ) => {
1925
+ const report = (range: SourceRange | undefined, message: string) => {
1926
+ if (range) unit.errors.push({ location: formatRange(range), message });
1927
+ return false;
1928
+ };
1929
+ const argumentError = getSelectorArgumentError(reference);
1930
+ if (argumentError?.index === 0) return report(argumentError.range, argumentError.message);
1931
+ const selectors = getSelectors(reference);
1932
+ const ranges = reference.selectorRanges;
1933
+ const failed = selectionErrors.get(def);
1934
+ if (!failed && !selections.has(def)) {
1935
+ const head = selectors[0];
1936
+ const name = head.kind === "Name" ? head.name : "";
1937
+ const local = lookupLocal(scope, name);
1938
+ const binding = local ?? findSymbol(name, unit);
1939
+ if (binding && (!SELECTABLE_KINDS.has(binding.kind) || local?.nonFactStep) && ranges?.[0]) {
1940
+ reportUnselectable(name, ranges[0], unit);
1941
+ return false;
1190
1942
  }
1191
- const name =
1192
- fact.kind === "Identifier" ? fact.name : fact.kind === "Apply" ? fact.operator : "";
1193
- if (fact.kind === "Identifier" && lookupLocal(scope, name)?.isNonFact) {
1943
+ if (argumentError) return report(argumentError.range, argumentError.message);
1944
+ if (checkReference(reference, scope, unit, false)) return false;
1945
+ const first = ranges?.[0];
1946
+ const last = ranges?.[selectors.findLastIndex((selector) => selector.kind === "Name")];
1947
+ const names = selectors.flatMap((selector) =>
1948
+ selector.kind === "Name" ? [selector.name] : [],
1949
+ );
1950
+ return report(
1951
+ first && last && { ...first, end: last.end },
1952
+ `Unknown operator: \`${resolveSynonym(names.join("!"))}'.`,
1953
+ );
1954
+ }
1955
+ if (argumentError) return report(argumentError.range, argumentError.message);
1956
+ const error = failed
1957
+ ? (findNullError(failed.nulls) ?? failed.error)
1958
+ : findNullError(nullSelections.get(def));
1959
+ if (error) {
1960
+ unit.errors.push(error);
1961
+ return false;
1962
+ }
1963
+ return selectors.at(-1)?.kind === "Name" && selectors.at(-2)?.kind !== "Name";
1964
+ };
1965
+
1966
+ const getHiddenExpressionLocation = (
1967
+ fact: Expression,
1968
+ reference: Fact,
1969
+ scope: LocalName | undefined,
1970
+ unit: Unit,
1971
+ ) => {
1972
+ const range = fact.location.range && formatRange(fact.location.range);
1973
+ if (selections.has(fact)) {
1974
+ return findNullError(nullSelections.get(fact))
1975
+ ? BUILTIN_LOCATION
1976
+ : reference.location.range && formatRange(reference.location.range);
1977
+ }
1978
+ if (selectionErrors.has(fact) || fact.kind === "ExceptAt") return BUILTIN_LOCATION;
1979
+ switch (fact.kind) {
1980
+ case "Number":
1981
+ case "String":
1982
+ case "Decimal":
1983
+ case "Let":
1984
+ case "Label":
1985
+ return undefined;
1986
+ case "Identifier":
1987
+ case "Apply":
1988
+ case "Subexpression": {
1989
+ const first = getSelectors(fact)[0];
1990
+ if (fact.kind === "Subexpression" || first.kind !== "Name") return undefined;
1991
+ const name = fact.kind === "Identifier" ? fact.name : fact.operator;
1992
+ const goal = lookupLocal(scope, first.name)?.goal ?? getGoal(first.name, unit);
1993
+ if (
1994
+ isFact(name, unit) ||
1995
+ goal ||
1996
+ (isStepName(name) && lookupLocal(scope, name)) ||
1997
+ (fact.kind === "Identifier" && isInstanceName(name, scope, unit))
1998
+ ) {
1999
+ return undefined;
2000
+ }
2001
+ const binding = findBinding(name, scope, unit);
2002
+ const count = fact.kind === "Apply" ? fact.args.length : 0;
2003
+ // Deviation from SANY: UseOrHideNode#factCheck crashes on a fact whose operator Generator#generateExpression could not resolve, where tla-ts reports it like a null node.
2004
+ return binding?.arity === count ? range : BUILTIN_LOCATION;
2005
+ }
2006
+ default:
2007
+ return range;
2008
+ }
2009
+ };
2010
+
2011
+ const checkUseOrHide = (
2012
+ statement: UseOrHide | Extract<Proof, { kind: "By" }>,
2013
+ scope: LocalName | undefined,
2014
+ unit: Unit,
2015
+ ) => {
2016
+ const references = factReferences.get(statement.facts) ?? statement.facts;
2017
+ const hidden = statement.facts.map((fact, index) =>
2018
+ checkFact(fact, references[index], scope, unit),
2019
+ );
2020
+ const factCount = statement.facts.filter(
2021
+ (fact) => fact.kind !== "ModuleFact" || unit.isModuleKnown(fact.name, fact.location),
2022
+ ).length;
2023
+ const defCount = statement.defs.filter((def) => isDefinitionEntry(def, scope, unit)).length;
2024
+ hidden.forEach((location) => {
2025
+ if (location && statement.kind === "Hide") {
1194
2026
  unit.errors.push({
1195
- location: formatRange(getSpelledNameRange(fact, name)),
1196
- message: "Step number of non-fact used as a fact",
2027
+ location,
2028
+ message:
2029
+ "The only expression allowed as a fact in a HIDE is \nthe name of a theorem, assumption, or step.",
1197
2030
  });
1198
- } else if (!unit.facts.has(name)) resolveExpression(fact, scope, unit);
2031
+ }
1199
2032
  });
2033
+ const range = statement.location.range;
2034
+ if (factCount + defCount === 0 && range) {
2035
+ unit.errors.push({
2036
+ location: formatRange(range),
2037
+ message: statement.kind === "By" ? "Empty BY" : "Empty USE or HIDE statement.",
2038
+ });
2039
+ }
2040
+ };
1200
2041
 
1201
2042
  const resolveNewSymbol = (symbol: NewSymbol, scope: LocalName | undefined, unit: Unit) => {
1202
2043
  if (symbol.set) resolveExpression(symbol.set, scope, unit);
@@ -1245,7 +2086,7 @@ const resolveStatement = (
1245
2086
 
1246
2087
  const resolveProof = (proof: Proof | undefined, scope: LocalName | undefined, outer: Unit) => {
1247
2088
  const unit = outer.hasLabelScope ? { ...outer, hasLabelScope: false } : outer;
1248
- if (proof?.kind === "By") checkFacts(proof.facts, scope, unit);
2089
+ if (proof?.kind === "By") checkUseOrHide(proof, scope, unit);
1249
2090
  if (proof?.kind !== "Steps") return;
1250
2091
  proof.steps.reduce((current, step) => resolveStep(step, current, unit), scope);
1251
2092
  };
@@ -1262,6 +2103,42 @@ const resolveLocalInstance = (instance: Instance, scope: LocalName | undefined,
1262
2103
  );
1263
2104
  };
1264
2105
 
2106
+ const getStepGoal = (body: StepBody, location: SourceLocation): Goal | undefined => {
2107
+ const createGoal = (keyword: string, statement: Expression) => ({
2108
+ statement,
2109
+ isSuffices: false,
2110
+ isInProof: false,
2111
+ keyword,
2112
+ });
2113
+ switch (body.kind) {
2114
+ case "Have":
2115
+ return createGoal("HAVE", { kind: "Tuple", elements: [body.expression], location });
2116
+ case "Case":
2117
+ return createGoal("CASE", { kind: "Tuple", elements: [body.expression], location });
2118
+ case "Witness":
2119
+ return createGoal("WITNESS", { kind: "Tuple", elements: body.expressions, location });
2120
+ case "Take":
2121
+ return createGoal("TAKE", { kind: "Tuple", elements: getBoundSets(body.bounds), location });
2122
+ case "Pick":
2123
+ return createGoal(
2124
+ "PICK",
2125
+ body.bounds.length > 0
2126
+ ? { kind: "Exists", bounds: body.bounds, body: body.body, location }
2127
+ : {
2128
+ kind: "UnboundedQuantifier",
2129
+ quantifier: "Exists",
2130
+ names: body.names,
2131
+ body: body.body,
2132
+ location,
2133
+ },
2134
+ );
2135
+ case "Qed":
2136
+ return createGoal("QED step", { kind: "Tuple", elements: [], location });
2137
+ default:
2138
+ return undefined;
2139
+ }
2140
+ };
2141
+
1265
2142
  const resolveStep = (
1266
2143
  step: ProofStep,
1267
2144
  scope: LocalName | undefined,
@@ -1272,12 +2149,16 @@ const resolveStep = (
1272
2149
  step.name === undefined
1273
2150
  ? unit
1274
2151
  : { ...unit, hasLabelScope: true, labelParams: [], labels: new Set<string>() };
2152
+ const goal = getStepGoal(body, step.location);
1275
2153
  const bindStep = (parent: LocalName | undefined): LocalName | undefined =>
1276
- step.name === undefined ? parent : { name: step.name, arity: 0, kind: "Theorem", parent };
1277
- const bindNonFactStep = (parent: LocalName | undefined): LocalName | undefined =>
2154
+ step.name === undefined ? parent : { name: step.name, arity: 0, kind: "Theorem", parent, goal };
2155
+ const bindNonFactStep = (
2156
+ parent: LocalName | undefined,
2157
+ nonFactStep: LocalName["nonFactStep"],
2158
+ ): LocalName | undefined =>
1278
2159
  step.name === undefined
1279
2160
  ? parent
1280
- : { name: step.name, arity: 0, kind: "Theorem", parent, isNonFact: true };
2161
+ : { name: step.name, arity: 0, kind: "Theorem", parent, nonFactStep };
1281
2162
  switch (body.kind) {
1282
2163
  case "Assert": {
1283
2164
  const assumed = resolveStatement(body.statement, scope, stepUnit);
@@ -1287,17 +2168,32 @@ const resolveStep = (
1287
2168
  resolveProof(step.proof, proofScope, unit);
1288
2169
  return body.isSuffices ? assumed : scope;
1289
2170
  }
1290
- const goal = { statement: body.statement, isSuffices: body.isSuffices, isInProof: true };
1291
- resolveProof(step.proof, { name, arity: 0, kind: "Theorem", parent: proofScope, goal }, unit);
1292
- goal.isInProof = false;
1293
- return { name, arity: 0, kind: "Theorem", parent: body.isSuffices ? assumed : scope, goal };
2171
+ const assertion = {
2172
+ statement: body.statement,
2173
+ isSuffices: body.isSuffices,
2174
+ isInProof: true,
2175
+ keyword: body.isSuffices && body.statement.kind !== "AssumeProve" ? "SUFFICES" : undefined,
2176
+ };
2177
+ resolveProof(
2178
+ step.proof,
2179
+ { name, arity: 0, kind: "Theorem", parent: proofScope, goal: assertion },
2180
+ unit,
2181
+ );
2182
+ assertion.isInProof = false;
2183
+ return {
2184
+ name,
2185
+ arity: 0,
2186
+ kind: "Theorem",
2187
+ parent: body.isSuffices ? assumed : scope,
2188
+ goal: assertion,
2189
+ };
1294
2190
  }
1295
2191
  case "Use":
1296
2192
  case "Hide":
1297
- checkFacts(body.facts, scope, unit);
1298
- return bindNonFactStep(scope);
2193
+ checkUseOrHide(body, scope, unit);
2194
+ return bindNonFactStep(scope, body.kind);
1299
2195
  case "Instance":
1300
- return bindNonFactStep(resolveLocalInstance(body, scope, stepUnit));
2196
+ return bindNonFactStep(resolveLocalInstance(body, scope, stepUnit), body.kind);
1301
2197
  case "Define":
1302
2198
  return bindNonFactStep(
1303
2199
  body.definitions.reduce(
@@ -1307,6 +2203,7 @@ const resolveStep = (
1307
2203
  : resolveDefinitions([definition], current, unit),
1308
2204
  scope,
1309
2205
  ),
2206
+ body.kind,
1310
2207
  );
1311
2208
  case "Have":
1312
2209
  case "Case":
@@ -1379,6 +2276,7 @@ export interface ModuleUnit {
1379
2276
  bound: Symbols;
1380
2277
  definitions: Map<string, Definition>;
1381
2278
  getKey: (definition: Definition) => string;
2279
+ isModuleKnown: (name: string, location: SourceLocation) => boolean;
1382
2280
  instanced: Map<Instance, Symbols>;
1383
2281
  facts: Set<string>;
1384
2282
  reports: ModuleReport[];
@@ -1417,18 +2315,94 @@ const checkSubstitutions = (
1417
2315
  (parent, param) => ({ name: param.name, arity: param.arity, kind: "Parameter", parent }),
1418
2316
  outer,
1419
2317
  );
2318
+ const reportArity = (declaration: Declaration, location: string) =>
2319
+ unit.errors.push({
2320
+ location,
2321
+ message: `An operator must be substituted for symbol '${resolveSynonym(declaration.name)}', and it must have arity ${declaration.arity}.`,
2322
+ });
1420
2323
  const resolveSubstitute = (declaration: Declaration, expression: Expression) => {
1421
- if (declaration.arity === 0 || expression.kind !== "Identifier") {
2324
+ const range = expression.location.range;
2325
+ if (declaration.arity === 0) {
2326
+ resolveExpressionArgument(expression, scope, unit);
2327
+ return;
2328
+ }
2329
+ const parenthesized = parenthesizedRanges.get(expression);
2330
+ const reference = parenthesized ? undefined : selections.get(expression);
2331
+ if (reference) {
2332
+ const arity = expression.kind === "Lambda" ? expression.params.length : 0;
2333
+ const failed = findNullError(nullSelections.get(expression));
2334
+ if (expression.kind === "Lambda") resolveExpression(expression, scope, unit);
2335
+ else if (failed) unit.errors.push(failed);
2336
+ if (!failed && arity !== declaration.arity && reference.location.range) {
2337
+ unit.errors.push({
2338
+ location: formatRange(reference.location.range),
2339
+ message: `Expected arity ${declaration.arity} but found operator of arity ${arity}.`,
2340
+ });
2341
+ }
2342
+ if (failed || arity !== declaration.arity) reportArity(declaration, BUILTIN_LOCATION);
2343
+ return;
2344
+ }
2345
+ if (expression.kind === "Subexpression" && !parenthesized) {
1422
2346
  resolveExpression(expression, scope, unit);
2347
+ reportArity(declaration, BUILTIN_LOCATION);
2348
+ return;
2349
+ }
2350
+ if (expression.kind === "Lambda" && !parenthesized) {
2351
+ resolveLambda(expression, scope, unit);
2352
+ if (expression.params.length !== declaration.arity && range) {
2353
+ reportArity(declaration, formatRange(range));
2354
+ }
2355
+ return;
2356
+ }
2357
+ if (expression.kind === "OperatorReference" && !parenthesized) {
2358
+ const arity = getSymbolArity(expression, expression.operator, scope, unit);
2359
+ if (arity === undefined) reportArity(declaration, BUILTIN_LOCATION);
2360
+ else if (arity !== declaration.arity && range) reportArity(declaration, formatRange(range));
2361
+ return;
2362
+ }
2363
+ if (expression.kind !== "Identifier" || parenthesized) {
2364
+ const errorRange = parenthesized ?? range;
2365
+ if (errorRange) {
2366
+ unit.errors.push({
2367
+ location: formatRange(errorRange),
2368
+ message: `Arity ${declaration.arity} operator (not an expression) is expected \nto substitute for CONSTANT '${resolveSynonym(declaration.name)}'.`,
2369
+ });
2370
+ }
2371
+ reportArity(declaration, BUILTIN_LOCATION);
1423
2372
  return;
1424
2373
  }
1425
2374
  const arity = getSymbolArity(expression, expression.name, scope, unit);
1426
2375
  if (arity !== undefined && arity !== declaration.arity) {
1427
- throw new TlaSyntaxError(
1428
- `An operator must be substituted for symbol '${declaration.name}', and it must have arity ${declaration.arity} in the instance of ${instance.module} at line ${instance.location.line}, column ${instance.location.column}`,
1429
- );
2376
+ unit.errors.push({
2377
+ location: formatRange(getSpelledNameRange(expression, expression.name)),
2378
+ message: `Expected arity ${declaration.arity} but found operator of arity ${arity}.`,
2379
+ });
1430
2380
  }
2381
+ if (arity !== declaration.arity) reportArity(declaration, BUILTIN_LOCATION);
1431
2382
  };
2383
+ const instanceRange = instance.location.range;
2384
+ const isFound = (declaration: Declaration) =>
2385
+ lookupLocal(scope, declaration.name) !== undefined ||
2386
+ findSymbol(declaration.name, unit) !== undefined;
2387
+ const implicit = declarations.filter(isFound).map((declaration) => {
2388
+ const expression: Expression & { kind: "Identifier" } = {
2389
+ kind: "Identifier",
2390
+ name: declaration.name,
2391
+ location: instance.location,
2392
+ };
2393
+ return { declaration, expression };
2394
+ });
2395
+ implicit
2396
+ .filter((item) => item.declaration.arity === 0)
2397
+ .forEach((item) => {
2398
+ const arity = getSymbolArity(item.expression, item.declaration.name, scope, unit);
2399
+ if (arity && instanceRange) {
2400
+ unit.errors.push({
2401
+ location: formatRange(instanceRange),
2402
+ message: `Wrong number of arguments (0) given to operator '${resolveSynonym(item.declaration.name)}', \nwhich requires ${arity} arguments.`,
2403
+ });
2404
+ }
2405
+ });
1432
2406
  const substitutions = new Map<string, Expression>();
1433
2407
  instance.substitutions.forEach((substitution) => {
1434
2408
  const name = substitution.name;
@@ -1451,30 +2425,29 @@ const checkSubstitutions = (
1451
2425
  });
1452
2426
  }
1453
2427
  });
1454
- const implicit = declarations.filter((declaration) => !substitutions.has(declaration.name));
1455
- const isMissing = (declaration: Declaration) =>
1456
- !lookupLocal(scope, declaration.name) && !findSymbol(declaration.name, unit);
1457
2428
  implicit
1458
- .filter((declaration) => !isMissing(declaration))
2429
+ .filter((item) => !substitutions.has(item.declaration.name))
2430
+ .forEach((item) => {
2431
+ const arity =
2432
+ item.declaration.arity === 0
2433
+ ? 0
2434
+ : getSymbolArity(item.expression, item.declaration.name, scope, unit);
2435
+ if (arity !== item.declaration.arity && instanceRange) {
2436
+ reportArity(item.declaration, formatRange(instanceRange));
2437
+ }
2438
+ substitutions.set(item.declaration.name, item.expression);
2439
+ });
2440
+ declarations
2441
+ .filter((declaration) => !substitutions.has(declaration.name))
1459
2442
  .forEach((declaration) => {
1460
- const expression: Expression = {
1461
- kind: "Identifier",
1462
- name: declaration.name,
1463
- location: instance.location,
1464
- };
1465
- resolveSubstitute(declaration, expression);
1466
- substitutions.set(declaration.name, expression);
2443
+ const declared = declaration.location.range;
2444
+ if (instanceRange && declared) {
2445
+ unit.errors.push({
2446
+ location: formatRange(instanceRange),
2447
+ message: `Substitution missing for symbol ${resolveSynonym(declaration.name)} declared at ${formatRange(declared)} \nand instantiated in module ${instancer}.`,
2448
+ });
2449
+ }
1467
2450
  });
1468
- implicit.filter(isMissing).forEach((declaration) => {
1469
- const range = instance.location.range;
1470
- const declared = declaration.location.range;
1471
- if (range && declared) {
1472
- unit.errors.push({
1473
- location: formatRange(range),
1474
- message: `Substitution missing for symbol ${declaration.name} declared at ${formatRange(declared)} \nand instantiated in module ${instancer}.`,
1475
- });
1476
- }
1477
- });
1478
2451
  return substitutions;
1479
2452
  };
1480
2453
 
@@ -1482,7 +2455,7 @@ const resolveInstance = (instance: Instance, scope: LocalName | undefined, unit:
1482
2455
  const instanced = unit.getInstance(instance);
1483
2456
  checkSubstitutions(instance, instanced.declarations, instanced.instancer, scope, unit);
1484
2457
  return [...instanced.symbols].reduce(
1485
- (parent, [name, symbol]) => bindName(parent, name, symbol, unit),
2458
+ (parent, entry) => bindName(parent, entry[0], entry[1], unit),
1486
2459
  scope,
1487
2460
  );
1488
2461
  };
@@ -1494,6 +2467,12 @@ export const resolveSubstitutions = (
1494
2467
  unit: ModuleUnit,
1495
2468
  ) => {
1496
2469
  const imported = createSymbols(module, unit.imported);
2470
+ const positions = new Map(
2471
+ [...module.constants, ...module.variables].map((declaration) => [
2472
+ declaration.name,
2473
+ declaration.location,
2474
+ ]),
2475
+ );
1497
2476
  const report: ModuleReport = { location: instance.location, errors: [], warnings: [] };
1498
2477
  unit.reports.push(report);
1499
2478
  return checkSubstitutions(instance, declarations, module.name, undefined, {
@@ -1501,12 +2480,16 @@ export const resolveSubstitutions = (
1501
2480
  getInstance: unit.getInstance,
1502
2481
  definitions: unit.definitions,
1503
2482
  getKey: unit.getKey,
2483
+ isModuleKnown: unit.isModuleKnown,
1504
2484
  location: instance.location,
1505
2485
  self: undefined,
1506
2486
  facts: new Set(),
1507
2487
  goals: new Map(),
1508
2488
  bindings: new Map(
1509
- [...imported].map(([name, symbol]) => [name, { ...symbol, position: MODULE_START }]),
2489
+ [...imported].map((entry) => [
2490
+ entry[0],
2491
+ { ...entry[1], position: positions.get(entry[0]) ?? MODULE_START },
2492
+ ]),
1510
2493
  ),
1511
2494
  errors: report.errors,
1512
2495
  warnings: report.warnings,
@@ -1536,13 +2519,7 @@ export const collectSemanticErrors = (units: SemanticUnit[], warnings: SanyError
1536
2519
  }
1537
2520
  };
1538
2521
  units
1539
- .toSorted((left, right) =>
1540
- isBefore(left.location, right.location)
1541
- ? -1
1542
- : isBefore(right.location, left.location)
1543
- ? 1
1544
- : 0,
1545
- )
2522
+ .toSorted((left, right) => compareLocations(left.location, right.location))
1546
2523
  .forEach((unit) => {
1547
2524
  const reported: SanyError[] = [];
1548
2525
  const warned: SanyError[] = [];
@@ -1562,62 +2539,103 @@ export const collectSemanticErrors = (units: SemanticUnit[], warnings: SanyError
1562
2539
 
1563
2540
  export const resolveModule = (module: Module, unit: ModuleUnit) => {
1564
2541
  const symbols = createSymbols(module, unit.imported);
1565
- const facts = new Set([
1566
- ...unit.facts,
1567
- ...[...module.theorems, ...module.assumptions].flatMap((fact) => fact.name ?? []),
1568
- ]);
1569
2542
  const goals = new Map(
1570
2543
  module.theorems.flatMap((theorem): [string, Goal][] =>
1571
2544
  theorem.name !== undefined && theorem.statement.kind === "AssumeProve"
1572
- ? [[theorem.name, { statement: theorem.statement, isSuffices: false, isInProof: false }]]
2545
+ ? [
2546
+ [
2547
+ theorem.name,
2548
+ {
2549
+ statement: theorem.statement,
2550
+ isSuffices: false,
2551
+ isInProof: false,
2552
+ keyword: undefined,
2553
+ },
2554
+ ],
2555
+ ]
1573
2556
  : [],
1574
2557
  ),
1575
2558
  );
1576
2559
  const bindings = new Map<string, ModuleBinding>(
1577
- [...CORE_SYMBOLS, ...unit.bound].map(([name, symbol]) => [
1578
- name,
1579
- { ...symbol, position: MODULE_START },
2560
+ [...CORE_SYMBOLS, ...unit.bound].map((entry) => [
2561
+ entry[0],
2562
+ { ...entry[1], position: MODULE_START },
1580
2563
  ]),
1581
2564
  );
1582
2565
  const recursive = new Set<Binding>();
1583
2566
  const declarations: { declaration: Declaration; binding: ModuleBinding | undefined }[] = [];
1584
- const createUnit = (
2567
+ const createCheck = (
1585
2568
  location: SourceLocation,
1586
2569
  self: Definition | undefined,
1587
- errors: SanyError[],
1588
- warnings: SanyError[],
1589
2570
  hasLabelScope: boolean,
1590
- ): Unit => ({
1591
- imported: symbols,
1592
- getInstance: unit.getInstance,
1593
- definitions: unit.definitions,
1594
- getKey: unit.getKey,
2571
+ check: (inner: Unit) => void,
2572
+ ): SemanticUnit => ({
1595
2573
  location,
1596
- self,
1597
- facts,
1598
- goals,
1599
- bindings,
1600
- errors,
1601
- warnings,
1602
- hasLabelScope,
1603
- isLabelForbidden: false,
1604
- isInExcept: false,
1605
- labelParams: [],
1606
- labels: new Set(),
1607
- isGenerated: false,
2574
+ check: (errors, warnings) =>
2575
+ check({
2576
+ imported: symbols,
2577
+ getInstance: unit.getInstance,
2578
+ definitions: unit.definitions,
2579
+ getKey: unit.getKey,
2580
+ isModuleKnown: unit.isModuleKnown,
2581
+ location,
2582
+ self,
2583
+ facts: unit.facts,
2584
+ goals,
2585
+ bindings,
2586
+ errors,
2587
+ warnings,
2588
+ hasLabelScope,
2589
+ isLabelForbidden: false,
2590
+ isInExcept: false,
2591
+ labelParams: [],
2592
+ labels: new Set(),
2593
+ isGenerated: false,
2594
+ }),
1608
2595
  });
1609
2596
  const bindDeclarations = (declarations: Declaration[], kind: "Constant" | "Variable") =>
1610
- declarations.map((declaration) => ({
1611
- location: declaration.location,
1612
- check: (errors: SanyError[], warnings: SanyError[]) =>
2597
+ declarations.map((declaration) =>
2598
+ createCheck(declaration.location, undefined, false, (inner) =>
1613
2599
  bindModuleName(
1614
2600
  declaration.name,
1615
2601
  { kind, arity: declaration.arity, range: declaration.location.range },
1616
- createUnit(declaration.location, undefined, errors, warnings, false),
2602
+ inner,
1617
2603
  ),
1618
- }));
2604
+ ),
2605
+ );
1619
2606
  return collectSemanticErrors(
1620
2607
  [
2608
+ ...module.units.flatMap((item): SemanticUnit[] => {
2609
+ const section =
2610
+ item.kind === "Variables"
2611
+ ? { type: "A VARIABLE declaration", location: item.location }
2612
+ : item.kind === "Constants"
2613
+ ? { type: "A declaration", location: item.location }
2614
+ : item.kind === "Module"
2615
+ ? { type: "A MODULE ", location: item.module.location }
2616
+ : item.kind === "Theorem"
2617
+ ? { type: "A THEOREM", location: item.theorem.location }
2618
+ : item.kind === "Assumption"
2619
+ ? { type: "An ASSUME", location: item.assumption.location }
2620
+ : item.kind === "Use"
2621
+ ? { type: "A USE or HIDE", location: item.use.location }
2622
+ : undefined;
2623
+ const range = section?.location.range;
2624
+ if (!section || !range) return [];
2625
+ return [
2626
+ {
2627
+ location: section.location,
2628
+ check: (errors) => {
2629
+ if (declarations.some((declared) => declared.binding?.isPending)) {
2630
+ errors.push({
2631
+ location: formatRange(range),
2632
+ message: `${section.type} may not appear within a recursive definition section.`,
2633
+ });
2634
+ }
2635
+ },
2636
+ },
2637
+ ];
2638
+ }),
1621
2639
  ...unit.reports.map((report) => ({
1622
2640
  location: report.location,
1623
2641
  check: (errors: SanyError[], warnings: SanyError[]) => {
@@ -1629,12 +2647,12 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
1629
2647
  ...bindDeclarations(module.variables, "Variable"),
1630
2648
  ...module.units
1631
2649
  .flatMap((item) => (item.kind === "Recursive" ? item.declarations : []))
1632
- .map((declaration) => ({
1633
- location: declaration.location,
1634
- check: (errors: SanyError[], warnings: SanyError[]) => {
2650
+ .map((declaration) =>
2651
+ createCheck(declaration.location, undefined, false, (inner) => {
1635
2652
  const binding: ModuleBinding = {
1636
2653
  kind: "Definition",
1637
2654
  arity: declaration.arity,
2655
+ params: Array(declaration.arity).fill(0),
1638
2656
  range: declaration.location.range,
1639
2657
  position: declaration.location,
1640
2658
  isPending: true,
@@ -1643,19 +2661,17 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
1643
2661
  declaration.name,
1644
2662
  bindings.get(declaration.name),
1645
2663
  binding,
1646
- createUnit(declaration.location, undefined, errors, warnings, false),
2664
+ inner,
1647
2665
  );
1648
2666
  if (isBound) {
1649
2667
  bindings.set(declaration.name, binding);
1650
2668
  recursive.add(binding);
1651
2669
  }
1652
2670
  declarations.push({ declaration, binding: isBound ? binding : undefined });
1653
- },
1654
- })),
1655
- ...module.definitions.map((definition) => ({
1656
- location: definition.location,
1657
- check: (errors: SanyError[], warnings: SanyError[]) => {
1658
- const inner = createUnit(definition.location, definition, errors, warnings, true);
2671
+ }),
2672
+ ),
2673
+ ...module.definitions.map((definition) =>
2674
+ createCheck(definition.location, definition, true, (inner) => {
1659
2675
  if (isTheoremDefinition(module, definition)) {
1660
2676
  resolveExpression(definition.body, undefined, inner);
1661
2677
  } else if (resolveDefinition(definition, undefined, inner, recursive)) {
@@ -1666,12 +2682,10 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
1666
2682
  position: definition.location,
1667
2683
  });
1668
2684
  }
1669
- },
1670
- })),
1671
- ...module.instances.map((instance) => ({
1672
- location: instance.location,
1673
- check: (errors: SanyError[], warnings: SanyError[]) => {
1674
- const inner = createUnit(instance.location, undefined, errors, warnings, false);
2685
+ }),
2686
+ ),
2687
+ ...module.instances.map((instance) =>
2688
+ createCheck(instance.location, undefined, false, (inner) => {
1675
2689
  bindParams(undefined, instance.params, inner);
1676
2690
  unit.instanced
1677
2691
  .get(instance)
@@ -1683,18 +2697,10 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
1683
2697
  inner,
1684
2698
  );
1685
2699
  }
1686
- },
1687
- })),
1688
- ...module.assumptions.map((assumption) => ({
1689
- location: assumption.location,
1690
- check: (errors: SanyError[], warnings: SanyError[]) => {
1691
- const inner = createUnit(
1692
- assumption.location,
1693
- undefined,
1694
- errors,
1695
- warnings,
1696
- assumption.name !== undefined,
1697
- );
2700
+ }),
2701
+ ),
2702
+ ...module.assumptions.map((assumption) =>
2703
+ createCheck(assumption.location, undefined, assumption.name !== undefined, (inner) => {
1698
2704
  resolveExpression(assumption.expression, undefined, inner);
1699
2705
  if (assumption.name !== undefined) {
1700
2706
  bindModuleName(
@@ -1703,25 +2709,18 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
1703
2709
  inner,
1704
2710
  );
1705
2711
  }
1706
- },
1707
- })),
1708
- ...module.theorems.map((theorem) => ({
1709
- location: theorem.location,
1710
- check: (errors: SanyError[], warnings: SanyError[]) =>
1711
- resolveTheorem(
1712
- theorem,
1713
- createUnit(theorem.location, undefined, errors, warnings, theorem.name !== undefined),
1714
- ),
1715
- })),
1716
- ...module.uses.map((use) => ({
1717
- location: use.location,
1718
- check: (errors: SanyError[], warnings: SanyError[]) =>
1719
- checkFacts(
1720
- use.facts,
1721
- undefined,
1722
- createUnit(use.location, undefined, errors, warnings, false),
1723
- ),
1724
- })),
2712
+ }),
2713
+ ),
2714
+ ...module.theorems.map((theorem) =>
2715
+ createCheck(theorem.location, undefined, theorem.name !== undefined, (inner) =>
2716
+ resolveTheorem(theorem, inner),
2717
+ ),
2718
+ ),
2719
+ ...module.uses.map((use) =>
2720
+ createCheck(use.location, undefined, false, (inner) =>
2721
+ checkUseOrHide(use, undefined, inner),
2722
+ ),
2723
+ ),
1725
2724
  {
1726
2725
  location: module.location.range?.end ?? module.location,
1727
2726
  check: (errors: SanyError[]) =>
@@ -1730,7 +2729,7 @@ export const resolveModule = (module: Module, unit: ModuleUnit) => {
1730
2729
  if (range && (!item.binding || item.binding.isPending)) {
1731
2730
  errors.push({
1732
2731
  location: formatRange(range),
1733
- message: `Symbol ${item.declaration.name} declared in RECURSIVE statement but not defined.`,
2732
+ message: `Symbol ${resolveSynonym(item.declaration.name)} declared in RECURSIVE statement but not defined.`,
1734
2733
  });
1735
2734
  }
1736
2735
  }),