tla-ts 0.0.3 → 0.0.4-dev.2a873ee

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (370) hide show
  1. package/README.md +46 -115
  2. package/dist/cli.cjs +1 -1
  3. package/dist/cli.js +1 -1
  4. package/dist/deciders.cjs +366 -0
  5. package/dist/deciders.js +366 -0
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +194 -8
  8. package/dist/index.d.ts +194 -8
  9. package/dist/index.js +1 -1
  10. package/dist/parallel-worker.cjs +1 -4
  11. package/dist/parallel-worker.js +1 -4
  12. package/dist/prove-worker.cjs +9 -0
  13. package/dist/prove-worker.d.cts +9 -0
  14. package/dist/prove-worker.d.ts +9 -0
  15. package/dist/prove-worker.js +9 -0
  16. package/dist/prove.cjs +996 -0
  17. package/dist/prove.js +996 -0
  18. package/dist/run-cli.cjs +37 -20
  19. package/dist/run-cli.js +37 -20
  20. package/dist/tlapm.cjs +10 -0
  21. package/dist/tlapm.js +10 -0
  22. package/dist/transfer.cjs +1387 -18
  23. package/dist/transfer.js +1387 -18
  24. package/dist/worker.cjs +21 -0
  25. package/dist/worker.js +21 -0
  26. package/package.json +24 -11
  27. package/src/ast.ts +149 -8
  28. package/src/bags.ts +4 -7
  29. package/src/builtins.ts +29 -11
  30. package/src/bundled-modules.ts +3 -3
  31. package/src/canonical.ts +4 -3
  32. package/src/check.ts +1540 -235
  33. package/src/cli-options.ts +12 -6
  34. package/src/cli.ts +8 -1
  35. package/src/codegen.ts +98 -39
  36. package/src/config.ts +254 -181
  37. package/src/dependencies.ts +2 -2
  38. package/src/environment.ts +540 -140
  39. package/src/errors.ts +284 -4
  40. package/src/evaluate.ts +1043 -293
  41. package/src/exit-codes.ts +22 -43
  42. package/src/fingerprints.ts +46 -11
  43. package/src/index.ts +11 -0
  44. package/src/instances.ts +19 -16
  45. package/src/java-overrides.ts +104 -25
  46. package/src/levels.ts +191 -45
  47. package/src/lexer.ts +127 -30
  48. package/src/live-check.ts +867 -0
  49. package/src/liveness.ts +218 -572
  50. package/src/{obligation-action.ts → obligations/action.ts} +247 -69
  51. package/src/{obligation-anon.ts → obligations/anon.ts} +49 -47
  52. package/src/obligations/ctx.ts +64 -0
  53. package/src/{obligation-deref.ts → obligations/deref.ts} +51 -92
  54. package/src/{obligation-expression.ts → obligations/expression.ts} +117 -57
  55. package/src/{obligation-format.ts → obligations/format.ts} +7 -8
  56. package/src/{obligation-generate.ts → obligations/generate.ts} +170 -192
  57. package/src/{obligations.ts → obligations/index.ts} +32 -16
  58. package/src/{obligation-levels.ts → obligations/levels.ts} +26 -28
  59. package/src/{obligation-module.ts → obligations/module.ts} +113 -121
  60. package/src/obligations/pickle.ts +98 -0
  61. package/src/obligations/pragma.ts +189 -0
  62. package/src/{obligation-printer.ts → obligations/printer.ts} +22 -80
  63. package/src/{obligation-proof.ts → obligations/proof.ts} +7 -2
  64. package/src/{obligation-source.ts → obligations/source.ts} +156 -99
  65. package/src/obligations/temporal.ts +321 -0
  66. package/src/{obligation-tuples.ts → obligations/tuples.ts} +38 -54
  67. package/src/ocaml-marshal.ts +166 -0
  68. package/src/parallel-worker.ts +169 -224
  69. package/src/parallel.ts +140 -81
  70. package/src/parser.ts +456 -147
  71. package/src/pcal-ast.ts +770 -0
  72. package/src/pcal-parse.ts +1523 -0
  73. package/src/pcal-tokenize.ts +516 -0
  74. package/src/pcal-translate.ts +1230 -0
  75. package/src/pcal-validate.ts +454 -0
  76. package/src/prove/decide-pool.ts +95 -0
  77. package/src/prove/deciders.ts +33 -0
  78. package/src/prove/first-order.ts +78 -0
  79. package/src/prove/isabelle/LICENSE +36 -0
  80. package/src/prove/isabelle/LICENSE-tlapm +26 -0
  81. package/src/prove/isabelle/decide.ts +47 -0
  82. package/src/prove/isabelle/encode.ts +446 -0
  83. package/src/prove/isabelle/isar/inner-syntax.ts +579 -0
  84. package/src/prove/isabelle/isar/method.ts +367 -0
  85. package/src/prove/isabelle/isar/proof.ts +28 -0
  86. package/src/prove/isabelle/isar/statement.ts +57 -0
  87. package/src/prove/isabelle/isar/theory.ts +192 -0
  88. package/src/prove/isabelle/isar/type-check.ts +278 -0
  89. package/src/prove/isabelle/provers/blast/blast.ts +258 -0
  90. package/src/prove/isabelle/provers/blast/branch.ts +322 -0
  91. package/src/prove/isabelle/provers/blast/prove.ts +347 -0
  92. package/src/prove/isabelle/provers/blast/rules.ts +330 -0
  93. package/src/prove/isabelle/provers/blast/state.ts +180 -0
  94. package/src/prove/isabelle/provers/blast/term.ts +546 -0
  95. package/src/prove/isabelle/provers/clasimp.ts +150 -0
  96. package/src/prove/isabelle/provers/classical.ts +389 -0
  97. package/src/prove/isabelle/provers/hypsubst.ts +433 -0
  98. package/src/prove/isabelle/pure/bicompose.ts +174 -0
  99. package/src/prove/isabelle/pure/consts.ts +32 -0
  100. package/src/prove/isabelle/pure/conv.ts +79 -0
  101. package/src/prove/isabelle/pure/drule.ts +264 -0
  102. package/src/prove/isabelle/pure/envir.ts +331 -0
  103. package/src/prove/isabelle/pure/goal.ts +53 -0
  104. package/src/prove/isabelle/pure/interrupt.ts +16 -0
  105. package/src/prove/isabelle/pure/list.ts +12 -0
  106. package/src/prove/isabelle/pure/logic.ts +330 -0
  107. package/src/prove/isabelle/pure/name.ts +98 -0
  108. package/src/prove/isabelle/pure/net.ts +215 -0
  109. package/src/prove/isabelle/pure/object-logic.ts +41 -0
  110. package/src/prove/isabelle/pure/pattern.ts +631 -0
  111. package/src/prove/isabelle/pure/raw-simplifier.ts +338 -0
  112. package/src/prove/isabelle/pure/rewriter.ts +602 -0
  113. package/src/prove/isabelle/pure/search.ts +68 -0
  114. package/src/prove/isabelle/pure/seq.ts +133 -0
  115. package/src/prove/isabelle/pure/simplifier.ts +106 -0
  116. package/src/prove/isabelle/pure/table.ts +201 -0
  117. package/src/prove/isabelle/pure/tactic.ts +168 -0
  118. package/src/prove/isabelle/pure/tactical.ts +264 -0
  119. package/src/prove/isabelle/pure/term-ord.ts +105 -0
  120. package/src/prove/isabelle/pure/term.ts +688 -0
  121. package/src/prove/isabelle/pure/thm.ts +783 -0
  122. package/src/prove/isabelle/pure/type.ts +121 -0
  123. package/src/prove/isabelle/pure/unify.ts +753 -0
  124. package/src/prove/isabelle/pure/variable.ts +25 -0
  125. package/src/prove/isabelle/tla/classical-setup.ts +101 -0
  126. package/src/prove/isabelle/tla/context.ts +74 -0
  127. package/src/prove/isabelle/tla/logic-data.ts +5 -0
  128. package/src/prove/isabelle/tla/logic.ts +215 -0
  129. package/src/prove/isabelle/tla/simpdata.ts +241 -0
  130. package/src/prove/isabelle/tools/intuitionistic.ts +132 -0
  131. package/src/prove/ocaml.ts +22 -0
  132. package/src/prove/prep/action.ts +508 -0
  133. package/src/prove/prep/defs.ts +33 -0
  134. package/src/prove/prep/elab.ts +156 -0
  135. package/src/prove/prep/enabled-axioms.ts +189 -0
  136. package/src/prove/prep/enabled.ts +43 -0
  137. package/src/prove/prep/fingerprint.ts +388 -0
  138. package/src/prove/prep/flatten.ts +70 -0
  139. package/src/prove/prep/level-comparison.ts +529 -0
  140. package/src/prove/prep/md5.ts +67 -0
  141. package/src/prove/prep/pragma.ts +221 -0
  142. package/src/prove/prep/trivial.ts +22 -0
  143. package/src/prove/prove-worker.ts +22 -0
  144. package/src/prove/prove.ts +498 -0
  145. package/src/prove/ptl/decide.ts +68 -0
  146. package/src/prove/ptl/encode.ts +255 -0
  147. package/src/prove/ptl/sat.ts +151 -0
  148. package/src/prove/ptl/tableau.ts +276 -0
  149. package/src/prove/smt/axiomatize.ts +69 -0
  150. package/src/prove/smt/axioms.ts +209 -0
  151. package/src/prove/smt/context.ts +108 -0
  152. package/src/prove/smt/data.ts +636 -0
  153. package/src/prove/smt/encode.ts +164 -0
  154. package/src/prove/smt/extensionality.ts +65 -0
  155. package/src/prove/smt/flatten.ts +112 -0
  156. package/src/prove/smt/format.ts +154 -0
  157. package/src/prove/smt/instances.ts +181 -0
  158. package/src/prove/smt/rewrite.ts +772 -0
  159. package/src/prove/smt/simplify.ts +57 -0
  160. package/src/prove/smt/solver/act-cache.ts +265 -0
  161. package/src/prove/smt/solver/arith-rewriter.ts +962 -0
  162. package/src/prove/smt/solver/array.ts +22 -0
  163. package/src/prove/smt/solver/asserted-formulas.ts +469 -0
  164. package/src/prove/smt/solver/ast-lt.ts +157 -0
  165. package/src/prove/smt/solver/ast-util.ts +91 -0
  166. package/src/prove/smt/solver/ast.ts +1315 -0
  167. package/src/prove/smt/solver/auf-solver.ts +572 -0
  168. package/src/prove/smt/solver/case-split-queue.ts +178 -0
  169. package/src/prove/smt/solver/cg-table.ts +175 -0
  170. package/src/prove/smt/solver/clause.ts +276 -0
  171. package/src/prove/smt/solver/conflict-resolution.ts +343 -0
  172. package/src/prove/smt/solver/context.ts +1292 -0
  173. package/src/prove/smt/solver/ctx-simplify.ts +334 -0
  174. package/src/prove/smt/solver/der.ts +224 -0
  175. package/src/prove/smt/solver/dyn-ack.ts +141 -0
  176. package/src/prove/smt/solver/e-matching.ts +659 -0
  177. package/src/prove/smt/solver/enode.ts +259 -0
  178. package/src/prove/smt/solver/expr-ref.ts +21 -0
  179. package/src/prove/smt/solver/expr-safe-replace.ts +172 -0
  180. package/src/prove/smt/solver/fingerprints.ts +92 -0
  181. package/src/prove/smt/solver/flat-literals.ts +51 -0
  182. package/src/prove/smt/solver/goal.ts +138 -0
  183. package/src/prove/smt/solver/hash.ts +173 -0
  184. package/src/prove/smt/solver/hashtable.ts +166 -0
  185. package/src/prove/smt/solver/internalizer.ts +1381 -0
  186. package/src/prove/smt/solver/lbool.ts +5 -0
  187. package/src/prove/smt/solver/literal.ts +24 -0
  188. package/src/prove/smt/solver/lp/bound-propagator.ts +391 -0
  189. package/src/prove/smt/solver/lp/constraints.ts +78 -0
  190. package/src/prove/smt/solver/lp/containers.ts +296 -0
  191. package/src/prove/smt/solver/lp/core-solver.ts +504 -0
  192. package/src/prove/smt/solver/lp/cross-nested.ts +224 -0
  193. package/src/prove/smt/solver/lp/dep-intervals.ts +642 -0
  194. package/src/prove/smt/solver/lp/dependency.ts +51 -0
  195. package/src/prove/smt/solver/lp/dioph-eq.ts +1181 -0
  196. package/src/prove/smt/solver/lp/explanation.ts +46 -0
  197. package/src/prove/smt/solver/lp/gomory.ts +255 -0
  198. package/src/prove/smt/solver/lp/hnf-cutter.ts +125 -0
  199. package/src/prove/smt/solver/lp/hnf.ts +281 -0
  200. package/src/prove/smt/solver/lp/int-cube.ts +295 -0
  201. package/src/prove/smt/solver/lp/int-solver.ts +514 -0
  202. package/src/prove/smt/solver/lp/lar-solver.ts +816 -0
  203. package/src/prove/smt/solver/lp/lar-term.ts +62 -0
  204. package/src/prove/smt/solver/lp/lp-settings.ts +91 -0
  205. package/src/prove/smt/solver/lp/maximize-term.ts +347 -0
  206. package/src/prove/smt/solver/lp/nex-creator.ts +381 -0
  207. package/src/prove/smt/solver/lp/nex.ts +120 -0
  208. package/src/prove/smt/solver/lp/nla-backoff.ts +43 -0
  209. package/src/prove/smt/solver/lp/nla-basics.ts +398 -0
  210. package/src/prove/smt/solver/lp/nla-core.ts +968 -0
  211. package/src/prove/smt/solver/lp/nla-divisions.ts +332 -0
  212. package/src/prove/smt/solver/lp/nla-emonics.ts +373 -0
  213. package/src/prove/smt/solver/lp/nla-factorization.ts +30 -0
  214. package/src/prove/smt/solver/lp/nla-grobner.ts +904 -0
  215. package/src/prove/smt/solver/lp/nla-horner.ts +126 -0
  216. package/src/prove/smt/solver/lp/nla-intervals.ts +265 -0
  217. package/src/prove/smt/solver/lp/nla-monomial-bounds.ts +715 -0
  218. package/src/prove/smt/solver/lp/nla-monotone.ts +59 -0
  219. package/src/prove/smt/solver/lp/nla-order.ts +307 -0
  220. package/src/prove/smt/solver/lp/nla-patcher.ts +112 -0
  221. package/src/prove/smt/solver/lp/nla-tangents.ts +251 -0
  222. package/src/prove/smt/solver/lp/nla-throttle.ts +85 -0
  223. package/src/prove/smt/solver/lp/nla-types.ts +124 -0
  224. package/src/prove/smt/solver/lp/nla-var-eqs.ts +141 -0
  225. package/src/prove/smt/solver/lp/nra-solver.ts +440 -0
  226. package/src/prove/smt/solver/lp/numeric-pair.ts +65 -0
  227. package/src/prove/smt/solver/lp/pdd-interval.ts +31 -0
  228. package/src/prove/smt/solver/lp/pdd-simplifier.ts +184 -0
  229. package/src/prove/smt/solver/lp/pdd-solver.ts +408 -0
  230. package/src/prove/smt/solver/lp/pdd.ts +971 -0
  231. package/src/prove/smt/solver/lp/random-updater.ts +138 -0
  232. package/src/prove/smt/solver/lp/static-matrix.ts +246 -0
  233. package/src/prove/smt/solver/lp/union-find.ts +96 -0
  234. package/src/prove/smt/solver/mam-compiler.ts +847 -0
  235. package/src/prove/smt/solver/mam-interpreter.ts +400 -0
  236. package/src/prove/smt/solver/maximize-ac-sharing.ts +118 -0
  237. package/src/prove/smt/solver/model-checker.ts +347 -0
  238. package/src/prove/smt/solver/model-evaluator.ts +262 -0
  239. package/src/prove/smt/solver/model-finder.ts +155 -0
  240. package/src/prove/smt/solver/model-generator.ts +97 -0
  241. package/src/prove/smt/solver/model-macro-solver.ts +728 -0
  242. package/src/prove/smt/solver/nlsat/algebraic.ts +1161 -0
  243. package/src/prove/smt/solver/nlsat/atoms.ts +238 -0
  244. package/src/prove/smt/solver/nlsat/evaluator.ts +303 -0
  245. package/src/prove/smt/solver/nlsat/explain.ts +607 -0
  246. package/src/prove/smt/solver/nlsat/interval-set.ts +351 -0
  247. package/src/prove/smt/solver/nlsat/levelwise.ts +737 -0
  248. package/src/prove/smt/solver/nlsat/mpbq.ts +161 -0
  249. package/src/prove/smt/solver/nlsat/polynomial.ts +1722 -0
  250. package/src/prove/smt/solver/nlsat/solver.ts +911 -0
  251. package/src/prove/smt/solver/nlsat/types.ts +43 -0
  252. package/src/prove/smt/solver/nlsat/upolynomial-factorization.ts +648 -0
  253. package/src/prove/smt/solver/nlsat/upolynomial.ts +996 -0
  254. package/src/prove/smt/solver/nnf.ts +469 -0
  255. package/src/prove/smt/solver/pattern-inference.ts +351 -0
  256. package/src/prove/smt/solver/poly-rewriter.ts +477 -0
  257. package/src/prove/smt/solver/propagate-values.ts +83 -0
  258. package/src/prove/smt/solver/proto-model.ts +551 -0
  259. package/src/prove/smt/solver/pull-quant.ts +139 -0
  260. package/src/prove/smt/solver/qe-lite-der.ts +526 -0
  261. package/src/prove/smt/solver/qe-lite-fm.ts +576 -0
  262. package/src/prove/smt/solver/qe-lite.ts +381 -0
  263. package/src/prove/smt/solver/qi-queue.ts +362 -0
  264. package/src/prove/smt/solver/quant-tactics.ts +117 -0
  265. package/src/prove/smt/solver/quantifier-analyzer.ts +562 -0
  266. package/src/prove/smt/solver/quantifier-manager.ts +186 -0
  267. package/src/prove/smt/solver/random-gen.ts +10 -0
  268. package/src/prove/smt/solver/rational.ts +165 -0
  269. package/src/prove/smt/solver/ref-vector.ts +62 -0
  270. package/src/prove/smt/solver/relevancy.ts +247 -0
  271. package/src/prove/smt/solver/rewriter-tpl.ts +1159 -0
  272. package/src/prove/smt/solver/rewriter.ts +843 -0
  273. package/src/prove/smt/solver/rlimit.ts +79 -0
  274. package/src/prove/smt/solver/smtlib-parser.ts +526 -0
  275. package/src/prove/smt/solver/solver.ts +71 -0
  276. package/src/prove/smt/solver/sort.ts +35 -0
  277. package/src/prove/smt/solver/sticky-generations.ts +69 -0
  278. package/src/prove/smt/solver/theory-lra-axioms.ts +340 -0
  279. package/src/prove/smt/solver/theory-lra-bounds.ts +226 -0
  280. package/src/prove/smt/solver/theory-lra-final-check.ts +252 -0
  281. package/src/prove/smt/solver/theory-lra-internalize.ts +476 -0
  282. package/src/prove/smt/solver/theory-lra-model.ts +243 -0
  283. package/src/prove/smt/solver/theory-lra-propagate.ts +405 -0
  284. package/src/prove/smt/solver/theory-lra-state.ts +43 -0
  285. package/src/prove/smt/solver/theory-lra.ts +56 -0
  286. package/src/prove/smt/solver/var-subst.ts +258 -0
  287. package/src/prove/smt/solver/z3-license.txt +10 -0
  288. package/src/prove/smt/table.ts +170 -0
  289. package/src/prove/tlapm/tlapm.ts +96 -0
  290. package/src/prove/tlaps-module.ts +510 -0
  291. package/src/prove/verdict.ts +18 -0
  292. package/src/prove/zenon/LICENSE +32 -0
  293. package/src/prove/zenon/check/check.ts +105 -0
  294. package/src/prove/zenon/check/definitions.ts +144 -0
  295. package/src/prove/zenon/check/equality.ts +182 -0
  296. package/src/prove/zenon/check/functions.ts +62 -0
  297. package/src/prove/zenon/check/keys.ts +125 -0
  298. package/src/prove/zenon/check/propositional.ts +104 -0
  299. package/src/prove/zenon/check/records.ts +188 -0
  300. package/src/prove/zenon/check/relations.ts +121 -0
  301. package/src/prove/zenon/check/rewrites.ts +224 -0
  302. package/src/prove/zenon/check/sets.ts +302 -0
  303. package/src/prove/zenon/check/terms.ts +127 -0
  304. package/src/prove/zenon/check/tla.ts +126 -0
  305. package/src/prove/zenon/decide.ts +113 -0
  306. package/src/prove/zenon/encode.ts +379 -0
  307. package/src/prove/zenon/eqrel.ts +300 -0
  308. package/src/prove/zenon/equality-rules.ts +435 -0
  309. package/src/prove/zenon/expr.ts +551 -0
  310. package/src/prove/zenon/index-table.ts +350 -0
  311. package/src/prove/zenon/isar-case.ts +513 -0
  312. package/src/prove/zenon/isar.ts +1249 -0
  313. package/src/prove/zenon/limits.ts +15 -0
  314. package/src/prove/zenon/llproof.ts +173 -0
  315. package/src/prove/zenon/mltoll.ts +1566 -0
  316. package/src/prove/zenon/node.ts +297 -0
  317. package/src/prove/zenon/ocaml.ts +169 -0
  318. package/src/prove/zenon/parse.ts +247 -0
  319. package/src/prove/zenon/phrase.ts +191 -0
  320. package/src/prove/zenon/proof.ts +198 -0
  321. package/src/prove/zenon/propositional-rules.ts +387 -0
  322. package/src/prove/zenon/rules.ts +94 -0
  323. package/src/prove/zenon/search.ts +288 -0
  324. package/src/prove/zenon/tla/functions.ts +151 -0
  325. package/src/prove/zenon/tla/llproof.ts +480 -0
  326. package/src/prove/zenon/tla/records.ts +225 -0
  327. package/src/prove/zenon/tla/rewrites.ts +447 -0
  328. package/src/prove/zenon/tla/sets.ts +304 -0
  329. package/src/prove/zenon/tla/terms.ts +162 -0
  330. package/src/prove/zenon/tla/tla.ts +506 -0
  331. package/src/randomization.ts +24 -7
  332. package/src/resolve.ts +1481 -426
  333. package/src/run-cli.ts +1483 -212
  334. package/src/runtime.ts +19 -1
  335. package/src/sany-builtins.ts +147 -0
  336. package/src/sany-generator.ts +3128 -0
  337. package/src/sany-levels.ts +1208 -0
  338. package/src/sany-lexer.ts +545 -0
  339. package/src/sany-linter.ts +122 -0
  340. package/src/sany-modules.ts +1398 -0
  341. package/src/sany-nodes.ts +463 -0
  342. package/src/sany-parse-error.ts +2161 -0
  343. package/src/sany-report.ts +356 -0
  344. package/src/sany-selectors.ts +738 -0
  345. package/src/sany-source.ts +248 -0
  346. package/src/sany-xml.ts +1017 -0
  347. package/src/spec-description.ts +42 -11
  348. package/src/standard-modules.ts +203 -148
  349. package/src/standard-ranges.ts +116 -0
  350. package/src/state-graph.ts +180 -0
  351. package/src/subexpressions.ts +231 -171
  352. package/src/substitution-levels.ts +38 -17
  353. package/src/successors.ts +241 -110
  354. package/src/symmetry.ts +194 -54
  355. package/src/tableau.ts +54 -25
  356. package/src/tlapm-cache.ts +236 -0
  357. package/src/tlc-ext.ts +42 -29
  358. package/src/tlc-messages.ts +329 -0
  359. package/src/tlc-module.ts +52 -43
  360. package/src/tlc-modules.ts +4 -0
  361. package/src/tlc-order.ts +78 -10
  362. package/src/tlc-random.ts +84 -33
  363. package/src/tlc-replay.ts +655 -0
  364. package/src/tlc-summary.ts +20 -5
  365. package/src/tlc-version.ts +19 -0
  366. package/src/transfer.ts +15 -3
  367. package/src/values.ts +787 -190
  368. package/src/worker.ts +65 -0
  369. package/dist/parallel.cjs +0 -12
  370. package/dist/parallel.js +0 -12
package/src/resolve.ts CHANGED
@@ -1,46 +1,127 @@
1
- import type {
2
- AssumeProve,
3
- Bound,
4
- BoundPattern,
5
- Definition,
6
- Expression,
7
- Instance,
8
- Module,
9
- NewSymbol,
10
- OperatorParam,
11
- Proof,
12
- ProofStep,
13
- SourceLocation,
14
- Theorem,
1
+ import {
2
+ getChildren,
3
+ isLocallyResolved,
4
+ type AssumeProve,
5
+ type Bound,
6
+ type BoundPattern,
7
+ type Declaration,
8
+ type Definition,
9
+ type Expression,
10
+ type Fact,
11
+ type Instance,
12
+ type LabelExpression,
13
+ type Module,
14
+ type NewSymbol,
15
+ type OperatorParam,
16
+ type Proof,
17
+ type ProofStep,
18
+ type Selector,
19
+ type SourceLocation,
20
+ type SourceRange,
21
+ type Theorem,
15
22
  } from "./ast";
16
- import { TlaSyntaxError } from "./errors";
17
- import { getChildren, isLocallyResolved } from "./evaluate";
23
+ import { formatRange, TlaSyntaxError, type SanyError } from "./errors";
18
24
 
19
- export interface ModuleSymbol {
20
- key: string;
25
+ // The kinds of symbol SANY tells apart when it binds a name twice. A parameter is also a bound name,
26
+ // and a NEW symbol has a kind for each level.
27
+ export type SymbolKind =
28
+ | "Builtin"
29
+ | "Constant"
30
+ | "Variable"
31
+ | "Definition"
32
+ | "Instance"
33
+ | "Theorem"
34
+ | "Parameter"
35
+ | `New${NewSymbol["level"]}`;
36
+
37
+ // range is where SANY reports the symbol, and two symbols at one range are one node to SANY. params
38
+ // holds the arity of each parameter of a defined operator.
39
+ interface Binding {
40
+ kind: SymbolKind;
21
41
  arity: number;
22
- declaration?: "Constant" | "Variable";
42
+ params?: number[];
43
+ range?: SourceRange;
44
+ }
45
+
46
+ export interface ModuleSymbol extends Binding {
47
+ key: string;
23
48
  }
24
49
 
25
50
  export type Symbols = Map<string, ModuleSymbol>;
26
51
 
27
- interface LocalName {
52
+ // A named theorem or proof step whose parts a name such as foo!lab or <1>2!1 selects. isInProof
53
+ // holds while SANY analyzes the proof of the theorem or step.
54
+ interface Goal {
55
+ statement: Expression | AssumeProve;
56
+ isSuffices: boolean;
57
+ isInProof: boolean;
58
+ }
59
+
60
+ // isPending holds for an operator a RECURSIVE declaration names until its definition.
61
+ // isNonFact holds for the name of a USE, HIDE, DEFINE or INSTANCE step, which SANY takes neither as
62
+ // a fact nor as an expression.
63
+ interface LocalName extends Binding {
28
64
  name: string;
29
- arity: number;
30
65
  parent: LocalName | undefined;
66
+ goal?: Goal;
67
+ isPending?: boolean;
68
+ isNonFact?: boolean;
69
+ }
70
+
71
+ // A name the module binds, from position on.
72
+ interface ModuleBinding extends Binding {
73
+ position: SourceLocation;
74
+ isPending?: boolean;
31
75
  }
32
76
 
77
+ // errors and warnings collect what SANY reports while it goes on analyzing the unit, and bindings
78
+ // holds the names the module binds. A label may appear where hasLabelScope holds, in a definition, a
79
+ // named theorem, or a numbered step, except where isLabelForbidden holds, in the scope of a NEW in a
80
+ // nested ASSUME, or where isInExcept holds, in the new value of an EXCEPT. labelParams holds the
81
+ // names bound since the innermost definition, label, or step, which a label must take as parameters,
82
+ // and labels the labels there. isGenerated holds in a definition tla-ts generates for a LET INSTANCE,
83
+ // and in a subexpression that a name selects, which SANY analyzes where it is defined.
84
+ // getInstance gives what an INSTANCE in a LET or a proof instantiates.
33
85
  interface Unit {
34
86
  imported: Symbols;
87
+ getInstance: (instance: Instance) => InstancedModule;
35
88
  definitions: Map<string, Definition>;
36
89
  getKey: (definition: Definition) => string;
37
90
  location: SourceLocation;
38
91
  self: Definition | undefined;
39
92
  facts: Set<string>;
93
+ goals: Map<string, Goal>;
94
+ bindings: Map<string, ModuleBinding>;
95
+ errors: SanyError[];
96
+ warnings: SanyError[];
97
+ hasLabelScope: boolean;
98
+ isLabelForbidden: boolean;
99
+ isInExcept: boolean;
100
+ labelParams: string[];
101
+ labels: Set<string>;
102
+ isGenerated: boolean;
103
+ }
104
+
105
+ interface SelectionError {
106
+ args: Expression[];
107
+ error: SanyError;
40
108
  }
41
109
 
110
+ interface SelectionState {
111
+ node: Expression | NewSymbol | AssumeProve;
112
+ isGoal: boolean;
113
+ isSufficesOpen: boolean;
114
+ }
115
+
116
+ type Reference = Expression & { kind: "Identifier" | "Apply" | "Subexpression" };
117
+
42
118
  export const LOCAL_RESOLUTION = { kind: "Local" } as const;
43
119
 
120
+ // The subexpressions that names select, and for a name that selects none, the error SANY reports and
121
+ // the arguments it analyzes before it.
122
+ export const selections = new WeakSet<Expression>();
123
+ export const selectionErrors = new WeakMap<Expression, SelectionError>();
124
+
44
125
  const renamedArities = new WeakMap<Expression, number>();
45
126
 
46
127
  export const KEY_SEPARATOR = "@";
@@ -52,7 +133,7 @@ const isKey = (name: string) => {
52
133
  };
53
134
 
54
135
  const CORE_SYMBOLS: Symbols = new Map(
55
- ["~>", "-+->", "\\cdot"].map((name) => [name, { key: name, arity: 2 }]),
136
+ ["~>", "-+->", "\\cdot"].map((name) => [name, { key: name, arity: 2, kind: "Builtin" }]),
56
137
  );
57
138
 
58
139
  export const isBefore = (left: SourceLocation, right: SourceLocation) =>
@@ -61,6 +142,9 @@ export const isBefore = (left: SourceLocation, right: SourceLocation) =>
61
142
  export const getArity = (definition: Definition) =>
62
143
  definition.kind === "Operator" ? definition.params.length : 0;
63
144
 
145
+ export const getParamArities = (definition: Definition) =>
146
+ definition.kind === "Operator" ? definition.params.map((param) => param.arity) : [];
147
+
64
148
  const isInstantiated = (definition: Definition) => definition.name.includes("!");
65
149
 
66
150
  const lookupLocal = (scope: LocalName | undefined, name: string) => {
@@ -70,12 +154,99 @@ const lookupLocal = (scope: LocalName | undefined, name: string) => {
70
154
  return undefined;
71
155
  };
72
156
 
73
- const bindNames = (scope: LocalName | undefined, names: string[], arity = 0) =>
74
- names.reduce<LocalName | undefined>((parent, name) => ({ name, arity, parent }), scope);
157
+ // A name the module binds before the unit and before the range, which a copy of a subexpression
158
+ // that a reference selects keeps from its definition.
159
+ const getModuleBinding = (name: string, unit: Unit, range: SourceRange | undefined) => {
160
+ const binding = unit.bindings.get(name);
161
+ return binding &&
162
+ isBefore(binding.position, unit.location) &&
163
+ (!range || isBefore(binding.position, range.start))
164
+ ? binding
165
+ : undefined;
166
+ };
167
+
168
+ const isSameRange = (left: SourceRange | undefined, right: SourceRange | undefined) =>
169
+ left !== undefined && right !== undefined && formatRange(left) === formatRange(right);
170
+
171
+ // SymbolTable.addSymbol binds a name nothing binds yet. It rejects a built-in operator, a parameter
172
+ // or bound name already in use, and a symbol of another kind or arity than the one bound, and warns
173
+ // of any other duplicate. tla-ts binds a symbol SANY never sees, such as one it generates. Tells
174
+ // whether to bind the added symbol.
175
+ const isBindable = (name: string, current: Binding | undefined, added: Binding, unit: Unit) => {
176
+ if (current === undefined) return true;
177
+ if (isSameRange(current.range, added.range)) return false;
178
+ const range = added.range;
179
+ if (range === undefined || unit.isGenerated || (current.kind !== "Builtin" && !current.range)) {
180
+ return true;
181
+ }
182
+ const location = formatRange(range);
183
+ const existing = current.range && formatRange(current.range);
184
+ if (current.kind === "Builtin") {
185
+ unit.errors.push({
186
+ location,
187
+ message: `Symbol ${name} is a built-in operator, and cannot be redefined.`,
188
+ });
189
+ } else if (
190
+ added.kind === "Parameter" ||
191
+ current.kind !== added.kind ||
192
+ current.arity !== added.arity
193
+ ) {
194
+ unit.errors.push({
195
+ location,
196
+ message: `Multiply-defined symbol '${name}': this definition or declaration conflicts \nwith the one at ${existing}.`,
197
+ });
198
+ } else {
199
+ unit.warnings.push({
200
+ location,
201
+ message: `Multiple declarations or definitions for symbol ${name}. \nThis duplicates the one at ${existing}.`,
202
+ });
203
+ }
204
+ return false;
205
+ };
206
+
207
+ const bindName = (
208
+ scope: LocalName | undefined,
209
+ name: string,
210
+ added: Binding,
211
+ unit: Unit,
212
+ ): LocalName | undefined =>
213
+ isBindable(
214
+ name,
215
+ lookupLocal(scope, name) ?? getModuleBinding(name, unit, added.range),
216
+ added,
217
+ unit,
218
+ )
219
+ ? { ...added, name, parent: scope }
220
+ : scope;
221
+
222
+ // Binds the names of a module from the unit on.
223
+ const bindModuleName = (name: string, added: Binding, unit: Unit) => {
224
+ if (isBindable(name, unit.bindings.get(name), added, unit)) {
225
+ unit.bindings.set(name, { ...added, position: unit.location });
226
+ }
227
+ };
228
+
229
+ const bindNames = (
230
+ scope: LocalName | undefined,
231
+ names: string[],
232
+ ranges: SourceRange[] | undefined,
233
+ unit: Unit,
234
+ ) =>
235
+ names.reduce(
236
+ (parent, name, index) =>
237
+ bindName(parent, name, { kind: "Parameter", arity: 0, range: ranges?.[index] }, unit),
238
+ scope,
239
+ );
75
240
 
76
- const bindParams = (scope: LocalName | undefined, params: OperatorParam[]) =>
77
- params.reduce<LocalName | undefined>(
78
- (parent, param) => ({ name: param.name, arity: param.arity, parent }),
241
+ const bindParams = (scope: LocalName | undefined, params: OperatorParam[], unit: Unit) =>
242
+ params.reduce(
243
+ (parent, param) =>
244
+ bindName(
245
+ parent,
246
+ param.name,
247
+ { kind: "Parameter", arity: param.arity, range: param.location?.range },
248
+ unit,
249
+ ),
79
250
  scope,
80
251
  );
81
252
 
@@ -98,19 +269,452 @@ const getVisibleDefinition = (name: string, unit: Unit) => {
98
269
  const findSymbol = (name: string, unit: Unit): ModuleSymbol | undefined => {
99
270
  const definition = getVisibleDefinition(name, unit);
100
271
  return definition
101
- ? { key: unit.getKey(definition), arity: getArity(definition) }
272
+ ? {
273
+ key: unit.getKey(definition),
274
+ arity: getArity(definition),
275
+ params: getParamArities(definition),
276
+ kind: "Definition",
277
+ }
102
278
  : unit.imported.get(name);
103
279
  };
104
280
 
281
+ const findBinding = (name: string, scope: LocalName | undefined, unit: Unit): Binding | undefined =>
282
+ lookupLocal(scope, name) ?? findSymbol(name, unit);
283
+
284
+ // SANY reports a name at the range of its text.
285
+ const getNameRange = (location: SourceLocation, name: string): SourceRange => ({
286
+ module: location.range?.module ?? "",
287
+ start: location,
288
+ end: { line: location.line, column: location.column + name.length - 1 },
289
+ });
290
+
291
+ // SANY reports a name at its tokens, such as M ! ⊕ for M!\oplus.
292
+ const getSpelledNameRange = (
293
+ expression: Expression & { kind: "Identifier" | "Apply" | "OperatorReference" },
294
+ name: string,
295
+ ): SourceRange => {
296
+ const selectorRange =
297
+ expression.kind === "OperatorReference" ? undefined : expression.selectorRanges?.at(-1);
298
+ return selectorRange
299
+ ? { module: selectorRange.module, start: expression.location, end: selectorRange.end }
300
+ : getNameRange(expression.location, expression.spelling ?? name);
301
+ };
302
+
303
+ // SANY reports an operator symbol applied to operands as one it cannot resolve.
304
+ const getFixity = (expression: Expression) => {
305
+ if (expression.kind !== "Apply") return undefined;
306
+ if (expression.args.length === 2) return "infix";
307
+ if (expression.args.length !== 1) return undefined;
308
+ return isBefore(expression.location, expression.args[0].location) ? "prefix" : "postfix";
309
+ };
310
+
105
311
  // SANY names an undefined operator symbol such as + differently from an undefined identifier.
106
- const isOperatorSymbol = (name: string) =>
107
- name[0].toLowerCase() === name[0].toUpperCase() &&
108
- name[0] !== "_" &&
109
- (name[0] < "0" || name[0] > "9");
312
+ const isOperatorSymbol = (name: string) => !/^[\p{L}\d_]/u.test(name);
110
313
 
111
314
  const isStepName = (name: string) =>
112
315
  name.startsWith("<") && ((name[1] >= "0" && name[1] <= "9") || name[1] === "*");
113
316
 
317
+ export const getOperandIndex = (operand: number | "<<" | ">>", count: number) => {
318
+ if (typeof operand === "number") return operand >= 1 && operand <= count ? operand - 1 : -1;
319
+ if (operand === "<<") return count > 0 ? 0 : -1;
320
+ return count === 2 ? 1 : -1;
321
+ };
322
+
323
+ // The parts of a name such as F(x)!l(y), each with its own arguments. counts holds the number each
324
+ // part takes, when a part before the last takes some.
325
+ export const getNameSelectors = (
326
+ name: string,
327
+ args: Expression[],
328
+ counts: number[] | undefined,
329
+ ): Selector[] => {
330
+ const parts = name.split("!");
331
+ const partCounts =
332
+ counts ?? parts.map((_, index) => (index === parts.length - 1 ? args.length : 0));
333
+ return parts.map((part, index) => {
334
+ const start = partCounts.slice(0, index).reduce((sum, count) => sum + count, 0);
335
+ return { kind: "Name", name: part, args: args.slice(start, start + partCounts[index]) };
336
+ });
337
+ };
338
+
339
+ const getSelectors = (reference: Reference): Selector[] =>
340
+ reference.kind === "Subexpression"
341
+ ? reference.selectors
342
+ : reference.kind === "Identifier"
343
+ ? getNameSelectors(reference.name, [], undefined)
344
+ : getNameSelectors(reference.operator, reference.args, reference.argumentCounts);
345
+
346
+ const getBoundSets = (bounds: Bound[]) =>
347
+ bounds
348
+ .filter((bound, index) => index === 0 || bounds[index - 1].set !== bound.set)
349
+ .map((bound) => bound.set);
350
+
351
+ // The names a binder binds, its body, and the sets it binds them to, which a selector such as !1
352
+ // chooses from.
353
+ export const getBinder = (
354
+ expression: Expression,
355
+ ): { names: string[]; body: Expression; sets: Expression[] } | undefined => {
356
+ switch (expression.kind) {
357
+ case "Forall":
358
+ case "Exists":
359
+ case "FunctionConstruction":
360
+ return {
361
+ names: getBoundNames(expression.bounds),
362
+ body: expression.body,
363
+ sets: getBoundSets(expression.bounds),
364
+ };
365
+ case "SetMap":
366
+ return {
367
+ names: getBoundNames(expression.bounds),
368
+ body: expression.expression,
369
+ sets: getBoundSets(expression.bounds),
370
+ };
371
+ case "SetFilter":
372
+ return {
373
+ names: getPatternNames(expression.bound.pattern),
374
+ body: expression.predicate,
375
+ sets: [expression.bound.set],
376
+ };
377
+ case "Choose":
378
+ return {
379
+ names: getPatternNames(expression.pattern),
380
+ body: expression.body,
381
+ sets: expression.set ? [expression.set] : [],
382
+ };
383
+ case "UnboundedQuantifier":
384
+ case "Lambda":
385
+ return {
386
+ names: expression.kind === "Lambda" ? expression.params : expression.names,
387
+ body: expression.body,
388
+ sets: [],
389
+ };
390
+ default:
391
+ return undefined;
392
+ }
393
+ };
394
+
395
+ // The operands that a selector such as !1 chooses from, where they do not depend on bound names.
396
+ export const getOperands = (expression: Expression): Expression[] | undefined => {
397
+ switch (expression.kind) {
398
+ case "Apply":
399
+ return expression.args;
400
+ case "And":
401
+ case "Or":
402
+ return expression.operands;
403
+ case "If":
404
+ return [expression.condition, expression.consequent, expression.alternative];
405
+ case "Tuple":
406
+ case "SetEnumeration":
407
+ return expression.elements;
408
+ case "Record":
409
+ case "RecordSet":
410
+ return expression.fields.map((field) => field.value);
411
+ case "FunctionApplication":
412
+ return [
413
+ expression.function,
414
+ expression.args.length === 1
415
+ ? expression.args[0]
416
+ : { kind: "Tuple", elements: expression.args, location: expression.location },
417
+ ];
418
+ case "FieldAccess":
419
+ return [
420
+ expression.record,
421
+ { kind: "String", value: expression.field, location: expression.location },
422
+ ];
423
+ case "Prime":
424
+ case "Unchanged":
425
+ case "Enabled":
426
+ case "Always":
427
+ case "Eventually":
428
+ return [expression.expression];
429
+ case "BoxAction":
430
+ case "AngleAction":
431
+ return [expression.action, expression.subscript];
432
+ case "WeakFairness":
433
+ case "StrongFairness":
434
+ return [expression.subscript, expression.action];
435
+ case "FunctionSet":
436
+ return [expression.domain, expression.range];
437
+ case "Product":
438
+ return expression.factors;
439
+ case "Except":
440
+ return [expression.function];
441
+ default:
442
+ return undefined;
443
+ }
444
+ };
445
+
446
+ const isReference = (expression: Expression): expression is Reference =>
447
+ expression.kind === "Identifier" ||
448
+ expression.kind === "Apply" ||
449
+ expression.kind === "Subexpression";
450
+
451
+ const isInScopeOfDeclaration = (assumeProve: AssumeProve, clause: number) =>
452
+ assumeProve.assumptions.slice(0, clause).some((assumption) => assumption.kind === "NewSymbol");
453
+
454
+ const findLabel = (expression: Expression, name: string): LabelExpression | undefined => {
455
+ if (expression.kind === "Label") return expression.name === name ? expression : undefined;
456
+ if (expression.kind === "Lambda") return undefined;
457
+ if (expression.kind === "Let") return findLabel(expression.body, name);
458
+ return getChildren(expression).reduce<LabelExpression | undefined>(
459
+ (found, child) => found ?? findLabel(child, name),
460
+ undefined,
461
+ );
462
+ };
463
+
464
+ // SANY drops a label in the scope of a NEW in a nested ASSUME, after it reports the label.
465
+ const findClauseLabel = (
466
+ clause: Expression | NewSymbol | AssumeProve,
467
+ name: string,
468
+ isForbidden: boolean,
469
+ ): LabelExpression | undefined => {
470
+ if (clause.kind === "AssumeProve") {
471
+ return [...clause.assumptions, clause.conclusion].reduce<LabelExpression | undefined>(
472
+ (found, inner, index) =>
473
+ found ?? findClauseLabel(inner, name, isForbidden || isInScopeOfDeclaration(clause, index)),
474
+ undefined,
475
+ );
476
+ }
477
+ if (isForbidden) return undefined;
478
+ if (clause.kind === "NewSymbol") return clause.set && findLabel(clause.set, name);
479
+ return findLabel(clause, name);
480
+ };
481
+
482
+ const getLabelBody = (expression: Expression): Expression =>
483
+ expression.kind === "Label" ? getLabelBody(expression.body) : expression;
484
+
485
+ const getOperandName = (operand: number | "<<" | ">>") =>
486
+ typeof operand === "number" ? `argument selector ${operand}` : operand;
487
+
488
+ const SCOPE_MESSAGE = "within the scope of a declaration\n from outside that declaration's scope.";
489
+
490
+ // Generator.selectorToNode for a name that selects part of a theorem or step. A part in the scope of
491
+ // a NEW in its ASSUME may be selected only within the proof of the theorem, or only after the proof
492
+ // of a SUFFICES step. A label takes its own arguments, and an operand must exist, unless the part
493
+ // selected depends on bound names. A fact may select an ASSUME/PROVE or a NEW clause.
494
+ const checkSelection = (
495
+ reference: Reference,
496
+ selectors: Selector[],
497
+ goal: Goal,
498
+ scope: LocalName | undefined,
499
+ unit: Unit,
500
+ isFact: boolean,
501
+ ) => {
502
+ const report = (index: number | undefined, message: string) => {
503
+ const range =
504
+ (index === undefined ? undefined : reference.selectorRanges?.[index]) ??
505
+ reference.location.range;
506
+ if (range) unit.errors.push({ location: formatRange(range), message });
507
+ };
508
+ const isOutOfScope = goal.isSuffices === goal.isInProof;
509
+ const statement = goal.statement;
510
+ const state: SelectionState = {
511
+ node: statement,
512
+ isGoal: true,
513
+ isSufficesOpen: goal.isSuffices,
514
+ };
515
+ for (const [offset, selector] of selectors.slice(1).entries()) {
516
+ const index = offset + 1;
517
+ const node = state.node;
518
+ if (selector.kind === "Name") {
519
+ if (selectors[index - 1].kind !== "Name") {
520
+ const isLet =
521
+ node.kind !== "NewSymbol" &&
522
+ node.kind !== "AssumeProve" &&
523
+ getLabelBody(node).kind === "Let";
524
+ return isLet
525
+ ? undefined
526
+ : report(index - 1, "A name selector here must be from a LET clause.");
527
+ }
528
+ const clauses =
529
+ statement.kind === "AssumeProve"
530
+ ? [...statement.assumptions, statement.conclusion]
531
+ : [statement];
532
+ const found =
533
+ index === 1
534
+ ? clauses
535
+ .map((clause, position) => ({
536
+ position,
537
+ label: findClauseLabel(clause, selector.name, false),
538
+ }))
539
+ .find((item) => item.label !== undefined)
540
+ : {
541
+ position: 0,
542
+ label: node.kind === "Label" ? findLabel(node.body, selector.name) : undefined,
543
+ };
544
+ if (!found?.label) return report(index, `Cannot find label \`${selector.name}'.`);
545
+ if (
546
+ index === 1 &&
547
+ statement.kind === "AssumeProve" &&
548
+ isInScopeOfDeclaration(statement, found.position) &&
549
+ isOutOfScope
550
+ ) {
551
+ return report(
552
+ 1,
553
+ `Accessing subexpression labeled \`${selector.name}' of ASSUME/PROVE clause ${SCOPE_MESSAGE}`,
554
+ );
555
+ }
556
+ if (selector.args.length !== found.label.params.length) {
557
+ return report(index, `Label \`${selector.name}' used with wrong number of arguments.`);
558
+ }
559
+ state.node = found.label;
560
+ state.isGoal = false;
561
+ state.isSufficesOpen = false;
562
+ continue;
563
+ }
564
+ if (selector.kind !== "Operand") return;
565
+ const operand = getOperandName(selector.operand);
566
+ if (state.isSufficesOpen) {
567
+ if (getOperandIndex(selector.operand, 1) !== 0) {
568
+ return report(
569
+ index,
570
+ node.kind === "AssumeProve"
571
+ ? "Accessing non-existent subexpression of a SUFFICES"
572
+ : `Nonexistent operand specified by \`${operand}'.`,
573
+ );
574
+ }
575
+ state.isSufficesOpen = false;
576
+ continue;
577
+ }
578
+ if (node.kind === "NewSymbol") return;
579
+ if (node.kind !== "AssumeProve") {
580
+ const expression = getLabelBody(node);
581
+ if (["Number", "Decimal", "String"].includes(expression.kind)) {
582
+ return report(index, "Selecting subexpression of expression that has none.");
583
+ }
584
+ const kind =
585
+ expression.kind === "Identifier"
586
+ ? findBinding(expression.name, scope, unit)?.kind
587
+ : undefined;
588
+ if (kind === "Variable" || kind?.startsWith("New")) {
589
+ return report(index, `Choosing operand \`${operand}' of subexpression with no operands.`);
590
+ }
591
+ const sets = getBinder(expression)?.sets;
592
+ const operands =
593
+ expression.kind === "Identifier"
594
+ ? []
595
+ : sets
596
+ ? sets.length > 0
597
+ ? sets
598
+ : undefined
599
+ : expression.kind === "Except"
600
+ ? undefined
601
+ : getOperands(expression);
602
+ if (!operands) return;
603
+ const position = getOperandIndex(selector.operand, operands.length);
604
+ if (position === -1) return report(index, `Nonexistent operand specified by \`${operand}'.`);
605
+ state.node = operands[position];
606
+ state.isGoal = false;
607
+ continue;
608
+ }
609
+ const clauses = [...node.assumptions, node.conclusion];
610
+ const position = getOperandIndex(selector.operand, clauses.length);
611
+ if (position === -1) return report(index, `Nonexistent operand specified by \`${operand}'.`);
612
+ if (isInScopeOfDeclaration(node, position) && (!state.isGoal || isOutOfScope)) {
613
+ return report(index, `Accessing ASSUME/PROVE clause ${SCOPE_MESSAGE}`);
614
+ }
615
+ const clause = clauses[position];
616
+ if (clause.kind === "NewSymbol" && index !== selectors.length - 1) {
617
+ return report(index, "Selected a subexpression of a NEW clause of an ASSUME.");
618
+ }
619
+ state.node = clause;
620
+ state.isGoal = false;
621
+ }
622
+ if (isFact) return;
623
+ if (state.node.kind === "AssumeProve") {
624
+ report(undefined, "Selected ASSUME/PROVE instead of expression.");
625
+ }
626
+ if (state.node.kind === "NewSymbol") {
627
+ report(undefined, "Selected a NEW declaration as an expression or operator.");
628
+ }
629
+ };
630
+
631
+ // Generator.generateLabel reports a label where it may not appear, and skips the label's body.
632
+ const isLabelReported = (label: LabelExpression, unit: Unit) => {
633
+ const message = unit.isGenerated
634
+ ? undefined
635
+ : !unit.hasLabelScope
636
+ ? "Label not in definition or proof step."
637
+ : unit.isLabelForbidden
638
+ ? "Label not allowed within scope of declaration in nested ASSUME/PROVE."
639
+ : unit.isInExcept
640
+ ? "Labels inside EXCEPT clauses are not yet implemented."
641
+ : undefined;
642
+ if (message === undefined || !label.location.range) return false;
643
+ unit.errors.push({ location: formatRange(label.location.range), message });
644
+ return true;
645
+ };
646
+
647
+ // Generator.generateLabel reports, after the label's body, each parameter that names no bound name,
648
+ // then formalParamsEqual each parameter given twice, each name bound since the label scope began
649
+ // that the label leaves out, and the parameters it adds, and then a label of a name already used.
650
+ const checkLabel = (label: LabelExpression, scope: LocalName | undefined, unit: Unit) => {
651
+ const range = label.location.range;
652
+ if (!range || unit.isGenerated) return;
653
+ const location = formatRange(range);
654
+ const legal = label.params.filter((param, index) => {
655
+ const isLegal = lookupLocal(scope, param)?.kind === "Parameter";
656
+ const paramRange = label.paramRanges?.[index];
657
+ if (!isLegal && paramRange) {
658
+ unit.errors.push({
659
+ location: formatRange(paramRange),
660
+ message: `Illegal parameter ${param} of label \`${label.name}'.`,
661
+ });
662
+ }
663
+ return isLegal;
664
+ });
665
+ legal
666
+ .filter((param, index) => legal.indexOf(param) !== index)
667
+ .forEach((param) =>
668
+ unit.errors.push({
669
+ location,
670
+ message: `Repeated formal parameter ${param} \nin label \`${label.name}'.`,
671
+ }),
672
+ );
673
+ unit.labelParams
674
+ .filter((param) => !legal.includes(param))
675
+ .forEach((param) =>
676
+ unit.errors.push({
677
+ location,
678
+ message: `Label ${label.name} must contain formal parameter \`${param}'.`,
679
+ }),
680
+ );
681
+ const extra = [
682
+ ...new Set(legal.filter((param) => !unit.labelParams.includes(param))),
683
+ ...label.params.filter((param) => !legal.includes(param)),
684
+ ];
685
+ if (extra.length > 0) {
686
+ unit.errors.push({
687
+ location,
688
+ message: `Label ${label.name} declares extra parameter(s) ${extra.map((param) => `${param} `).join("")}`,
689
+ });
690
+ }
691
+ if (unit.labels.has(label.name)) {
692
+ unit.errors.push({ location, message: `Duplicate label \`${label.name}'.` });
693
+ }
694
+ unit.labels.add(label.name);
695
+ };
696
+
697
+ // Checks a name that selects part of a theorem or step, and tells whether it is one.
698
+ const checkReference = (
699
+ expression: Expression,
700
+ scope: LocalName | undefined,
701
+ unit: Unit,
702
+ isFact: boolean,
703
+ ) => {
704
+ if (!isReference(expression)) return false;
705
+ const selectors = getSelectors(expression);
706
+ const first = selectors[0];
707
+ const goal =
708
+ selectors.length > 1 && first.kind === "Name"
709
+ ? (lookupLocal(scope, first.name)?.goal ?? unit.goals.get(first.name))
710
+ : undefined;
711
+ if (goal) checkSelection(expression, selectors, goal, scope, unit, isFact);
712
+ return goal !== undefined;
713
+ };
714
+
715
+ // Generator.selectorToNode reports an unknown operator and goes on without analyzing its arguments,
716
+ // so its arity is undefined. It does the same for an operator given the wrong number of arguments,
717
+ // and for a name that selects nothing, after the arguments of the parts before.
114
718
  const getSymbolArity = (
115
719
  expression: Expression & { kind: "Identifier" | "Apply" | "OperatorReference" },
116
720
  name: string,
@@ -118,11 +722,21 @@ const getSymbolArity = (
118
722
  unit: Unit,
119
723
  ) => {
120
724
  const location = expression.location;
725
+ if (isSelectionReported(expression, scope, unit)) return undefined;
121
726
  const renamed = renamedArities.get(expression);
122
727
  if (renamed !== undefined) return renamed;
123
728
  if (isKey(name)) return expression.kind === "Apply" ? expression.args.length : 0;
124
- if (isStepName(name)) return 0;
125
729
  const local = lookupLocal(scope, name);
730
+ if (local?.isNonFact) {
731
+ unit.errors.push({
732
+ location: formatRange(getSpelledNameRange(expression, name)),
733
+ message: "Step number of non-expression step used as an expression.",
734
+ });
735
+ return undefined;
736
+ }
737
+ if (checkReference(expression, scope, unit, false) || (isStepName(name) && local)) {
738
+ return expression.kind === "Apply" ? expression.args.length : 0;
739
+ }
126
740
  if (local && expression.kind !== "OperatorReference") expression.resolution = LOCAL_RESOLUTION;
127
741
  if (local) return local.arity;
128
742
  const symbol = findSymbol(name, unit);
@@ -134,7 +748,7 @@ const getSymbolArity = (
134
748
  }
135
749
  // A name such as Inv!P1 selects the label P1 of a definition or theorem, which takes its own
136
750
  // arguments.
137
- const prefix = name.slice(0, name.indexOf("!"));
751
+ const prefix = name.includes("!") ? name.slice(0, name.indexOf("!")) : "";
138
752
  const isSelected =
139
753
  prefix !== "" &&
140
754
  (lookupLocal(scope, prefix) !== undefined ||
@@ -143,18 +757,35 @@ const getSymbolArity = (
143
757
  if (isSelected) {
144
758
  return expression.kind === "Apply" ? expression.args.length : 0;
145
759
  }
146
- const position = `at line ${location.line}, column ${location.column}`;
147
- throw new TlaSyntaxError(
148
- isOperatorSymbol(name)
149
- ? `Could not find declaration or definition of symbol '${name}' ${position}`
150
- : `Unknown operator: \`${name}' ${position}`,
760
+ const spelling = (expression.kind === "Identifier" ? undefined : expression.spelling) ?? name;
761
+ const range = formatRange(
762
+ expression.kind === "Apply" && spelling === "-."
763
+ ? getNameRange(location, "-")
764
+ : getSpelledNameRange(expression, name),
151
765
  );
766
+ if (!isOperatorSymbol(name) || isStepName(name)) {
767
+ unit.errors.push({ location: range, message: `Unknown operator: \`${name}'.` });
768
+ return undefined;
769
+ }
770
+ unit.errors.push({
771
+ location: range,
772
+ message: `Could not find declaration or definition of symbol '${spelling}'.`,
773
+ });
774
+ const fixity = getFixity(expression);
775
+ if (fixity && location.range) {
776
+ unit.errors.push({
777
+ location: formatRange(location.range),
778
+ message: `Couldn't resolve ${fixity} operator symbol \`${spelling}'.`,
779
+ });
780
+ }
781
+ return undefined;
152
782
  };
153
783
 
154
784
  const resolveBounds = (bounds: Bound[], scope: LocalName | undefined, unit: Unit) => {
155
785
  bounds.forEach((bound) => resolveExpression(bound.set, scope, unit));
156
786
  return bounds.reduce(
157
- (current, bound) => bindNames(current, getPatternNames(bound.pattern)),
787
+ (current, bound) =>
788
+ bindNames(current, getPatternNames(bound.pattern), bound.pattern.ranges, unit),
158
789
  scope,
159
790
  );
160
791
  };
@@ -170,94 +801,286 @@ const markRecursiveConstructions = (expression: Expression, name: string): void
170
801
  getChildren(expression).forEach((child) => markRecursiveConstructions(child, name));
171
802
  };
172
803
 
173
- const resolveDefinition = (definition: Definition, scope: LocalName | undefined, unit: Unit) => {
174
- const self = bindNames(scope, definition.kind === "Function" ? [definition.name] : []);
804
+ // Generator.processOperator binds the parameters, reports a name already bound unless a RECURSIVE
805
+ // declaration of this level awaits the definition, analyzes the body, and then binds the name.
806
+ // processFunction binds the bound names before it looks up the name, and binds the name only where
807
+ // nothing else does. recursive holds the declarations of this level. Tells whether to bind the name.
808
+ const resolveDefinition = (
809
+ definition: Definition,
810
+ scope: LocalName | undefined,
811
+ outer: Unit,
812
+ recursive: Set<Binding>,
813
+ ) => {
814
+ const unit = {
815
+ ...outer,
816
+ hasLabelScope: true,
817
+ labelParams: definition.kind === "Function" ? getBoundNames(definition.bounds) : [],
818
+ labels: new Set<string>(),
819
+ };
820
+ const name = definition.name;
821
+ const range = definition.location.range;
822
+ const report = (message: string) => {
823
+ if (range && !unit.isGenerated) unit.errors.push({ location: formatRange(range), message });
824
+ };
825
+ const inner =
826
+ definition.kind === "Function"
827
+ ? resolveBounds(definition.bounds, scope, unit)
828
+ : bindParams(scope, definition.params, unit);
829
+ const current = lookupLocal(inner, name) ?? getModuleBinding(name, unit, range);
830
+ const isDeclared = current?.isPending === true && recursive.has(current);
831
+ if (current?.isPending && !isDeclared) {
832
+ report(
833
+ `Recursive ${definition.kind === "Function" ? "function" : "operator"} ${name} defined at wrong LET/IN level.`,
834
+ );
835
+ } else if (current && !isDeclared) {
836
+ report(
837
+ definition.kind === "Function"
838
+ ? `Function name \`${name}' already defined or declared.`
839
+ : `Operator ${name} already defined or declared.`,
840
+ );
841
+ }
175
842
  if (definition.kind === "Function") {
176
- resolveExpression(definition.body, resolveBounds(definition.bounds, self, unit), unit);
177
- markRecursiveConstructions(definition.body, definition.name);
178
- return;
843
+ resolveExpression(
844
+ definition.body,
845
+ { name, kind: "Parameter", arity: 0, range, parent: inner },
846
+ unit,
847
+ );
848
+ markRecursiveConstructions(definition.body, name);
849
+ definition.isSelfReferential = isReferenced(definition.body, name);
850
+ } else resolveExpression(definition.body, inner, unit);
851
+ if (current && isDeclared) {
852
+ current.isPending = false;
853
+ current.range = range;
854
+ return false;
179
855
  }
180
- resolveExpression(definition.body, bindParams(self, definition.params), unit);
856
+ return definition.kind === "Function"
857
+ ? current === undefined
858
+ : isBindable(
859
+ name,
860
+ lookupLocal(scope, name) ?? getModuleBinding(name, unit, range),
861
+ { kind: "Definition", arity: getArity(definition), range },
862
+ unit,
863
+ );
181
864
  };
182
865
 
866
+ // SANY analyzes an INSTANCE in a LET where it appears, before the definitions that follow it, which
867
+ // tla-ts generates at its location and analyzes without reporting.
183
868
  const resolveDefinitions = (
184
869
  definitions: Definition[],
185
870
  scope: LocalName | undefined,
186
871
  unit: Unit,
872
+ instances: Instance[] = [],
187
873
  ) => {
188
- const recursiveScope = definitions
874
+ const recursive = new Set<Binding>();
875
+ const declared = definitions
189
876
  .filter((definition) => definition.isRecursive)
190
- .reduce<LocalName | undefined>(
191
- (parent, definition) => ({ name: definition.name, arity: getArity(definition), parent }),
192
- scope,
193
- );
194
- return definitions.reduce((current, definition) => {
195
- if (!isInstantiated(definition)) resolveDefinition(definition, current, unit);
196
- return { name: definition.name, arity: getArity(definition), parent: current };
197
- }, recursiveScope);
877
+ .reduce<LocalName | undefined>((parent, definition) => {
878
+ if (lookupLocal(parent, definition.name)?.isPending) return parent;
879
+ const local: LocalName = {
880
+ name: definition.name,
881
+ arity: getArity(definition),
882
+ params: getParamArities(definition),
883
+ kind: "Definition",
884
+ parent,
885
+ isPending: true,
886
+ };
887
+ recursive.add(local);
888
+ return local;
889
+ }, scope);
890
+ const pending = unit.isGenerated ? [] : [...instances];
891
+ const resolveInstances = (
892
+ current: LocalName | undefined,
893
+ isDue: (instance: Instance) => boolean,
894
+ ) => {
895
+ const count = pending.findIndex((instance) => !isDue(instance));
896
+ return pending
897
+ .splice(0, count === -1 ? pending.length : count)
898
+ .reduce((parent, instance) => resolveLocalInstance(instance, parent, unit), current);
899
+ };
900
+ const resolved = definitions.reduce<LocalName | undefined>((previous, definition) => {
901
+ const current = isKey(definition.name)
902
+ ? previous
903
+ : resolveInstances(previous, (instance) => !isBefore(definition.location, instance.location));
904
+ const local: LocalName = {
905
+ name: definition.name,
906
+ arity: getArity(definition),
907
+ kind: "Definition",
908
+ range: definition.location.range,
909
+ parent: current,
910
+ };
911
+ if (isInstantiated(definition)) return local;
912
+ const isInstanced = instances.some((instance) => instance.location === definition.location);
913
+ const isGenerated = unit.isGenerated || definition.isLocal || isKey(definition.name);
914
+ const inner = isInstanced
915
+ ? { ...unit, isGenerated: true, errors: [], warnings: [] }
916
+ : isGenerated
917
+ ? { ...unit, isGenerated }
918
+ : unit;
919
+ return resolveDefinition(definition, current, inner, recursive)
920
+ ? { ...local, params: getParamArities(definition) }
921
+ : current;
922
+ }, declared);
923
+ return resolveInstances(resolved, () => true);
198
924
  };
199
925
 
200
- // OpDefNode#match: a parameter of arity 0 takes an expression, and a parameter of arity n takes an
201
- // operator of arity n whose own parameters take expressions.
202
- const checkArgument = (
203
- definition: Definition,
204
- index: number,
205
- arg: Expression,
206
- argArity: number,
207
- argDefinition: Definition | undefined,
926
+ // The INSTANCE that a name such as K!C starts with, whose arguments SANY requires at its name.
927
+ const findInstance = (name: string, scope: LocalName | undefined, unit: Unit) => {
928
+ const prefix = name.split("!")[0];
929
+ const binding =
930
+ prefix === name
931
+ ? undefined
932
+ : (lookupLocal(scope, prefix) ?? getModuleBinding(prefix, unit, undefined));
933
+ return binding?.kind === "Instance" ? { name: prefix, arity: binding.arity } : undefined;
934
+ };
935
+
936
+ // Generator.selectorToNode reports an INSTANCE given the wrong number of arguments at its name,
937
+ // as in K!C or K(1, 2)!C, and goes on without analyzing them. Tells whether it reports one.
938
+ const isInstanceArityReported = (
939
+ expression: Expression,
940
+ scope: LocalName | undefined,
941
+ unit: Unit,
208
942
  ) => {
209
- const param = definition.kind === "Operator" ? definition.params[index] : undefined;
210
- const location = arg.location;
211
- if (param?.arity === 0 && argArity > 0) {
212
- throw new TlaSyntaxError(
213
- `Operator used in argument number ${index + 1} has incorrect number of arguments at line ${location.line}, column ${location.column}`,
214
- );
215
- }
216
- const isHigherOrder =
217
- argDefinition?.kind === "Operator" && argDefinition.params.some((inner) => inner.arity > 0);
218
- if (param !== undefined && param.arity > 0 && (argArity !== param.arity || isHigherOrder)) {
219
- throw new TlaSyntaxError(
220
- `Argument number ${index + 1} to operator '${definition.name}' should be a ${param.arity}-parameter operator at line ${location.line}, column ${location.column}`,
221
- );
943
+ if (expression.kind !== "Identifier" && expression.kind !== "Apply") return false;
944
+ const instance = findInstance(
945
+ expression.kind === "Identifier" ? expression.name : expression.operator,
946
+ scope,
947
+ unit,
948
+ );
949
+ const count = expression.kind === "Apply" ? (expression.argumentCounts?.[0] ?? 0) : 0;
950
+ if (!instance || count === instance.arity) return false;
951
+ const range =
952
+ (expression.kind === "Apply" ? expression.argumentRanges?.[0] : undefined) ??
953
+ expression.location.range;
954
+ if (range) {
955
+ unit.errors.push({
956
+ location: formatRange(range),
957
+ message: `The operator ${instance.name} requires ${instance.arity} arguments.`,
958
+ });
222
959
  }
960
+ return true;
223
961
  };
224
962
 
225
- const getArgumentName = (arg: Expression) =>
226
- arg.kind === "Identifier"
227
- ? arg.name
228
- : arg.kind === "OperatorReference"
229
- ? arg.operator
230
- : undefined;
231
-
963
+ // Generator.generateExprOrOpArg analyzes an argument as an expression, unless a defined operator
964
+ // takes an operator in its place, which a name, a built-in operator, or a LAMBDA of the parameter's
965
+ // arity must give. OpDefNode#match then reports each argument that gives no such operator, or one
966
+ // whose own parameters take operators. tla-ts lets an operator whose parameters it does not know
967
+ // take any argument.
232
968
  const resolveApply = (
233
969
  expression: Expression & { kind: "Apply" },
234
970
  scope: LocalName | undefined,
235
971
  unit: Unit,
236
972
  ) => {
237
- const callee = lookupLocal(scope, expression.operator)
238
- ? undefined
239
- : getVisibleDefinition(expression.operator, unit);
240
- const arity = getSymbolArity(expression, expression.operator, scope, unit);
973
+ if (isInstanceArityReported(expression, scope, unit)) return;
974
+ const operator = expression.operator;
975
+ const callee = findBinding(operator, scope, unit);
976
+ const arity = getSymbolArity(expression, operator, scope, unit);
977
+ if (arity === undefined) return;
241
978
  if (arity !== expression.args.length) {
242
- throw new TlaSyntaxError(
243
- `The operator ${expression.operator} requires ${arity} arguments at line ${expression.location.line}, column ${expression.location.column}`,
244
- );
979
+ unit.errors.push({
980
+ location: formatRange(expression.argumentsRange ?? getSpelledNameRange(expression, operator)),
981
+ message: `The operator ${operator} requires ${arity - (findInstance(operator, scope, unit)?.arity ?? 0)} arguments.`,
982
+ });
983
+ return;
245
984
  }
246
- expression.args.forEach((arg, index) => {
247
- const name = getArgumentName(arg);
248
- const argDefinition =
249
- name === undefined || lookupLocal(scope, name) ? undefined : getVisibleDefinition(name, unit);
250
- const argArity = resolveArgument(arg, scope, unit);
251
- if (callee) checkArgument(callee, index, arg, argArity, argDefinition);
252
- });
985
+ const params = callee && (callee.kind === "Definition" ? callee.params : []);
986
+ if (params === undefined) {
987
+ expression.args.forEach((arg) => resolveArgument(arg, scope, unit));
988
+ return;
989
+ }
990
+ const report = (range: SourceRange | undefined, message: string) => {
991
+ if (range) unit.errors.push({ location: formatRange(range), message });
992
+ };
993
+ expression.args
994
+ .map((arg, index) => {
995
+ const expected = params[index] ?? 0;
996
+ const range = arg.location.range;
997
+ if (expected === 0) {
998
+ // SANY fails on an operator here with an internal error, so tla-ts words it as it does for
999
+ // a name.
1000
+ if (arg.kind === "Lambda" && arg.operator !== undefined) {
1001
+ report(range, `The operator ${arg.operator} requires 1 arguments.`);
1002
+ } else if (arg.kind === "Lambda" && range) {
1003
+ report(range, "LAMBDA expression used where an expression is required.");
1004
+ } else if (arg.kind === "OperatorReference") {
1005
+ const argArity = getSymbolArity(arg, arg.operator, scope, unit);
1006
+ if (argArity !== undefined) {
1007
+ report(range, `The operator ${arg.operator} requires ${argArity} arguments.`);
1008
+ }
1009
+ } else resolveExpression(arg, scope, unit);
1010
+ return true;
1011
+ }
1012
+ // A name that selects a subexpression gives an operator of the names it leaves unbound.
1013
+ if (arg.kind === "Lambda") {
1014
+ resolveExpression(arg, scope, unit);
1015
+ const isMatched = arg.params.length === expected;
1016
+ if (!isMatched && selections.has(arg)) {
1017
+ report(
1018
+ range,
1019
+ `Expected arity ${expected} but found operator of arity ${arg.params.length}.`,
1020
+ );
1021
+ } else if (!isMatched && range && arg.operator === undefined) {
1022
+ report(
1023
+ expression.selectorRanges?.at(-1) ?? getSpelledNameRange(expression, operator),
1024
+ `Lambda expression with arity ${arg.params.length} used as argument ${index + 1} of operator \`${operator}', \nbut an operator of arity ${expected} is required.`,
1025
+ );
1026
+ }
1027
+ return isMatched;
1028
+ }
1029
+ if (arg.kind === "Subexpression") {
1030
+ resolveExpression(arg, scope, unit);
1031
+ return true;
1032
+ }
1033
+ // Generator.selectorToNode: a name such as K(1)!C names an operator, but none of its parts
1034
+ // may take arguments.
1035
+ if (arg.kind === "Apply" && arg.argumentCounts?.at(-1) === 0) {
1036
+ const index = arg.argumentCounts.findIndex((count) => count > 0);
1037
+ report(
1038
+ arg.selectorRanges?.[index],
1039
+ `Selector \`${arg.operator.split("!")[index]}' should not have argument(s).`,
1040
+ );
1041
+ return false;
1042
+ }
1043
+ if (arg.kind !== "Identifier" && arg.kind !== "OperatorReference") {
1044
+ report(
1045
+ range,
1046
+ `An expression appears as argument number ${index + 1} (counting from 1) to operator '${operator}', in a position an operator is required.`,
1047
+ );
1048
+ return false;
1049
+ }
1050
+ const name = arg.kind === "Identifier" ? arg.name : arg.operator;
1051
+ const argParams = findBinding(name, scope, unit)?.params ?? [];
1052
+ const argArity = getSymbolArity(arg, name, scope, unit);
1053
+ if (arg.kind === "Identifier" && argArity !== undefined && argArity !== expected) {
1054
+ report(
1055
+ getSpelledNameRange(arg, name),
1056
+ `Expected arity ${expected} but found operator of arity ${argArity}.`,
1057
+ );
1058
+ }
1059
+ return argArity === expected && argParams.every((param) => param === 0);
1060
+ })
1061
+ .forEach((isMatched, index) => {
1062
+ if (!isMatched) {
1063
+ report(
1064
+ expression.location.range,
1065
+ `Argument number ${index + 1} to operator '${operator}' \nshould be a ${params[index]}-parameter operator.`,
1066
+ );
1067
+ }
1068
+ });
253
1069
  };
254
1070
 
255
1071
  // An argument may name an operator that takes arguments of its own.
256
1072
  const resolveArgument = (arg: Expression, scope: LocalName | undefined, unit: Unit) => {
257
- if (arg.kind === "Identifier") return getSymbolArity(arg, arg.name, scope, unit);
258
- if (arg.kind === "OperatorReference") return getSymbolArity(arg, arg.operator, scope, unit);
259
- resolveExpression(arg, scope, unit);
260
- return arg.kind === "Lambda" ? arg.params.length : 0;
1073
+ if (arg.kind === "Identifier") getSymbolArity(arg, arg.name, scope, unit);
1074
+ else resolveExpression(arg, scope, unit);
1075
+ };
1076
+
1077
+ // Reports the error of a name that selects nothing, after the arguments SANY analyzes before it.
1078
+ const isSelectionReported = (expression: Expression, scope: LocalName | undefined, unit: Unit) => {
1079
+ const failed = selectionErrors.get(expression);
1080
+ if (!failed) return false;
1081
+ failed.args.forEach((arg) => resolveArgument(arg, scope, unit));
1082
+ unit.errors.push(failed.error);
1083
+ return true;
261
1084
  };
262
1085
 
263
1086
  const resolveExpression = (
@@ -265,8 +1088,16 @@ const resolveExpression = (
265
1088
  scope: LocalName | undefined,
266
1089
  unit: Unit,
267
1090
  ): void => {
1091
+ if (selections.has(expression) && !unit.isGenerated) {
1092
+ resolveExpression(expression, scope, { ...unit, isGenerated: true });
1093
+ return;
1094
+ }
268
1095
  const resolveAll = (expressions: Expression[]) =>
269
1096
  expressions.forEach((child) => resolveExpression(child, scope, unit));
1097
+ const bindLabelParams = (names: string[]) => ({
1098
+ ...unit,
1099
+ labelParams: [...unit.labelParams, ...names],
1100
+ });
270
1101
  switch (expression.kind) {
271
1102
  case "Number":
272
1103
  case "Decimal":
@@ -274,11 +1105,14 @@ const resolveExpression = (
274
1105
  case "ExceptAt":
275
1106
  return;
276
1107
  case "Identifier": {
277
- const arity = getSymbolArity(expression, expression.name, scope, unit);
278
- if (arity > 0) {
279
- throw new TlaSyntaxError(
280
- `The operator ${expression.name} requires ${arity} arguments at line ${expression.location.line}, column ${expression.location.column}`,
281
- );
1108
+ if (isInstanceArityReported(expression, scope, unit)) return;
1109
+ const name = expression.name;
1110
+ const arity = getSymbolArity(expression, name, scope, unit);
1111
+ if (arity !== undefined && arity > 0) {
1112
+ unit.errors.push({
1113
+ location: formatRange(getSpelledNameRange(expression, name)),
1114
+ message: `The operator ${name} requires ${arity} arguments.`,
1115
+ });
282
1116
  }
283
1117
  return;
284
1118
  }
@@ -289,7 +1123,11 @@ const resolveExpression = (
289
1123
  resolveApply(expression, scope, unit);
290
1124
  return;
291
1125
  case "Lambda":
292
- resolveExpression(expression.body, bindNames(scope, expression.params), unit);
1126
+ resolveExpression(
1127
+ expression.body,
1128
+ bindNames(scope, expression.params, expression.paramRanges, unit),
1129
+ bindLabelParams(expression.params),
1130
+ );
293
1131
  return;
294
1132
  case "And":
295
1133
  case "Or":
@@ -312,24 +1150,32 @@ const resolveExpression = (
312
1150
  case "Let":
313
1151
  resolveExpression(
314
1152
  expression.body,
315
- resolveDefinitions(expression.definitions, scope, unit),
1153
+ resolveDefinitions(expression.definitions, scope, unit, expression.instances),
316
1154
  unit,
317
1155
  );
318
1156
  return;
319
1157
  case "Forall":
320
1158
  case "Exists":
321
1159
  case "FunctionConstruction":
322
- resolveExpression(expression.body, resolveBounds(expression.bounds, scope, unit), unit);
1160
+ resolveExpression(
1161
+ expression.body,
1162
+ resolveBounds(expression.bounds, scope, unit),
1163
+ bindLabelParams(getBoundNames(expression.bounds)),
1164
+ );
323
1165
  return;
324
1166
  case "UnboundedQuantifier":
325
- resolveExpression(expression.body, bindNames(scope, expression.names), unit);
1167
+ resolveExpression(
1168
+ expression.body,
1169
+ bindNames(scope, expression.names, expression.nameRanges, unit),
1170
+ bindLabelParams(expression.names),
1171
+ );
326
1172
  return;
327
1173
  case "Choose":
328
1174
  if (expression.set) resolveExpression(expression.set, scope, unit);
329
1175
  resolveExpression(
330
1176
  expression.body,
331
- bindNames(scope, getPatternNames(expression.pattern)),
332
- unit,
1177
+ bindNames(scope, getPatternNames(expression.pattern), expression.pattern.ranges, unit),
1178
+ bindLabelParams(getPatternNames(expression.pattern)),
333
1179
  );
334
1180
  return;
335
1181
  case "SetEnumeration":
@@ -337,31 +1183,40 @@ const resolveExpression = (
337
1183
  resolveAll(expression.elements);
338
1184
  return;
339
1185
  case "SetFilter":
340
- resolveExpression(expression.predicate, resolveBounds([expression.bound], scope, unit), unit);
1186
+ resolveExpression(
1187
+ expression.predicate,
1188
+ resolveBounds([expression.bound], scope, unit),
1189
+ bindLabelParams(getPatternNames(expression.bound.pattern)),
1190
+ );
341
1191
  return;
342
1192
  case "SetMap":
343
- resolveExpression(expression.expression, resolveBounds(expression.bounds, scope, unit), unit);
1193
+ resolveExpression(
1194
+ expression.expression,
1195
+ resolveBounds(expression.bounds, scope, unit),
1196
+ bindLabelParams(getBoundNames(expression.bounds)),
1197
+ );
344
1198
  return;
345
1199
  case "FunctionSet":
346
1200
  resolveAll([expression.domain, expression.range]);
347
1201
  return;
348
1202
  case "Record":
349
1203
  case "RecordSet":
350
- if (new Set(expression.fields.map((field) => field.name)).size < expression.fields.length) {
351
- throw new TlaSyntaxError(
352
- `Non-unique fields in constructor at line ${expression.location.line}, column ${expression.location.column}`,
353
- );
354
- }
355
- resolveAll(expression.fields.map((field) => field.value));
1204
+ expression.fields.forEach((field, index) => {
1205
+ if (expression.fields.slice(0, index).some((earlier) => earlier.name === field.name)) {
1206
+ unit.errors.push({
1207
+ location: formatRange(field.location.range ?? getNameRange(field.location, field.name)),
1208
+ message: "Non-unique fields in constructor.",
1209
+ });
1210
+ }
1211
+ resolveExpression(field.value, scope, unit);
1212
+ });
356
1213
  return;
357
1214
  case "Except":
358
- resolveAll([
359
- expression.function,
360
- ...expression.updates.flatMap((update) => [
361
- ...update.path.flatMap((step) => (step.kind === "Index" ? step.args : [])),
362
- update.value,
363
- ]),
364
- ]);
1215
+ resolveExpression(expression.function, scope, unit);
1216
+ expression.updates.forEach((update) => {
1217
+ resolveAll(update.path.flatMap((step) => (step.kind === "Index" ? step.args : [])));
1218
+ resolveExpression(update.value, scope, { ...unit, isInExcept: true });
1219
+ });
365
1220
  return;
366
1221
  case "FunctionApplication":
367
1222
  resolveAll([expression.function, ...expression.args]);
@@ -381,34 +1236,77 @@ const resolveExpression = (
381
1236
  resolveAll([expression.subscript, expression.action]);
382
1237
  return;
383
1238
  case "Label":
384
- resolveExpression(expression.body, scope, unit);
1239
+ if (isLabelReported(expression, unit)) return;
1240
+ resolveExpression(expression.body, scope, { ...unit, labelParams: [], labels: new Set() });
1241
+ checkLabel(expression, scope, unit);
385
1242
  return;
386
- case "Subexpression":
1243
+ case "Subexpression": {
1244
+ if (isSelectionReported(expression, scope, unit)) return;
387
1245
  expression.selectors
388
1246
  .flatMap((selector) => ("args" in selector ? selector.args : []))
389
1247
  .forEach((arg) => resolveArgument(arg, scope, unit));
1248
+ checkReference(expression, scope, unit, false);
1249
+ }
390
1250
  }
391
1251
  };
392
1252
 
1253
+ // Generator.generateUseOrHide looks up a fact that is a name as it looks up a name in an expression,
1254
+ // except that the name may select an ASSUME/PROVE or a NEW clause or name a theorem or assumption,
1255
+ // and analyzes any other fact as an expression.
1256
+ const checkFacts = (facts: Fact[], scope: LocalName | undefined, unit: Unit) =>
1257
+ facts.forEach((fact) => {
1258
+ if (
1259
+ fact.kind === "ModuleFact" ||
1260
+ isInstanceArityReported(fact, scope, unit) ||
1261
+ checkReference(fact, scope, unit, true)
1262
+ ) {
1263
+ return;
1264
+ }
1265
+ const name =
1266
+ fact.kind === "Identifier" ? fact.name : fact.kind === "Apply" ? fact.operator : "";
1267
+ if (fact.kind === "Identifier" && lookupLocal(scope, name)?.isNonFact) {
1268
+ unit.errors.push({
1269
+ location: formatRange(getSpelledNameRange(fact, name)),
1270
+ message: "Step number of non-fact used as a fact",
1271
+ });
1272
+ } else if (!unit.facts.has(name)) resolveExpression(fact, scope, unit);
1273
+ });
1274
+
393
1275
  const resolveNewSymbol = (symbol: NewSymbol, scope: LocalName | undefined, unit: Unit) => {
394
1276
  if (symbol.set) resolveExpression(symbol.set, scope, unit);
395
- return { name: symbol.name, arity: symbol.arity, parent: scope };
1277
+ return bindName(
1278
+ scope,
1279
+ symbol.name,
1280
+ { kind: `New${symbol.level}`, arity: symbol.arity, range: symbol.nameRange },
1281
+ unit,
1282
+ );
396
1283
  };
397
1284
 
398
- // The NEW symbols of an ASSUME stay in scope for its conclusion and the proof that follows.
1285
+ // The NEW symbols of an ASSUME stay in scope for its conclusion and the proof that follows. SANY
1286
+ // forbids a label in the scope of a NEW in a nested ASSUME.
399
1287
  const resolveAssumeProve = (
400
1288
  assumeProve: AssumeProve,
401
1289
  scope: LocalName | undefined,
402
1290
  unit: Unit,
1291
+ isNested = false,
403
1292
  ): LocalName | undefined => {
404
- const assumed = assumeProve.assumptions.reduce((current, assumption) => {
405
- if (assumption.kind === "NewSymbol") return resolveNewSymbol(assumption, current, unit);
406
- if (assumption.kind === "AssumeProve") resolveAssumeProve(assumption, current, unit);
407
- else resolveExpression(assumption, current, unit);
408
- return current;
409
- }, scope);
410
- resolveExpression(assumeProve.conclusion, assumed, unit);
411
- return assumed;
1293
+ const assumed = assumeProve.assumptions.reduce(
1294
+ (current, assumption) => {
1295
+ if (assumption.kind === "NewSymbol") {
1296
+ return {
1297
+ scope: resolveNewSymbol(assumption, current.scope, current.unit),
1298
+ unit: isNested ? { ...current.unit, isLabelForbidden: true } : current.unit,
1299
+ };
1300
+ }
1301
+ if (assumption.kind === "AssumeProve") {
1302
+ resolveAssumeProve(assumption, current.scope, current.unit, true);
1303
+ } else resolveExpression(assumption, current.scope, current.unit);
1304
+ return current;
1305
+ },
1306
+ { scope, unit },
1307
+ );
1308
+ resolveExpression(assumeProve.conclusion, assumed.scope, assumed.unit);
1309
+ return assumed.scope;
412
1310
  };
413
1311
 
414
1312
  const resolveStatement = (
@@ -423,371 +1321,528 @@ const resolveStatement = (
423
1321
 
424
1322
  // SANY resolves the expressions of a proof, while its facts and DEF clauses may also name
425
1323
  // theorems, assumptions, and modules.
426
- const resolveProof = (proof: Proof | undefined, scope: LocalName | undefined, unit: Unit) => {
1324
+ const resolveProof = (proof: Proof | undefined, scope: LocalName | undefined, outer: Unit) => {
1325
+ const unit = outer.hasLabelScope ? { ...outer, hasLabelScope: false } : outer;
1326
+ if (proof?.kind === "By") checkFacts(proof.facts, scope, unit);
427
1327
  if (proof?.kind !== "Steps") return;
428
1328
  proof.steps.reduce((current, step) => resolveStep(step, current, unit), scope);
429
1329
  };
430
1330
 
1331
+ // A LET or a step binds the name of the INSTANCE after the names it adds.
1332
+ const resolveLocalInstance = (instance: Instance, scope: LocalName | undefined, unit: Unit) => {
1333
+ const instanced = resolveInstance(instance, scope, unit);
1334
+ return instance.name === undefined
1335
+ ? instanced
1336
+ : bindName(
1337
+ instanced,
1338
+ instance.name,
1339
+ { kind: "Instance", arity: instance.params.length, range: instance.location.range },
1340
+ unit,
1341
+ );
1342
+ };
1343
+
1344
+ // Generator.generateProof binds the name of a step after its statement and before its proof, or
1345
+ // after the step where it takes no proof.
431
1346
  const resolveStep = (
432
1347
  step: ProofStep,
433
1348
  scope: LocalName | undefined,
434
1349
  unit: Unit,
435
1350
  ): LocalName | undefined => {
436
1351
  const body = step.body;
1352
+ const stepUnit =
1353
+ step.name === undefined
1354
+ ? unit
1355
+ : { ...unit, hasLabelScope: true, labelParams: [], labels: new Set<string>() };
1356
+ const bindStep = (parent: LocalName | undefined): LocalName | undefined =>
1357
+ step.name === undefined ? parent : { name: step.name, arity: 0, kind: "Theorem", parent };
1358
+ const bindNonFactStep = (parent: LocalName | undefined): LocalName | undefined =>
1359
+ step.name === undefined
1360
+ ? parent
1361
+ : { name: step.name, arity: 0, kind: "Theorem", parent, isNonFact: true };
437
1362
  switch (body.kind) {
1363
+ // The NEW symbols of a SUFFICES ASSUME are in scope after its proof, and those of any other
1364
+ // ASSUME in its proof.
438
1365
  case "Assert": {
439
- const assumed = resolveStatement(body.statement, scope, unit);
440
- resolveProof(step.proof, assumed, unit);
441
- return body.isSuffices ? assumed : scope;
1366
+ const assumed = resolveStatement(body.statement, scope, stepUnit);
1367
+ const proofScope = body.isSuffices ? scope : assumed;
1368
+ const name = step.name;
1369
+ if (name === undefined) {
1370
+ resolveProof(step.proof, proofScope, unit);
1371
+ return body.isSuffices ? assumed : scope;
1372
+ }
1373
+ const goal = { statement: body.statement, isSuffices: body.isSuffices, isInProof: true };
1374
+ resolveProof(step.proof, { name, arity: 0, kind: "Theorem", parent: proofScope, goal }, unit);
1375
+ goal.isInProof = false;
1376
+ return { name, arity: 0, kind: "Theorem", parent: body.isSuffices ? assumed : scope, goal };
442
1377
  }
1378
+ case "Use":
1379
+ case "Hide":
1380
+ checkFacts(body.facts, scope, unit);
1381
+ return bindNonFactStep(scope);
1382
+ case "Instance":
1383
+ return bindNonFactStep(resolveLocalInstance(body, scope, stepUnit));
443
1384
  case "Define":
444
- return resolveDefinitions(
445
- body.definitions.flatMap((definition) =>
446
- definition.kind === "Instance" ? [] : [definition],
1385
+ return bindNonFactStep(
1386
+ body.definitions.reduce(
1387
+ (current, definition) =>
1388
+ definition.kind === "Instance"
1389
+ ? resolveLocalInstance(definition, current, stepUnit)
1390
+ : resolveDefinitions([definition], current, unit),
1391
+ scope,
447
1392
  ),
448
- scope,
449
- unit,
450
1393
  );
451
1394
  case "Have":
452
1395
  case "Case":
453
- resolveExpression(body.expression, scope, unit);
454
- resolveProof(step.proof, scope, unit);
455
- return scope;
1396
+ resolveExpression(body.expression, scope, stepUnit);
1397
+ resolveProof(step.proof, bindStep(scope), unit);
1398
+ return bindStep(scope);
456
1399
  case "Witness":
457
- body.expressions.forEach((expression) => resolveExpression(expression, scope, unit));
458
- return scope;
1400
+ body.expressions.forEach((expression) => resolveExpression(expression, scope, stepUnit));
1401
+ return bindStep(scope);
459
1402
  case "Take":
460
- return bindNames(resolveBounds(body.bounds, scope, unit), body.names);
1403
+ return bindStep(
1404
+ bindNames(
1405
+ resolveBounds(body.bounds, scope, stepUnit),
1406
+ body.names,
1407
+ body.nameRanges,
1408
+ stepUnit,
1409
+ ),
1410
+ );
461
1411
  case "Pick": {
462
- const picked = bindNames(resolveBounds(body.bounds, scope, unit), body.names);
463
- resolveExpression(body.body, picked, unit);
464
- resolveProof(step.proof, scope, unit);
465
- return picked;
1412
+ const picked = bindNames(
1413
+ resolveBounds(body.bounds, scope, stepUnit),
1414
+ body.names,
1415
+ body.nameRanges,
1416
+ stepUnit,
1417
+ );
1418
+ resolveExpression(body.body, picked, {
1419
+ ...stepUnit,
1420
+ labelParams: [...stepUnit.labelParams, ...getBoundNames(body.bounds), ...body.names],
1421
+ });
1422
+ resolveProof(step.proof, bindStep(scope), unit);
1423
+ return bindStep(picked);
466
1424
  }
467
1425
  default:
468
- resolveProof(step.proof, scope, unit);
469
- return scope;
1426
+ resolveProof(step.proof, bindStep(scope), unit);
1427
+ return bindStep(scope);
470
1428
  }
471
1429
  };
472
1430
 
1431
+ // SANY binds the name of a theorem after its statement and before its proof.
473
1432
  const resolveTheorem = (theorem: Theorem, unit: Unit) => {
474
1433
  const isDefinition = theorem.name !== undefined && theorem.statement.kind !== "AssumeProve";
475
1434
  const scope = isDefinition ? undefined : resolveStatement(theorem.statement, undefined, unit);
1435
+ if (theorem.name !== undefined) {
1436
+ bindModuleName(
1437
+ theorem.name,
1438
+ { kind: "Theorem", arity: 0, range: theorem.location.range },
1439
+ unit,
1440
+ );
1441
+ }
1442
+ const goal = unit.goals.get(theorem.name ?? "");
1443
+ if (goal) goal.isInProof = true;
476
1444
  resolveProof(theorem.proof, scope, unit);
1445
+ if (goal) goal.isInProof = false;
477
1446
  };
478
1447
 
479
- interface ModuleUnit {
480
- imported: Symbols;
481
- importedAt: Map<string, SourceLocation>;
482
- definitions: Map<string, Definition>;
483
- getKey: (definition: Definition) => string;
1448
+ // The declarations of the module an INSTANCE instantiates, the names the INSTANCE adds, and the
1449
+ // module that instantiates it.
1450
+ export interface InstancedModule {
1451
+ declarations: Declaration[];
1452
+ symbols: Symbols;
1453
+ instancer: string;
484
1454
  }
485
1455
 
486
- interface ModuleName {
487
- name: string;
488
- kind: "Definition" | "Constant" | "Variable";
1456
+ // What SANY reports at a location as it links a module, such as a conflict between the modules it
1457
+ // extends.
1458
+ export interface ModuleReport {
489
1459
  location: SourceLocation;
490
- isRecursive: boolean;
1460
+ errors: SanyError[];
1461
+ warnings: SanyError[];
1462
+ }
1463
+
1464
+ // bound holds the names in scope where the module starts: the built-in operators, the names of the
1465
+ // module that encloses it, and those of the modules it extends. instanced holds the names each
1466
+ // INSTANCE adds, getInstance what an INSTANCE in a LET or a proof instantiates, facts the theorems
1467
+ // and assumptions the modules it extends or instantiates export, and warnings the warnings SANY
1468
+ // reports for the spec.
1469
+ export interface ModuleUnit {
1470
+ imported: Symbols;
1471
+ getInstance: (instance: Instance) => InstancedModule;
1472
+ bound: Symbols;
1473
+ definitions: Map<string, Definition>;
1474
+ getKey: (definition: Definition) => string;
1475
+ instanced: Map<Instance, Symbols>;
1476
+ facts: Set<string>;
1477
+ reports: ModuleReport[];
1478
+ warnings: SanyError[];
491
1479
  }
492
1480
 
493
- type IsDefined = (name: string) => boolean;
1481
+ export const MODULE_START: SourceLocation = { line: 0, column: 0 };
494
1482
 
495
- const createRedefinitionError = (name: string, location: SourceLocation) =>
496
- new TlaSyntaxError(
497
- `Multiply-defined symbol '${name}' at line ${location.line}, column ${location.column}`,
1483
+ // A named theorem or assumption is linked as a definition too.
1484
+ export const isTheoremDefinition = (module: Module, definition: Definition) =>
1485
+ [...module.theorems, ...module.assumptions].some(
1486
+ (item) =>
1487
+ item.name === definition.name &&
1488
+ item.location.line === definition.location.line &&
1489
+ item.location.column === definition.location.column,
498
1490
  );
499
1491
 
500
- const bindUnique = (
501
- scope: LocalName | undefined,
502
- names: string[],
503
- isDefined: IsDefined,
504
- location: SourceLocation,
505
- ) =>
506
- names.reduce<LocalName | undefined>((parent, name) => {
507
- if (lookupLocal(parent, name) || isDefined(name)) throw createRedefinitionError(name, location);
508
- return { name, arity: 0, parent };
509
- }, scope);
510
-
511
- const checkBoundNames = (
512
- bounds: Bound[],
513
- scope: LocalName | undefined,
514
- isDefined: IsDefined,
515
- location: SourceLocation,
516
- ) => {
517
- bounds.forEach((bound) => checkNames(bound.set, scope, isDefined));
518
- return bounds.reduce(
519
- (current, bound) => bindUnique(current, getPatternNames(bound.pattern), isDefined, location),
520
- scope,
1492
+ const createSymbols = (module: Module, imported: Symbols) => {
1493
+ const symbols = new Map([...CORE_SYMBOLS, ...imported]);
1494
+ module.constants.forEach((constant) =>
1495
+ symbols.set(constant.name, { key: constant.name, arity: constant.arity, kind: "Constant" }),
1496
+ );
1497
+ module.variables.forEach((variable) =>
1498
+ symbols.set(variable.name, { key: variable.name, arity: 0, kind: "Variable" }),
521
1499
  );
1500
+ return symbols;
522
1501
  };
523
1502
 
524
- const checkDefinitionNames = (
525
- definition: Definition,
526
- scope: LocalName | undefined,
527
- isDefined: IsDefined,
1503
+ // Generator.processSubst analyzes the explicit substitutions in the order they appear, then the
1504
+ // implicit ones, and then reports each declaration left without one. The parameters of the INSTANCE
1505
+ // are in scope.
1506
+ const checkSubstitutions = (
1507
+ instance: Instance,
1508
+ declarations: Declaration[],
1509
+ instancer: string,
1510
+ outer: LocalName | undefined,
1511
+ unit: Unit,
528
1512
  ) => {
529
- if (definition.kind === "Function") {
530
- const self = bindNames(scope, [definition.name]);
531
- const bound = checkBoundNames(definition.bounds, self, isDefined, definition.location);
532
- checkNames(definition.body, bound, isDefined);
533
- return;
534
- }
535
- const params = bindUnique(
536
- scope,
537
- definition.params.map((param) => param.name),
538
- isDefined,
539
- definition.location,
1513
+ const scope = instance.params.reduce<LocalName | undefined>(
1514
+ (parent, param) => ({ name: param.name, arity: param.arity, kind: "Parameter", parent }),
1515
+ outer,
540
1516
  );
541
- checkNames(definition.body, params, isDefined);
542
- };
543
-
544
- const checkNames = (
545
- expression: Expression,
546
- scope: LocalName | undefined,
547
- isDefined: IsDefined,
548
- ): void => {
549
- const location = expression.location;
550
- switch (expression.kind) {
551
- case "Lambda":
552
- checkNames(
553
- expression.body,
554
- bindUnique(scope, expression.params, isDefined, location),
555
- isDefined,
556
- );
557
- return;
558
- case "Let": {
559
- const recursive = expression.definitions
560
- .filter((definition) => definition.isRecursive)
561
- .map((definition) => definition.name);
562
- const inner = expression.definitions.reduce((current, definition) => {
563
- if (lookupLocal(current, definition.name) || isDefined(definition.name)) {
564
- throw createRedefinitionError(definition.name, definition.location);
565
- }
566
- checkDefinitionNames(definition, bindNames(current, recursive), isDefined);
567
- return bindNames(current, [definition.name]);
568
- }, scope);
569
- checkNames(
570
- expression.body,
571
- bindUnique(
572
- inner,
573
- (expression.instances ?? []).flatMap((instance) =>
574
- instance.name === undefined ? [] : [instance.name],
575
- ),
576
- isDefined,
577
- location,
578
- ),
579
- isDefined,
580
- );
1517
+ const resolveSubstitute = (declaration: Declaration, expression: Expression) => {
1518
+ if (declaration.arity === 0 || expression.kind !== "Identifier") {
1519
+ resolveExpression(expression, scope, unit);
581
1520
  return;
582
1521
  }
583
- case "Forall":
584
- case "Exists":
585
- case "FunctionConstruction":
586
- checkNames(
587
- expression.body,
588
- checkBoundNames(expression.bounds, scope, isDefined, location),
589
- isDefined,
590
- );
591
- return;
592
- case "SetFilter":
593
- checkNames(
594
- expression.predicate,
595
- checkBoundNames([expression.bound], scope, isDefined, location),
596
- isDefined,
597
- );
598
- return;
599
- case "SetMap":
600
- checkNames(
601
- expression.expression,
602
- checkBoundNames(expression.bounds, scope, isDefined, location),
603
- isDefined,
604
- );
605
- return;
606
- case "UnboundedQuantifier":
607
- checkNames(
608
- expression.body,
609
- bindUnique(scope, expression.names, isDefined, location),
610
- isDefined,
611
- );
612
- return;
613
- case "Choose":
614
- if (expression.set) checkNames(expression.set, scope, isDefined);
615
- checkNames(
616
- expression.body,
617
- bindUnique(scope, getPatternNames(expression.pattern), isDefined, location),
618
- isDefined,
1522
+ const arity = getSymbolArity(expression, expression.name, scope, unit);
1523
+ if (arity !== undefined && arity !== declaration.arity) {
1524
+ throw new TlaSyntaxError(
1525
+ `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}`,
619
1526
  );
620
- return;
621
- default:
622
- getChildren(expression).forEach((child) => checkNames(child, scope, isDefined));
623
- }
624
- };
625
-
626
- const getModuleNames = (module: Module) => [
627
- ...module.definitions.map((definition): ModuleName => ({
628
- name: definition.name,
629
- kind: "Definition",
630
- location: definition.location,
631
- isRecursive: definition.isRecursive,
632
- })),
633
- ...module.instances.flatMap((instance): ModuleName[] =>
634
- instance.name === undefined
635
- ? []
636
- : [
637
- {
638
- name: instance.name,
639
- kind: "Definition",
640
- location: instance.location,
641
- isRecursive: false,
642
- },
643
- ],
644
- ),
645
- ...module.constants.map((constant): ModuleName => ({
646
- name: constant.name,
647
- kind: "Constant",
648
- location: constant.location,
649
- isRecursive: false,
650
- })),
651
- ...module.variables.map((variable): ModuleName => ({
652
- name: variable.name,
653
- kind: "Variable",
654
- location: variable.location,
655
- isRecursive: false,
656
- })),
657
- ];
658
-
659
- export const checkRedefinitions = (module: Module, unit: ModuleUnit) => {
660
- const byName = new Map<string, ModuleName[]>();
661
- getModuleNames(module)
662
- .sort((left, right) => (isBefore(left.location, right.location) ? -1 : 1))
663
- .forEach((entry) => byName.set(entry.name, [...(byName.get(entry.name) ?? []), entry]));
664
- const isImportedBefore = (name: string, location: SourceLocation) => {
665
- if (!unit.imported.has(name) && !CORE_SYMBOLS.has(name)) return false;
666
- const importedAt = unit.importedAt.get(name);
667
- return importedAt === undefined || isBefore(importedAt, location);
1527
+ }
668
1528
  };
669
- byName.forEach((entries) =>
670
- entries.forEach((entry, index) => {
671
- const isDuplicate = entries
672
- .slice(0, index)
673
- .some(
674
- (earlier) =>
675
- earlier.kind === "Definition" ||
676
- entry.kind === "Definition" ||
677
- earlier.kind !== entry.kind,
678
- );
679
- // A module may declare again a constant or variable that it extends or that encloses it.
680
- const isRedeclared = unit.imported.get(entry.name)?.declaration === entry.kind;
681
- if (isDuplicate || (!isRedeclared && isImportedBefore(entry.name, entry.location)))
682
- throw createRedefinitionError(entry.name, entry.location);
683
- }),
684
- );
685
- const getIsDefined =
686
- (location: SourceLocation): IsDefined =>
687
- (name) =>
688
- (byName.get(name) ?? []).some(
689
- (entry) => entry.isRecursive || isBefore(entry.location, location),
690
- ) || isImportedBefore(name, location);
691
- module.definitions.forEach((definition) =>
692
- checkDefinitionNames(definition, undefined, getIsDefined(definition.location)),
693
- );
694
- module.assumptions.forEach((assumption) =>
695
- checkNames(assumption.expression, undefined, getIsDefined(assumption.location)),
696
- );
697
- module.instances.forEach((instance) => {
698
- const isDefined = getIsDefined(instance.location);
699
- const params = bindUnique(
700
- undefined,
701
- instance.params.map((param) => param.name),
702
- isDefined,
703
- instance.location,
704
- );
705
- instance.substitutions.forEach((substitution) =>
706
- checkNames(substitution.expression, params, isDefined),
707
- );
1529
+ const substitutions = new Map<string, Expression>();
1530
+ instance.substitutions.forEach((substitution) => {
1531
+ const name = substitution.name;
1532
+ const declaration = declarations.find((item) => item.name === name);
1533
+ if (!declaration) {
1534
+ unit.errors.push({
1535
+ location: formatRange(substitution.nameRange),
1536
+ message: `Identifier '${name}' is not a legal target of a substitution. \nA legal target must be a declared CONSTANT or VARIABLE in the module being instantiated. \n(Also, check for warnings about multiple declarations of this same identifier.)`,
1537
+ });
1538
+ return;
1539
+ }
1540
+ const expression = substitution.expression;
1541
+ resolveSubstitute(declaration, expression);
1542
+ const range = expression.location.range;
1543
+ if (!substitutions.has(name)) substitutions.set(name, expression);
1544
+ else if (range) {
1545
+ unit.errors.push({
1546
+ location: formatRange(range),
1547
+ message: `Multiple substitutions for symbol '${name}' in substitution.`,
1548
+ });
1549
+ }
1550
+ });
1551
+ const implicit = declarations.filter((declaration) => !substitutions.has(declaration.name));
1552
+ const isMissing = (declaration: Declaration) =>
1553
+ !lookupLocal(scope, declaration.name) && !findSymbol(declaration.name, unit);
1554
+ implicit
1555
+ .filter((declaration) => !isMissing(declaration))
1556
+ .forEach((declaration) => {
1557
+ const expression: Expression = {
1558
+ kind: "Identifier",
1559
+ name: declaration.name,
1560
+ location: instance.location,
1561
+ };
1562
+ resolveSubstitute(declaration, expression);
1563
+ substitutions.set(declaration.name, expression);
1564
+ });
1565
+ implicit.filter(isMissing).forEach((declaration) => {
1566
+ const range = instance.location.range;
1567
+ const declared = declaration.location.range;
1568
+ if (range && declared) {
1569
+ unit.errors.push({
1570
+ location: formatRange(range),
1571
+ message: `Substitution missing for symbol ${declaration.name} declared at ${formatRange(declared)} \nand instantiated in module ${instancer}.`,
1572
+ });
1573
+ }
708
1574
  });
1575
+ return substitutions;
709
1576
  };
710
1577
 
711
- const createSymbols = (module: Module, imported: Symbols) => {
712
- const symbols = new Map([...CORE_SYMBOLS, ...imported]);
713
- module.constants.forEach((constant) =>
714
- symbols.set(constant.name, { key: constant.name, arity: constant.arity }),
715
- );
716
- module.variables.forEach((variable) =>
717
- symbols.set(variable.name, { key: variable.name, arity: 0 }),
1578
+ // Generator.processSubst analyzes an INSTANCE in a LET or a proof, which then binds the names the
1579
+ // INSTANCE adds.
1580
+ const resolveInstance = (instance: Instance, scope: LocalName | undefined, unit: Unit) => {
1581
+ const instanced = unit.getInstance(instance);
1582
+ checkSubstitutions(instance, instanced.declarations, instanced.instancer, scope, unit);
1583
+ return [...instanced.symbols].reduce(
1584
+ (parent, [name, symbol]) => bindName(parent, name, symbol, unit),
1585
+ scope,
718
1586
  );
719
- return symbols;
720
1587
  };
721
1588
 
1589
+ // tla-ts reports what SANY goes on after with an INSTANCE of the module.
722
1590
  export const resolveSubstitutions = (
723
1591
  instance: Instance,
724
- declarations: OperatorParam[],
1592
+ declarations: Declaration[],
725
1593
  module: Module,
726
1594
  unit: ModuleUnit,
727
1595
  ) => {
728
- const scope = bindParams(undefined, instance.params);
729
- const context: Unit = {
730
- imported: createSymbols(module, unit.imported),
1596
+ const imported = createSymbols(module, unit.imported);
1597
+ const report: ModuleReport = { location: instance.location, errors: [], warnings: [] };
1598
+ unit.reports.push(report);
1599
+ return checkSubstitutions(instance, declarations, module.name, undefined, {
1600
+ imported,
1601
+ getInstance: unit.getInstance,
731
1602
  definitions: unit.definitions,
732
1603
  getKey: unit.getKey,
733
1604
  location: instance.location,
734
1605
  self: undefined,
735
1606
  facts: new Set(),
736
- };
737
- const explicit = new Map(instance.substitutions.map((item) => [item.name, item.expression]));
738
- const position = `in the instance of ${instance.module} at line ${instance.location.line}, column ${instance.location.column}`;
739
- explicit.forEach((_, name) => {
740
- if (declarations.every((declaration) => declaration.name !== name)) {
741
- throw new TlaSyntaxError(
742
- `Identifier '${name}' is not a legal target of a substitution ${position}`,
743
- );
744
- }
1607
+ goals: new Map(),
1608
+ bindings: new Map(
1609
+ [...imported].map(([name, symbol]) => [name, { ...symbol, position: MODULE_START }]),
1610
+ ),
1611
+ errors: report.errors,
1612
+ warnings: report.warnings,
1613
+ hasLabelScope: false,
1614
+ isLabelForbidden: false,
1615
+ isInExcept: false,
1616
+ labelParams: [],
1617
+ labels: new Set(),
1618
+ isGenerated: false,
745
1619
  });
746
- return new Map(
747
- declarations.map((declaration): [string, Expression] => {
748
- const name = declaration.name;
749
- if (!explicit.has(name) && !lookupLocal(scope, name) && !findSymbol(name, context)) {
750
- throw new TlaSyntaxError(`Substitution missing for symbol ${name} ${position}`);
751
- }
752
- const expression: Expression = explicit.get(name) ?? {
753
- kind: "Identifier",
754
- name,
755
- location: instance.location,
756
- };
757
- if (declaration.arity === 0 || expression.kind !== "Identifier") {
758
- resolveExpression(expression, scope, context);
759
- return [name, expression];
760
- }
761
- if (getSymbolArity(expression, expression.name, scope, context) !== declaration.arity) {
762
- throw new TlaSyntaxError(
763
- `An operator must be substituted for symbol '${name}', and it must have arity ${declaration.arity} ${position}`,
764
- );
1620
+ };
1621
+
1622
+ // SANY reports the errors of every unit it checks, in the order of the units in the module, after
1623
+ // the warnings it reports for the spec. A unit reports to its lists what SANY goes on after, and
1624
+ // throws the error that stops it. An error tla-ts cannot word as SANY does yields to the errors the
1625
+ // unit reported before it. Returns the errors.
1626
+ export const collectSemanticErrors = (
1627
+ units: {
1628
+ location: SourceLocation;
1629
+ check: (reported: SanyError[], warned: SanyError[]) => void;
1630
+ }[],
1631
+ warnings: SanyError[],
1632
+ ) => {
1633
+ const errors: SanyError[] = [];
1634
+ const add = (list: SanyError[], item: SanyError) => {
1635
+ if (
1636
+ list.every(
1637
+ (existing) => existing.location !== item.location || existing.message !== item.message,
1638
+ )
1639
+ ) {
1640
+ list.push(item);
1641
+ }
1642
+ };
1643
+ units
1644
+ .toSorted((left, right) =>
1645
+ isBefore(left.location, right.location)
1646
+ ? -1
1647
+ : isBefore(right.location, left.location)
1648
+ ? 1
1649
+ : 0,
1650
+ )
1651
+ .forEach((unit) => {
1652
+ const reported: SanyError[] = [];
1653
+ const warned: SanyError[] = [];
1654
+ try {
1655
+ unit.check(reported, warned);
1656
+ } catch (error) {
1657
+ if (!(error instanceof TlaSyntaxError) || (!error.sany && reported.length === 0)) {
1658
+ throw error;
1659
+ }
1660
+ reported.push(...(error.sany?.errors ?? []));
765
1661
  }
766
- return [name, expression];
767
- }),
768
- );
1662
+ reported.forEach((item) => add(errors, item));
1663
+ warned.forEach((item) => add(warnings, item));
1664
+ });
1665
+ return errors;
769
1666
  };
770
1667
 
1668
+ // SANY binds the names of a module in the order of its units, and reports a RECURSIVE declaration
1669
+ // that no definition follows at the end. Returns the errors.
771
1670
  export const resolveModule = (module: Module, unit: ModuleUnit) => {
772
1671
  const symbols = createSymbols(module, unit.imported);
773
- const facts = new Set(
774
- [...module.theorems, ...module.assumptions].flatMap((fact) => fact.name ?? []),
1672
+ const facts = new Set([
1673
+ ...unit.facts,
1674
+ ...[...module.theorems, ...module.assumptions].flatMap((fact) => fact.name ?? []),
1675
+ ]);
1676
+ const goals = new Map(
1677
+ module.theorems.flatMap((theorem): [string, Goal][] =>
1678
+ theorem.name !== undefined && theorem.statement.kind === "AssumeProve"
1679
+ ? [[theorem.name, { statement: theorem.statement, isSuffices: false, isInProof: false }]]
1680
+ : [],
1681
+ ),
775
1682
  );
776
- const createUnit = (location: SourceLocation, self: Definition | undefined) => ({
1683
+ const bindings = new Map<string, ModuleBinding>(
1684
+ [...CORE_SYMBOLS, ...unit.bound].map(([name, symbol]) => [
1685
+ name,
1686
+ { ...symbol, position: MODULE_START },
1687
+ ]),
1688
+ );
1689
+ const recursive = new Set<Binding>();
1690
+ const declarations: { declaration: Declaration; binding: ModuleBinding | undefined }[] = [];
1691
+ const createUnit = (
1692
+ location: SourceLocation,
1693
+ self: Definition | undefined,
1694
+ errors: SanyError[],
1695
+ warnings: SanyError[],
1696
+ hasLabelScope: boolean,
1697
+ ): Unit => ({
777
1698
  imported: symbols,
1699
+ getInstance: unit.getInstance,
778
1700
  definitions: unit.definitions,
779
1701
  getKey: unit.getKey,
780
1702
  location,
781
1703
  self,
782
1704
  facts,
1705
+ goals,
1706
+ bindings,
1707
+ errors,
1708
+ warnings,
1709
+ hasLabelScope,
1710
+ isLabelForbidden: false,
1711
+ isInExcept: false,
1712
+ labelParams: [],
1713
+ labels: new Set(),
1714
+ isGenerated: false,
783
1715
  });
784
- module.definitions.forEach((definition) =>
785
- resolveDefinition(definition, undefined, createUnit(definition.location, definition)),
786
- );
787
- module.assumptions.forEach((assumption) =>
788
- resolveExpression(assumption.expression, undefined, createUnit(assumption.location, undefined)),
789
- );
790
- module.theorems.forEach((theorem) =>
791
- resolveTheorem(theorem, createUnit(theorem.location, undefined)),
1716
+ const bindDeclarations = (declarations: Declaration[], kind: "Constant" | "Variable") =>
1717
+ declarations.map((declaration) => ({
1718
+ location: declaration.location,
1719
+ check: (errors: SanyError[], warnings: SanyError[]) =>
1720
+ bindModuleName(
1721
+ declaration.name,
1722
+ { kind, arity: declaration.arity, range: declaration.location.range },
1723
+ createUnit(declaration.location, undefined, errors, warnings, false),
1724
+ ),
1725
+ }));
1726
+ return collectSemanticErrors(
1727
+ [
1728
+ ...unit.reports.map((report) => ({
1729
+ location: report.location,
1730
+ check: (errors: SanyError[], warnings: SanyError[]) => {
1731
+ errors.push(...report.errors);
1732
+ warnings.push(...report.warnings);
1733
+ },
1734
+ })),
1735
+ ...bindDeclarations(module.constants, "Constant"),
1736
+ ...bindDeclarations(module.variables, "Variable"),
1737
+ ...module.units
1738
+ .flatMap((item) => (item.kind === "Recursive" ? item.declarations : []))
1739
+ .map((declaration) => ({
1740
+ location: declaration.location,
1741
+ check: (errors: SanyError[], warnings: SanyError[]) => {
1742
+ const binding: ModuleBinding = {
1743
+ kind: "Definition",
1744
+ arity: declaration.arity,
1745
+ range: declaration.location.range,
1746
+ position: declaration.location,
1747
+ isPending: true,
1748
+ };
1749
+ const isBound = isBindable(
1750
+ declaration.name,
1751
+ bindings.get(declaration.name),
1752
+ binding,
1753
+ createUnit(declaration.location, undefined, errors, warnings, false),
1754
+ );
1755
+ if (isBound) {
1756
+ bindings.set(declaration.name, binding);
1757
+ recursive.add(binding);
1758
+ }
1759
+ declarations.push({ declaration, binding: isBound ? binding : undefined });
1760
+ },
1761
+ })),
1762
+ ...module.definitions.map((definition) => ({
1763
+ location: definition.location,
1764
+ check: (errors: SanyError[], warnings: SanyError[]) => {
1765
+ const inner = createUnit(definition.location, definition, errors, warnings, true);
1766
+ if (isTheoremDefinition(module, definition)) {
1767
+ resolveExpression(definition.body, undefined, inner);
1768
+ } else if (resolveDefinition(definition, undefined, inner, recursive)) {
1769
+ bindings.set(definition.name, {
1770
+ kind: "Definition",
1771
+ arity: getArity(definition),
1772
+ range: definition.location.range,
1773
+ position: definition.location,
1774
+ });
1775
+ }
1776
+ },
1777
+ })),
1778
+ ...module.instances.map((instance) => ({
1779
+ location: instance.location,
1780
+ check: (errors: SanyError[], warnings: SanyError[]) => {
1781
+ const inner = createUnit(instance.location, undefined, errors, warnings, false);
1782
+ bindParams(undefined, instance.params, inner);
1783
+ unit.instanced
1784
+ .get(instance)
1785
+ ?.forEach((symbol, name) => bindModuleName(name, symbol, inner));
1786
+ if (instance.name !== undefined) {
1787
+ bindModuleName(
1788
+ instance.name,
1789
+ { kind: "Instance", arity: instance.params.length, range: instance.location.range },
1790
+ inner,
1791
+ );
1792
+ }
1793
+ },
1794
+ })),
1795
+ ...module.assumptions.map((assumption) => ({
1796
+ location: assumption.location,
1797
+ check: (errors: SanyError[], warnings: SanyError[]) => {
1798
+ const inner = createUnit(
1799
+ assumption.location,
1800
+ undefined,
1801
+ errors,
1802
+ warnings,
1803
+ assumption.name !== undefined,
1804
+ );
1805
+ resolveExpression(assumption.expression, undefined, inner);
1806
+ if (assumption.name !== undefined) {
1807
+ bindModuleName(
1808
+ assumption.name,
1809
+ { kind: "Theorem", arity: 0, range: assumption.location.range },
1810
+ inner,
1811
+ );
1812
+ }
1813
+ },
1814
+ })),
1815
+ ...module.theorems.map((theorem) => ({
1816
+ location: theorem.location,
1817
+ check: (errors: SanyError[], warnings: SanyError[]) =>
1818
+ resolveTheorem(
1819
+ theorem,
1820
+ createUnit(theorem.location, undefined, errors, warnings, theorem.name !== undefined),
1821
+ ),
1822
+ })),
1823
+ ...module.uses.map((use) => ({
1824
+ location: use.location,
1825
+ check: (errors: SanyError[], warnings: SanyError[]) =>
1826
+ checkFacts(
1827
+ use.facts,
1828
+ undefined,
1829
+ createUnit(use.location, undefined, errors, warnings, false),
1830
+ ),
1831
+ })),
1832
+ {
1833
+ location: module.location.range?.end ?? module.location,
1834
+ check: (errors: SanyError[]) =>
1835
+ declarations.forEach((item) => {
1836
+ const range = item.declaration.location.range;
1837
+ if (range && (!item.binding || item.binding.isPending)) {
1838
+ errors.push({
1839
+ location: formatRange(range),
1840
+ message: `Symbol ${item.declaration.name} declared in RECURSIVE statement but not defined.`,
1841
+ });
1842
+ }
1843
+ }),
1844
+ },
1845
+ ],
1846
+ unit.warnings,
792
1847
  );
793
1848
  };