tla-ts 0.0.9 → 0.0.10-dev.28c823e4b

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 (390) hide show
  1. package/README.md +29 -1
  2. package/dist/compile.cjs +23 -0
  3. package/dist/compile.js +23 -0
  4. package/dist/deciders.cjs +28 -28
  5. package/dist/deciders.js +43 -43
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +106 -10
  8. package/dist/index.d.ts +106 -10
  9. package/dist/index.js +1 -1
  10. package/dist/parallel-worker.cjs +1 -1
  11. package/dist/parallel-worker.js +1 -1
  12. package/dist/prove-worker.cjs +1 -1
  13. package/dist/prove-worker.js +1 -1
  14. package/dist/prove.cjs +116 -36
  15. package/dist/prove.js +116 -36
  16. package/dist/run.cjs +143 -31
  17. package/dist/run.js +143 -31
  18. package/dist/tlapm.cjs +2 -2
  19. package/dist/tlapm.js +2 -2
  20. package/dist/transfer.cjs +129 -104
  21. package/dist/transfer.js +129 -104
  22. package/dist/worker.cjs +7 -7
  23. package/dist/worker.js +7 -7
  24. package/package.json +3 -1
  25. package/src/ast.ts +4 -23
  26. package/src/bags.ts +99 -102
  27. package/src/builtins.ts +40 -78
  28. package/src/bundled-modules.ts +1 -8
  29. package/src/check.ts +599 -388
  30. package/src/cli/options.ts +11 -6
  31. package/src/cli/run.ts +0 -2
  32. package/src/cli/runtime-invariants.ts +136 -0
  33. package/src/cli/shared.ts +18 -11
  34. package/src/cli/tlapm.ts +0 -12
  35. package/src/cli/tlc-arguments.ts +640 -0
  36. package/src/cli/tlc-usage.ts +361 -0
  37. package/src/cli/tlc.ts +538 -220
  38. package/src/cli/typescript.ts +23 -0
  39. package/src/cli/xml-exporter.ts +4 -16
  40. package/src/cli.ts +0 -1
  41. package/src/codegen.ts +191 -64
  42. package/src/config.ts +140 -109
  43. package/src/coverage.ts +837 -0
  44. package/src/dependencies.ts +6 -40
  45. package/src/dfid.ts +618 -0
  46. package/src/environment.ts +240 -118
  47. package/src/errors.ts +70 -55
  48. package/src/evaluate.ts +596 -339
  49. package/src/exit-codes.ts +37 -3
  50. package/src/fingerprints.ts +10 -10
  51. package/src/index.ts +3 -0
  52. package/src/instances.ts +79 -11
  53. package/src/java-overrides.ts +4 -19
  54. package/src/json-reader.ts +455 -0
  55. package/src/json.ts +255 -139
  56. package/src/levels.ts +8 -17
  57. package/src/lexer.ts +80 -100
  58. package/src/liveness-checker.ts +82 -119
  59. package/src/liveness.ts +112 -64
  60. package/src/obligations/action.ts +4 -28
  61. package/src/obligations/anonymize.ts +84 -80
  62. package/src/obligations/equality.ts +1 -1
  63. package/src/obligations/expression.ts +2 -19
  64. package/src/obligations/format.ts +1 -9
  65. package/src/obligations/generate.ts +1 -11
  66. package/src/obligations/index.ts +0 -11
  67. package/src/obligations/levels.ts +4 -8
  68. package/src/obligations/module.ts +1 -15
  69. package/src/obligations/normalize.ts +5 -24
  70. package/src/obligations/operators.ts +1 -2
  71. package/src/obligations/pragma.ts +1 -10
  72. package/src/obligations/printer.ts +47 -46
  73. package/src/obligations/proof.ts +1 -5
  74. package/src/obligations/regroup.ts +1 -4
  75. package/src/obligations/simplify.ts +3 -14
  76. package/src/obligations/source.ts +1 -21
  77. package/src/obligations/subexpression.ts +5 -11
  78. package/src/obligations/substitution.ts +1 -3
  79. package/src/obligations/temporal.ts +8 -14
  80. package/src/obligations/tuples.ts +3 -9
  81. package/src/parallel-worker.ts +29 -39
  82. package/src/parallel.ts +53 -44
  83. package/src/parser.ts +565 -282
  84. package/src/pcal/ast.ts +53 -86
  85. package/src/pcal/parse.ts +144 -219
  86. package/src/pcal/tokenize.ts +91 -131
  87. package/src/pcal/translate.ts +83 -130
  88. package/src/pcal/validate.ts +48 -68
  89. package/src/pretty-print.ts +7 -8
  90. package/src/prover/decide-pool.ts +5 -10
  91. package/src/prover/deciders.ts +0 -4
  92. package/src/prover/first-order.ts +0 -11
  93. package/src/prover/isabelle/decide.ts +0 -6
  94. package/src/prover/isabelle/encode.ts +11 -23
  95. package/src/prover/isabelle/isar/inner-syntax.ts +108 -114
  96. package/src/prover/isabelle/isar/method.ts +25 -38
  97. package/src/prover/isabelle/isar/proof.ts +1 -10
  98. package/src/prover/isabelle/isar/statement.ts +1 -6
  99. package/src/prover/isabelle/isar/theory.ts +15 -26
  100. package/src/prover/isabelle/isar/type-check.ts +11 -25
  101. package/src/prover/isabelle/provers/blast/blast.ts +10 -41
  102. package/src/prover/isabelle/provers/blast/branch.ts +1 -32
  103. package/src/prover/isabelle/provers/blast/prove.ts +1 -35
  104. package/src/prover/isabelle/provers/blast/rules.ts +6 -44
  105. package/src/prover/isabelle/provers/blast/state.ts +2 -28
  106. package/src/prover/isabelle/provers/blast/term.ts +9 -36
  107. package/src/prover/isabelle/provers/clasimp.ts +1 -13
  108. package/src/prover/isabelle/provers/classical.ts +14 -42
  109. package/src/prover/isabelle/provers/hypsubst.ts +11 -25
  110. package/src/prover/isabelle/pure/bicompose.ts +16 -13
  111. package/src/prover/isabelle/pure/consts.ts +1 -7
  112. package/src/prover/isabelle/pure/conv.ts +1 -9
  113. package/src/prover/isabelle/pure/drule.ts +24 -40
  114. package/src/prover/isabelle/pure/envir.ts +3 -52
  115. package/src/prover/isabelle/pure/goal.ts +1 -7
  116. package/src/prover/isabelle/pure/interrupt.ts +0 -5
  117. package/src/prover/isabelle/pure/list.ts +0 -3
  118. package/src/prover/isabelle/pure/logic.ts +1 -14
  119. package/src/prover/isabelle/pure/name.ts +2 -9
  120. package/src/prover/isabelle/pure/net.ts +3 -59
  121. package/src/prover/isabelle/pure/object-logic.ts +3 -10
  122. package/src/prover/isabelle/pure/pattern.ts +2 -19
  123. package/src/prover/isabelle/pure/raw-simplifier.ts +13 -49
  124. package/src/prover/isabelle/pure/rewriter.ts +26 -58
  125. package/src/prover/isabelle/pure/search.ts +3 -10
  126. package/src/prover/isabelle/pure/seq.ts +1 -10
  127. package/src/prover/isabelle/pure/simplifier.ts +4 -12
  128. package/src/prover/isabelle/pure/table.ts +1 -31
  129. package/src/prover/isabelle/pure/tactic.ts +12 -22
  130. package/src/prover/isabelle/pure/tactical.ts +6 -12
  131. package/src/prover/isabelle/pure/term-ord.ts +2 -6
  132. package/src/prover/isabelle/pure/term.ts +2 -43
  133. package/src/prover/isabelle/pure/thm.ts +13 -36
  134. package/src/prover/isabelle/pure/type.ts +2 -15
  135. package/src/prover/isabelle/pure/unify.ts +20 -30
  136. package/src/prover/isabelle/pure/variable.ts +3 -7
  137. package/src/prover/isabelle/tla/classical-setup.ts +9 -19
  138. package/src/prover/isabelle/tla/context.ts +8 -16
  139. package/src/prover/isabelle/tla/logic.ts +4 -11
  140. package/src/prover/isabelle/tla/simpdata.ts +46 -34
  141. package/src/prover/isabelle/tools/intuitionistic.ts +1 -10
  142. package/src/prover/ocaml.ts +0 -6
  143. package/src/prover/prep/action.ts +4 -36
  144. package/src/prover/prep/enabled-axioms.ts +12 -19
  145. package/src/prover/prep/fingerprint.ts +0 -16
  146. package/src/prover/prep/level-comparison.ts +8 -12
  147. package/src/prover/prep/md5.ts +0 -2
  148. package/src/prover/prep/methods.ts +9 -36
  149. package/src/prover/prep/normalize.ts +4 -28
  150. package/src/prover/prove-worker.ts +0 -2
  151. package/src/prover/prove.ts +0 -36
  152. package/src/prover/ptl/decide.ts +7 -12
  153. package/src/prover/ptl/encode.ts +14 -36
  154. package/src/prover/ptl/sat.ts +24 -32
  155. package/src/prover/ptl/tableau.ts +12 -26
  156. package/src/prover/smt/axioms.ts +0 -7
  157. package/src/prover/smt/context.ts +19 -26
  158. package/src/prover/smt/data.ts +51 -54
  159. package/src/prover/smt/encode.ts +14 -35
  160. package/src/prover/smt/extensionality.ts +0 -10
  161. package/src/prover/smt/flatten.ts +3 -22
  162. package/src/prover/smt/format.ts +5 -10
  163. package/src/prover/smt/instances.ts +0 -10
  164. package/src/prover/smt/rewrite.ts +66 -101
  165. package/src/prover/smt/solver/act-cache.ts +0 -15
  166. package/src/prover/smt/solver/arith-rewriter.ts +3 -48
  167. package/src/prover/smt/solver/array.ts +1 -3
  168. package/src/prover/smt/solver/asserted-formulas.ts +1 -43
  169. package/src/prover/smt/solver/ast-lt.ts +1 -11
  170. package/src/prover/smt/solver/ast-util.ts +1 -6
  171. package/src/prover/smt/solver/ast.ts +1 -143
  172. package/src/prover/smt/solver/auf-solver.ts +6 -39
  173. package/src/prover/smt/solver/case-split-queue.ts +1 -9
  174. package/src/prover/smt/solver/cg-table.ts +1 -18
  175. package/src/prover/smt/solver/clause.ts +1 -27
  176. package/src/prover/smt/solver/conflict-resolution.ts +0 -9
  177. package/src/prover/smt/solver/context.ts +4 -61
  178. package/src/prover/smt/solver/ctx-simplify.ts +14 -41
  179. package/src/prover/smt/solver/der.ts +2 -21
  180. package/src/prover/smt/solver/dyn-ack.ts +1 -11
  181. package/src/prover/smt/solver/e-matching.ts +3 -34
  182. package/src/prover/smt/solver/enode.ts +1 -21
  183. package/src/prover/smt/solver/expr-ref.ts +1 -5
  184. package/src/prover/smt/solver/expr-safe-replace.ts +0 -5
  185. package/src/prover/smt/solver/fingerprints.ts +1 -12
  186. package/src/prover/smt/solver/flat-literals.ts +1 -9
  187. package/src/prover/smt/solver/goal.ts +2 -14
  188. package/src/prover/smt/solver/hash.ts +0 -8
  189. package/src/prover/smt/solver/hashtable.ts +1 -12
  190. package/src/prover/smt/solver/internalizer.ts +6 -98
  191. package/src/prover/smt/solver/lbool.ts +1 -2
  192. package/src/prover/smt/solver/literal.ts +0 -3
  193. package/src/prover/smt/solver/lp/bound-propagator.ts +8 -26
  194. package/src/prover/smt/solver/lp/constraints.ts +2 -8
  195. package/src/prover/smt/solver/lp/containers.ts +12 -30
  196. package/src/prover/smt/solver/lp/core-solver.ts +10 -31
  197. package/src/prover/smt/solver/lp/cross-nested.ts +6 -20
  198. package/src/prover/smt/solver/lp/dep-intervals.ts +7 -22
  199. package/src/prover/smt/solver/lp/dependency.ts +1 -4
  200. package/src/prover/smt/solver/lp/dioph-eq.ts +12 -98
  201. package/src/prover/smt/solver/lp/explanation.ts +1 -6
  202. package/src/prover/smt/solver/lp/gomory.ts +9 -22
  203. package/src/prover/smt/solver/lp/hnf-cutter.ts +17 -23
  204. package/src/prover/smt/solver/lp/hnf.ts +11 -26
  205. package/src/prover/smt/solver/lp/int-cube.ts +15 -36
  206. package/src/prover/smt/solver/lp/int-solver.ts +4 -34
  207. package/src/prover/smt/solver/lp/lar-solver.ts +32 -81
  208. package/src/prover/smt/solver/lp/lar-term.ts +1 -5
  209. package/src/prover/smt/solver/lp/lp-settings.ts +1 -14
  210. package/src/prover/smt/solver/lp/maximize-term.ts +20 -45
  211. package/src/prover/smt/solver/lp/nex-creator.ts +5 -28
  212. package/src/prover/smt/solver/lp/nex.ts +1 -6
  213. package/src/prover/smt/solver/lp/nla-backoff.ts +1 -4
  214. package/src/prover/smt/solver/lp/nla-basics.ts +5 -30
  215. package/src/prover/smt/solver/lp/nla-core.ts +35 -130
  216. package/src/prover/smt/solver/lp/nla-divisions.ts +32 -42
  217. package/src/prover/smt/solver/lp/nla-emonics.ts +4 -21
  218. package/src/prover/smt/solver/lp/nla-factorization.ts +1 -4
  219. package/src/prover/smt/solver/lp/nla-grobner.ts +15 -69
  220. package/src/prover/smt/solver/lp/nla-horner.ts +3 -11
  221. package/src/prover/smt/solver/lp/nla-intervals.ts +2 -12
  222. package/src/prover/smt/solver/lp/nla-monomial-bounds.ts +16 -41
  223. package/src/prover/smt/solver/lp/nla-monotone.ts +2 -6
  224. package/src/prover/smt/solver/lp/nla-order.ts +2 -13
  225. package/src/prover/smt/solver/lp/nla-patcher.ts +4 -7
  226. package/src/prover/smt/solver/lp/nla-tangents.ts +1 -9
  227. package/src/prover/smt/solver/lp/nla-throttle.ts +1 -6
  228. package/src/prover/smt/solver/lp/nla-types.ts +1 -11
  229. package/src/prover/smt/solver/lp/nla-var-eqs.ts +4 -25
  230. package/src/prover/smt/solver/lp/nra-solver.ts +5 -52
  231. package/src/prover/smt/solver/lp/numeric-pair.ts +1 -4
  232. package/src/prover/smt/solver/lp/pdd-interval.ts +1 -3
  233. package/src/prover/smt/solver/lp/pdd-simplifier.ts +2 -14
  234. package/src/prover/smt/solver/lp/pdd-solver.ts +4 -33
  235. package/src/prover/smt/solver/lp/pdd.ts +7 -70
  236. package/src/prover/smt/solver/lp/random-updater.ts +1 -8
  237. package/src/prover/smt/solver/lp/static-matrix.ts +9 -19
  238. package/src/prover/smt/solver/lp/union-find.ts +1 -6
  239. package/src/prover/smt/solver/mam-compiler.ts +14 -56
  240. package/src/prover/smt/solver/mam-interpreter.ts +1 -21
  241. package/src/prover/smt/solver/maximize-ac-sharing.ts +2 -17
  242. package/src/prover/smt/solver/model-checker.ts +2 -36
  243. package/src/prover/smt/solver/model-evaluator.ts +3 -29
  244. package/src/prover/smt/solver/model-finder.ts +3 -15
  245. package/src/prover/smt/solver/model-generator.ts +1 -12
  246. package/src/prover/smt/solver/model-macro-solver.ts +12 -69
  247. package/src/prover/smt/solver/nlsat/algebraic.ts +55 -151
  248. package/src/prover/smt/solver/nlsat/atoms.ts +5 -19
  249. package/src/prover/smt/solver/nlsat/evaluator.ts +17 -22
  250. package/src/prover/smt/solver/nlsat/explain.ts +3 -47
  251. package/src/prover/smt/solver/nlsat/interval-set.ts +9 -50
  252. package/src/prover/smt/solver/nlsat/levelwise.ts +48 -129
  253. package/src/prover/smt/solver/nlsat/mpbq.ts +3 -14
  254. package/src/prover/smt/solver/nlsat/polynomial.ts +17 -156
  255. package/src/prover/smt/solver/nlsat/solver.ts +7 -67
  256. package/src/prover/smt/solver/nlsat/types.ts +1 -8
  257. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +1 -44
  258. package/src/prover/smt/solver/nlsat/upolynomial.ts +11 -92
  259. package/src/prover/smt/solver/nnf.ts +3 -38
  260. package/src/prover/smt/solver/pattern-inference.ts +2 -15
  261. package/src/prover/smt/solver/poly-rewriter.ts +3 -23
  262. package/src/prover/smt/solver/propagate-values.ts +1 -10
  263. package/src/prover/smt/solver/proto-model.ts +3 -48
  264. package/src/prover/smt/solver/pull-quant.ts +1 -12
  265. package/src/prover/smt/solver/qe-lite-der.ts +1 -29
  266. package/src/prover/smt/solver/qe-lite-fm.ts +2 -25
  267. package/src/prover/smt/solver/qe-lite.ts +3 -33
  268. package/src/prover/smt/solver/qi-queue.ts +1 -16
  269. package/src/prover/smt/solver/quant-tactics.ts +5 -22
  270. package/src/prover/smt/solver/quantifier-analyzer.ts +17 -37
  271. package/src/prover/smt/solver/quantifier-manager.ts +1 -8
  272. package/src/prover/smt/solver/random-gen.ts +1 -2
  273. package/src/prover/smt/solver/rational.ts +1 -8
  274. package/src/prover/smt/solver/ref-vector.ts +1 -6
  275. package/src/prover/smt/solver/relevancy.ts +2 -15
  276. package/src/prover/smt/solver/rewriter-tpl.ts +3 -147
  277. package/src/prover/smt/solver/rewriter.ts +3 -85
  278. package/src/prover/smt/solver/rlimit.ts +2 -20
  279. package/src/prover/smt/solver/smtlib-parser.ts +2 -37
  280. package/src/prover/smt/solver/solver.ts +23 -34
  281. package/src/prover/smt/solver/sort.ts +1 -5
  282. package/src/prover/smt/solver/sticky-generations.ts +0 -5
  283. package/src/prover/smt/solver/theory-lra-axioms.ts +3 -24
  284. package/src/prover/smt/solver/theory-lra-bounds.ts +0 -5
  285. package/src/prover/smt/solver/theory-lra-final-check.ts +4 -22
  286. package/src/prover/smt/solver/theory-lra-internalize.ts +1 -27
  287. package/src/prover/smt/solver/theory-lra-model.ts +4 -19
  288. package/src/prover/smt/solver/theory-lra-propagate.ts +1 -15
  289. package/src/prover/smt/solver/theory-lra-state.ts +3 -8
  290. package/src/prover/smt/solver/theory-lra.ts +1 -8
  291. package/src/prover/smt/solver/var-subst.ts +2 -26
  292. package/src/prover/smt/table.ts +0 -8
  293. package/src/prover/tlapm/cache.ts +20 -25
  294. package/src/prover/tlapm/ocaml-marshal.ts +19 -21
  295. package/src/prover/tlapm/tlapm.ts +12 -17
  296. package/src/prover/verdict.ts +0 -2
  297. package/src/prover/zenon/check/check.ts +0 -9
  298. package/src/prover/zenon/check/definitions.ts +5 -15
  299. package/src/prover/zenon/check/equality.ts +0 -8
  300. package/src/prover/zenon/check/functions.ts +0 -4
  301. package/src/prover/zenon/check/keys.ts +0 -7
  302. package/src/prover/zenon/check/propositional.ts +0 -3
  303. package/src/prover/zenon/check/records.ts +0 -5
  304. package/src/prover/zenon/check/relations.ts +0 -13
  305. package/src/prover/zenon/check/rewrites.ts +0 -6
  306. package/src/prover/zenon/check/sets.ts +0 -3
  307. package/src/prover/zenon/check/terms.ts +0 -17
  308. package/src/prover/zenon/check/tla.ts +0 -6
  309. package/src/prover/zenon/decide.ts +0 -12
  310. package/src/prover/zenon/encode.ts +1 -8
  311. package/src/prover/zenon/eqrel.ts +0 -13
  312. package/src/prover/zenon/equality-rules.ts +0 -4
  313. package/src/prover/zenon/expr.ts +1 -26
  314. package/src/prover/zenon/index-table.ts +17 -38
  315. package/src/prover/zenon/isar-case.ts +9 -19
  316. package/src/prover/zenon/isar.ts +1 -29
  317. package/src/prover/zenon/limits.ts +0 -4
  318. package/src/prover/zenon/llproof.ts +0 -9
  319. package/src/prover/zenon/mltoll.ts +54 -76
  320. package/src/prover/zenon/node.ts +1 -11
  321. package/src/prover/zenon/ocaml.ts +1 -17
  322. package/src/prover/zenon/parse.ts +2 -7
  323. package/src/prover/zenon/phrase.ts +1 -11
  324. package/src/prover/zenon/proof.ts +0 -9
  325. package/src/prover/zenon/propositional-rules.ts +0 -5
  326. package/src/prover/zenon/rules.ts +2 -6
  327. package/src/prover/zenon/search.ts +1 -17
  328. package/src/prover/zenon/tla/functions.ts +57 -29
  329. package/src/prover/zenon/tla/llproof.ts +63 -70
  330. package/src/prover/zenon/tla/records.ts +56 -27
  331. package/src/prover/zenon/tla/rewrites.ts +12 -19
  332. package/src/prover/zenon/tla/sets.ts +68 -39
  333. package/src/prover/zenon/tla/terms.ts +0 -6
  334. package/src/prover/zenon/tla/tla.ts +59 -58
  335. package/src/randomization.ts +81 -35
  336. package/src/resolve.ts +12 -112
  337. package/src/runtime.ts +22 -22
  338. package/src/sany/builtins.ts +2 -5
  339. package/src/sany/generator.ts +149 -252
  340. package/src/sany/levels.ts +6 -34
  341. package/src/sany/lexer.ts +41 -61
  342. package/src/sany/linter.ts +1 -9
  343. package/src/sany/modules.ts +1 -5
  344. package/src/sany/nodes.ts +0 -31
  345. package/src/sany/parse-error.ts +39 -117
  346. package/src/sany/report.ts +29 -63
  347. package/src/sany/selectors.ts +15 -39
  348. package/src/sany/source.ts +1 -17
  349. package/src/sany/xml.ts +13 -63
  350. package/src/search.ts +495 -155
  351. package/src/simulate.ts +685 -0
  352. package/src/spec-description.ts +176 -69
  353. package/src/standard-definitions.ts +0 -4
  354. package/src/standard-modules.ts +254 -69
  355. package/src/state-graph.ts +50 -24
  356. package/src/subexpressions.ts +69 -52
  357. package/src/substitution-levels.ts +2 -3
  358. package/src/successors.ts +263 -94
  359. package/src/symmetry.ts +33 -25
  360. package/src/tableau.ts +27 -24
  361. package/src/tlc/fingerprint.ts +183 -67
  362. package/src/tlc/jar-data.ts +112 -6
  363. package/src/tlc/messages.ts +110 -44
  364. package/src/tlc/order.ts +37 -60
  365. package/src/tlc/random.ts +33 -45
  366. package/src/tlc/replay.ts +549 -217
  367. package/src/tlc/summary.ts +36 -47
  368. package/src/tlc/tlc-operators.ts +76 -41
  369. package/src/tlc/tlcext-operators.ts +139 -122
  370. package/src/tlc/trace-spec.ts +269 -0
  371. package/src/tlc/value-stream.ts +139 -0
  372. package/src/tlc/version.ts +1 -4
  373. package/src/transfer.ts +22 -25
  374. package/src/typescript/actions.ts +481 -0
  375. package/src/typescript/collections.ts +600 -0
  376. package/src/typescript/compile.ts +65 -0
  377. package/src/typescript/context.ts +94 -0
  378. package/src/typescript/emit.ts +121 -0
  379. package/src/typescript/expressions.ts +496 -0
  380. package/src/typescript/formula.ts +152 -0
  381. package/src/typescript/functions.ts +284 -0
  382. package/src/typescript/model.ts +163 -0
  383. package/src/typescript/names.ts +114 -0
  384. package/src/typescript/program.ts +48 -0
  385. package/src/typescript/properties.ts +139 -0
  386. package/src/typescript/scope.ts +112 -0
  387. package/src/typescript/steps.ts +165 -0
  388. package/src/typescript/types.ts +171 -0
  389. package/src/values.ts +780 -337
  390. package/src/worker.ts +7 -8
package/src/parser.ts CHANGED
@@ -35,16 +35,8 @@ interface InfixOperator extends Precedence {
35
35
  isAssociative: boolean;
36
36
  }
37
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 };
38
+ const POSTFIX_PRECEDENCE = { low: 15, high: 15 };
39
+ const FUNCTION_PRECEDENCE = { low: 16, high: 16 };
48
40
 
49
41
  const createInfix = (low: number, high: number, isAssociative: boolean) => ({
50
42
  low,
@@ -154,9 +146,10 @@ const NEGATION_PRECEDENCE = 12;
154
146
 
155
147
  const POSTFIX_OPERATORS = new Set(["^+", "^*", "^#"]);
156
148
 
149
+ const DEFINABLE_POSTFIX_OPERATORS = new Set([...POSTFIX_OPERATORS, "'"]);
150
+
157
151
  const PREFIX_OPERATOR_REFERENCES = new Set(["-", "~", "-."]);
158
152
 
159
- // The prefix operators SANY reads in a definition's left-hand side, built-in ones included.
160
153
  const DEFINABLE_PREFIX_OPERATORS = new Set([
161
154
  "-.",
162
155
  "~",
@@ -193,8 +186,7 @@ const OPERATOR_ARGUMENTS = new Set([
193
186
  "UNCHANGED",
194
187
  "[]",
195
188
  "<>",
196
- "'",
197
- ...POSTFIX_OPERATORS,
189
+ ...DEFINABLE_POSTFIX_OPERATORS,
198
190
  ]);
199
191
 
200
192
  const SELECTOR_SYMBOLS = new Set(["<<", ">>", ":", "@", "("]);
@@ -259,6 +251,79 @@ const TLAPM_PUNCTUATION = new Set([
259
251
 
260
252
  const UNNAMED_STEP_LABELS = new Set(["", "*", "-"]);
261
253
 
254
+ interface Point {
255
+ line: number;
256
+ column: number;
257
+ }
258
+
259
+ interface Span {
260
+ start: Point;
261
+ stop: Point;
262
+ }
263
+
264
+ interface RangedName {
265
+ name: string;
266
+ range: SourceRange;
267
+ }
268
+
269
+ type Preproof =
270
+ | { kind: "Leaf"; proof: Proof; span: Span; first: number; end: number }
271
+ | {
272
+ kind: "Step";
273
+ token: Token;
274
+ isProof: boolean;
275
+ body: StepBody;
276
+ head: SourceRange;
277
+ statement: SourceRange;
278
+ span: Span;
279
+ first: number;
280
+ start: number;
281
+ end: number;
282
+ };
283
+
284
+ interface NestedProof {
285
+ proof: Proof | undefined;
286
+ span: Span;
287
+ next: number;
288
+ end: number | undefined;
289
+ }
290
+
291
+ interface NestedSteps {
292
+ level: number;
293
+ steps: ProofStep[];
294
+ span: Span;
295
+ next: number;
296
+ end: number;
297
+ }
298
+
299
+ const LEAF_NAMES: Record<string, string> = {
300
+ Obvious: "n OBVIOUS",
301
+ Omitted: "n OMITTED",
302
+ By: " BY",
303
+ };
304
+
305
+ const comparePoints = (left: Point, right: Point) =>
306
+ left.line - right.line || left.column - right.column;
307
+
308
+ const mergeSpans = (left: Span, right: Span): Span => ({
309
+ start: comparePoints(left.start, right.start) <= 0 ? left.start : right.start,
310
+ stop: comparePoints(left.stop, right.stop) >= 0 ? left.stop : right.stop,
311
+ });
312
+
313
+ const getSpan = (range: SourceRange): Span => ({
314
+ start: { line: range.start.line, column: range.start.column },
315
+ stop: { line: range.end.line, column: range.end.column + 1 },
316
+ });
317
+
318
+ const createProofError = (message: string, span: Span, exception = "Proof.Parser") =>
319
+ new TlaSyntaxError(message, undefined, {
320
+ reason: message,
321
+ line: span.start.line,
322
+ column: span.start.column,
323
+ isEnd: false,
324
+ proof: { stop: span.stop, exception },
325
+ });
326
+
262
327
  const FACT_KEYWORDS = new Set([
263
328
  "CASE",
264
329
  "CHOOSE",
@@ -297,7 +362,6 @@ const BUILTIN_CONSTANTS = new Set(["TRUE", "FALSE", "BOOLEAN", "STRING"]);
297
362
 
298
363
  const NO_OFFSIDE = -1;
299
364
 
300
- // A SANY InfixExpr or PostfixExpr.
301
365
  const isOperatorExpression = (expression: Expression) =>
302
366
  expression.kind === "Prime" ||
303
367
  expression.kind === "Product" ||
@@ -307,6 +371,11 @@ const isOperatorExpression = (expression: Expression) =>
307
371
  ? INFIX_OPERATORS.has(expression.operator)
308
372
  : POSTFIX_OPERATORS.has(expression.operator)));
309
373
 
374
+ const isBullet = (token: Token) =>
375
+ (token.text === "/\\" || token.text === "\\/") &&
376
+ token.spelling !== "\\land" &&
377
+ token.spelling !== "\\lor";
378
+
310
379
  const isOperatorName = (text: string) =>
311
380
  INFIX_OPERATORS.has(text) || POSTFIX_OPERATORS.has(text) || text === "-.";
312
381
 
@@ -331,33 +400,31 @@ const getOperatorApplication = (
331
400
  }
332
401
  };
333
402
 
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.
336
403
  export const extractModule = (source: string, name: string) => {
337
404
  const header = new RegExp(`^-{4,}\\s*MODULE\\s+${name}\\s*-{3,}$`);
338
- const lines = source.split(/\r?\n/);
405
+ const lines = source.replace(/\r?\n$/, "").split(/\r?\n/);
339
406
  const start = lines.findIndex((line) => header.test(line));
340
407
  if (start === -1) return undefined;
341
408
  const end = lines.findIndex((line, index) => index > start && line.startsWith("===="));
342
409
  return `${lines.slice(start, end === -1 ? undefined : end + 1).join("\n")}\n`;
343
410
  };
344
411
 
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
412
  type ParseMode = "tlc" | "tlapm" | "sany";
349
413
 
350
- const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source)): Module => {
414
+ const parse = (
415
+ source: string,
416
+ mode: ParseMode,
417
+ sourceTokens = tokenize(source, mode === "tlapm"),
418
+ ): Module => {
351
419
  const isTlapm = mode === "tlapm";
352
420
  const tokens = isTlapm ? sourceTokens : sourceTokens.map(readAtAsIdentifier);
353
- const cursor = { index: 0, offsideColumns: [] as number[] };
354
- const operators: OperatorContext = {};
355
- // A RECURSIVE declaration covers the definitions of its own LET or module.
421
+ let cursor = 0;
422
+ const offsideColumns: number[] = [];
423
+ let lastOperator: Precedence | undefined;
424
+ let precedingOperator: Precedence | undefined;
356
425
  const recursiveScopes: Set<string>[] = [];
357
426
  const factNames = new Set<string>();
358
- // The NEW, TAKE, and PICK names in scope, which a DEF clause cannot cite.
359
427
  const proofScopes: Set<string>[] = [];
360
- // SANY reports a location in a nested module as one in the module of its file.
361
428
  const openModules: Module[] = [];
362
429
 
363
430
  const isRecursiveName = (name: string) => recursiveScopes[recursiveScopes.length - 1].has(name);
@@ -372,7 +439,7 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
372
439
  const tokenEnds: SourceLocation[] = [];
373
440
  const tokenRanges: SourceRange[] = [];
374
441
 
375
- const getRange = (startIndex: number, endIndex = cursor.index - 1) => {
442
+ const getRange = (startIndex: number, endIndex = cursor - 1) => {
376
443
  const cached = startIndex === endIndex ? tokenRanges[startIndex] : undefined;
377
444
  if (cached) return cached;
378
445
  const last = tokens[endIndex];
@@ -387,17 +454,16 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
387
454
  return range;
388
455
  };
389
456
 
390
- // Each node gets its own location object from getLocation, so the range can be set in place.
391
457
  const withRange = <Node extends { location: SourceLocation }>(node: Node, startIndex: number) => {
392
458
  node.location.range = getRange(startIndex);
393
459
  return node;
394
460
  };
395
461
 
396
- const peekRaw = (offset = 0) => tokens[Math.min(cursor.index + offset, tokens.length - 1)];
462
+ const peekRaw = (offset = 0) => tokens[Math.min(cursor + offset, tokens.length - 1)];
397
463
 
398
464
  const peek = (offset = 0) => {
399
465
  const token = peekRaw(offset);
400
- const offsideColumn = cursor.offsideColumns[cursor.offsideColumns.length - 1];
466
+ const offsideColumn = offsideColumns[offsideColumns.length - 1];
401
467
  if (offsideColumn === undefined || offsideColumn === NO_OFFSIDE || token.kind === "End") {
402
468
  return token;
403
469
  }
@@ -407,20 +473,19 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
407
473
  const describeToken = (token: Token) =>
408
474
  token.kind === "End" ? "end of input" : JSON.stringify(token.text);
409
475
 
410
- const unitStart = { index: 0 };
476
+ let unitStart = 0;
411
477
 
412
- const getDefinitionEnd = (fallback: { line: number; column: number }) => {
478
+ const getDefinitionEnd = (fallback: Point) => {
413
479
  const equals = tokens
414
- .slice(unitStart.index, cursor.index)
480
+ .slice(unitStart, cursor)
415
481
  .find((token) => token.text === "==" && token.kind !== "String");
416
482
  return equals ? { line: equals.line, column: equals.endColumn + 1 } : fallback;
417
483
  };
418
484
 
419
- // tlapm reads TRUE, FALSE, BOOLEAN, STRING and the other keywords only as keywords.
420
485
  const isTlapmKeyword = (token: Token) =>
421
486
  isTlapm && (token.kind === "Keyword" || BUILTIN_CONSTANTS.has(token.text));
422
487
 
423
- const getPreviousEnd = (position: { line: number; column: number }) => {
488
+ const getPreviousEnd = (position: Point) => {
424
489
  const previous = tokens.findLast(
425
490
  (token) =>
426
491
  token.kind !== "End" &&
@@ -436,15 +501,12 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
436
501
  if (TLAPM_PUNCTUATION.has(token.text) || token.kind === "Number" || token.kind === "Decimal")
437
502
  return token.text;
438
503
  if (token.kind === "String") return JSON.stringify(token.text);
504
+ if (token.kind === "Step") return token.text;
439
505
  if (isTlapmKeyword(token)) return `keyword ${token.text}`;
440
506
  return token.kind === "Identifier" ? `identifier ${token.text}` : `operator ${token.text}`;
441
507
  };
442
508
 
443
- const createError = (
444
- message: string,
445
- token: { line: number; column: number } = peekRaw(),
446
- unexpected?: Token,
447
- ) => {
509
+ const createError = (message: string, token: Point = peekRaw(), unexpected?: Token) => {
448
510
  const end = tokens[tokens.length - 1];
449
511
  const isEnd = token.line === end.line && token.column === end.column;
450
512
  return new TlaSyntaxError(
@@ -456,7 +518,7 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
456
518
 
457
519
  const getFailure = (
458
520
  message: string,
459
- token: { line: number; column: number },
521
+ token: Point,
460
522
  isEnd: boolean,
461
523
  unexpected: Token | undefined,
462
524
  ) => {
@@ -477,7 +539,6 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
477
539
  const createUnexpected = (message: string, token: Token = peekRaw()) =>
478
540
  createError(message, token, token);
479
541
 
480
- // TLAplusParser.isFieldNameToken: a keyword or an underscore names a field or a module too.
481
542
  const isFieldName = (token: Token) =>
482
543
  (token.kind === "Identifier" ||
483
544
  token.kind === "Keyword" ||
@@ -492,13 +553,13 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
492
553
  const advance = () => {
493
554
  const token = peek();
494
555
  if (token.kind === "End") throw createError("Unexpected end of expression");
495
- cursor.index++;
556
+ cursor++;
496
557
  return token;
497
558
  };
498
559
 
499
560
  const accept = (text: string) => {
500
561
  if (!isAt(text)) return false;
501
- cursor.index++;
562
+ cursor++;
502
563
  return true;
503
564
  };
504
565
 
@@ -514,49 +575,44 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
514
575
  throw createUnexpected(`Expected an identifier but found ${describeToken(token)}`);
515
576
  }
516
577
  if (isTlapmKeyword(token)) throw createUnexpected(`Unexpected keyword ${token.text}`);
517
- cursor.index++;
578
+ cursor++;
518
579
  return token.text;
519
580
  };
520
581
 
521
582
  const expectName = () => {
522
- const start = cursor.index;
583
+ const start = cursor;
523
584
  return { name: expectIdentifier(), range: getRange(start) };
524
585
  };
525
586
 
526
- const getNames = (names: { name: string; range: SourceRange }[]) => ({
527
- names: names.map((item) => item.name),
528
- ranges: names.map((item) => item.range),
587
+ const getNames = (names: RangedName[]) => ({
588
+ names: names.map((named) => named.name),
589
+ ranges: names.map((named) => named.range),
529
590
  });
530
591
 
531
- // TLAplusParser.Substitution: an identifier, or a prefix, infix or postfix operator.
532
592
  const expectSubstitutionTarget = () => {
533
593
  const token = peek();
534
594
  const isOperator =
535
595
  token.kind !== "String" &&
536
596
  (DEFINABLE_PREFIX_OPERATORS.has(token.text) ||
537
597
  INFIX_OPERATORS.has(token.text) ||
538
- POSTFIX_OPERATORS.has(token.text) ||
539
- token.text === "'");
598
+ DEFINABLE_POSTFIX_OPERATORS.has(token.text));
540
599
  if (!isOperator) return expectIdentifier();
541
- cursor.index++;
600
+ cursor++;
542
601
  return token.text;
543
602
  };
544
603
 
545
- // SANY takes a keyword for the name of a module, as it does for a field.
546
- const keywordModuleName = { isUsed: false };
604
+ let isKeywordModuleName = false;
547
605
  const expectModuleName = () => {
548
606
  if (peek().kind === "Identifier" || !isFieldName(peek())) return expectIdentifier();
549
- keywordModuleName.isUsed = true;
607
+ isKeywordModuleName = true;
550
608
  return advance().text;
551
609
  };
552
610
 
553
- // tlapm reads a bracketed expression apart from the junction list around it, whose alignment
554
- // SANY keeps applying.
555
611
  const withBracketLayout = <Result>(parse: () => Result) => {
556
612
  if (!isTlapm) return parse();
557
- cursor.offsideColumns.push(NO_OFFSIDE);
613
+ offsideColumns.push(NO_OFFSIDE);
558
614
  const result = parse();
559
- cursor.offsideColumns.pop();
615
+ offsideColumns.pop();
560
616
  return result;
561
617
  };
562
618
 
@@ -568,15 +624,15 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
568
624
 
569
625
  const isBoundAhead = () => {
570
626
  if (isAt("<<")) {
571
- const offset = { value: 1 };
572
- while (peek(offset.value).kind === "Identifier" || isAt(",", offset.value)) offset.value++;
573
- return isAt(">>", offset.value) && isAt("\\in", offset.value + 1);
627
+ let offset = 1;
628
+ while (peek(offset).kind === "Identifier" || isAt(",", offset)) offset++;
629
+ return isAt(">>", offset) && isAt("\\in", offset + 1);
574
630
  }
575
- const offset = { value: 0 };
576
- while (peek(offset.value).kind === "Identifier") {
577
- if (isAt("\\in", offset.value + 1)) return true;
578
- if (!isAt(",", offset.value + 1)) return false;
579
- offset.value += 2;
631
+ let offset = 0;
632
+ while (peek(offset).kind === "Identifier") {
633
+ if (isAt("\\in", offset + 1)) return true;
634
+ if (!isAt(",", offset + 1)) return false;
635
+ offset += 2;
580
636
  }
581
637
  return false;
582
638
  };
@@ -584,14 +640,9 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
584
640
  const isLabelAhead = () => {
585
641
  if (isAt("::")) return true;
586
642
  if (!isAt("(")) return false;
587
- const offset = { value: 1 };
588
- while (peek(offset.value).kind === "Identifier" && isAt(",", offset.value + 1))
589
- offset.value += 2;
590
- return (
591
- peek(offset.value).kind === "Identifier" &&
592
- isAt(")", offset.value + 1) &&
593
- isAt("::", offset.value + 2)
594
- );
643
+ let offset = 1;
644
+ while (peek(offset).kind === "Identifier" && isAt(",", offset + 1)) offset += 2;
645
+ return peek(offset).kind === "Identifier" && isAt(")", offset + 1) && isAt("::", offset + 2);
595
646
  };
596
647
 
597
648
  const parsePattern = (): BoundPattern => {
@@ -599,7 +650,7 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
599
650
  const named = expectName();
600
651
  return { kind: "Name", name: named.name, ranges: [named.range] };
601
652
  }
602
- const names = getNames(parseSeparated(expectName));
653
+ const names = getNames(isAt(">>") ? [] : parseSeparated(expectName));
603
654
  expect(">>");
604
655
  return { kind: "Tuple", names: names.names, ranges: names.ranges };
605
656
  };
@@ -612,21 +663,59 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
612
663
  return patterns.map((pattern) => ({ pattern, set }));
613
664
  }).flat();
614
665
 
615
- const parseSubscript = (): Expression => {
666
+ const parseSubscript = (): { subscript: Expression; lastArgs: Expression[] } => {
616
667
  const token = peek();
668
+ if (isTlapm && BUILTIN_CONSTANTS.has(token.text)) {
669
+ const start = cursor;
670
+ advance();
671
+ const constant: Expression = {
672
+ kind: "Identifier",
673
+ name: token.text,
674
+ location: getLocation(token),
675
+ };
676
+ return { subscript: withRange(constant, start), lastArgs: [] };
677
+ }
678
+ const isTlapmAtom =
679
+ isTlapm && (token.kind === "Number" || token.kind === "String" || isAt("@"));
617
680
  if (token.kind === "Identifier") {
618
- const start = cursor.index;
619
- const names = [advance().text];
681
+ const start = cursor;
682
+ const names: string[] = [];
683
+ const selectorRanges: SourceRange[] = [];
684
+ const parseElement = (isApplicable: boolean) => {
685
+ selectorRanges.push(getRange(cursor, cursor));
686
+ names.push(expectIdentifier());
687
+ return isApplicable && isAt("(") ? parseArguments() : [];
688
+ };
689
+ const elementArgs = [parseElement(!isTlapm)];
620
690
  while (isAt("!") && peek(1).kind === "Identifier") {
621
691
  advance();
622
- names.push(expectIdentifier());
692
+ elementArgs.push(parseElement(true));
623
693
  }
624
- return withRange(
625
- { kind: "Identifier", name: names.join("!"), location: getLocation(token) },
626
- start,
627
- );
694
+ const prefixArgs = elementArgs.slice(0, -1);
695
+ const location = getLocation(token);
696
+ location.range = { ...getRange(start), end: selectorRanges[selectorRanges.length - 1].end };
697
+ const name = names.join("!");
698
+ const subscript: Expression = prefixArgs.every((args) => args.length === 0)
699
+ ? { kind: "Identifier", name, location }
700
+ : {
701
+ kind: "Apply",
702
+ operator: name,
703
+ args: prefixArgs.flat(),
704
+ argumentCounts: [...prefixArgs.map((args) => args.length), 0],
705
+ argumentsRange: location.range,
706
+ selectorRanges,
707
+ location,
708
+ };
709
+ return { subscript, lastArgs: elementArgs[elementArgs.length - 1] };
710
+ }
711
+ if (isAt("<<") || isAt("(") || isAt("{") || isAt("[") || isTlapmAtom) {
712
+ const start = cursor;
713
+ const subscript = parsePrimary();
714
+ return {
715
+ subscript: subscript.location.range ? subscript : withRange(subscript, start),
716
+ lastArgs: [],
717
+ };
628
718
  }
629
- if (isAt("<<") || isAt("(")) return parsePrimary();
630
719
  throw createUnexpected(`Expected a subscript but found ${describeToken(token)}`);
631
720
  };
632
721
 
@@ -640,12 +729,11 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
640
729
  token.kind === "Identifier" &&
641
730
  (next.text === "(" ||
642
731
  next.text === "[" ||
643
- (next.kind === "Operator" && isAt("==", POSTFIX_OPERATORS.has(next.text) ? 3 : 4)))
732
+ (next.kind === "Operator" &&
733
+ isAt("==", DEFINABLE_POSTFIX_OPERATORS.has(next.text) ? 3 : 4)))
644
734
  );
645
735
  };
646
736
 
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.
649
737
  const isStandalone = (operator: Token) => {
650
738
  const token = peek(1);
651
739
  return (
@@ -665,8 +753,6 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
665
753
  token.kind === "Operator" &&
666
754
  (INFIX_OPERATORS.has(token.text) || PREFIX_OPERATOR_REFERENCES.has(token.text)) &&
667
755
  isStandalone(token);
668
- // tlapm reads a prefix operator as the start of an expression, and (+), (-), (/) and (\X) as
669
- // the operators \oplus, \ominus, \oslash and \otimes.
670
756
  const isTlapmIncomplete =
671
757
  isTlapm &&
672
758
  token.kind !== "String" &&
@@ -682,8 +768,11 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
682
768
  peek(1).line === token.line &&
683
769
  peek(1).column === token.endColumn + 1));
684
770
  if (isTlapmIncomplete && isStandalone(token)) throw createError("incomplete expression", token);
771
+ if (isOperatorAlone && !isTlapm && token.text === "\\X" && token.spelling !== "×") {
772
+ throw createError("\\X may not be used as an infix operator", token);
773
+ }
685
774
  if (isOperatorAlone) {
686
- cursor.index++;
775
+ cursor++;
687
776
  return withRange(
688
777
  {
689
778
  kind: "OperatorReference",
@@ -691,18 +780,18 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
691
780
  spelling: token.spelling,
692
781
  location: getLocation(token),
693
782
  },
694
- cursor.index - 1,
783
+ cursor - 1,
695
784
  );
696
785
  }
697
786
  const isPrefixAlone =
698
787
  token.kind !== "String" && OPERATOR_ARGUMENTS.has(token.text) && isStandalone(token);
699
788
  if (isPrefixAlone) {
700
- cursor.index++;
789
+ cursor++;
701
790
  const location = getLocation(token);
702
791
  if (POSTFIX_OPERATORS.has(token.text)) {
703
792
  return withRange(
704
793
  { kind: "OperatorReference", operator: token.text, spelling: token.spelling, location },
705
- cursor.index - 1,
794
+ cursor - 1,
706
795
  );
707
796
  }
708
797
  const argument: Expression = { kind: "Identifier", name: "argument", location };
@@ -714,11 +803,11 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
714
803
  operator: token.text,
715
804
  location: getLocation(token),
716
805
  },
717
- cursor.index - 1,
806
+ cursor - 1,
718
807
  );
719
808
  }
720
809
  if (isAt("LAMBDA")) {
721
- const start = cursor.index;
810
+ const start = cursor;
722
811
  advance();
723
812
  const params = getNames(parseSeparated(expectName));
724
813
  expect(":");
@@ -737,27 +826,31 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
737
826
  return parseExpression();
738
827
  };
739
828
 
740
- const lastArguments: { range: SourceRange | undefined } = { range: undefined };
829
+ let lastArgumentsRange: SourceRange | undefined;
741
830
 
742
831
  const parseArguments = () =>
743
832
  withBracketLayout(() => {
744
- const start = cursor.index;
833
+ const start = cursor;
745
834
  expect("(");
746
835
  const args = parseSeparated(parseArgument);
747
836
  expect(")");
748
- lastArguments.range = getRange(start);
837
+ lastArgumentsRange = getRange(start);
749
838
  return args;
750
839
  });
751
840
 
752
841
  const parseJunctionList = (): Expression => {
753
842
  const bullet = advance();
754
- cursor.offsideColumns.push(bullet.column);
843
+ offsideColumns.push(bullet.column);
755
844
  const operands = [parseExpression()];
756
- while (peekRaw().text === bullet.text && peekRaw().column === bullet.column) {
757
- cursor.index++;
845
+ while (
846
+ isBullet(peekRaw()) &&
847
+ peekRaw().text === bullet.text &&
848
+ peekRaw().column === bullet.column
849
+ ) {
850
+ cursor++;
758
851
  operands.push(parseExpression());
759
852
  }
760
- cursor.offsideColumns.pop();
853
+ offsideColumns.pop();
761
854
  return {
762
855
  kind: bullet.text === "/\\" ? "And" : "Or",
763
856
  operands,
@@ -769,13 +862,12 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
769
862
  const parseBracket = (start: Token): Expression =>
770
863
  withBracketLayout(() => {
771
864
  const location = getLocation(start);
772
- // SANY takes a keyword for the first field of a record, as it does for a selected field.
773
865
  const isIdentifier = peek().kind === "Identifier";
774
866
  const isRecord = isAt("|->", 1) && (isIdentifier || isFieldName(peek()));
775
867
  if (isRecord || (isIdentifier && isAt(":", 1))) {
776
868
  const kind = isRecord ? "Record" : "RecordSet";
777
869
  const parseField = (readName: () => string) => {
778
- const fieldStart = cursor.index;
870
+ const fieldStart = cursor;
779
871
  const fieldLocation = getLocation(peek());
780
872
  const name = readName();
781
873
  fieldLocation.range = getRange(fieldStart);
@@ -790,11 +882,15 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
790
882
  return { kind, fields, location };
791
883
  }
792
884
  if (isBoundAhead()) {
885
+ const checkpoint = cursor;
793
886
  const bounds = parseBounds();
794
- expect("|->");
795
- const body = parseExpression();
796
- expect("]");
797
- return { kind: "FunctionConstruction", bounds, body, location };
887
+ if (!isTlapm || isAt("|->")) {
888
+ expect("|->");
889
+ const body = parseExpression();
890
+ expect("]");
891
+ return { kind: "FunctionConstruction", bounds, body, location };
892
+ }
893
+ cursor = checkpoint;
798
894
  }
799
895
  const expression = parseExpression();
800
896
  if (accept("->")) {
@@ -810,6 +906,7 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
810
906
  if (accept(".")) {
811
907
  if (!isFieldName(peek()))
812
908
  throw createUnexpected(`Expected a field name but found ${describeToken(peek())}`);
909
+ if (!isTlapm && isAt("@")) throw createUnexpected("@ used in !.@");
813
910
  path.push({ kind: "Field", name: advance().text });
814
911
  continue;
815
912
  }
@@ -830,12 +927,16 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
830
927
  return { kind: "Bracket", args, location };
831
928
  }
832
929
  expect("]_");
833
- return { kind: "BoxAction", action: expression, subscript: parseSubscript(), location };
930
+ return {
931
+ kind: "BoxAction",
932
+ action: expression,
933
+ subscript: parseSubscript().subscript,
934
+ location,
935
+ };
834
936
  });
835
937
 
836
- // SANY reads the set after the \in of {x \in S} as a whole expression, whatever operators it has.
837
938
  const parseSetMembership = (): Expression => {
838
- const start = cursor.index;
939
+ const start = cursor;
839
940
  const element = withRange(parsePrefix(), start);
840
941
  const location = getLocation(advance());
841
942
  return withRange(
@@ -849,7 +950,7 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
849
950
  const location = getLocation(start);
850
951
  if (accept("}")) return { kind: "SetEnumeration", elements: [], location };
851
952
  if (isBoundAhead() && (peek(1).text === "\\in" || isAt("<<"))) {
852
- const checkpoint = cursor.index;
953
+ const checkpoint = cursor;
853
954
  const pattern = parsePattern();
854
955
  expect("\\in");
855
956
  const set = parseExpression();
@@ -858,7 +959,7 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
858
959
  expect("}");
859
960
  return { kind: "SetFilter", bound: { pattern, set }, predicate, location };
860
961
  }
861
- cursor.index = checkpoint;
962
+ cursor = checkpoint;
862
963
  }
863
964
  const first =
864
965
  peek().kind === "Identifier" && isAt("\\in", 1) ? parseSetMembership() : parseExpression();
@@ -881,7 +982,12 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
881
982
  if (accept(">>_")) {
882
983
  if (elements.length !== 1)
883
984
  throw createError("Expected a single action inside <<A>>_v", start);
884
- return { kind: "AngleAction", action: elements[0], subscript: parseSubscript(), location };
985
+ return {
986
+ kind: "AngleAction",
987
+ action: elements[0],
988
+ subscript: parseSubscript().subscript,
989
+ location,
990
+ };
885
991
  }
886
992
  expect(">>");
887
993
  return { kind: "Tuple", elements, location };
@@ -912,9 +1018,17 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
912
1018
  const parseCase = (start: Token): Expression => {
913
1019
  const arms: CaseArm[] = [];
914
1020
  do {
1021
+ const otherStart = cursor;
915
1022
  if (accept("OTHER")) {
916
1023
  expect("->");
917
- return { kind: "Case", arms, other: parseExpression(), location: getLocation(start) };
1024
+ const other = parseExpression();
1025
+ return {
1026
+ kind: "Case",
1027
+ arms,
1028
+ other,
1029
+ otherRange: getRange(otherStart),
1030
+ location: getLocation(start),
1031
+ };
918
1032
  }
919
1033
  const condition = parseExpression();
920
1034
  expect("->");
@@ -931,9 +1045,9 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
931
1045
  next.kind === "Number" ||
932
1046
  SELECTOR_SYMBOLS.has(next.text) ||
933
1047
  (next.kind === "Operator" &&
934
- (INFIX_OPERATORS.has(next.text) ||
935
- POSTFIX_OPERATORS.has(next.text) ||
936
- PREFIX_OPERATOR_REFERENCES.has(next.text))))
1048
+ (INFIX_OPERATORS.has(next.text) || DEFINABLE_POSTFIX_OPERATORS.has(next.text))) ||
1049
+ ((next.kind === "Operator" || next.kind === "Keyword") &&
1050
+ DEFINABLE_PREFIX_OPERATORS.has(next.text)))
937
1051
  );
938
1052
  };
939
1053
 
@@ -949,7 +1063,7 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
949
1063
  case "@":
950
1064
  return { kind: "At" };
951
1065
  case "(": {
952
- cursor.index--;
1066
+ cursor--;
953
1067
  return { kind: "Bound", args: parseArguments() };
954
1068
  }
955
1069
  }
@@ -957,7 +1071,7 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
957
1071
  };
958
1072
 
959
1073
  const parsePrimary = (preceding?: Precedence): Expression => {
960
- const start = cursor.index;
1074
+ const start = cursor;
961
1075
  const token = advance();
962
1076
  const location = getLocation(token);
963
1077
  if (isTlapm && token.kind === "Keyword" && token.text === "LAMBDA") {
@@ -972,7 +1086,7 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
972
1086
  if (token.kind === "Decimal") return { kind: "Decimal", text: token.text, location };
973
1087
  if (token.kind === "String") return { kind: "String", value: token.text, location };
974
1088
  const isStep = token.kind === "Step" && isStepReference(token);
975
- if (isStep && getProofLevel() < 0 && proofLevels.length <= 1) {
1089
+ if (!isTlapm && isStep && getProofLevel() < 0 && proofLevels.length <= 1) {
976
1090
  throw createError("Step number used outside proof", token);
977
1091
  }
978
1092
  if (isStep && token.text[1] === "+") {
@@ -984,14 +1098,14 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
984
1098
  const params = getNames(accept("(") ? parseSeparated(expectName) : []);
985
1099
  if (params.names.length > 0) expect(")");
986
1100
  expect("::");
1101
+ const head = getRange(start);
987
1102
  const body = parseExpression();
988
- // TLAplusParser.labelDoesNotChangeParse.
989
1103
  if (
990
1104
  !isTlapm &&
991
1105
  preceding !== undefined &&
992
- operators.last !== undefined &&
1106
+ lastOperator !== undefined &&
993
1107
  isOperatorExpression(body) &&
994
- preceding.high >= operators.last.low
1108
+ preceding.high >= lastOperator.low
995
1109
  ) {
996
1110
  throw createError("Removing the label would change expression parsing", token);
997
1111
  }
@@ -1000,6 +1114,7 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1000
1114
  name,
1001
1115
  params: params.names,
1002
1116
  paramRanges: params.ranges,
1117
+ head,
1003
1118
  body,
1004
1119
  location,
1005
1120
  };
@@ -1008,20 +1123,20 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1008
1123
  if (name === "@" && !hasArguments && !isSelectorAhead())
1009
1124
  return { kind: "ExceptAt", location };
1010
1125
  const args = hasArguments ? parseArguments() : [];
1011
- const argumentRanges = [hasArguments ? lastArguments.range : undefined];
1126
+ const argumentRanges = [hasArguments ? lastArgumentsRange : undefined];
1012
1127
  if (!isSelectorAhead()) {
1013
1128
  return hasArguments
1014
- ? { kind: "Apply", operator: name, args, argumentsRange: lastArguments.range, location }
1129
+ ? { kind: "Apply", operator: name, args, argumentsRange: lastArgumentsRange, location }
1015
1130
  : { kind: "Identifier", name, location };
1016
1131
  }
1017
1132
  const selectors: Selector[] = [{ kind: "Name", name, args }];
1018
1133
  const selectorRanges = [getRange(start, start)];
1019
1134
  while (isSelectorAhead()) {
1020
1135
  advance();
1021
- selectorRanges.push(getRange(cursor.index, cursor.index));
1022
- lastArguments.range = undefined;
1136
+ selectorRanges.push(getRange(cursor, cursor));
1137
+ lastArgumentsRange = undefined;
1023
1138
  selectors.push(parseSelector());
1024
- argumentRanges.push(lastArguments.range);
1139
+ argumentRanges.push(lastArgumentsRange);
1025
1140
  }
1026
1141
  const names = selectors.flatMap((selector) =>
1027
1142
  selector.kind === "Name" ? [selector.name] : [],
@@ -1049,15 +1164,12 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1049
1164
  location,
1050
1165
  };
1051
1166
  }
1052
- // SANY reads an infix or postfix operator as a primary expression, with or without arguments.
1053
1167
  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
- };
1168
+ const args = parseArguments();
1169
+ // Deviation from TLC: SANY's built-in \X has no definition for TLC to evaluate, a TLC bug.
1170
+ return mode === "tlc" && token.text === "\\X" && args.length === 2
1171
+ ? { kind: "Product", factors: args, location }
1172
+ : { kind: "Apply", operator: token.text, spelling: token.spelling, args, location };
1061
1173
  }
1062
1174
  if (token.kind === "Operator" && isOperatorName(token.text) && !isTlapm) {
1063
1175
  return { kind: "Identifier", name: token.text, spelling: token.spelling, location };
@@ -1101,7 +1213,7 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1101
1213
  declareRecursive();
1102
1214
  continue;
1103
1215
  }
1104
- const unit = parseDefinition(false);
1216
+ const unit = parseDefinition(!isTlapm && accept("LOCAL"));
1105
1217
  if (unit.kind === "Instance") instances.push(unit);
1106
1218
  else definitions.push(unit);
1107
1219
  }
@@ -1120,15 +1232,18 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1120
1232
  case "WF_":
1121
1233
  case "SF_": {
1122
1234
  const subscript = parseSubscript();
1123
- const action = withBracketLayout(() => {
1124
- expect("(");
1125
- const expression = parseExpression();
1126
- expect(")");
1127
- return expression;
1128
- });
1235
+ const action =
1236
+ !isAt("(") && subscript.lastArgs.length === 1
1237
+ ? subscript.lastArgs[0]
1238
+ : withBracketLayout(() => {
1239
+ expect("(");
1240
+ const expression = parseExpression();
1241
+ expect(")");
1242
+ return expression;
1243
+ });
1129
1244
  return {
1130
1245
  kind: token.text === "WF_" ? "WeakFairness" : "StrongFairness",
1131
- subscript,
1246
+ subscript: subscript.subscript,
1132
1247
  action,
1133
1248
  location,
1134
1249
  };
@@ -1137,16 +1252,15 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1137
1252
  throw createUnexpected(`Unexpected ${describeToken(token)}`, token);
1138
1253
  };
1139
1254
 
1140
- // SANY rejects the operator after a prefix operator's operand unless it binds looser than the
1141
- // prefix operator.
1142
1255
  const parsePrefixOperand = (operator: Token, low: number, high: number) => {
1143
- operators.last = operators.preceding = { low, high };
1144
- const operand = parseExpression(high + 1);
1256
+ lastOperator = precedingOperator = { low, high };
1257
+ const operand = parseExpression(
1258
+ isTlapm ? Math.min(high + 1, POSTFIX_PRECEDENCE.low) : high + 1,
1259
+ );
1145
1260
  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;
1261
+ const nextHigh = DEFINABLE_POSTFIX_OPERATORS.has(next.text)
1262
+ ? POSTFIX_PRECEDENCE.high
1263
+ : INFIX_OPERATORS.get(next.text)?.high;
1150
1264
  if (!isTlapm && next.kind === "Operator" && nextHigh !== undefined && nextHigh >= low) {
1151
1265
  throw createError(`Precedence conflict between ${operator.text} and ${next.text}`, next);
1152
1266
  }
@@ -1154,13 +1268,33 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1154
1268
  };
1155
1269
 
1156
1270
  const parsePrefix = (): Expression => {
1157
- const preceding = operators.preceding;
1158
- operators.preceding = undefined;
1271
+ const preceding = precedingOperator;
1272
+ precedingOperator = undefined;
1159
1273
  const token = peek();
1160
1274
  const location = getLocation(token);
1161
- if (token.kind === "Operator" && (token.text === "/\\" || token.text === "\\/")) {
1275
+ if (token.kind === "Operator" && isBullet(token)) {
1162
1276
  return parseJunctionList();
1163
1277
  }
1278
+ if (isTlapm && INFIX_OPERATORS.has(token.text) && isAt("(", 1)) {
1279
+ const start = cursor;
1280
+ const nonfix = withBracketLayout(() => {
1281
+ advance();
1282
+ advance();
1283
+ const left = parseExpression();
1284
+ if (!accept(",")) return undefined;
1285
+ const right = parseExpression();
1286
+ expect(")");
1287
+ const apply: Expression = {
1288
+ kind: "Apply",
1289
+ operator: token.text,
1290
+ args: [left, right],
1291
+ location,
1292
+ };
1293
+ return withRange(apply, start);
1294
+ });
1295
+ if (nonfix !== undefined) return nonfix;
1296
+ cursor = start;
1297
+ }
1164
1298
  if (token.kind === "Operator" || token.kind === "Keyword") {
1165
1299
  switch (token.text) {
1166
1300
  case "~":
@@ -1172,6 +1306,8 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1172
1306
  location,
1173
1307
  };
1174
1308
  case "-":
1309
+ case "-.":
1310
+ if (token.text === "-." && !isTlapm) break;
1175
1311
  advance();
1176
1312
  return {
1177
1313
  kind: "Apply",
@@ -1198,7 +1334,6 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1198
1334
  return {
1199
1335
  kind: "Apply",
1200
1336
  operator: token.text,
1201
- // tlapm gives these operators the precedence 8 of the TLA+ book, and SANY 10-13.
1202
1337
  args: [isTlapm ? parseExpression(9) : parsePrefixOperand(token, 10, 13)],
1203
1338
  location,
1204
1339
  };
@@ -1208,31 +1343,29 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1208
1343
  };
1209
1344
 
1210
1345
  const parseExpression = (minimumPrecedence = 0): Expression => {
1211
- const start = cursor.index;
1346
+ const start = cursor;
1212
1347
  const prefix = parsePrefix();
1213
- const state = {
1214
- left: prefix.location.range ? prefix : withRange(prefix, start),
1215
- previous: undefined as (InfixOperator & { text: string }) | undefined,
1216
- };
1348
+ let left = prefix.location.range ? prefix : withRange(prefix, start);
1349
+ let previous: (InfixOperator & { text: string }) | undefined;
1217
1350
  while (true) {
1218
1351
  const token = peek();
1219
1352
  if (token.kind !== "Operator") break;
1220
1353
  const location = getLocation(token);
1221
1354
  if (token.text === "'" && minimumPrecedence <= 15) {
1222
1355
  advance();
1223
- operators.last = POSTFIX_PRECEDENCE;
1224
- state.left = withRange({ kind: "Prime", expression: state.left, location }, start);
1356
+ lastOperator = POSTFIX_PRECEDENCE;
1357
+ left = withRange({ kind: "Prime", expression: left, location }, start);
1225
1358
  continue;
1226
1359
  }
1227
1360
  if (POSTFIX_OPERATORS.has(token.text) && minimumPrecedence <= 15) {
1228
1361
  advance();
1229
- operators.last = POSTFIX_PRECEDENCE;
1230
- state.left = withRange(
1362
+ lastOperator = POSTFIX_PRECEDENCE;
1363
+ left = withRange(
1231
1364
  {
1232
1365
  kind: "Apply",
1233
1366
  operator: token.text,
1234
1367
  spelling: token.spelling,
1235
- args: [state.left],
1368
+ args: [left],
1236
1369
  location,
1237
1370
  },
1238
1371
  start,
@@ -1243,22 +1376,18 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1243
1376
  advance();
1244
1377
  const args = withBracketLayout(() => parseSeparated(() => parseExpression()));
1245
1378
  withBracketLayout(() => expect("]"));
1246
- operators.last = FUNCTION_PRECEDENCE;
1247
- state.left = withRange(
1248
- { kind: "FunctionApplication", function: state.left, args, location },
1249
- start,
1250
- );
1379
+ lastOperator = FUNCTION_PRECEDENCE;
1380
+ left = withRange({ kind: "FunctionApplication", function: left, args, location }, start);
1251
1381
  continue;
1252
1382
  }
1253
1383
  if (token.text === "." && isFieldName(peek(1))) {
1254
1384
  advance();
1255
1385
  const field = advance().text;
1256
- state.left = withRange({ kind: "FieldAccess", record: state.left, field, location }, start);
1386
+ left = withRange({ kind: "FieldAccess", record: left, field, location }, start);
1257
1387
  continue;
1258
1388
  }
1259
1389
  const infix = INFIX_OPERATORS.get(token.text);
1260
1390
  if (!infix || infix.low < minimumPrecedence) break;
1261
- const previous = state.previous;
1262
1391
  if (previous) {
1263
1392
  const isOverlapping = !(previous.low > infix.high || previous.high < infix.low);
1264
1393
  const isChain = previous.text === token.text && infix.isAssociative;
@@ -1270,17 +1399,15 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1270
1399
  }
1271
1400
  }
1272
1401
  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("-")) {
1402
+ if (!isTlapm && infix.low > NEGATION_PRECEDENCE && isAt("-")) {
1275
1403
  throw createError(`Precedence conflict between ${token.text} and -`, peek());
1276
1404
  }
1277
- operators.last = operators.preceding = infix;
1405
+ lastOperator = precedingOperator = infix;
1278
1406
  const right = parseExpression(infix.high + 1);
1279
- const left = state.left;
1280
1407
  if (token.text === "/\\" || token.text === "\\/") {
1281
1408
  const kind = token.text === "/\\" ? "And" : "Or";
1282
1409
  const prefixEnds = [getRange(start).end];
1283
- state.left =
1410
+ left =
1284
1411
  left.kind === kind && previous?.text === token.text
1285
1412
  ? {
1286
1413
  ...left,
@@ -1289,12 +1416,12 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1289
1416
  }
1290
1417
  : { kind, operands: [left, right], prefixEnds, location };
1291
1418
  } else if (token.text === "\\X") {
1292
- state.left =
1419
+ left =
1293
1420
  left.kind === "Product" && previous?.text === "\\X"
1294
1421
  ? { ...left, factors: [...left.factors, right] }
1295
1422
  : { kind: "Product", factors: [left, right], location };
1296
1423
  } else {
1297
- state.left = {
1424
+ left = {
1298
1425
  kind: "Apply",
1299
1426
  operator: token.text,
1300
1427
  spelling: token.spelling,
@@ -1302,10 +1429,10 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1302
1429
  location,
1303
1430
  };
1304
1431
  }
1305
- state.left = withRange(state.left, start);
1306
- state.previous = { ...infix, text: token.text };
1432
+ left = withRange(left, start);
1433
+ previous = { ...infix, text: token.text };
1307
1434
  }
1308
- return state.left;
1435
+ return left;
1309
1436
  };
1310
1437
 
1311
1438
  const parseParams = () => {
@@ -1318,17 +1445,17 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1318
1445
  const parseBody = () => {
1319
1446
  const start = getLocation(peek());
1320
1447
  const body = parseExpression();
1321
- const last = tokens[cursor.index - 1];
1448
+ const last = tokens[cursor - 1];
1322
1449
  const end = { line: last.line, column: last.endColumn };
1323
1450
  return { body, bodyRange: { module: openModules[0].name, start, end } };
1324
1451
  };
1325
1452
 
1326
1453
  const parseDefinition = (isLocal: boolean): Definition | Instance => {
1327
- const start = cursor.index;
1454
+ const start = cursor;
1328
1455
  return withRange(parseDefinitionUnit(isLocal), start);
1329
1456
  };
1330
1457
 
1331
- const toParam = (named: { name: string; range: SourceRange }): OperatorParam => ({
1458
+ const toParam = (named: RangedName): OperatorParam => ({
1332
1459
  name: named.name,
1333
1460
  arity: 0,
1334
1461
  location: {
@@ -1340,11 +1467,13 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1340
1467
 
1341
1468
  const parseDefinitionUnit = (isLocal: boolean): Definition | Instance => {
1342
1469
  const token = peek();
1470
+ const start = cursor;
1343
1471
  const location = getLocation(token);
1344
1472
  const parseOperator = (name: string, params: OperatorParam[]): Definition => ({
1345
1473
  kind: "Operator",
1346
1474
  name,
1347
1475
  params,
1476
+ head: getRange(start, cursor - 2),
1348
1477
  ...parseBody(),
1349
1478
  isLocal,
1350
1479
  isRecursive: isRecursiveName(name),
@@ -1366,7 +1495,7 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1366
1495
  const isPrefixDefinition =
1367
1496
  token.kind !== "String" && DEFINABLE_PREFIX_OPERATORS.has(token.text);
1368
1497
  const isPostfixDefinition =
1369
- token.kind === "Identifier" && POSTFIX_OPERATORS.has(peek(1).text) && isAt("==", 2);
1498
+ token.kind === "Identifier" && DEFINABLE_POSTFIX_OPERATORS.has(peek(1).text) && isAt("==", 2);
1370
1499
  if (isPrefixDefinition || isPostfixDefinition) {
1371
1500
  const operator = isPrefixDefinition ? token.text : peek(1).text;
1372
1501
  if (isPrefixDefinition) advance();
@@ -1390,7 +1519,7 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1390
1519
  location,
1391
1520
  };
1392
1521
  }
1393
- const definitionStart = cursor.index;
1522
+ const definitionStart = cursor;
1394
1523
  const params = parseParams();
1395
1524
  expect("==");
1396
1525
  if (isAt("INSTANCE")) {
@@ -1406,12 +1535,12 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1406
1535
  isLocal: boolean,
1407
1536
  location: SourceLocation,
1408
1537
  ): Instance => {
1409
- const start = cursor.index;
1538
+ const start = cursor;
1410
1539
  expect("INSTANCE");
1411
1540
  const module = expectModuleName();
1412
1541
  const substitutions = accept("WITH")
1413
1542
  ? parseSeparated(() => {
1414
- const targetStart = cursor.index;
1543
+ const targetStart = cursor;
1415
1544
  const target = expectSubstitutionTarget();
1416
1545
  const nameRange = getRange(targetStart);
1417
1546
  expect("<-");
@@ -1431,7 +1560,7 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1431
1560
  };
1432
1561
 
1433
1562
  const parseDeclaration = (): Declaration => {
1434
- const start = cursor.index;
1563
+ const start = cursor;
1435
1564
  return withRange(parseDeclarationUnit(), start);
1436
1565
  };
1437
1566
 
@@ -1442,7 +1571,10 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1442
1571
  const name = advance().text;
1443
1572
  return { name, arity: accept("_") ? 2 : 1, location };
1444
1573
  }
1445
- if (peek().kind === "Operator" && isAt("_", 1)) {
1574
+ const isPrefixOperator =
1575
+ peek().kind !== "String" &&
1576
+ (DEFINABLE_PREFIX_OPERATORS.has(peek().text) || (isTlapm && peek().kind === "Operator"));
1577
+ if (isPrefixOperator && isAt("_", 1)) {
1446
1578
  const operator = advance().text;
1447
1579
  advance();
1448
1580
  return { name: operator === "-" ? "-." : operator, arity: 1, location };
@@ -1464,19 +1596,19 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1464
1596
  return declarations;
1465
1597
  };
1466
1598
 
1467
- const getClosingOffset = (offset: number) => {
1468
- const depth = { value: 0, offset };
1599
+ const getClosingOffset = (start: number) => {
1600
+ let depth = 0;
1601
+ let offset = start;
1469
1602
  do {
1470
- const token = peek(depth.offset);
1471
- if (token.kind === "End") return depth.offset;
1472
- if (token.kind === "Operator" && OPENING_BRACKETS.has(token.text)) depth.value++;
1473
- if (token.kind === "Operator" && CLOSING_BRACKETS.has(token.text)) depth.value--;
1474
- depth.offset++;
1475
- } while (depth.value > 0);
1476
- return depth.offset;
1603
+ const token = peek(offset);
1604
+ if (token.kind === "End") return offset;
1605
+ if (token.kind === "Operator" && OPENING_BRACKETS.has(token.text)) depth++;
1606
+ if (token.kind === "Operator" && CLOSING_BRACKETS.has(token.text)) depth--;
1607
+ offset++;
1608
+ } while (depth > 0);
1609
+ return offset;
1477
1610
  };
1478
1611
 
1479
- // SANY inserts a break before each definition, which ends the fact list or step before it.
1480
1612
  const isDefinitionStart = () => {
1481
1613
  const token = peek();
1482
1614
  const next = peek(1);
@@ -1489,14 +1621,14 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1489
1621
  );
1490
1622
  }
1491
1623
  if (isAt("(", 1) || isAt("[", 1)) return isAt("==", getClosingOffset(1));
1492
- if (next.kind === "Operator" && POSTFIX_OPERATORS.has(next.text)) return isAt("==", 2);
1624
+ if (next.kind === "Operator" && DEFINABLE_POSTFIX_OPERATORS.has(next.text))
1625
+ return isAt("==", 2);
1493
1626
  if (next.kind === "Operator" && INFIX_OPERATORS.has(next.text)) {
1494
1627
  return peek(2).kind === "Identifier" && isAt("==", 3);
1495
1628
  }
1496
1629
  return isAt("==", 1);
1497
1630
  };
1498
1631
 
1499
- // SANY's proof levels, one for each open proof, which stay -1 until a step sets them.
1500
1632
  const proofLevels: number[] = [];
1501
1633
 
1502
1634
  const getProofLevel = () => proofLevels[proofLevels.length - 1] ?? -1;
@@ -1509,9 +1641,9 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1509
1641
 
1510
1642
  const getStepLabel = (step: Token) => {
1511
1643
  const label = step.text.slice(step.text.indexOf(">") + 1);
1512
- const end = { value: label.length };
1513
- while (label[end.value - 1] === ".") end.value--;
1514
- return label.slice(0, end.value);
1644
+ let end = label.length;
1645
+ while (label[end - 1] === ".") end--;
1646
+ return label.slice(0, end);
1515
1647
  };
1516
1648
 
1517
1649
  const isStepReference = (step: Token) =>
@@ -1574,17 +1706,15 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1574
1706
  return !isDefinitionStart();
1575
1707
  };
1576
1708
 
1577
- // SANY reads an infix or postfix operator alone as its name, but a prefix operator such as - as the
1578
- // start of an expression.
1579
1709
  const parseFact = (): Fact => {
1580
- const start = cursor.index;
1710
+ const start = cursor;
1581
1711
  const token = peek();
1582
1712
  if (
1583
1713
  token.kind === "Operator" &&
1584
1714
  !EXPRESSION_PREFIXES.has(token.text) &&
1585
1715
  isOperatorName(token.text)
1586
1716
  ) {
1587
- cursor.index++;
1717
+ cursor++;
1588
1718
  return withRange(
1589
1719
  {
1590
1720
  kind: "OperatorReference",
@@ -1619,9 +1749,8 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1619
1749
  module.variables.some((variable) => variable.name === name),
1620
1750
  );
1621
1751
 
1622
- // tlapm's definable: names and operators joined by !.
1623
1752
  const parseDefinable = (): Fact => {
1624
- const start = cursor.index;
1753
+ const start = cursor;
1625
1754
  const token = peek();
1626
1755
  const parts = parseSeparated(() => {
1627
1756
  const part = peek();
@@ -1629,7 +1758,7 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1629
1758
  if (!isName && part.kind !== "Operator") {
1630
1759
  throw createUnexpected(`Expected a definition name but found ${describeToken(part)}`, part);
1631
1760
  }
1632
- cursor.index++;
1761
+ cursor++;
1633
1762
  return part.text;
1634
1763
  }, "!");
1635
1764
  const location = getLocation(token);
@@ -1654,13 +1783,15 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1654
1783
  return defs;
1655
1784
  };
1656
1785
 
1657
- const parseFacts = () => ({
1658
- facts: isFactAhead() ? parseSeparated(parseFact) : [],
1659
- defs: accept("DEF") || accept("DEFS") ? parseDefs() : [],
1660
- });
1786
+ const parseFacts = () => {
1787
+ const facts = isFactAhead() ? parseSeparated(parseFact) : [];
1788
+ const isDef = accept("DEF") || accept("DEFS");
1789
+ if (isTlapm && facts.length === 0 && !isDef) throw createUnexpected("Expected a fact");
1790
+ return { facts, defs: isDef ? parseDefs() : [] };
1791
+ };
1661
1792
 
1662
1793
  const parseUseOrHide = (): UseOrHide => {
1663
- const start = cursor.index;
1794
+ const start = cursor;
1664
1795
  const keyword = advance();
1665
1796
  const isOnly = keyword.text === "USE" && accept("ONLY");
1666
1797
  const keywordRange = getRange(start);
@@ -1686,9 +1817,11 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1686
1817
  };
1687
1818
 
1688
1819
  const parseNewSymbol = (): NewSymbol => {
1689
- const start = cursor.index;
1690
- const location = getLocation(peek());
1820
+ const newStart = cursor;
1821
+ const newLocation = getLocation(peek());
1691
1822
  const isNew = accept("NEW");
1823
+ const start = isTlapm ? cursor : newStart;
1824
+ const location = isTlapm ? getLocation(peek()) : newLocation;
1692
1825
  const level = peek().kind === "Keyword" ? NEW_SYMBOL_LEVELS.get(peek().text) : undefined;
1693
1826
  if (!isNew && level === undefined) {
1694
1827
  throw createUnexpected(`Expected a declaration but found ${describeToken(peek())}`);
@@ -1732,9 +1865,13 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1732
1865
  };
1733
1866
 
1734
1867
  const parseAssumeProve = (): AssumeProve => {
1735
- const start = cursor.index;
1868
+ const start = cursor;
1736
1869
  const location = getLocation(expect("ASSUME"));
1737
1870
  const assumptions = parseSeparated(() => {
1871
+ if (peek().kind === "Identifier" && isAt("::", 1) && isAt("ASSUME", 2)) {
1872
+ advance();
1873
+ advance();
1874
+ }
1738
1875
  if (isAt("ASSUME")) return withProofScope(parseAssumeProve);
1739
1876
  if (peek().kind === "Keyword" && NEW_SYMBOL_STARTS.has(peek().text)) return parseNewSymbol();
1740
1877
  return parseExpression();
@@ -1747,11 +1884,11 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1747
1884
  };
1748
1885
 
1749
1886
  const isNameListAhead = (terminator: string) => {
1750
- const offset = { value: 0 };
1751
- while (peek(offset.value).kind === "Identifier" && isAt(",", offset.value + 1)) {
1752
- offset.value += 2;
1887
+ let offset = 0;
1888
+ while (peek(offset).kind === "Identifier" && isAt(",", offset + 1)) {
1889
+ offset += 2;
1753
1890
  }
1754
- return peek(offset.value).kind === "Identifier" && isAt(terminator, offset.value + 1);
1891
+ return peek(offset).kind === "Identifier" && isAt(terminator, offset + 1);
1755
1892
  };
1756
1893
 
1757
1894
  const declareProofSymbols = (names: string[], bounds: Bound[]) => {
@@ -1767,11 +1904,11 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1767
1904
  const token = peek();
1768
1905
  if (isAt("USE") || isAt("HIDE")) return parseUseOrHide();
1769
1906
  if (isAt("INSTANCE")) {
1770
- const start = cursor.index;
1907
+ const start = cursor;
1771
1908
  return withRange(parseInstance(undefined, [], false, getLocation(token)), start);
1772
1909
  }
1773
1910
  if (isAt("DEFINE") || isDefinitionStart()) {
1774
- const start = cursor.index;
1911
+ const start = cursor;
1775
1912
  accept("DEFINE");
1776
1913
  const definitions = [parseDefinition(false)];
1777
1914
  while (isDefinitionStart()) definitions.push(parseDefinition(false));
@@ -1819,19 +1956,17 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1819
1956
  if (!isCorrectLevel(step)) {
1820
1957
  throw createError(`${isQed ? "QED step" : "step"}'s number has bad level`, step);
1821
1958
  }
1822
- if (getStepLevel(step) < 0 && getStepName(step) !== undefined) {
1959
+ if (mode !== "sany" && getStepLevel(step) < 0 && getStepName(step) !== undefined) {
1823
1960
  throw createError("<*> and <+> cannot be used for a named step", step);
1824
1961
  }
1825
- cursor.index++;
1962
+ cursor++;
1826
1963
  return { name: getStepName(step), token: step.text, location: getLocation(step) };
1827
1964
  };
1828
1965
 
1829
- // The names an assertion assumes stay in its own proof, and other steps declare theirs for the rest
1830
- // of the enclosing proof.
1831
1966
  const parseStep = (): ProofStep => {
1832
- const start = cursor.index;
1967
+ const start = cursor;
1833
1968
  const step = parseStepStart(isAt("QED", 1));
1834
- const statementStart = cursor.index;
1969
+ const statementStart = cursor;
1835
1970
  const scope = new Set<string>();
1836
1971
  proofScopes.push(scope);
1837
1972
  const body: StepBody = accept("QED") ? { kind: "Qed" } : parseStepBody();
@@ -1847,56 +1982,210 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1847
1982
  return withRange({ ...step, body, head, statement, proof }, start);
1848
1983
  };
1849
1984
 
1850
- const parseProofBody = (): Proof => {
1851
- const location = getLocation(peek());
1852
- if (isAt("BY") || (isAt("PROOF") && isAt("BY", 1))) {
1853
- accept("PROOF");
1854
- advance();
1855
- const keyword = getRange(cursor.index - 1);
1985
+ const parseLeafProof = (
1986
+ location: SourceLocation,
1987
+ ): Exclude<Proof, { kind: "Steps" }> | undefined => {
1988
+ if (accept("BY")) {
1989
+ const keyword = getRange(cursor - 1);
1856
1990
  return { kind: "By", isOnly: accept("ONLY"), ...parseFacts(), keyword, location };
1857
1991
  }
1858
- const terminal = peek(isAt("PROOF") ? 1 : 0);
1859
- if (
1860
- terminal.kind === "Keyword" &&
1861
- (terminal.text === "OBVIOUS" || terminal.text === "OMITTED")
1862
- ) {
1863
- accept("PROOF");
1864
- advance();
1865
- const keyword = getRange(cursor.index - 1);
1866
- return { kind: terminal.text === "OBVIOUS" ? "Obvious" : "Omitted", keyword, location };
1867
- }
1992
+ const terminal = peek();
1993
+ if (terminal.kind !== "Keyword" || (terminal.text !== "OBVIOUS" && terminal.text !== "OMITTED"))
1994
+ return undefined;
1995
+ advance();
1996
+ const keyword = getRange(cursor - 1);
1997
+ return { kind: terminal.text === "OBVIOUS" ? "Obvious" : "Omitted", keyword, location };
1998
+ };
1999
+
2000
+ const parseProofBody = (): Proof => {
2001
+ const location = getLocation(peek());
1868
2002
  accept("PROOF");
2003
+ const leaf = parseLeafProof(location);
2004
+ if (leaf) return leaf;
1869
2005
  const steps = [parseStep()];
1870
2006
  while (steps[steps.length - 1].body.kind !== "Qed") steps.push(parseStep());
1871
2007
  return { kind: "Steps", level: getProofLevel(), steps, location };
1872
2008
  };
1873
2009
 
1874
2010
  const parseProof = (): Proof => {
1875
- const start = cursor.index;
2011
+ const start = cursor;
1876
2012
  proofLevels.push(-1);
1877
2013
  const proof = withProofScope(parseProofBody);
1878
2014
  proofLevels.pop();
1879
2015
  return withRange(proof, start);
1880
2016
  };
1881
2017
 
1882
- // SANY binds the name of a theorem or assumption that a module already defines to the first
1883
- // definition, warning of the second.
2018
+ const isPreproofStart = () =>
2019
+ peek().kind === "Step" || (peek().kind === "Keyword" && PROOF_STARTS.has(peek().text));
2020
+
2021
+ const getStepSpan = (head: SourceRange, body: StepBody) => {
2022
+ if (body.kind !== "Use" && body.kind !== "Hide") return getSpan(head);
2023
+ const lastDef = body.defs[body.defs.length - 1]?.location.range;
2024
+ return mergeSpans(getSpan({ ...head, end: head.start }), getSpan(lastDef ?? body.keyword));
2025
+ };
2026
+
2027
+ const parsePreproof = (): Preproof => {
2028
+ const first = cursor;
2029
+ const location = getLocation(peek());
2030
+ const isProof = accept("PROOF");
2031
+ const leaf = parseLeafProof(location);
2032
+ if (leaf) {
2033
+ const proof = withRange(leaf, first);
2034
+ return { kind: "Leaf", proof, span: getSpan(proof.keyword), first, end: cursor - 1 };
2035
+ }
2036
+ const token = peek();
2037
+ if (token.kind !== "Step") {
2038
+ throw createUnexpected(`Expected a step number but found ${describeToken(token)}`);
2039
+ }
2040
+ const start = cursor;
2041
+ advance();
2042
+ const statementStart = cursor;
2043
+ const body: StepBody = accept("QED") ? { kind: "Qed" } : parseStepBody();
2044
+ const head = getRange(start);
2045
+ return {
2046
+ kind: "Step",
2047
+ token,
2048
+ isProof,
2049
+ body,
2050
+ head,
2051
+ statement: getRange(statementStart),
2052
+ span: getStepSpan(head, body),
2053
+ first,
2054
+ start,
2055
+ end: cursor - 1,
2056
+ };
2057
+ };
2058
+
2059
+ const nestProof = (
2060
+ items: Preproof[],
2061
+ index: number,
2062
+ level: number,
2063
+ levelSpan: Span,
2064
+ ): NestedProof => {
2065
+ const item = items[index];
2066
+ if (!item) return { proof: undefined, span: levelSpan, next: index, end: undefined };
2067
+ if (item.kind === "Leaf")
2068
+ return { proof: item.proof, span: item.span, next: index + 1, end: item.end };
2069
+ const nested = nestSteps(items, index, level, levelSpan, true);
2070
+ if (!nested) return { proof: undefined, span: levelSpan, next: index, end: undefined };
2071
+ const location = {
2072
+ ...getLocation(tokens[item.first]),
2073
+ range: getRange(item.first, nested.end),
2074
+ };
2075
+ return {
2076
+ proof: { kind: "Steps", level: nested.level, steps: nested.steps, location },
2077
+ span: nested.span,
2078
+ next: nested.next,
2079
+ end: nested.end,
2080
+ };
2081
+ };
2082
+
2083
+ const nestSteps = (
2084
+ items: Preproof[],
2085
+ index: number,
2086
+ level: number,
2087
+ levelSpan: Span,
2088
+ isFirst: boolean,
2089
+ ): NestedSteps | undefined => {
2090
+ const item = items[index];
2091
+ if (!item) {
2092
+ throw createProofError(
2093
+ `Unexpected end of (sub)proof at level ${level} before QED step`,
2094
+ levelSpan,
2095
+ );
2096
+ }
2097
+ if (item.kind === "Leaf") {
2098
+ throw createProofError(
2099
+ `Expecting a proof step but found a${LEAF_NAMES[item.proof.kind]} leaf proof`,
2100
+ item.span,
2101
+ );
2102
+ }
2103
+ if (!isFirst && item.isProof) {
2104
+ throw createProofError("PROOF keyword found in step that does not begin subproof", item.span);
2105
+ }
2106
+ const implicit = item.token.text[1];
2107
+ if (implicit === "+" && !isFirst) {
2108
+ throw createProofError("<+> used but no subproof expected", item.span);
2109
+ }
2110
+ const stepLevel =
2111
+ implicit === "*"
2112
+ ? level - (isFirst && !item.isProof ? 1 : 0)
2113
+ : implicit === "+"
2114
+ ? level
2115
+ : getStepLevel(item.token);
2116
+ if (stepLevel < level || (!isFirst && stepLevel > level)) return undefined;
2117
+ const proof = PROVABLE_STEPS.has(item.body.kind)
2118
+ ? nestProof(items, index + 1, stepLevel + 1, item.span)
2119
+ : { proof: undefined, span: item.span, next: index + 1, end: undefined };
2120
+ const end = proof.end ?? item.end;
2121
+ const step: ProofStep = {
2122
+ name: getStepName(item.token),
2123
+ token: item.token.text,
2124
+ body: item.body,
2125
+ head: item.head,
2126
+ statement: item.statement,
2127
+ proof: proof.proof,
2128
+ location: { ...getLocation(item.token), range: getRange(item.start, end) },
2129
+ };
2130
+ const span = mergeSpans(item.span, proof.span);
2131
+ if (item.body.kind === "Qed") {
2132
+ return { level: stepLevel, steps: [step], span, next: proof.next, end };
2133
+ }
2134
+ const rest = nestSteps(
2135
+ items,
2136
+ proof.next,
2137
+ stepLevel,
2138
+ { start: span.stop, stop: span.stop },
2139
+ false,
2140
+ );
2141
+ return (
2142
+ rest && {
2143
+ ...rest,
2144
+ level: stepLevel,
2145
+ steps: [step, ...rest.steps],
2146
+ span: mergeSpans(span, rest.span),
2147
+ }
2148
+ );
2149
+ };
2150
+
2151
+ const parseTlapmProof = () => {
2152
+ if (!isPreproofStart()) return undefined;
2153
+ const items: Preproof[] = [];
2154
+ while (isPreproofStart()) items.push(parsePreproof());
2155
+ const first = items[0];
2156
+ if (first.kind === "Step") items[0] = { ...first, isProof: true };
2157
+ const nested = nestProof(items, 0, 0, first.span);
2158
+ const extra = items[nested.next];
2159
+ if (extra) {
2160
+ throw createProofError(
2161
+ "extra step(s) after finished proof",
2162
+ extra.span,
2163
+ "Proof.Parser.toplevel",
2164
+ );
2165
+ }
2166
+ return nested.proof;
2167
+ };
2168
+
1884
2169
  const addFactDefinition = (module: Module, definition: Definition) => {
1885
2170
  if (module.definitions.some((other) => other.name === definition.name)) return;
1886
2171
  module.definitions.push(definition);
1887
2172
  };
1888
2173
 
2174
+ const parseFactName = () => {
2175
+ if (peek().kind !== "Identifier" || !isAt("==", 1)) return undefined;
2176
+ const name = expectIdentifier();
2177
+ factNames.add(name);
2178
+ advance();
2179
+ return name;
2180
+ };
2181
+
1889
2182
  const parseTheorem = (module: Module) => {
1890
- const start = cursor.index;
2183
+ const start = cursor;
1891
2184
  const keyword = advance();
1892
- const isNamed = peek().kind === "Identifier" && isAt("==", 1);
1893
- const name = isNamed ? expectIdentifier() : undefined;
1894
- if (name !== undefined) {
1895
- factNames.add(name);
1896
- advance();
1897
- }
2185
+ const name = parseFactName();
1898
2186
  const parsed = withProofScope(() => {
1899
2187
  const statement = isAt("ASSUME") ? parseAssumeProve() : parseExpression();
2188
+ if (isTlapm) return { statement, proof: parseTlapmProof() };
1900
2189
  return { statement, proof: isProofStart(peek()) ? parseProof() : undefined };
1901
2190
  });
1902
2191
  const statement = parsed.statement;
@@ -1925,14 +2214,9 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1925
2214
  };
1926
2215
 
1927
2216
  const parseAssumption = (): Assumption => {
1928
- const start = cursor.index;
2217
+ const start = cursor;
1929
2218
  const keyword = advance();
1930
- const isNamed = peek().kind === "Identifier" && isAt("==", 1);
1931
- const name = isNamed ? expectIdentifier() : undefined;
1932
- if (name !== undefined) {
1933
- factNames.add(name);
1934
- advance();
1935
- }
2219
+ const name = parseFactName();
1936
2220
  return withRange(
1937
2221
  {
1938
2222
  name,
@@ -1968,14 +2252,14 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1968
2252
  recursiveScopes.push(new Set());
1969
2253
  if (accept("EXTENDS")) {
1970
2254
  parseSeparated(() => {
1971
- const start = cursor.index;
2255
+ const start = cursor;
1972
2256
  module.extends.push(expectModuleName());
1973
2257
  module.extendsRanges.push(getRange(start));
1974
2258
  });
1975
2259
  }
1976
2260
  while (true) {
1977
- const tokenIndex = cursor.index;
1978
- unitStart.index = tokenIndex;
2261
+ const tokenIndex = cursor;
2262
+ unitStart = tokenIndex;
1979
2263
  const token = peek();
1980
2264
  if (token.kind === "ModuleEnd") {
1981
2265
  location.range = {
@@ -2012,7 +2296,7 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
2012
2296
  case "VARIABLES": {
2013
2297
  const unitLocation = getLocation(advance());
2014
2298
  const declarations = parseSeparated(() => {
2015
- const start = cursor.index;
2299
+ const start = cursor;
2016
2300
  const location = getLocation(peek());
2017
2301
  return withRange({ name: expectIdentifier(), arity: 0, location }, start);
2018
2302
  });
@@ -2042,7 +2326,6 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
2042
2326
  }
2043
2327
  case "USE":
2044
2328
  case "HIDE": {
2045
- // SANY's module body takes a USE only when ONLY doesn't follow it.
2046
2329
  if (isAt("USE") && isAt("ONLY", 1)) {
2047
2330
  throw createUnexpected(`Expected a module unit but found ${describeToken(token)}`);
2048
2331
  }
@@ -2051,10 +2334,13 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
2051
2334
  module.units.push({ kind: "Use", use });
2052
2335
  continue;
2053
2336
  }
2054
- case "RECURSIVE":
2055
- advance();
2056
- module.units.push({ kind: "Recursive", declarations: declareRecursive() });
2337
+ case "RECURSIVE": {
2338
+ const unitLocation = getLocation(advance());
2339
+ const declarations = declareRecursive();
2340
+ unitLocation.range = getRange(tokenIndex);
2341
+ module.units.push({ kind: "Recursive", declarations, location: unitLocation });
2057
2342
  continue;
2343
+ }
2058
2344
  case "INSTANCE":
2059
2345
  addDefinitionUnit(
2060
2346
  module,
@@ -2093,16 +2379,13 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
2093
2379
  };
2094
2380
 
2095
2381
  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;
2382
+ const sanyError = isKeywordModuleName ? getSanyParseError(source) : undefined;
2099
2383
  if (sanyError !== undefined) throw new TlaSyntaxError(sanyError);
2100
2384
  return module;
2101
2385
  };
2102
2386
 
2103
2387
  export const parseModule = (source: string) => parse(source, "tlc");
2104
2388
 
2105
- // Parses a module the caller has tokenized already.
2106
2389
  export const parseModuleTokens = (source: string, tokens: Token[]) => parse(source, "tlc", tokens);
2107
2390
 
2108
2391
  export const parseTlapmModule = (source: string) => parse(source, "tlapm");