tla-ts 0.0.3 → 0.0.4-dev.1a3acf6

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 (381) 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 +1006 -0
  17. package/dist/prove.js +1006 -0
  18. package/dist/run.cjs +45 -0
  19. package/dist/run.js +45 -0
  20. package/dist/tlapm.cjs +10 -0
  21. package/dist/tlapm.js +10 -0
  22. package/dist/transfer.cjs +1377 -18
  23. package/dist/transfer.js +1377 -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 +26 -30
  29. package/src/builtins.ts +45 -19
  30. package/src/bundled-modules.ts +3 -3
  31. package/src/check.ts +1182 -900
  32. package/src/cli/options.ts +109 -0
  33. package/src/cli/run.ts +63 -0
  34. package/src/cli/shared.ts +106 -0
  35. package/src/cli/tlapm.ts +374 -0
  36. package/src/cli/tlc.ts +941 -0
  37. package/src/cli/xml-exporter.ts +221 -0
  38. package/src/cli.ts +9 -2
  39. package/src/codegen.ts +112 -51
  40. package/src/config.ts +254 -181
  41. package/src/dependencies.ts +5 -7
  42. package/src/environment.ts +579 -184
  43. package/src/errors.ts +287 -4
  44. package/src/evaluate.ts +1095 -365
  45. package/src/exit-codes.ts +22 -43
  46. package/src/fingerprints.ts +49 -14
  47. package/src/index.ts +11 -0
  48. package/src/instances.ts +73 -60
  49. package/src/java-overrides.ts +183 -66
  50. package/src/json.ts +31 -36
  51. package/src/levels.ts +197 -54
  52. package/src/lexer.ts +127 -30
  53. package/src/liveness-checker.ts +894 -0
  54. package/src/liveness.ts +246 -596
  55. package/src/{obligation-action.ts → obligations/action.ts} +248 -74
  56. package/src/{obligation-anon.ts → obligations/anonymize.ts} +55 -57
  57. package/src/obligations/equality.ts +260 -0
  58. package/src/obligations/expression.ts +618 -0
  59. package/src/{obligation-format.ts → obligations/format.ts} +7 -8
  60. package/src/obligations/generate.ts +457 -0
  61. package/src/{obligations.ts → obligations/index.ts} +46 -32
  62. package/src/{obligation-levels.ts → obligations/levels.ts} +44 -40
  63. package/src/obligations/module.ts +445 -0
  64. package/src/obligations/normalize.ts +554 -0
  65. package/src/obligations/operators.ts +176 -0
  66. package/src/obligations/pragma.ts +195 -0
  67. package/src/{obligation-printer.ts → obligations/printer.ts} +65 -230
  68. package/src/{obligation-proof.ts → obligations/proof.ts} +7 -2
  69. package/src/obligations/regroup.ts +100 -0
  70. package/src/{obligation-generate.ts → obligations/simplify.ts} +130 -536
  71. package/src/{obligation-source.ts → obligations/source.ts} +174 -216
  72. package/src/{obligation-deref.ts → obligations/subexpression.ts} +84 -115
  73. package/src/obligations/substitution.ts +261 -0
  74. package/src/obligations/temporal.ts +321 -0
  75. package/src/{obligation-tuples.ts → obligations/tuples.ts} +38 -54
  76. package/src/parallel-worker.ts +184 -235
  77. package/src/parallel.ts +156 -91
  78. package/src/parser.ts +490 -188
  79. package/src/pcal/ast.ts +755 -0
  80. package/src/pcal/parse.ts +1487 -0
  81. package/src/pcal/tokenize.ts +487 -0
  82. package/src/pcal/translate.ts +1151 -0
  83. package/src/pcal/validate.ts +444 -0
  84. package/src/prover/decide-pool.ts +95 -0
  85. package/src/prover/deciders.ts +33 -0
  86. package/src/prover/first-order.ts +175 -0
  87. package/src/prover/isabelle/LICENSE +36 -0
  88. package/src/prover/isabelle/LICENSE-tlapm +26 -0
  89. package/src/prover/isabelle/decide.ts +44 -0
  90. package/src/prover/isabelle/encode.ts +445 -0
  91. package/src/prover/isabelle/isar/inner-syntax.ts +579 -0
  92. package/src/prover/isabelle/isar/method.ts +367 -0
  93. package/src/prover/isabelle/isar/proof.ts +28 -0
  94. package/src/prover/isabelle/isar/statement.ts +57 -0
  95. package/src/prover/isabelle/isar/theory.ts +192 -0
  96. package/src/prover/isabelle/isar/type-check.ts +278 -0
  97. package/src/prover/isabelle/provers/blast/blast.ts +258 -0
  98. package/src/prover/isabelle/provers/blast/branch.ts +322 -0
  99. package/src/prover/isabelle/provers/blast/prove.ts +347 -0
  100. package/src/prover/isabelle/provers/blast/rules.ts +330 -0
  101. package/src/prover/isabelle/provers/blast/state.ts +180 -0
  102. package/src/prover/isabelle/provers/blast/term.ts +546 -0
  103. package/src/prover/isabelle/provers/clasimp.ts +150 -0
  104. package/src/prover/isabelle/provers/classical.ts +389 -0
  105. package/src/prover/isabelle/provers/hypsubst.ts +433 -0
  106. package/src/prover/isabelle/pure/bicompose.ts +174 -0
  107. package/src/prover/isabelle/pure/consts.ts +32 -0
  108. package/src/prover/isabelle/pure/conv.ts +79 -0
  109. package/src/prover/isabelle/pure/drule.ts +264 -0
  110. package/src/prover/isabelle/pure/envir.ts +331 -0
  111. package/src/prover/isabelle/pure/goal.ts +53 -0
  112. package/src/prover/isabelle/pure/interrupt.ts +16 -0
  113. package/src/prover/isabelle/pure/list.ts +12 -0
  114. package/src/prover/isabelle/pure/logic.ts +330 -0
  115. package/src/prover/isabelle/pure/name.ts +98 -0
  116. package/src/prover/isabelle/pure/net.ts +215 -0
  117. package/src/prover/isabelle/pure/object-logic.ts +41 -0
  118. package/src/prover/isabelle/pure/pattern.ts +631 -0
  119. package/src/prover/isabelle/pure/raw-simplifier.ts +338 -0
  120. package/src/prover/isabelle/pure/rewriter.ts +602 -0
  121. package/src/prover/isabelle/pure/search.ts +68 -0
  122. package/src/prover/isabelle/pure/seq.ts +133 -0
  123. package/src/prover/isabelle/pure/simplifier.ts +106 -0
  124. package/src/prover/isabelle/pure/table.ts +201 -0
  125. package/src/prover/isabelle/pure/tactic.ts +168 -0
  126. package/src/prover/isabelle/pure/tactical.ts +264 -0
  127. package/src/prover/isabelle/pure/term-ord.ts +105 -0
  128. package/src/prover/isabelle/pure/term.ts +688 -0
  129. package/src/prover/isabelle/pure/thm.ts +783 -0
  130. package/src/prover/isabelle/pure/type.ts +121 -0
  131. package/src/prover/isabelle/pure/unify.ts +753 -0
  132. package/src/prover/isabelle/pure/variable.ts +25 -0
  133. package/src/prover/isabelle/tla/classical-setup.ts +101 -0
  134. package/src/prover/isabelle/tla/context.ts +74 -0
  135. package/src/prover/isabelle/tla/logic-data.ts +5 -0
  136. package/src/prover/isabelle/tla/logic.ts +215 -0
  137. package/src/prover/isabelle/tla/simpdata.ts +241 -0
  138. package/src/prover/isabelle/tools/intuitionistic.ts +132 -0
  139. package/src/prover/ocaml.ts +22 -0
  140. package/src/prover/prep/action.ts +508 -0
  141. package/src/prover/prep/enabled-axioms.ts +189 -0
  142. package/src/prover/prep/fingerprint.ts +388 -0
  143. package/src/prover/prep/level-comparison.ts +529 -0
  144. package/src/prover/prep/md5.ts +60 -0
  145. package/src/prover/prep/methods.ts +221 -0
  146. package/src/prover/prep/normalize.ts +309 -0
  147. package/src/prover/prove-worker.ts +22 -0
  148. package/src/prover/prove.ts +492 -0
  149. package/src/prover/ptl/decide.ts +68 -0
  150. package/src/prover/ptl/encode.ts +244 -0
  151. package/src/prover/ptl/sat.ts +151 -0
  152. package/src/prover/ptl/tableau.ts +276 -0
  153. package/src/prover/smt/axioms.ts +209 -0
  154. package/src/prover/smt/context.ts +108 -0
  155. package/src/prover/smt/data.ts +636 -0
  156. package/src/prover/smt/encode.ts +275 -0
  157. package/src/prover/smt/extensionality.ts +65 -0
  158. package/src/prover/smt/flatten.ts +112 -0
  159. package/src/prover/smt/format.ts +154 -0
  160. package/src/prover/smt/instances.ts +181 -0
  161. package/src/prover/smt/rewrite.ts +766 -0
  162. package/src/prover/smt/solver/act-cache.ts +265 -0
  163. package/src/prover/smt/solver/arith-rewriter.ts +962 -0
  164. package/src/prover/smt/solver/array.ts +22 -0
  165. package/src/prover/smt/solver/asserted-formulas.ts +469 -0
  166. package/src/prover/smt/solver/ast-lt.ts +157 -0
  167. package/src/prover/smt/solver/ast-util.ts +91 -0
  168. package/src/prover/smt/solver/ast.ts +1315 -0
  169. package/src/prover/smt/solver/auf-solver.ts +572 -0
  170. package/src/prover/smt/solver/case-split-queue.ts +178 -0
  171. package/src/prover/smt/solver/cg-table.ts +175 -0
  172. package/src/prover/smt/solver/clause.ts +276 -0
  173. package/src/prover/smt/solver/conflict-resolution.ts +343 -0
  174. package/src/prover/smt/solver/context.ts +1292 -0
  175. package/src/prover/smt/solver/ctx-simplify.ts +334 -0
  176. package/src/prover/smt/solver/der.ts +224 -0
  177. package/src/prover/smt/solver/dyn-ack.ts +141 -0
  178. package/src/prover/smt/solver/e-matching.ts +659 -0
  179. package/src/prover/smt/solver/enode.ts +259 -0
  180. package/src/prover/smt/solver/expr-ref.ts +21 -0
  181. package/src/prover/smt/solver/expr-safe-replace.ts +172 -0
  182. package/src/prover/smt/solver/fingerprints.ts +92 -0
  183. package/src/prover/smt/solver/flat-literals.ts +51 -0
  184. package/src/prover/smt/solver/goal.ts +138 -0
  185. package/src/prover/smt/solver/hash.ts +173 -0
  186. package/src/prover/smt/solver/hashtable.ts +166 -0
  187. package/src/prover/smt/solver/internalizer.ts +1381 -0
  188. package/src/prover/smt/solver/lbool.ts +5 -0
  189. package/src/prover/smt/solver/literal.ts +24 -0
  190. package/src/prover/smt/solver/lp/bound-propagator.ts +391 -0
  191. package/src/prover/smt/solver/lp/constraints.ts +78 -0
  192. package/src/prover/smt/solver/lp/containers.ts +296 -0
  193. package/src/prover/smt/solver/lp/core-solver.ts +504 -0
  194. package/src/prover/smt/solver/lp/cross-nested.ts +224 -0
  195. package/src/prover/smt/solver/lp/dep-intervals.ts +642 -0
  196. package/src/prover/smt/solver/lp/dependency.ts +51 -0
  197. package/src/prover/smt/solver/lp/dioph-eq.ts +1181 -0
  198. package/src/prover/smt/solver/lp/explanation.ts +46 -0
  199. package/src/prover/smt/solver/lp/gomory.ts +255 -0
  200. package/src/prover/smt/solver/lp/hnf-cutter.ts +125 -0
  201. package/src/prover/smt/solver/lp/hnf.ts +281 -0
  202. package/src/prover/smt/solver/lp/int-cube.ts +295 -0
  203. package/src/prover/smt/solver/lp/int-solver.ts +514 -0
  204. package/src/prover/smt/solver/lp/lar-solver.ts +816 -0
  205. package/src/prover/smt/solver/lp/lar-term.ts +62 -0
  206. package/src/prover/smt/solver/lp/lp-settings.ts +91 -0
  207. package/src/prover/smt/solver/lp/maximize-term.ts +347 -0
  208. package/src/prover/smt/solver/lp/nex-creator.ts +381 -0
  209. package/src/prover/smt/solver/lp/nex.ts +120 -0
  210. package/src/prover/smt/solver/lp/nla-backoff.ts +43 -0
  211. package/src/prover/smt/solver/lp/nla-basics.ts +398 -0
  212. package/src/prover/smt/solver/lp/nla-core.ts +968 -0
  213. package/src/prover/smt/solver/lp/nla-divisions.ts +332 -0
  214. package/src/prover/smt/solver/lp/nla-emonics.ts +373 -0
  215. package/src/prover/smt/solver/lp/nla-factorization.ts +30 -0
  216. package/src/prover/smt/solver/lp/nla-grobner.ts +904 -0
  217. package/src/prover/smt/solver/lp/nla-horner.ts +126 -0
  218. package/src/prover/smt/solver/lp/nla-intervals.ts +265 -0
  219. package/src/prover/smt/solver/lp/nla-monomial-bounds.ts +715 -0
  220. package/src/prover/smt/solver/lp/nla-monotone.ts +59 -0
  221. package/src/prover/smt/solver/lp/nla-order.ts +307 -0
  222. package/src/prover/smt/solver/lp/nla-patcher.ts +112 -0
  223. package/src/prover/smt/solver/lp/nla-tangents.ts +251 -0
  224. package/src/prover/smt/solver/lp/nla-throttle.ts +85 -0
  225. package/src/prover/smt/solver/lp/nla-types.ts +124 -0
  226. package/src/prover/smt/solver/lp/nla-var-eqs.ts +141 -0
  227. package/src/prover/smt/solver/lp/nra-solver.ts +440 -0
  228. package/src/prover/smt/solver/lp/numeric-pair.ts +65 -0
  229. package/src/prover/smt/solver/lp/pdd-interval.ts +31 -0
  230. package/src/prover/smt/solver/lp/pdd-simplifier.ts +184 -0
  231. package/src/prover/smt/solver/lp/pdd-solver.ts +408 -0
  232. package/src/prover/smt/solver/lp/pdd.ts +971 -0
  233. package/src/prover/smt/solver/lp/random-updater.ts +138 -0
  234. package/src/prover/smt/solver/lp/static-matrix.ts +246 -0
  235. package/src/prover/smt/solver/lp/union-find.ts +96 -0
  236. package/src/prover/smt/solver/mam-compiler.ts +847 -0
  237. package/src/prover/smt/solver/mam-interpreter.ts +400 -0
  238. package/src/prover/smt/solver/maximize-ac-sharing.ts +118 -0
  239. package/src/prover/smt/solver/model-checker.ts +347 -0
  240. package/src/prover/smt/solver/model-evaluator.ts +262 -0
  241. package/src/prover/smt/solver/model-finder.ts +155 -0
  242. package/src/prover/smt/solver/model-generator.ts +97 -0
  243. package/src/prover/smt/solver/model-macro-solver.ts +728 -0
  244. package/src/prover/smt/solver/nlsat/algebraic.ts +1161 -0
  245. package/src/prover/smt/solver/nlsat/atoms.ts +238 -0
  246. package/src/prover/smt/solver/nlsat/evaluator.ts +303 -0
  247. package/src/prover/smt/solver/nlsat/explain.ts +607 -0
  248. package/src/prover/smt/solver/nlsat/interval-set.ts +351 -0
  249. package/src/prover/smt/solver/nlsat/levelwise.ts +737 -0
  250. package/src/prover/smt/solver/nlsat/mpbq.ts +161 -0
  251. package/src/prover/smt/solver/nlsat/polynomial.ts +1722 -0
  252. package/src/prover/smt/solver/nlsat/solver.ts +911 -0
  253. package/src/prover/smt/solver/nlsat/types.ts +43 -0
  254. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +648 -0
  255. package/src/prover/smt/solver/nlsat/upolynomial.ts +996 -0
  256. package/src/prover/smt/solver/nnf.ts +469 -0
  257. package/src/prover/smt/solver/pattern-inference.ts +351 -0
  258. package/src/prover/smt/solver/poly-rewriter.ts +477 -0
  259. package/src/prover/smt/solver/propagate-values.ts +83 -0
  260. package/src/prover/smt/solver/proto-model.ts +551 -0
  261. package/src/prover/smt/solver/pull-quant.ts +139 -0
  262. package/src/prover/smt/solver/qe-lite-der.ts +526 -0
  263. package/src/prover/smt/solver/qe-lite-fm.ts +576 -0
  264. package/src/prover/smt/solver/qe-lite.ts +381 -0
  265. package/src/prover/smt/solver/qi-queue.ts +362 -0
  266. package/src/prover/smt/solver/quant-tactics.ts +117 -0
  267. package/src/prover/smt/solver/quantifier-analyzer.ts +562 -0
  268. package/src/prover/smt/solver/quantifier-manager.ts +186 -0
  269. package/src/prover/smt/solver/random-gen.ts +10 -0
  270. package/src/prover/smt/solver/rational.ts +165 -0
  271. package/src/prover/smt/solver/ref-vector.ts +62 -0
  272. package/src/prover/smt/solver/relevancy.ts +247 -0
  273. package/src/prover/smt/solver/rewriter-tpl.ts +1159 -0
  274. package/src/prover/smt/solver/rewriter.ts +843 -0
  275. package/src/prover/smt/solver/rlimit.ts +79 -0
  276. package/src/prover/smt/solver/smtlib-parser.ts +526 -0
  277. package/src/prover/smt/solver/solver.ts +71 -0
  278. package/src/prover/smt/solver/sort.ts +35 -0
  279. package/src/prover/smt/solver/sticky-generations.ts +69 -0
  280. package/src/prover/smt/solver/theory-lra-axioms.ts +340 -0
  281. package/src/prover/smt/solver/theory-lra-bounds.ts +226 -0
  282. package/src/prover/smt/solver/theory-lra-final-check.ts +252 -0
  283. package/src/prover/smt/solver/theory-lra-internalize.ts +476 -0
  284. package/src/prover/smt/solver/theory-lra-model.ts +243 -0
  285. package/src/prover/smt/solver/theory-lra-propagate.ts +405 -0
  286. package/src/prover/smt/solver/theory-lra-state.ts +43 -0
  287. package/src/prover/smt/solver/theory-lra.ts +56 -0
  288. package/src/prover/smt/solver/var-subst.ts +258 -0
  289. package/src/prover/smt/solver/z3-license.txt +10 -0
  290. package/src/prover/smt/table.ts +170 -0
  291. package/src/prover/tlapm/cache.ts +236 -0
  292. package/src/prover/tlapm/ocaml-marshal.ts +166 -0
  293. package/src/prover/tlapm/tlapm.ts +96 -0
  294. package/src/prover/tlaps-module.ts +510 -0
  295. package/src/prover/verdict.ts +13 -0
  296. package/src/prover/zenon/LICENSE +32 -0
  297. package/src/prover/zenon/check/check.ts +105 -0
  298. package/src/prover/zenon/check/definitions.ts +144 -0
  299. package/src/prover/zenon/check/equality.ts +182 -0
  300. package/src/prover/zenon/check/functions.ts +62 -0
  301. package/src/prover/zenon/check/keys.ts +125 -0
  302. package/src/prover/zenon/check/propositional.ts +104 -0
  303. package/src/prover/zenon/check/records.ts +188 -0
  304. package/src/prover/zenon/check/relations.ts +121 -0
  305. package/src/prover/zenon/check/rewrites.ts +224 -0
  306. package/src/prover/zenon/check/sets.ts +302 -0
  307. package/src/prover/zenon/check/terms.ts +127 -0
  308. package/src/prover/zenon/check/tla.ts +126 -0
  309. package/src/prover/zenon/decide.ts +107 -0
  310. package/src/prover/zenon/encode.ts +378 -0
  311. package/src/prover/zenon/eqrel.ts +300 -0
  312. package/src/prover/zenon/equality-rules.ts +435 -0
  313. package/src/prover/zenon/expr.ts +551 -0
  314. package/src/prover/zenon/index-table.ts +350 -0
  315. package/src/prover/zenon/isar-case.ts +513 -0
  316. package/src/prover/zenon/isar.ts +1249 -0
  317. package/src/prover/zenon/limits.ts +15 -0
  318. package/src/prover/zenon/llproof.ts +173 -0
  319. package/src/prover/zenon/mltoll.ts +1566 -0
  320. package/src/prover/zenon/node.ts +297 -0
  321. package/src/prover/zenon/ocaml.ts +169 -0
  322. package/src/prover/zenon/parse.ts +247 -0
  323. package/src/prover/zenon/phrase.ts +191 -0
  324. package/src/prover/zenon/proof.ts +198 -0
  325. package/src/prover/zenon/propositional-rules.ts +387 -0
  326. package/src/prover/zenon/rules.ts +94 -0
  327. package/src/prover/zenon/search.ts +288 -0
  328. package/src/prover/zenon/tla/functions.ts +151 -0
  329. package/src/prover/zenon/tla/llproof.ts +480 -0
  330. package/src/prover/zenon/tla/records.ts +225 -0
  331. package/src/prover/zenon/tla/rewrites.ts +447 -0
  332. package/src/prover/zenon/tla/sets.ts +304 -0
  333. package/src/prover/zenon/tla/terms.ts +162 -0
  334. package/src/prover/zenon/tla/tla.ts +506 -0
  335. package/src/randomization.ts +39 -27
  336. package/src/resolve.ts +1474 -426
  337. package/src/runtime.ts +25 -7
  338. package/src/sany/builtins.ts +147 -0
  339. package/src/sany/generator.ts +3111 -0
  340. package/src/sany/levels.ts +1205 -0
  341. package/src/sany/lexer.ts +544 -0
  342. package/src/sany/linter.ts +122 -0
  343. package/src/sany/modules.ts +1398 -0
  344. package/src/sany/nodes.ts +463 -0
  345. package/src/sany/parse-error.ts +2161 -0
  346. package/src/sany/report.ts +355 -0
  347. package/src/sany/selectors.ts +736 -0
  348. package/src/sany/source.ts +247 -0
  349. package/src/sany/xml.ts +1016 -0
  350. package/src/search.ts +969 -0
  351. package/src/spec-description.ts +66 -29
  352. package/src/{standard-levels.ts → standard-definitions.ts} +118 -2
  353. package/src/standard-modules.ts +215 -164
  354. package/src/state-graph.ts +181 -0
  355. package/src/subexpressions.ts +231 -171
  356. package/src/substitution-levels.ts +40 -19
  357. package/src/successors.ts +253 -125
  358. package/src/symmetry.ts +194 -54
  359. package/src/tableau.ts +60 -32
  360. package/src/tlc/fingerprint.ts +214 -0
  361. package/src/{tlc-modules.ts → tlc/jar-data.ts} +4 -0
  362. package/src/tlc/messages.ts +441 -0
  363. package/src/{tlc-order.ts → tlc/order.ts} +84 -16
  364. package/src/{tlc-random.ts → tlc/random.ts} +30 -189
  365. package/src/tlc/replay.ts +659 -0
  366. package/src/{tlc-summary.ts → tlc/summary.ts} +20 -5
  367. package/src/{tlc-module.ts → tlc/tlc-operators.ts} +59 -50
  368. package/src/{tlc-ext.ts → tlc/tlcext-operators.ts} +63 -45
  369. package/src/tlc/version.ts +19 -0
  370. package/src/transfer.ts +44 -32
  371. package/src/values.ts +843 -241
  372. package/src/worker.ts +62 -0
  373. package/dist/parallel.cjs +0 -12
  374. package/dist/parallel.js +0 -12
  375. package/dist/run-cli.cjs +0 -28
  376. package/dist/run-cli.js +0 -28
  377. package/src/canonical.ts +0 -39
  378. package/src/cli-options.ts +0 -58
  379. package/src/obligation-expression.ts +0 -1060
  380. package/src/obligation-module.ts +0 -1042
  381. package/src/run-cli.ts +0 -478
package/src/parser.ts CHANGED
@@ -22,15 +22,30 @@ import type {
22
22
  StepBody,
23
23
  UseOrHide,
24
24
  } from "./ast";
25
- import { TlaSyntaxError } from "./errors";
26
- import { getNumeralValue, tokenize, type Token } from "./lexer";
25
+ import { createSanyError, formatRange, TlaSyntaxError } from "./errors";
26
+ import { getNumeralValue, readAtAsIdentifier, tokenize, type Token } from "./lexer";
27
+ import { getSanyParseError } from "./sany/parse-error";
27
28
 
28
- interface InfixOperator {
29
+ interface Precedence {
29
30
  low: number;
30
31
  high: number;
32
+ }
33
+
34
+ interface InfixOperator extends Precedence {
31
35
  isAssociative: boolean;
32
36
  }
33
37
 
38
+ // TLAplusParser.lastOp, the operator parsed last, and the operator an operand being parsed follows
39
+ // in its expression.
40
+ interface OperatorContext {
41
+ last?: Precedence;
42
+ preceding?: Precedence;
43
+ }
44
+
45
+ // SANY's precedences of a postfix operator and of the "[" of a function application.
46
+ const POSTFIX_PRECEDENCE: Precedence = { low: 15, high: 15 };
47
+ const FUNCTION_PRECEDENCE: Precedence = { low: 16, high: 16 };
48
+
34
49
  const createInfix = (low: number, high: number, isAssociative: boolean) => ({
35
50
  low,
36
51
  high,
@@ -135,10 +150,25 @@ const INFIX_OPERATORS = new Map<string, InfixOperator>([
135
150
  ["^^", createInfix(14, 14, false)],
136
151
  ]);
137
152
 
153
+ const NEGATION_PRECEDENCE = 12;
154
+
138
155
  const POSTFIX_OPERATORS = new Set(["^+", "^*", "^#"]);
139
156
 
140
157
  const PREFIX_OPERATOR_REFERENCES = new Set(["-", "~", "-."]);
141
158
 
159
+ // The prefix operators SANY reads in a definition's left-hand side, built-in ones included.
160
+ const DEFINABLE_PREFIX_OPERATORS = new Set([
161
+ "-.",
162
+ "~",
163
+ "[]",
164
+ "<>",
165
+ "ENABLED",
166
+ "UNCHANGED",
167
+ "SUBSET",
168
+ "UNION",
169
+ "DOMAIN",
170
+ ]);
171
+
142
172
  const EXPRESSION_PREFIXES = new Set([
143
173
  "-",
144
174
  "~",
@@ -167,29 +197,6 @@ const OPERATOR_ARGUMENTS = new Set([
167
197
  ...POSTFIX_OPERATORS,
168
198
  ]);
169
199
 
170
- const isOperatorName = (text: string) =>
171
- INFIX_OPERATORS.has(text) || POSTFIX_OPERATORS.has(text) || text === "-.";
172
-
173
- const getOperatorApplication = (
174
- operator: string,
175
- argument: Expression,
176
- location: SourceLocation,
177
- ): Expression => {
178
- switch (operator) {
179
- case "ENABLED":
180
- return { kind: "Enabled", expression: argument, location };
181
- case "UNCHANGED":
182
- return { kind: "Unchanged", expression: argument, location };
183
- case "[]":
184
- return { kind: "Always", expression: argument, location };
185
- case "<>":
186
- return { kind: "Eventually", expression: argument, location };
187
- case "'":
188
- return { kind: "Prime", expression: argument, location };
189
- default:
190
- return { kind: "Apply", operator, args: [argument], location };
191
- }
192
- };
193
200
  const SELECTOR_SYMBOLS = new Set(["<<", ">>", ":", "@", "("]);
194
201
 
195
202
  const UNIT_KEYWORDS = new Set([
@@ -260,6 +267,7 @@ const FACT_KEYWORDS = new Set([
260
267
  "IF",
261
268
  "LAMBDA",
262
269
  "LET",
270
+ "MODULE",
263
271
  "SF_",
264
272
  "SUBSET",
265
273
  "UNCHANGED",
@@ -289,30 +297,67 @@ const BUILTIN_CONSTANTS = new Set(["TRUE", "FALSE", "BOOLEAN", "STRING"]);
289
297
 
290
298
  const NO_OFFSIDE = -1;
291
299
 
292
- const getModuleHeader = (name: string) => new RegExp(`^-{4,}\\s*MODULE\\s+${name}\\s*-{3,}$`);
300
+ // A SANY InfixExpr or PostfixExpr.
301
+ const isOperatorExpression = (expression: Expression) =>
302
+ expression.kind === "Prime" ||
303
+ expression.kind === "Product" ||
304
+ ((expression.kind === "And" || expression.kind === "Or") && !expression.isBulleted) ||
305
+ (expression.kind === "Apply" &&
306
+ (expression.args.length === 2
307
+ ? INFIX_OPERATORS.has(expression.operator)
308
+ : POSTFIX_OPERATORS.has(expression.operator)));
309
+
310
+ const isOperatorName = (text: string) =>
311
+ INFIX_OPERATORS.has(text) || POSTFIX_OPERATORS.has(text) || text === "-.";
312
+
313
+ const getOperatorApplication = (
314
+ operator: string,
315
+ argument: Expression,
316
+ location: SourceLocation,
317
+ ): Expression => {
318
+ switch (operator) {
319
+ case "ENABLED":
320
+ return { kind: "Enabled", expression: argument, location };
321
+ case "UNCHANGED":
322
+ return { kind: "Unchanged", expression: argument, location };
323
+ case "[]":
324
+ return { kind: "Always", expression: argument, location };
325
+ case "<>":
326
+ return { kind: "Eventually", expression: argument, location };
327
+ case "'":
328
+ return { kind: "Prime", expression: argument, location };
329
+ default:
330
+ return { kind: "Apply", operator, args: [argument], location };
331
+ }
332
+ };
293
333
 
294
- // The text of a module that starts on its own line in a file, as TLC's monolith extractor reads
295
- // modules that follow the root module.
334
+ // MonolithSpecExtractor.module: a module that no file defines can follow the root module in the
335
+ // root module's file, from its ---- MODULE line to the next ==== line.
296
336
  export const extractModule = (source: string, name: string) => {
337
+ const header = new RegExp(`^-{4,}\\s*MODULE\\s+${name}\\s*-{3,}$`);
297
338
  const lines = source.split(/\r?\n/);
298
- const start = lines.findIndex((line) => getModuleHeader(name).test(line));
339
+ const start = lines.findIndex((line) => header.test(line));
299
340
  if (start === -1) return undefined;
300
341
  const end = lines.findIndex((line, index) => index > start && line.startsWith("===="));
301
- return lines.slice(start, end === -1 ? undefined : end + 1).join("\n");
342
+ return `${lines.slice(start, end === -1 ? undefined : end + 1).join("\n")}\n`;
302
343
  };
303
344
 
304
- // isTlapm parses as tlapm does for proof obligations, which accepts and rejects some modules that
305
- // SANY does not.
306
- const parse = (source: string, isTlapm: boolean): Module => {
307
- const tokens = tokenize(source);
345
+ // The tlapm mode parses as tlapm does for proof obligations, which accepts and rejects some modules
346
+ // that SANY does not. The sany mode leaves the checks that SANY makes after parsing to the SANY
347
+ // generator.
348
+ type ParseMode = "tlc" | "tlapm" | "sany";
349
+
350
+ const parse = (source: string, mode: ParseMode): Module => {
351
+ const isTlapm = mode === "tlapm";
352
+ const tokens = isTlapm ? tokenize(source) : tokenize(source).map(readAtAsIdentifier);
308
353
  const cursor = { index: 0, offsideColumns: [] as number[] };
354
+ const operators: OperatorContext = {};
309
355
  // A RECURSIVE declaration covers the definitions of its own LET or module.
310
356
  const recursiveScopes: Set<string>[] = [];
311
357
  const factNames = new Set<string>();
312
358
  // The NEW, TAKE, and PICK names in scope, which a DEF clause cannot cite.
313
359
  const proofScopes: Set<string>[] = [];
314
- // A fact may cite an operator of a parameterized instance without the instance's arguments.
315
- const factStart = { index: -1 };
360
+ // SANY reports a location in a nested module as one in the module of its file.
316
361
  const openModules: Module[] = [];
317
362
 
318
363
  const isRecursiveName = (name: string) => recursiveScopes[recursiveScopes.length - 1].has(name);
@@ -327,15 +372,14 @@ const parse = (source: string, isTlapm: boolean): Module => {
327
372
  const tokenEnds: SourceLocation[] = [];
328
373
  const tokenRanges: SourceRange[] = [];
329
374
 
330
- const getRange = (startIndex: number) => {
331
- const endIndex = cursor.index - 1;
375
+ const getRange = (startIndex: number, endIndex = cursor.index - 1) => {
332
376
  const cached = startIndex === endIndex ? tokenRanges[startIndex] : undefined;
333
377
  if (cached) return cached;
334
378
  const last = tokens[endIndex];
335
379
  tokenStarts[startIndex] ??= getLocation(tokens[startIndex]);
336
380
  tokenEnds[endIndex] ??= { line: last.line, column: last.endColumn };
337
381
  const range = {
338
- module: openModules[openModules.length - 1].name,
382
+ module: openModules[0].name,
339
383
  start: tokenStarts[startIndex],
340
384
  end: tokenEnds[endIndex],
341
385
  };
@@ -360,7 +404,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
360
404
  return token.column <= offsideColumn ? { ...token, kind: "End" as const, text: "" } : token;
361
405
  };
362
406
 
363
- const describe = (token: Token) =>
407
+ const describeToken = (token: Token) =>
364
408
  token.kind === "End" ? "end of input" : JSON.stringify(token.text);
365
409
 
366
410
  const unitStart = { index: 0 };
@@ -433,8 +477,12 @@ const parse = (source: string, isTlapm: boolean): Module => {
433
477
  const createUnexpected = (message: string, token: Token = peekRaw()) =>
434
478
  createError(message, token, token);
435
479
 
480
+ // TLAplusParser.isFieldNameToken: a keyword or an underscore names a field or a module too.
436
481
  const isFieldName = (token: Token) =>
437
- (token.kind === "Identifier" || token.kind === "Keyword") && !isTlapmKeyword(token);
482
+ (token.kind === "Identifier" ||
483
+ token.kind === "Keyword" ||
484
+ (token.kind === "Operator" && token.text === "_")) &&
485
+ !isTlapmKeyword(token);
438
486
 
439
487
  const isAt = (text: string, offset = 0) => {
440
488
  const token = peek(offset);
@@ -456,21 +504,56 @@ const parse = (source: string, isTlapm: boolean): Module => {
456
504
 
457
505
  const expect = (text: string) => {
458
506
  if (!isAt(text))
459
- throw createUnexpected(`Expected ${JSON.stringify(text)} but found ${describe(peek())}`);
507
+ throw createUnexpected(`Expected ${JSON.stringify(text)} but found ${describeToken(peek())}`);
460
508
  return advance();
461
509
  };
462
510
 
463
511
  const expectIdentifier = () => {
464
512
  const token = peek();
465
513
  if (token.kind !== "Identifier") {
466
- throw createUnexpected(`Expected an identifier but found ${describe(token)}`);
514
+ throw createUnexpected(`Expected an identifier but found ${describeToken(token)}`);
467
515
  }
468
516
  if (isTlapmKeyword(token)) throw createUnexpected(`Unexpected keyword ${token.text}`);
469
517
  cursor.index++;
470
518
  return token.text;
471
519
  };
472
520
 
473
- const withoutOffside = <Result>(parse: () => Result) => {
521
+ const expectName = () => {
522
+ const start = cursor.index;
523
+ return { name: expectIdentifier(), range: getRange(start) };
524
+ };
525
+
526
+ const getNames = (names: { name: string; range: SourceRange }[]) => ({
527
+ names: names.map((item) => item.name),
528
+ ranges: names.map((item) => item.range),
529
+ });
530
+
531
+ // TLAplusParser.Substitution: an identifier, or a prefix, infix or postfix operator.
532
+ const expectSubstitutionTarget = () => {
533
+ const token = peek();
534
+ const isOperator =
535
+ token.kind !== "String" &&
536
+ (DEFINABLE_PREFIX_OPERATORS.has(token.text) ||
537
+ INFIX_OPERATORS.has(token.text) ||
538
+ POSTFIX_OPERATORS.has(token.text) ||
539
+ token.text === "'");
540
+ if (!isOperator) return expectIdentifier();
541
+ cursor.index++;
542
+ return token.text;
543
+ };
544
+
545
+ // SANY takes a keyword for the name of a module, as it does for a field.
546
+ const keywordModuleName = { isUsed: false };
547
+ const expectModuleName = () => {
548
+ if (peek().kind === "Identifier" || !isFieldName(peek())) return expectIdentifier();
549
+ keywordModuleName.isUsed = true;
550
+ return advance().text;
551
+ };
552
+
553
+ // tlapm reads a bracketed expression apart from the junction list around it, whose alignment
554
+ // SANY keeps applying.
555
+ const withBracketLayout = <Result>(parse: () => Result) => {
556
+ if (!isTlapm) return parse();
474
557
  cursor.offsideColumns.push(NO_OFFSIDE);
475
558
  const result = parse();
476
559
  cursor.offsideColumns.pop();
@@ -512,10 +595,13 @@ const parse = (source: string, isTlapm: boolean): Module => {
512
595
  };
513
596
 
514
597
  const parsePattern = (): BoundPattern => {
515
- if (!accept("<<")) return { kind: "Name", name: expectIdentifier() };
516
- const names = parseSeparated(expectIdentifier);
598
+ if (!accept("<<")) {
599
+ const named = expectName();
600
+ return { kind: "Name", name: named.name, ranges: [named.range] };
601
+ }
602
+ const names = getNames(parseSeparated(expectName));
517
603
  expect(">>");
518
- return { kind: "Tuple", names };
604
+ return { kind: "Tuple", names: names.names, ranges: names.ranges };
519
605
  };
520
606
 
521
607
  const parseBounds = () =>
@@ -541,7 +627,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
541
627
  );
542
628
  }
543
629
  if (isAt("<<") || isAt("(")) return parsePrimary();
544
- throw createUnexpected(`Expected a subscript but found ${describe(token)}`);
630
+ throw createUnexpected(`Expected a subscript but found ${describeToken(token)}`);
545
631
  };
546
632
 
547
633
  const isDefinitionAhead = (operator: Token) => {
@@ -558,8 +644,9 @@ const parse = (source: string, isTlapm: boolean): Module => {
558
644
  );
559
645
  };
560
646
 
647
+ // SANY's OpOrExpr reads an operator as an argument only before what ends the argument, and as
648
+ // the start of an expression, such as -.(1), otherwise.
561
649
  const isStandalone = (operator: Token) => {
562
- if (!EXPRESSION_PREFIXES.has(operator.text)) return true;
563
650
  const token = peek(1);
564
651
  return (
565
652
  token.kind === "End" ||
@@ -598,7 +685,12 @@ const parse = (source: string, isTlapm: boolean): Module => {
598
685
  if (isOperatorAlone) {
599
686
  cursor.index++;
600
687
  return withRange(
601
- { kind: "OperatorReference", operator: token.text, location: getLocation(token) },
688
+ {
689
+ kind: "OperatorReference",
690
+ operator: token.text,
691
+ spelling: token.spelling,
692
+ location: getLocation(token),
693
+ },
602
694
  cursor.index - 1,
603
695
  );
604
696
  }
@@ -608,32 +700,52 @@ const parse = (source: string, isTlapm: boolean): Module => {
608
700
  cursor.index++;
609
701
  const location = getLocation(token);
610
702
  if (POSTFIX_OPERATORS.has(token.text)) {
611
- return { kind: "OperatorReference", operator: token.text, location };
703
+ return withRange(
704
+ { kind: "OperatorReference", operator: token.text, spelling: token.spelling, location },
705
+ cursor.index - 1,
706
+ );
612
707
  }
613
708
  const argument: Expression = { kind: "Identifier", name: "argument", location };
614
- return {
615
- kind: "Lambda",
616
- params: [argument.name],
617
- body: getOperatorApplication(token.text, argument, location),
618
- location,
619
- };
709
+ return withRange(
710
+ {
711
+ kind: "Lambda",
712
+ params: [argument.name],
713
+ body: getOperatorApplication(token.text, argument, location),
714
+ operator: token.text,
715
+ location: getLocation(token),
716
+ },
717
+ cursor.index - 1,
718
+ );
620
719
  }
621
720
  if (isAt("LAMBDA")) {
622
721
  const start = cursor.index;
623
722
  advance();
624
- const params = parseSeparated(expectIdentifier);
723
+ const params = getNames(parseSeparated(expectName));
625
724
  expect(":");
626
725
  const body = parseExpression();
627
- return withRange({ kind: "Lambda", params, body, location: getLocation(token) }, start);
726
+ return withRange(
727
+ {
728
+ kind: "Lambda",
729
+ params: params.names,
730
+ paramRanges: params.ranges,
731
+ body,
732
+ location: getLocation(token),
733
+ },
734
+ start,
735
+ );
628
736
  }
629
737
  return parseExpression();
630
738
  };
631
739
 
740
+ const lastArguments: { range: SourceRange | undefined } = { range: undefined };
741
+
632
742
  const parseArguments = () =>
633
- withoutOffside(() => {
743
+ withBracketLayout(() => {
744
+ const start = cursor.index;
634
745
  expect("(");
635
746
  const args = parseSeparated(parseArgument);
636
747
  expect(")");
748
+ lastArguments.range = getRange(start);
637
749
  return args;
638
750
  });
639
751
 
@@ -655,15 +767,25 @@ const parse = (source: string, isTlapm: boolean): Module => {
655
767
  };
656
768
 
657
769
  const parseBracket = (start: Token): Expression =>
658
- withoutOffside(() => {
770
+ withBracketLayout(() => {
659
771
  const location = getLocation(start);
660
- if (peek().kind === "Identifier" && (isAt("|->", 1) || isAt(":", 1))) {
661
- const kind = isAt("|->", 1) ? "Record" : "RecordSet";
662
- const fields = parseSeparated(() => {
663
- const name = expectIdentifier();
664
- expect(kind === "Record" ? "|->" : ":");
665
- return { name, value: parseExpression() };
666
- });
772
+ // SANY takes a keyword for the first field of a record, as it does for a selected field.
773
+ const isIdentifier = peek().kind === "Identifier";
774
+ const isRecord = isAt("|->", 1) && (isIdentifier || isFieldName(peek()));
775
+ if (isRecord || (isIdentifier && isAt(":", 1))) {
776
+ const kind = isRecord ? "Record" : "RecordSet";
777
+ const parseField = (readName: () => string) => {
778
+ const fieldStart = cursor.index;
779
+ const fieldLocation = getLocation(peek());
780
+ const name = readName();
781
+ fieldLocation.range = getRange(fieldStart);
782
+ expect(isRecord ? "|->" : ":");
783
+ return { name, value: parseExpression(), location: fieldLocation };
784
+ };
785
+ const fields = [
786
+ parseField(() => (isIdentifier ? expectIdentifier() : advance().text)),
787
+ ...(accept(",") ? parseSeparated(() => parseField(expectIdentifier)) : []),
788
+ ];
667
789
  expect("]");
668
790
  return { kind, fields, location };
669
791
  }
@@ -687,7 +809,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
687
809
  while (isAt(".") || isAt("[")) {
688
810
  if (accept(".")) {
689
811
  if (!isFieldName(peek()))
690
- throw createUnexpected(`Expected a field name but found ${describe(peek())}`);
812
+ throw createUnexpected(`Expected a field name but found ${describeToken(peek())}`);
691
813
  path.push({ kind: "Field", name: advance().text });
692
814
  continue;
693
815
  }
@@ -701,17 +823,29 @@ const parse = (source: string, isTlapm: boolean): Module => {
701
823
  expect("]");
702
824
  return { kind: "Except", function: expression, updates, location };
703
825
  }
826
+ if (!isTlapm && !isAt("]_")) {
827
+ const args = [expression];
828
+ while (accept(",")) args.push(parseExpression());
829
+ expect("]");
830
+ return { kind: "Bracket", args, location };
831
+ }
704
832
  expect("]_");
705
- return {
706
- kind: "BoxAction",
707
- action: expression,
708
- subscript: parseSubscript(),
709
- location,
710
- };
833
+ return { kind: "BoxAction", action: expression, subscript: parseSubscript(), location };
711
834
  });
712
835
 
836
+ // SANY reads the set after the \in of {x \in S} as a whole expression, whatever operators it has.
837
+ const parseSetMembership = (): Expression => {
838
+ const start = cursor.index;
839
+ const element = withRange(parsePrefix(), start);
840
+ const location = getLocation(advance());
841
+ return withRange(
842
+ { kind: "Apply", operator: "\\in", args: [element, parseExpression()], location },
843
+ start,
844
+ );
845
+ };
846
+
713
847
  const parseBrace = (start: Token): Expression =>
714
- withoutOffside(() => {
848
+ withBracketLayout(() => {
715
849
  const location = getLocation(start);
716
850
  if (accept("}")) return { kind: "SetEnumeration", elements: [], location };
717
851
  if (isBoundAhead() && (peek(1).text === "\\in" || isAt("<<"))) {
@@ -726,7 +860,8 @@ const parse = (source: string, isTlapm: boolean): Module => {
726
860
  }
727
861
  cursor.index = checkpoint;
728
862
  }
729
- const first = parseExpression();
863
+ const first =
864
+ peek().kind === "Identifier" && isAt("\\in", 1) ? parseSetMembership() : parseExpression();
730
865
  if (accept(":")) {
731
866
  const bounds = parseBounds();
732
867
  expect("}");
@@ -740,7 +875,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
740
875
 
741
876
  const parseTuple = (start: Token): Expression => {
742
877
  const location = getLocation(start);
743
- const elements = withoutOffside(() =>
878
+ const elements = withBracketLayout(() =>
744
879
  isAt(">>") || isAt(">>_") ? [] : parseSeparated(() => parseExpression()),
745
880
  );
746
881
  if (accept(">>_")) {
@@ -761,12 +896,13 @@ const parse = (source: string, isTlapm: boolean): Module => {
761
896
  expect(":");
762
897
  return { kind, bounds, body: parseExpression(), location };
763
898
  }
764
- const names = parseSeparated(expectIdentifier);
899
+ const names = getNames(parseSeparated(expectName));
765
900
  expect(":");
766
901
  return {
767
902
  kind: "UnboundedQuantifier",
768
903
  quantifier: start.text === "\\A" || start.text === "\\AA" ? "Forall" : "Exists",
769
- names,
904
+ names: names.names,
905
+ nameRanges: names.ranges,
770
906
  body: parseExpression(),
771
907
  isTemporal,
772
908
  location,
@@ -820,8 +956,8 @@ const parse = (source: string, isTlapm: boolean): Module => {
820
956
  return { kind: "Name", name: token.text, args: isAt("(") ? parseArguments() : [] };
821
957
  };
822
958
 
823
- const parsePrimary = (): Expression => {
824
- const isFactStart = cursor.index === factStart.index;
959
+ const parsePrimary = (preceding?: Precedence): Expression => {
960
+ const start = cursor.index;
825
961
  const token = advance();
826
962
  const location = getLocation(token);
827
963
  if (isTlapm && token.kind === "Keyword" && token.text === "LAMBDA") {
@@ -845,53 +981,90 @@ const parse = (source: string, isTlapm: boolean): Module => {
845
981
  if (token.kind === "Identifier" || isStep) {
846
982
  const name = isStep ? (getStepName(token) ?? token.text) : token.text;
847
983
  if (isLabelAhead()) {
848
- const params = accept("(") ? parseSeparated(expectIdentifier) : [];
849
- if (params.length > 0) expect(")");
984
+ const params = getNames(accept("(") ? parseSeparated(expectName) : []);
985
+ if (params.names.length > 0) expect(")");
850
986
  expect("::");
851
- return { kind: "Label", name, params, body: parseExpression(), location };
987
+ const body = parseExpression();
988
+ // TLAplusParser.labelDoesNotChangeParse.
989
+ if (
990
+ !isTlapm &&
991
+ preceding !== undefined &&
992
+ operators.last !== undefined &&
993
+ isOperatorExpression(body) &&
994
+ preceding.high >= operators.last.low
995
+ ) {
996
+ throw createError("Removing the label would change expression parsing", token);
997
+ }
998
+ return {
999
+ kind: "Label",
1000
+ name,
1001
+ params: params.names,
1002
+ paramRanges: params.ranges,
1003
+ body,
1004
+ location,
1005
+ };
852
1006
  }
853
1007
  const hasArguments = isAt("(");
1008
+ if (name === "@" && !hasArguments && !isSelectorAhead())
1009
+ return { kind: "ExceptAt", location };
854
1010
  const args = hasArguments ? parseArguments() : [];
1011
+ const argumentRanges = [hasArguments ? lastArguments.range : undefined];
855
1012
  if (!isSelectorAhead()) {
856
1013
  return hasArguments
857
- ? { kind: "Apply", operator: name, args, location }
1014
+ ? { kind: "Apply", operator: name, args, argumentsRange: lastArguments.range, location }
858
1015
  : { kind: "Identifier", name, location };
859
1016
  }
860
- const instance = openModules
861
- .flatMap((module) => module.instances)
862
- .find((candidate) => candidate.name === name);
863
- if (instance && !isFactStart && !isTlapm && instance.params.length !== args.length) {
864
- throw createError(
865
- `The operator ${name} requires ${instance.params.length} arguments`,
866
- token,
867
- );
868
- }
869
1017
  const selectors: Selector[] = [{ kind: "Name", name, args }];
1018
+ const selectorRanges = [getRange(start, start)];
870
1019
  while (isSelectorAhead()) {
871
1020
  advance();
1021
+ selectorRanges.push(getRange(cursor.index, cursor.index));
1022
+ lastArguments.range = undefined;
872
1023
  selectors.push(parseSelector());
1024
+ argumentRanges.push(lastArguments.range);
873
1025
  }
874
1026
  const names = selectors.flatMap((selector) =>
875
1027
  selector.kind === "Name" ? [selector.name] : [],
876
1028
  );
877
- if (names.length < selectors.length) return { kind: "Subexpression", selectors, location };
878
1029
  const operator = names.join("!");
879
1030
  const qualifiedArgs = selectors.flatMap((selector) =>
880
1031
  "args" in selector ? selector.args : [],
881
1032
  );
882
- if (qualifiedArgs.length === 0) return { kind: "Identifier", name: operator, location };
883
1033
  const argumentCounts = selectors.map((selector) =>
884
1034
  "args" in selector ? selector.args.length : 0,
885
1035
  );
886
- return argumentCounts.slice(0, -1).some((count) => count > 0)
887
- ? { kind: "Apply", operator, args: qualifiedArgs, argumentCounts, location }
888
- : { kind: "Apply", operator, args: qualifiedArgs, location };
1036
+ const argumentsRange = argumentRanges.at(-1) ?? getRange(start);
1037
+ return names.length < selectors.length
1038
+ ? { kind: "Subexpression", selectors, selectorRanges, argumentRanges, location }
1039
+ : qualifiedArgs.length === 0
1040
+ ? { kind: "Identifier", name: operator, selectorRanges, location }
1041
+ : {
1042
+ kind: "Apply",
1043
+ operator,
1044
+ args: qualifiedArgs,
1045
+ ...(argumentCounts.slice(0, -1).some((count) => count > 0) && { argumentCounts }),
1046
+ argumentsRange,
1047
+ selectorRanges,
1048
+ argumentRanges,
1049
+ location,
1050
+ };
1051
+ }
1052
+ // SANY reads an infix or postfix operator as a primary expression, with or without arguments.
1053
+ if (token.kind === "Operator" && isOperatorName(token.text) && isAt("(")) {
1054
+ return {
1055
+ kind: "Apply",
1056
+ operator: token.text,
1057
+ spelling: token.spelling,
1058
+ args: parseArguments(),
1059
+ location,
1060
+ };
1061
+ }
1062
+ if (token.kind === "Operator" && isOperatorName(token.text) && !isTlapm) {
1063
+ return { kind: "Identifier", name: token.text, spelling: token.spelling, location };
889
1064
  }
890
- if (token.kind === "Operator" && isOperatorName(token.text) && isAt("("))
891
- return { kind: "Apply", operator: token.text, args: parseArguments(), location };
892
1065
  switch (token.text) {
893
1066
  case "(": {
894
- const expression = withoutOffside(() => parseExpression());
1067
+ const expression = withBracketLayout(() => parseExpression());
895
1068
  expect(")");
896
1069
  return expression;
897
1070
  }
@@ -947,7 +1120,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
947
1120
  case "WF_":
948
1121
  case "SF_": {
949
1122
  const subscript = parseSubscript();
950
- const action = withoutOffside(() => {
1123
+ const action = withBracketLayout(() => {
951
1124
  expect("(");
952
1125
  const expression = parseExpression();
953
1126
  expect(")");
@@ -961,10 +1134,28 @@ const parse = (source: string, isTlapm: boolean): Module => {
961
1134
  };
962
1135
  }
963
1136
  }
964
- throw createUnexpected(`Unexpected ${describe(token)}`, token);
1137
+ throw createUnexpected(`Unexpected ${describeToken(token)}`, token);
1138
+ };
1139
+
1140
+ // SANY rejects the operator after a prefix operator's operand unless it binds looser than the
1141
+ // prefix operator.
1142
+ const parsePrefixOperand = (operator: Token, low: number, high: number) => {
1143
+ operators.last = operators.preceding = { low, high };
1144
+ const operand = parseExpression(high + 1);
1145
+ const next = peek();
1146
+ const nextHigh =
1147
+ next.text === "'" || POSTFIX_OPERATORS.has(next.text)
1148
+ ? POSTFIX_PRECEDENCE.high
1149
+ : INFIX_OPERATORS.get(next.text)?.high;
1150
+ if (!isTlapm && next.kind === "Operator" && nextHigh !== undefined && nextHigh >= low) {
1151
+ throw createError(`Precedence conflict between ${operator.text} and ${next.text}`, next);
1152
+ }
1153
+ return operand;
965
1154
  };
966
1155
 
967
1156
  const parsePrefix = (): Expression => {
1157
+ const preceding = operators.preceding;
1158
+ operators.preceding = undefined;
968
1159
  const token = peek();
969
1160
  const location = getLocation(token);
970
1161
  if (token.kind === "Operator" && (token.text === "/\\" || token.text === "\\/")) {
@@ -974,30 +1165,46 @@ const parse = (source: string, isTlapm: boolean): Module => {
974
1165
  switch (token.text) {
975
1166
  case "~":
976
1167
  advance();
977
- return { kind: "Apply", operator: "~", args: [parseExpression(5)], location };
1168
+ return {
1169
+ kind: "Apply",
1170
+ operator: "~",
1171
+ args: [parsePrefixOperand(token, 4, 4)],
1172
+ location,
1173
+ };
978
1174
  case "-":
979
1175
  advance();
980
- return { kind: "Apply", operator: "-.", args: [parseExpression(13)], location };
1176
+ return {
1177
+ kind: "Apply",
1178
+ operator: "-.",
1179
+ args: [parsePrefixOperand(token, NEGATION_PRECEDENCE, NEGATION_PRECEDENCE)],
1180
+ location,
1181
+ };
981
1182
  case "[]":
982
1183
  advance();
983
- return { kind: "Always", expression: parseExpression(16), location };
1184
+ return { kind: "Always", expression: parsePrefixOperand(token, 4, 15), location };
984
1185
  case "<>":
985
1186
  advance();
986
- return { kind: "Eventually", expression: parseExpression(16), location };
1187
+ return { kind: "Eventually", expression: parsePrefixOperand(token, 4, 15), location };
987
1188
  case "ENABLED":
988
1189
  advance();
989
- return { kind: "Enabled", expression: parseExpression(16), location };
1190
+ return { kind: "Enabled", expression: parsePrefixOperand(token, 4, 15), location };
990
1191
  case "UNCHANGED":
991
1192
  advance();
992
- return { kind: "Unchanged", expression: parseExpression(16), location };
1193
+ return { kind: "Unchanged", expression: parsePrefixOperand(token, 4, 15), location };
993
1194
  case "SUBSET":
994
1195
  case "UNION":
995
1196
  case "DOMAIN":
996
1197
  advance();
997
- return { kind: "Apply", operator: token.text, args: [parseExpression(9)], location };
1198
+ return {
1199
+ kind: "Apply",
1200
+ operator: token.text,
1201
+ // tlapm gives these operators the precedence 8 of the TLA+ book, and SANY 10-13.
1202
+ args: [isTlapm ? parseExpression(9) : parsePrefixOperand(token, 10, 13)],
1203
+ location,
1204
+ };
998
1205
  }
999
1206
  }
1000
- return parsePrimary();
1207
+ return parsePrimary(preceding);
1001
1208
  };
1002
1209
 
1003
1210
  const parseExpression = (minimumPrecedence = 0): Expression => {
@@ -1013,21 +1220,30 @@ const parse = (source: string, isTlapm: boolean): Module => {
1013
1220
  const location = getLocation(token);
1014
1221
  if (token.text === "'" && minimumPrecedence <= 15) {
1015
1222
  advance();
1223
+ operators.last = POSTFIX_PRECEDENCE;
1016
1224
  state.left = withRange({ kind: "Prime", expression: state.left, location }, start);
1017
1225
  continue;
1018
1226
  }
1019
1227
  if (POSTFIX_OPERATORS.has(token.text) && minimumPrecedence <= 15) {
1020
1228
  advance();
1229
+ operators.last = POSTFIX_PRECEDENCE;
1021
1230
  state.left = withRange(
1022
- { kind: "Apply", operator: token.text, args: [state.left], location },
1231
+ {
1232
+ kind: "Apply",
1233
+ operator: token.text,
1234
+ spelling: token.spelling,
1235
+ args: [state.left],
1236
+ location,
1237
+ },
1023
1238
  start,
1024
1239
  );
1025
1240
  continue;
1026
1241
  }
1027
1242
  if (token.text === "[") {
1028
1243
  advance();
1029
- const args = withoutOffside(() => parseSeparated(() => parseExpression()));
1030
- withoutOffside(() => expect("]"));
1244
+ const args = withBracketLayout(() => parseSeparated(() => parseExpression()));
1245
+ withBracketLayout(() => expect("]"));
1246
+ operators.last = FUNCTION_PRECEDENCE;
1031
1247
  state.left = withRange(
1032
1248
  { kind: "FunctionApplication", function: state.left, args, location },
1033
1249
  start,
@@ -1054,21 +1270,37 @@ const parse = (source: string, isTlapm: boolean): Module => {
1054
1270
  }
1055
1271
  }
1056
1272
  advance();
1273
+ // SANY reads - after an infix operator as prefix -, and rejects it after one that binds tighter.
1274
+ if (infix.low > NEGATION_PRECEDENCE && isAt("-")) {
1275
+ throw createError(`Precedence conflict between ${token.text} and -`, peek());
1276
+ }
1277
+ operators.last = operators.preceding = infix;
1057
1278
  const right = parseExpression(infix.high + 1);
1058
1279
  const left = state.left;
1059
1280
  if (token.text === "/\\" || token.text === "\\/") {
1060
1281
  const kind = token.text === "/\\" ? "And" : "Or";
1282
+ const prefixEnds = [getRange(start).end];
1061
1283
  state.left =
1062
1284
  left.kind === kind && previous?.text === token.text
1063
- ? { ...left, operands: [...left.operands, right] }
1064
- : { kind, operands: [left, right], location };
1285
+ ? {
1286
+ ...left,
1287
+ operands: [...left.operands, right],
1288
+ prefixEnds: [...(left.prefixEnds ?? []), ...prefixEnds],
1289
+ }
1290
+ : { kind, operands: [left, right], prefixEnds, location };
1065
1291
  } else if (token.text === "\\X") {
1066
1292
  state.left =
1067
1293
  left.kind === "Product" && previous?.text === "\\X"
1068
1294
  ? { ...left, factors: [...left.factors, right] }
1069
1295
  : { kind: "Product", factors: [left, right], location };
1070
1296
  } else {
1071
- state.left = { kind: "Apply", operator: token.text, args: [left, right], location };
1297
+ state.left = {
1298
+ kind: "Apply",
1299
+ operator: token.text,
1300
+ spelling: token.spelling,
1301
+ args: [left, right],
1302
+ location,
1303
+ };
1072
1304
  }
1073
1305
  state.left = withRange(state.left, start);
1074
1306
  state.previous = { ...infix, text: token.text };
@@ -1088,7 +1320,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
1088
1320
  const body = parseExpression();
1089
1321
  const last = tokens[cursor.index - 1];
1090
1322
  const end = { line: last.line, column: last.endColumn };
1091
- return { body, bodyRange: { module: openModules[openModules.length - 1].name, start, end } };
1323
+ return { body, bodyRange: { module: openModules[0].name, start, end } };
1092
1324
  };
1093
1325
 
1094
1326
  const parseDefinition = (isLocal: boolean): Definition | Instance => {
@@ -1096,6 +1328,16 @@ const parse = (source: string, isTlapm: boolean): Module => {
1096
1328
  return withRange(parseDefinitionUnit(isLocal), start);
1097
1329
  };
1098
1330
 
1331
+ const toParam = (named: { name: string; range: SourceRange }): OperatorParam => ({
1332
+ name: named.name,
1333
+ arity: 0,
1334
+ location: {
1335
+ line: named.range.start.line,
1336
+ column: named.range.start.column,
1337
+ range: named.range,
1338
+ },
1339
+ });
1340
+
1099
1341
  const parseDefinitionUnit = (isLocal: boolean): Definition | Instance => {
1100
1342
  const token = peek();
1101
1343
  const location = getLocation(token);
@@ -1115,28 +1357,27 @@ const parse = (source: string, isTlapm: boolean): Module => {
1115
1357
  peek(2).kind === "Identifier" &&
1116
1358
  isAt("==", 3)
1117
1359
  ) {
1118
- const left = expectIdentifier();
1360
+ const left = expectName();
1119
1361
  const operator = advance().text;
1120
- const right = expectIdentifier();
1362
+ const right = expectName();
1121
1363
  expect("==");
1122
- return parseOperator(operator, [
1123
- { name: left, arity: 0 },
1124
- { name: right, arity: 0 },
1125
- ]);
1364
+ return parseOperator(operator, [toParam(left), toParam(right)]);
1126
1365
  }
1127
- const isPrefixDefinition = token.kind === "Operator" && token.text === "-.";
1366
+ const isPrefixDefinition =
1367
+ token.kind !== "String" && DEFINABLE_PREFIX_OPERATORS.has(token.text);
1128
1368
  const isPostfixDefinition =
1129
1369
  token.kind === "Identifier" && POSTFIX_OPERATORS.has(peek(1).text) && isAt("==", 2);
1130
1370
  if (isPrefixDefinition || isPostfixDefinition) {
1131
1371
  const operator = isPrefixDefinition ? token.text : peek(1).text;
1132
- cursor.index += isPrefixDefinition ? 1 : 2;
1133
- const param = isPrefixDefinition ? expectIdentifier() : token.text;
1372
+ if (isPrefixDefinition) advance();
1373
+ const param = expectName();
1374
+ if (isPostfixDefinition) advance();
1134
1375
  expect("==");
1135
- return parseOperator(operator, [{ name: param, arity: 0 }]);
1376
+ return parseOperator(operator, [toParam(param)]);
1136
1377
  }
1137
1378
  const name = expectIdentifier();
1138
1379
  if (accept("[")) {
1139
- const bounds = withoutOffside(() => parseBounds());
1380
+ const bounds = withBracketLayout(() => parseBounds());
1140
1381
  expect("]");
1141
1382
  expect("==");
1142
1383
  return {
@@ -1167,12 +1408,14 @@ const parse = (source: string, isTlapm: boolean): Module => {
1167
1408
  ): Instance => {
1168
1409
  const start = cursor.index;
1169
1410
  expect("INSTANCE");
1170
- const module = expectIdentifier();
1411
+ const module = expectModuleName();
1171
1412
  const substitutions = accept("WITH")
1172
1413
  ? parseSeparated(() => {
1173
- const target = advance().text;
1414
+ const targetStart = cursor.index;
1415
+ const target = expectSubstitutionTarget();
1416
+ const nameRange = getRange(targetStart);
1174
1417
  expect("<-");
1175
- return { name: target, expression: parseArgument() };
1418
+ return { name: target, nameRange, expression: parseArgument() };
1176
1419
  })
1177
1420
  : [];
1178
1421
  return {
@@ -1188,6 +1431,11 @@ const parse = (source: string, isTlapm: boolean): Module => {
1188
1431
  };
1189
1432
 
1190
1433
  const parseDeclaration = (): Declaration => {
1434
+ const start = cursor.index;
1435
+ return withRange(parseDeclarationUnit(), start);
1436
+ };
1437
+
1438
+ const parseDeclarationUnit = (): Declaration => {
1191
1439
  const location = getLocation(peek());
1192
1440
  if (isAt("_") && peek(1).kind === "Operator") {
1193
1441
  advance();
@@ -1233,7 +1481,12 @@ const parse = (source: string, isTlapm: boolean): Module => {
1233
1481
  const token = peek();
1234
1482
  const next = peek(1);
1235
1483
  if (token.kind !== "Identifier") {
1236
- return isAt("-.") && next.kind === "Identifier" && isAt("==", 2);
1484
+ return (
1485
+ token.kind !== "String" &&
1486
+ DEFINABLE_PREFIX_OPERATORS.has(token.text) &&
1487
+ next.kind === "Identifier" &&
1488
+ isAt("==", 2)
1489
+ );
1237
1490
  }
1238
1491
  if (isAt("(", 1) || isAt("[", 1)) return isAt("==", getClosingOffset(1));
1239
1492
  if (next.kind === "Operator" && POSTFIX_OPERATORS.has(next.text)) return isAt("==", 2);
@@ -1325,7 +1578,6 @@ const parse = (source: string, isTlapm: boolean): Module => {
1325
1578
  // start of an expression.
1326
1579
  const parseFact = (): Fact => {
1327
1580
  const start = cursor.index;
1328
- factStart.index = start;
1329
1581
  const token = peek();
1330
1582
  if (
1331
1583
  token.kind === "Operator" &&
@@ -1334,7 +1586,12 @@ const parse = (source: string, isTlapm: boolean): Module => {
1334
1586
  ) {
1335
1587
  cursor.index++;
1336
1588
  return withRange(
1337
- { kind: "OperatorReference", operator: token.text, location: getLocation(token) },
1589
+ {
1590
+ kind: "OperatorReference",
1591
+ operator: token.text,
1592
+ spelling: token.spelling,
1593
+ location: getLocation(token),
1594
+ },
1338
1595
  start,
1339
1596
  );
1340
1597
  }
@@ -1370,7 +1627,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
1370
1627
  const part = peek();
1371
1628
  const isName = part.kind === "Identifier" && !isTlapmKeyword(part);
1372
1629
  if (!isName && part.kind !== "Operator") {
1373
- throw createUnexpected(`Expected a definition name but found ${describe(part)}`, part);
1630
+ throw createUnexpected(`Expected a definition name but found ${describeToken(part)}`, part);
1374
1631
  }
1375
1632
  cursor.index++;
1376
1633
  return part.text;
@@ -1387,7 +1644,10 @@ const parse = (source: string, isTlapm: boolean): Module => {
1387
1644
  const parseDefs = () => {
1388
1645
  if (isTlapm) return parseSeparated(parseDefinable);
1389
1646
  const defs = parseSeparated(parseFact);
1390
- const invalid = defs.find((def) => def.kind === "Identifier" && isDeclaredSymbol(def.name));
1647
+ const invalid =
1648
+ mode === "tlc"
1649
+ ? defs.find((def) => def.kind === "Identifier" && isDeclaredSymbol(def.name))
1650
+ : undefined;
1391
1651
  if (invalid) {
1392
1652
  throw createError("DEF clause entry should describe a defined operator", invalid.location);
1393
1653
  }
@@ -1412,11 +1672,14 @@ const parse = (source: string, isTlapm: boolean): Module => {
1412
1672
  location: getLocation(keyword),
1413
1673
  };
1414
1674
  const invalid =
1415
- use.kind === "Hide" && !isTlapm ? use.facts.find((fact) => !isHideFact(fact)) : undefined;
1416
- if (invalid) {
1417
- throw createError(
1418
- "The only expression allowed as a fact in a HIDE is the name of a theorem, assumption, or step",
1419
- invalid.location,
1675
+ use.kind === "Hide" && mode === "tlc" ? use.facts.filter((fact) => !isHideFact(fact)) : [];
1676
+ if (invalid.length > 0) {
1677
+ throw createSanyError(
1678
+ invalid.map((fact) => ({
1679
+ location: formatRange(fact.location.range ?? getRange(start)),
1680
+ message:
1681
+ "The only expression allowed as a fact in a HIDE is \nthe name of a theorem, assumption, or step.",
1682
+ })),
1420
1683
  );
1421
1684
  }
1422
1685
  return withRange(use, start);
@@ -1428,14 +1691,22 @@ const parse = (source: string, isTlapm: boolean): Module => {
1428
1691
  const isNew = accept("NEW");
1429
1692
  const level = peek().kind === "Keyword" ? NEW_SYMBOL_LEVELS.get(peek().text) : undefined;
1430
1693
  if (!isNew && level === undefined) {
1431
- throw createUnexpected(`Expected a declaration but found ${describe(peek())}`);
1694
+ throw createUnexpected(`Expected a declaration but found ${describeToken(peek())}`);
1432
1695
  }
1433
1696
  if (level !== undefined) advance();
1434
1697
  if (level === "Variable") {
1435
- const name = expectIdentifier();
1436
- declareProofSymbol(name);
1698
+ const named = expectName();
1699
+ declareProofSymbol(named.name);
1437
1700
  return withRange(
1438
- { kind: "NewSymbol", name, arity: 0, level, set: undefined, location },
1701
+ {
1702
+ kind: "NewSymbol",
1703
+ name: named.name,
1704
+ arity: 0,
1705
+ level,
1706
+ set: undefined,
1707
+ nameRange: named.range,
1708
+ location,
1709
+ },
1439
1710
  start,
1440
1711
  );
1441
1712
  }
@@ -1453,6 +1724,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
1453
1724
  arity: declaration.arity,
1454
1725
  level: level ?? "Constant",
1455
1726
  set: isBounded ? parseExpression() : undefined,
1727
+ nameRange: declaration.location.range,
1456
1728
  location,
1457
1729
  },
1458
1730
  start,
@@ -1495,7 +1767,8 @@ const parse = (source: string, isTlapm: boolean): Module => {
1495
1767
  const token = peek();
1496
1768
  if (isAt("USE") || isAt("HIDE")) return parseUseOrHide();
1497
1769
  if (isAt("INSTANCE")) {
1498
- return withRange(parseInstance(undefined, [], false, getLocation(token)), cursor.index);
1770
+ const start = cursor.index;
1771
+ return withRange(parseInstance(undefined, [], false, getLocation(token)), start);
1499
1772
  }
1500
1773
  if (isAt("DEFINE") || isDefinitionStart()) {
1501
1774
  const start = cursor.index;
@@ -1508,21 +1781,27 @@ const parse = (source: string, isTlapm: boolean): Module => {
1508
1781
  if (accept("HAVE")) return { kind: "Have", expression: parseExpression() };
1509
1782
  if (accept("TAKE")) {
1510
1783
  const isBounded = isBoundAhead();
1511
- const names = isBounded ? [] : parseSeparated(expectIdentifier);
1784
+ const names = getNames(isBounded ? [] : parseSeparated(expectName));
1512
1785
  const bounds = isBounded ? parseBounds() : [];
1513
- declareProofSymbols(names, bounds);
1514
- return { kind: "Take", names, bounds };
1786
+ declareProofSymbols(names.names, bounds);
1787
+ return { kind: "Take", names: names.names, nameRanges: names.ranges, bounds };
1515
1788
  }
1516
1789
  if (accept("WITNESS")) {
1517
1790
  return { kind: "Witness", expressions: parseSeparated(() => parseExpression()) };
1518
1791
  }
1519
1792
  if (accept("PICK")) {
1520
1793
  const isNames = isNameListAhead(":");
1521
- const names = isNames ? parseSeparated(expectIdentifier) : [];
1794
+ const names = getNames(isNames ? parseSeparated(expectName) : []);
1522
1795
  const bounds = isNames ? [] : parseBounds();
1523
- declareProofSymbols(names, bounds);
1796
+ declareProofSymbols(names.names, bounds);
1524
1797
  expect(":");
1525
- return { kind: "Pick", names, bounds, body: parseExpression() };
1798
+ return {
1799
+ kind: "Pick",
1800
+ names: names.names,
1801
+ nameRanges: names.ranges,
1802
+ bounds,
1803
+ body: parseExpression(),
1804
+ };
1526
1805
  }
1527
1806
  if (accept("CASE")) return { kind: "Case", expression: parseExpression() };
1528
1807
  return {
@@ -1535,7 +1814,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
1535
1814
  const parseStepStart = (isQed: boolean) => {
1536
1815
  const step = peek();
1537
1816
  if (step.kind !== "Step") {
1538
- throw createUnexpected(`Expected a step number but found ${describe(step)}`, step);
1817
+ throw createUnexpected(`Expected a step number but found ${describeToken(step)}`, step);
1539
1818
  }
1540
1819
  if (!isCorrectLevel(step)) {
1541
1820
  throw createError(`${isQed ? "QED step" : "step"}'s number has bad level`, step);
@@ -1552,10 +1831,12 @@ const parse = (source: string, isTlapm: boolean): Module => {
1552
1831
  const parseStep = (): ProofStep => {
1553
1832
  const start = cursor.index;
1554
1833
  const step = parseStepStart(isAt("QED", 1));
1834
+ const statementStart = cursor.index;
1555
1835
  const scope = new Set<string>();
1556
1836
  proofScopes.push(scope);
1557
1837
  const body: StepBody = accept("QED") ? { kind: "Qed" } : parseStepBody();
1558
1838
  const head = getRange(start);
1839
+ const statement = getRange(statementStart);
1559
1840
  const hasProof = isProofStart(peek());
1560
1841
  if (hasProof && !PROVABLE_STEPS.has(body.kind)) {
1561
1842
  throw createError("Proof of a step that does not take a proof");
@@ -1563,7 +1844,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
1563
1844
  const proof = hasProof ? parseProof() : undefined;
1564
1845
  proofScopes.pop();
1565
1846
  if (body.kind !== "Assert" || body.isSuffices) scope.forEach(declareProofSymbol);
1566
- return withRange({ ...step, body, head, proof }, start);
1847
+ return withRange({ ...step, body, head, statement, proof }, start);
1567
1848
  };
1568
1849
 
1569
1850
  const parseProofBody = (): Proof => {
@@ -1598,6 +1879,13 @@ const parse = (source: string, isTlapm: boolean): Module => {
1598
1879
  return withRange(proof, start);
1599
1880
  };
1600
1881
 
1882
+ // SANY binds the name of a theorem or assumption that a module already defines to the first
1883
+ // definition, warning of the second.
1884
+ const addFactDefinition = (module: Module, definition: Definition) => {
1885
+ if (module.definitions.some((other) => other.name === definition.name)) return;
1886
+ module.definitions.push(definition);
1887
+ };
1888
+
1601
1889
  const parseTheorem = (module: Module) => {
1602
1890
  const start = cursor.index;
1603
1891
  const keyword = advance();
@@ -1619,7 +1907,8 @@ const parse = (source: string, isTlapm: boolean): Module => {
1619
1907
  module.theorems.push(theorem);
1620
1908
  module.units.push({ kind: "Theorem", theorem });
1621
1909
  if (name === undefined || statement.kind === "AssumeProve") return;
1622
- module.definitions.push(
1910
+ addFactDefinition(
1911
+ module,
1623
1912
  withRange(
1624
1913
  {
1625
1914
  kind: "Operator",
@@ -1637,26 +1926,28 @@ const parse = (source: string, isTlapm: boolean): Module => {
1637
1926
 
1638
1927
  const parseAssumption = (): Assumption => {
1639
1928
  const start = cursor.index;
1640
- return withRange(parseAssumptionUnit(), start);
1641
- };
1642
-
1643
- const parseAssumptionUnit = (): Assumption => {
1644
1929
  const keyword = advance();
1645
- const location = getLocation(keyword);
1646
- const isAxiom = keyword.text === "AXIOM";
1647
- if (peek().kind === "Identifier" && isAt("==", 1)) {
1648
- const name = expectIdentifier();
1930
+ const isNamed = peek().kind === "Identifier" && isAt("==", 1);
1931
+ const name = isNamed ? expectIdentifier() : undefined;
1932
+ if (name !== undefined) {
1649
1933
  factNames.add(name);
1650
1934
  advance();
1651
- return { name, expression: parseExpression(), isAxiom, location };
1652
1935
  }
1653
- return { name: undefined, expression: parseExpression(), isAxiom, location };
1936
+ return withRange(
1937
+ {
1938
+ name,
1939
+ expression: parseExpression(),
1940
+ isAxiom: keyword.text === "AXIOM",
1941
+ location: getLocation(keyword),
1942
+ },
1943
+ start,
1944
+ );
1654
1945
  };
1655
1946
 
1656
1947
  const parseModuleBody = (): Module => {
1657
1948
  const location = getLocation(expect("----"));
1658
1949
  expect("MODULE");
1659
- const name = expectIdentifier();
1950
+ const name = expectModuleName();
1660
1951
  expect("----");
1661
1952
  const module: Module = {
1662
1953
  name,
@@ -1678,7 +1969,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
1678
1969
  if (accept("EXTENDS")) {
1679
1970
  parseSeparated(() => {
1680
1971
  const start = cursor.index;
1681
- module.extends.push(expectIdentifier());
1972
+ module.extends.push(expectModuleName());
1682
1973
  module.extendsRanges.push(getRange(start));
1683
1974
  });
1684
1975
  }
@@ -1686,14 +1977,12 @@ const parse = (source: string, isTlapm: boolean): Module => {
1686
1977
  const tokenIndex = cursor.index;
1687
1978
  unitStart.index = tokenIndex;
1688
1979
  const token = peek();
1689
- if (token.kind === "ModuleEnd" || token.kind === "End") {
1690
- if (token.kind === "ModuleEnd") {
1691
- location.range = {
1692
- module: name,
1693
- start: { line: location.line, column: location.column },
1694
- end: { line: token.line, column: token.endColumn },
1695
- };
1696
- }
1980
+ if (token.kind === "ModuleEnd") {
1981
+ location.range = {
1982
+ module: openModules[0].name,
1983
+ start: { line: location.line, column: location.column },
1984
+ end: { line: token.line, column: token.endColumn },
1985
+ };
1697
1986
  openModules.pop();
1698
1987
  recursiveScopes.pop();
1699
1988
  return module;
@@ -1712,22 +2001,24 @@ const parse = (source: string, isTlapm: boolean): Module => {
1712
2001
  switch (token.text) {
1713
2002
  case "CONSTANT":
1714
2003
  case "CONSTANTS": {
1715
- advance();
2004
+ const unitLocation = getLocation(advance());
1716
2005
  const declarations = parseDeclarations();
1717
2006
  module.constants.push(...declarations);
1718
- module.units.push({ kind: "Constants", declarations });
2007
+ unitLocation.range = getRange(tokenIndex);
2008
+ module.units.push({ kind: "Constants", declarations, location: unitLocation });
1719
2009
  continue;
1720
2010
  }
1721
2011
  case "VARIABLE":
1722
2012
  case "VARIABLES": {
1723
- advance();
2013
+ const unitLocation = getLocation(advance());
1724
2014
  const declarations = parseSeparated(() => {
1725
2015
  const start = cursor.index;
1726
2016
  const location = getLocation(peek());
1727
2017
  return withRange({ name: expectIdentifier(), arity: 0, location }, start);
1728
2018
  });
1729
2019
  module.variables.push(...declarations);
1730
- module.units.push({ kind: "Variables", declarations });
2020
+ unitLocation.range = getRange(tokenIndex);
2021
+ module.units.push({ kind: "Variables", declarations, location: unitLocation });
1731
2022
  continue;
1732
2023
  }
1733
2024
  case "ASSUME":
@@ -1737,7 +2028,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
1737
2028
  module.assumptions.push(assumption);
1738
2029
  module.units.push({ kind: "Assumption", assumption });
1739
2030
  if (assumption.name !== undefined) {
1740
- module.definitions.push({
2031
+ addFactDefinition(module, {
1741
2032
  kind: "Operator",
1742
2033
  name: assumption.name,
1743
2034
  params: [],
@@ -1751,6 +2042,10 @@ const parse = (source: string, isTlapm: boolean): Module => {
1751
2042
  }
1752
2043
  case "USE":
1753
2044
  case "HIDE": {
2045
+ // SANY's module body takes a USE only when ONLY doesn't follow it.
2046
+ if (isAt("USE") && isAt("ONLY", 1)) {
2047
+ throw createUnexpected(`Expected a module unit but found ${describeToken(token)}`);
2048
+ }
1754
2049
  const use = parseUseOrHide();
1755
2050
  module.uses.push(use);
1756
2051
  module.units.push({ kind: "Use", use });
@@ -1775,7 +2070,7 @@ const parse = (source: string, isTlapm: boolean): Module => {
1775
2070
  );
1776
2071
  continue;
1777
2072
  }
1778
- addDefinitionUnit(module, parseDefinition(true));
2073
+ addDefinitionUnit(module, withRange(parseDefinitionUnit(true), tokenIndex));
1779
2074
  continue;
1780
2075
  }
1781
2076
  }
@@ -1797,9 +2092,16 @@ const parse = (source: string, isTlapm: boolean): Module => {
1797
2092
  module.units.push({ kind: "Definition", definition: unit });
1798
2093
  };
1799
2094
 
1800
- return parseModuleBody();
2095
+ const module = parseModuleBody();
2096
+ // SANY's lexer marks where each definition begins before its parser runs, which can split a
2097
+ // module's name from a keyword that the parser would take for one.
2098
+ const sanyError = keywordModuleName.isUsed ? getSanyParseError(source) : undefined;
2099
+ if (sanyError !== undefined) throw new TlaSyntaxError(sanyError);
2100
+ return module;
1801
2101
  };
1802
2102
 
1803
- export const parseModule = (source: string) => parse(source, false);
2103
+ export const parseModule = (source: string) => parse(source, "tlc");
2104
+
2105
+ export const parseTlapmModule = (source: string) => parse(source, "tlapm");
1804
2106
 
1805
- export const parseTlapmModule = (source: string) => parse(source, true);
2107
+ export const parseSanyModule = (source: string) => parse(source, "sany");