tla-ts 0.0.9 → 0.0.10-dev.63a6693bd

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 (400) 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 +29 -29
  5. package/dist/deciders.js +42 -42
  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 +117 -37
  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 +48 -62
  26. package/src/bags.ts +99 -102
  27. package/src/builtins.ts +28 -75
  28. package/src/bundled-modules.ts +1 -8
  29. package/src/check-failure.ts +116 -0
  30. package/src/check-trace.ts +282 -0
  31. package/src/check.ts +599 -754
  32. package/src/cli/options.ts +12 -32
  33. package/src/cli/run.ts +0 -2
  34. package/src/cli/runtime-invariants.ts +136 -0
  35. package/src/cli/shared.ts +19 -12
  36. package/src/cli/tlapm.ts +14 -25
  37. package/src/cli/tlc-arguments.ts +652 -0
  38. package/src/cli/tlc-output.ts +687 -0
  39. package/src/cli/tlc-usage.ts +361 -0
  40. package/src/cli/tlc.ts +309 -658
  41. package/src/cli/typescript.ts +23 -0
  42. package/src/cli/xml-exporter.ts +27 -49
  43. package/src/cli.ts +0 -1
  44. package/src/codegen.ts +196 -74
  45. package/src/config.ts +140 -109
  46. package/src/coverage.ts +830 -0
  47. package/src/dependencies.ts +14 -53
  48. package/src/dfid.ts +618 -0
  49. package/src/environment-config.ts +315 -0
  50. package/src/environment.ts +169 -335
  51. package/src/errors.ts +71 -55
  52. package/src/evaluate.ts +598 -340
  53. package/src/exit-codes.ts +37 -3
  54. package/src/fingerprints.ts +75 -11
  55. package/src/index.ts +3 -0
  56. package/src/instances.ts +126 -21
  57. package/src/java-hash.ts +7 -0
  58. package/src/java-overrides.ts +4 -19
  59. package/src/json-reader.ts +455 -0
  60. package/src/json.ts +252 -139
  61. package/src/levels.ts +46 -58
  62. package/src/lexer.ts +80 -100
  63. package/src/liveness-checker.ts +103 -153
  64. package/src/liveness.ts +150 -109
  65. package/src/obligations/action.ts +8 -39
  66. package/src/obligations/anonymize.ts +88 -82
  67. package/src/obligations/equality.ts +1 -1
  68. package/src/obligations/expression.ts +20 -21
  69. package/src/obligations/format.ts +1 -9
  70. package/src/obligations/generate.ts +46 -49
  71. package/src/obligations/index.ts +2 -13
  72. package/src/obligations/levels.ts +4 -8
  73. package/src/obligations/module.ts +28 -53
  74. package/src/obligations/normalize.ts +7 -25
  75. package/src/obligations/operators.ts +1 -2
  76. package/src/obligations/pragma.ts +1 -10
  77. package/src/obligations/printer.ts +47 -46
  78. package/src/obligations/proof.ts +1 -5
  79. package/src/obligations/regroup.ts +1 -4
  80. package/src/obligations/simplify.ts +42 -58
  81. package/src/obligations/source.ts +48 -78
  82. package/src/obligations/subexpression.ts +5 -11
  83. package/src/obligations/substitution.ts +1 -3
  84. package/src/obligations/temporal.ts +13 -19
  85. package/src/obligations/tuples.ts +3 -9
  86. package/src/parallel-worker.ts +30 -60
  87. package/src/parallel.ts +57 -71
  88. package/src/parser.ts +584 -316
  89. package/src/pcal/ast.ts +53 -86
  90. package/src/pcal/parse.ts +144 -219
  91. package/src/pcal/tokenize.ts +91 -131
  92. package/src/pcal/translate.ts +83 -130
  93. package/src/pcal/validate.ts +48 -68
  94. package/src/pretty-print.ts +7 -8
  95. package/src/prover/decide-pool.ts +8 -13
  96. package/src/prover/deciders.ts +3 -7
  97. package/src/prover/first-order.ts +0 -11
  98. package/src/prover/isabelle/decide.ts +0 -6
  99. package/src/prover/isabelle/encode.ts +11 -23
  100. package/src/prover/isabelle/isar/inner-syntax.ts +114 -115
  101. package/src/prover/isabelle/isar/method.ts +29 -53
  102. package/src/prover/isabelle/isar/proof.ts +1 -10
  103. package/src/prover/isabelle/isar/statement.ts +1 -6
  104. package/src/prover/isabelle/isar/theory.ts +26 -36
  105. package/src/prover/isabelle/isar/type-check.ts +17 -31
  106. package/src/prover/isabelle/provers/blast/blast.ts +17 -104
  107. package/src/prover/isabelle/provers/blast/branch.ts +1 -32
  108. package/src/prover/isabelle/provers/blast/prove.ts +1 -35
  109. package/src/prover/isabelle/provers/blast/rules.ts +6 -44
  110. package/src/prover/isabelle/provers/blast/state.ts +2 -28
  111. package/src/prover/isabelle/provers/blast/term.ts +9 -36
  112. package/src/prover/isabelle/provers/clasimp.ts +1 -13
  113. package/src/prover/isabelle/provers/classical.ts +14 -42
  114. package/src/prover/isabelle/provers/hypsubst.ts +28 -51
  115. package/src/prover/isabelle/pure/bicompose.ts +25 -38
  116. package/src/prover/isabelle/pure/consts.ts +1 -7
  117. package/src/prover/isabelle/pure/conv.ts +3 -17
  118. package/src/prover/isabelle/pure/drule.ts +33 -42
  119. package/src/prover/isabelle/pure/envir.ts +3 -52
  120. package/src/prover/isabelle/pure/goal.ts +1 -7
  121. package/src/prover/isabelle/pure/interrupt.ts +0 -5
  122. package/src/prover/isabelle/pure/list.ts +0 -3
  123. package/src/prover/isabelle/pure/logic.ts +2 -15
  124. package/src/prover/isabelle/pure/name.ts +2 -9
  125. package/src/prover/isabelle/pure/net.ts +3 -59
  126. package/src/prover/isabelle/pure/object-logic.ts +3 -10
  127. package/src/prover/isabelle/pure/pattern.ts +2 -19
  128. package/src/prover/isabelle/pure/raw-simplifier.ts +17 -62
  129. package/src/prover/isabelle/pure/rewriter.ts +31 -67
  130. package/src/prover/isabelle/pure/search.ts +3 -10
  131. package/src/prover/isabelle/pure/seq.ts +1 -10
  132. package/src/prover/isabelle/pure/simplifier.ts +4 -12
  133. package/src/prover/isabelle/pure/table.ts +3 -32
  134. package/src/prover/isabelle/pure/tactic.ts +12 -22
  135. package/src/prover/isabelle/pure/tactical.ts +48 -47
  136. package/src/prover/isabelle/pure/term-ord.ts +2 -6
  137. package/src/prover/isabelle/pure/term.ts +2 -43
  138. package/src/prover/isabelle/pure/thm.ts +27 -47
  139. package/src/prover/isabelle/pure/type.ts +2 -15
  140. package/src/prover/isabelle/pure/unify.ts +20 -30
  141. package/src/prover/isabelle/pure/variable.ts +3 -7
  142. package/src/prover/isabelle/tla/classical-setup.ts +17 -24
  143. package/src/prover/isabelle/tla/context.ts +15 -18
  144. package/src/prover/isabelle/tla/logic.ts +14 -32
  145. package/src/prover/isabelle/tla/simpdata.ts +46 -43
  146. package/src/prover/isabelle/tools/intuitionistic.ts +1 -10
  147. package/src/prover/ocaml.ts +0 -6
  148. package/src/prover/prep/action.ts +14 -54
  149. package/src/prover/prep/enabled-axioms.ts +12 -19
  150. package/src/prover/prep/fingerprint.ts +2 -21
  151. package/src/prover/prep/level-comparison.ts +8 -12
  152. package/src/prover/prep/md5.ts +0 -2
  153. package/src/prover/prep/methods.ts +33 -39
  154. package/src/prover/prep/normalize.ts +4 -28
  155. package/src/prover/prove-worker.ts +0 -2
  156. package/src/prover/prove.ts +87 -100
  157. package/src/prover/ptl/decide.ts +7 -12
  158. package/src/prover/ptl/encode.ts +14 -36
  159. package/src/prover/ptl/sat.ts +24 -32
  160. package/src/prover/ptl/tableau.ts +12 -26
  161. package/src/prover/smt/axioms.ts +0 -7
  162. package/src/prover/smt/context.ts +20 -28
  163. package/src/prover/smt/data.ts +433 -424
  164. package/src/prover/smt/encode.ts +43 -52
  165. package/src/prover/smt/extensionality.ts +0 -10
  166. package/src/prover/smt/flatten.ts +3 -22
  167. package/src/prover/smt/format.ts +5 -10
  168. package/src/prover/smt/instances.ts +0 -10
  169. package/src/prover/smt/rewrite.ts +663 -667
  170. package/src/prover/smt/solver/act-cache.ts +0 -15
  171. package/src/prover/smt/solver/arith-rewriter.ts +3 -48
  172. package/src/prover/smt/solver/array.ts +1 -3
  173. package/src/prover/smt/solver/asserted-formulas.ts +1 -43
  174. package/src/prover/smt/solver/ast-lt.ts +1 -11
  175. package/src/prover/smt/solver/ast-util.ts +1 -6
  176. package/src/prover/smt/solver/ast.ts +1 -165
  177. package/src/prover/smt/solver/auf-solver.ts +8 -44
  178. package/src/prover/smt/solver/case-split-queue.ts +1 -9
  179. package/src/prover/smt/solver/cg-table.ts +1 -18
  180. package/src/prover/smt/solver/clause.ts +1 -27
  181. package/src/prover/smt/solver/conflict-resolution.ts +0 -9
  182. package/src/prover/smt/solver/context.ts +7 -64
  183. package/src/prover/smt/solver/ctx-simplify.ts +14 -41
  184. package/src/prover/smt/solver/der.ts +2 -21
  185. package/src/prover/smt/solver/dyn-ack.ts +1 -11
  186. package/src/prover/smt/solver/e-matching.ts +4 -35
  187. package/src/prover/smt/solver/enode.ts +1 -21
  188. package/src/prover/smt/solver/expr-ref.ts +1 -5
  189. package/src/prover/smt/solver/expr-safe-replace.ts +1 -6
  190. package/src/prover/smt/solver/fingerprints.ts +1 -12
  191. package/src/prover/smt/solver/flat-literals.ts +1 -9
  192. package/src/prover/smt/solver/goal.ts +2 -14
  193. package/src/prover/smt/solver/hash.ts +0 -8
  194. package/src/prover/smt/solver/hashtable.ts +1 -12
  195. package/src/prover/smt/solver/internalizer.ts +7 -100
  196. package/src/prover/smt/solver/lbool.ts +1 -2
  197. package/src/prover/smt/solver/literal.ts +0 -3
  198. package/src/prover/smt/solver/lp/bound-propagator.ts +8 -26
  199. package/src/prover/smt/solver/lp/constraints.ts +2 -8
  200. package/src/prover/smt/solver/lp/containers.ts +12 -30
  201. package/src/prover/smt/solver/lp/core-solver.ts +10 -31
  202. package/src/prover/smt/solver/lp/cross-nested.ts +6 -20
  203. package/src/prover/smt/solver/lp/dep-intervals.ts +7 -22
  204. package/src/prover/smt/solver/lp/dependency.ts +1 -4
  205. package/src/prover/smt/solver/lp/dioph-eq.ts +9 -102
  206. package/src/prover/smt/solver/lp/explanation.ts +1 -6
  207. package/src/prover/smt/solver/lp/gomory.ts +9 -22
  208. package/src/prover/smt/solver/lp/hnf-cutter.ts +17 -23
  209. package/src/prover/smt/solver/lp/hnf.ts +11 -26
  210. package/src/prover/smt/solver/lp/int-cube.ts +15 -36
  211. package/src/prover/smt/solver/lp/int-solver.ts +4 -34
  212. package/src/prover/smt/solver/lp/lar-solver.ts +32 -81
  213. package/src/prover/smt/solver/lp/lar-term.ts +1 -5
  214. package/src/prover/smt/solver/lp/lp-settings.ts +1 -14
  215. package/src/prover/smt/solver/lp/maximize-term.ts +20 -45
  216. package/src/prover/smt/solver/lp/nex-creator.ts +5 -28
  217. package/src/prover/smt/solver/lp/nex.ts +1 -6
  218. package/src/prover/smt/solver/lp/nla-backoff.ts +1 -4
  219. package/src/prover/smt/solver/lp/nla-basics.ts +5 -30
  220. package/src/prover/smt/solver/lp/nla-core.ts +36 -135
  221. package/src/prover/smt/solver/lp/nla-divisions.ts +32 -42
  222. package/src/prover/smt/solver/lp/nla-emonics.ts +4 -21
  223. package/src/prover/smt/solver/lp/nla-factorization.ts +1 -4
  224. package/src/prover/smt/solver/lp/nla-grobner.ts +15 -69
  225. package/src/prover/smt/solver/lp/nla-horner.ts +3 -11
  226. package/src/prover/smt/solver/lp/nla-intervals.ts +2 -12
  227. package/src/prover/smt/solver/lp/nla-monomial-bounds.ts +16 -41
  228. package/src/prover/smt/solver/lp/nla-monotone.ts +2 -6
  229. package/src/prover/smt/solver/lp/nla-order.ts +2 -13
  230. package/src/prover/smt/solver/lp/nla-patcher.ts +4 -7
  231. package/src/prover/smt/solver/lp/nla-tangents.ts +1 -9
  232. package/src/prover/smt/solver/lp/nla-throttle.ts +1 -6
  233. package/src/prover/smt/solver/lp/nla-types.ts +1 -11
  234. package/src/prover/smt/solver/lp/nla-var-eqs.ts +4 -25
  235. package/src/prover/smt/solver/lp/nra-solver.ts +5 -52
  236. package/src/prover/smt/solver/lp/numeric-pair.ts +1 -4
  237. package/src/prover/smt/solver/lp/pdd-interval.ts +1 -3
  238. package/src/prover/smt/solver/lp/pdd-simplifier.ts +2 -14
  239. package/src/prover/smt/solver/lp/pdd-solver.ts +4 -33
  240. package/src/prover/smt/solver/lp/pdd.ts +7 -70
  241. package/src/prover/smt/solver/lp/random-updater.ts +1 -8
  242. package/src/prover/smt/solver/lp/static-matrix.ts +9 -19
  243. package/src/prover/smt/solver/lp/union-find.ts +1 -6
  244. package/src/prover/smt/solver/mam-compiler.ts +18 -58
  245. package/src/prover/smt/solver/mam-interpreter.ts +1 -21
  246. package/src/prover/smt/solver/maximize-ac-sharing.ts +2 -17
  247. package/src/prover/smt/solver/model-checker.ts +3 -37
  248. package/src/prover/smt/solver/model-evaluator.ts +3 -29
  249. package/src/prover/smt/solver/model-finder.ts +15 -32
  250. package/src/prover/smt/solver/model-generator.ts +1 -12
  251. package/src/prover/smt/solver/model-macro-solver.ts +23 -88
  252. package/src/prover/smt/solver/nlsat/algebraic.ts +63 -159
  253. package/src/prover/smt/solver/nlsat/atoms.ts +25 -23
  254. package/src/prover/smt/solver/nlsat/evaluator.ts +17 -22
  255. package/src/prover/smt/solver/nlsat/explain.ts +10 -69
  256. package/src/prover/smt/solver/nlsat/interval-set.ts +9 -50
  257. package/src/prover/smt/solver/nlsat/levelwise.ts +49 -135
  258. package/src/prover/smt/solver/nlsat/mpbq.ts +3 -14
  259. package/src/prover/smt/solver/nlsat/polynomial.ts +29 -159
  260. package/src/prover/smt/solver/nlsat/solver.ts +18 -90
  261. package/src/prover/smt/solver/nlsat/types.ts +1 -8
  262. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +2 -45
  263. package/src/prover/smt/solver/nlsat/upolynomial.ts +11 -92
  264. package/src/prover/smt/solver/nnf.ts +3 -38
  265. package/src/prover/smt/solver/pattern-inference.ts +2 -15
  266. package/src/prover/smt/solver/poly-rewriter.ts +3 -23
  267. package/src/prover/smt/solver/propagate-values.ts +1 -10
  268. package/src/prover/smt/solver/proto-model.ts +3 -52
  269. package/src/prover/smt/solver/pull-quant.ts +1 -12
  270. package/src/prover/smt/solver/qe-lite-der.ts +1 -29
  271. package/src/prover/smt/solver/qe-lite-fm.ts +2 -25
  272. package/src/prover/smt/solver/qe-lite.ts +3 -33
  273. package/src/prover/smt/solver/qi-queue.ts +1 -16
  274. package/src/prover/smt/solver/quant-tactics.ts +5 -22
  275. package/src/prover/smt/solver/quantifier-analyzer.ts +27 -47
  276. package/src/prover/smt/solver/quantifier-manager.ts +2 -13
  277. package/src/prover/smt/solver/random-gen.ts +1 -2
  278. package/src/prover/smt/solver/rational.ts +1 -8
  279. package/src/prover/smt/solver/ref-vector.ts +1 -6
  280. package/src/prover/smt/solver/relevancy.ts +2 -15
  281. package/src/prover/smt/solver/rewriter-tpl.ts +3 -147
  282. package/src/prover/smt/solver/rewriter.ts +3 -85
  283. package/src/prover/smt/solver/rlimit.ts +2 -20
  284. package/src/prover/smt/solver/smtlib-parser.ts +80 -131
  285. package/src/prover/smt/solver/solver.ts +23 -34
  286. package/src/prover/smt/solver/sort.ts +1 -5
  287. package/src/prover/smt/solver/sticky-generations.ts +0 -5
  288. package/src/prover/smt/solver/theory-lra-axioms.ts +3 -24
  289. package/src/prover/smt/solver/theory-lra-bounds.ts +1 -7
  290. package/src/prover/smt/solver/theory-lra-final-check.ts +4 -22
  291. package/src/prover/smt/solver/theory-lra-internalize.ts +6 -43
  292. package/src/prover/smt/solver/theory-lra-model.ts +4 -19
  293. package/src/prover/smt/solver/theory-lra-propagate.ts +1 -15
  294. package/src/prover/smt/solver/theory-lra-state.ts +3 -8
  295. package/src/prover/smt/solver/theory-lra.ts +1 -8
  296. package/src/prover/smt/solver/var-subst.ts +2 -26
  297. package/src/prover/smt/table.ts +0 -8
  298. package/src/prover/tlapm/cache.ts +45 -40
  299. package/src/prover/tlapm/ocaml-marshal.ts +19 -21
  300. package/src/prover/tlapm/tlapm.ts +21 -20
  301. package/src/prover/verdict.ts +7 -2
  302. package/src/prover/zenon/check/check.ts +1 -11
  303. package/src/prover/zenon/check/definitions.ts +5 -15
  304. package/src/prover/zenon/check/equality.ts +0 -8
  305. package/src/prover/zenon/check/functions.ts +0 -4
  306. package/src/prover/zenon/check/keys.ts +0 -7
  307. package/src/prover/zenon/check/propositional.ts +0 -3
  308. package/src/prover/zenon/check/records.ts +1 -6
  309. package/src/prover/zenon/check/relations.ts +2 -14
  310. package/src/prover/zenon/check/rewrites.ts +2 -21
  311. package/src/prover/zenon/check/sets.ts +40 -61
  312. package/src/prover/zenon/check/terms.ts +1 -19
  313. package/src/prover/zenon/check/tla.ts +0 -6
  314. package/src/prover/zenon/decide.ts +0 -12
  315. package/src/prover/zenon/encode.ts +1 -8
  316. package/src/prover/zenon/eqrel.ts +2 -13
  317. package/src/prover/zenon/equality-rules.ts +0 -4
  318. package/src/prover/zenon/expr.ts +8 -26
  319. package/src/prover/zenon/index-table.ts +26 -57
  320. package/src/prover/zenon/isar-case.ts +9 -19
  321. package/src/prover/zenon/isar.ts +36 -64
  322. package/src/prover/zenon/limits.ts +0 -4
  323. package/src/prover/zenon/llproof.ts +2 -20
  324. package/src/prover/zenon/mltoll.ts +66 -104
  325. package/src/prover/zenon/node.ts +1 -11
  326. package/src/prover/zenon/ocaml.ts +1 -17
  327. package/src/prover/zenon/parse.ts +4 -12
  328. package/src/prover/zenon/phrase.ts +1 -11
  329. package/src/prover/zenon/proof.ts +0 -9
  330. package/src/prover/zenon/propositional-rules.ts +0 -5
  331. package/src/prover/zenon/rules.ts +2 -6
  332. package/src/prover/zenon/search.ts +5 -31
  333. package/src/prover/zenon/tla/functions.ts +59 -31
  334. package/src/prover/zenon/tla/llproof.ts +67 -76
  335. package/src/prover/zenon/tla/records.ts +57 -33
  336. package/src/prover/zenon/tla/rewrites.ts +12 -19
  337. package/src/prover/zenon/tla/sets.ts +83 -53
  338. package/src/prover/zenon/tla/terms.ts +0 -6
  339. package/src/prover/zenon/tla/tla.ts +66 -64
  340. package/src/randomization.ts +81 -35
  341. package/src/resolve.ts +67 -184
  342. package/src/runtime.ts +22 -22
  343. package/src/sany/builtins.ts +2 -5
  344. package/src/sany/generation.ts +394 -0
  345. package/src/sany/generator-def-entries.ts +210 -0
  346. package/src/sany/generator-definitions.ts +686 -0
  347. package/src/sany/generator-expressions.ts +1100 -0
  348. package/src/sany/generator-proofs.ts +662 -0
  349. package/src/sany/generator.ts +191 -2764
  350. package/src/sany/levels.ts +6 -34
  351. package/src/sany/lexer.ts +58 -77
  352. package/src/sany/linter.ts +1 -9
  353. package/src/sany/modules.ts +1 -5
  354. package/src/sany/nodes.ts +5 -43
  355. package/src/sany/parse-error.ts +39 -117
  356. package/src/sany/report.ts +32 -69
  357. package/src/sany/selectors.ts +49 -76
  358. package/src/sany/source.ts +1 -17
  359. package/src/sany/xml.ts +35 -117
  360. package/src/search.ts +541 -163
  361. package/src/simulate.ts +709 -0
  362. package/src/spec-description.ts +192 -100
  363. package/src/standard-definitions.ts +0 -4
  364. package/src/standard-modules.ts +264 -95
  365. package/src/state-graph.ts +52 -31
  366. package/src/subexpressions.ts +69 -52
  367. package/src/substitution-levels.ts +7 -7
  368. package/src/successors.ts +266 -99
  369. package/src/symmetry.ts +33 -25
  370. package/src/tableau.ts +27 -24
  371. package/src/tlc/fingerprint.ts +183 -67
  372. package/src/tlc/jar-data.ts +112 -6
  373. package/src/tlc/messages.ts +125 -54
  374. package/src/tlc/order.ts +39 -69
  375. package/src/tlc/random.ts +37 -49
  376. package/src/tlc/replay.ts +553 -228
  377. package/src/tlc/summary.ts +36 -47
  378. package/src/tlc/tlc-operators.ts +78 -44
  379. package/src/tlc/tlcext-operators.ts +139 -122
  380. package/src/tlc/trace-spec.ts +249 -0
  381. package/src/tlc/value-stream.ts +139 -0
  382. package/src/tlc/version.ts +1 -4
  383. package/src/transfer.ts +22 -25
  384. package/src/typescript/actions.ts +479 -0
  385. package/src/typescript/collections.ts +614 -0
  386. package/src/typescript/compile.ts +63 -0
  387. package/src/typescript/context.ts +94 -0
  388. package/src/typescript/emit.ts +121 -0
  389. package/src/typescript/expressions.ts +496 -0
  390. package/src/typescript/formula.ts +154 -0
  391. package/src/typescript/functions.ts +284 -0
  392. package/src/typescript/model.ts +162 -0
  393. package/src/typescript/names.ts +114 -0
  394. package/src/typescript/program.ts +48 -0
  395. package/src/typescript/properties.ts +139 -0
  396. package/src/typescript/scope.ts +112 -0
  397. package/src/typescript/steps.ts +167 -0
  398. package/src/typescript/types.ts +171 -0
  399. package/src/values.ts +832 -484
  400. 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",
@@ -1180,17 +1316,11 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1180
1316
  location,
1181
1317
  };
1182
1318
  case "[]":
1183
- advance();
1184
- return { kind: "Always", expression: parsePrefixOperand(token, 4, 15), location };
1185
1319
  case "<>":
1186
- advance();
1187
- return { kind: "Eventually", expression: parsePrefixOperand(token, 4, 15), location };
1188
1320
  case "ENABLED":
1189
- advance();
1190
- return { kind: "Enabled", expression: parsePrefixOperand(token, 4, 15), location };
1191
1321
  case "UNCHANGED":
1192
1322
  advance();
1193
- return { kind: "Unchanged", expression: parsePrefixOperand(token, 4, 15), location };
1323
+ return getOperatorApplication(token.text, parsePrefixOperand(token, 4, 15), location);
1194
1324
  case "SUBSET":
1195
1325
  case "UNION":
1196
1326
  case "DOMAIN":
@@ -1198,7 +1328,6 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1198
1328
  return {
1199
1329
  kind: "Apply",
1200
1330
  operator: token.text,
1201
- // tlapm gives these operators the precedence 8 of the TLA+ book, and SANY 10-13.
1202
1331
  args: [isTlapm ? parseExpression(9) : parsePrefixOperand(token, 10, 13)],
1203
1332
  location,
1204
1333
  };
@@ -1208,31 +1337,29 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1208
1337
  };
1209
1338
 
1210
1339
  const parseExpression = (minimumPrecedence = 0): Expression => {
1211
- const start = cursor.index;
1340
+ const start = cursor;
1212
1341
  const prefix = parsePrefix();
1213
- const state = {
1214
- left: prefix.location.range ? prefix : withRange(prefix, start),
1215
- previous: undefined as (InfixOperator & { text: string }) | undefined,
1216
- };
1342
+ let left = prefix.location.range ? prefix : withRange(prefix, start);
1343
+ let previous: (InfixOperator & { text: string }) | undefined;
1217
1344
  while (true) {
1218
1345
  const token = peek();
1219
1346
  if (token.kind !== "Operator") break;
1220
1347
  const location = getLocation(token);
1221
1348
  if (token.text === "'" && minimumPrecedence <= 15) {
1222
1349
  advance();
1223
- operators.last = POSTFIX_PRECEDENCE;
1224
- state.left = withRange({ kind: "Prime", expression: state.left, location }, start);
1350
+ lastOperator = POSTFIX_PRECEDENCE;
1351
+ left = withRange({ kind: "Prime", expression: left, location }, start);
1225
1352
  continue;
1226
1353
  }
1227
1354
  if (POSTFIX_OPERATORS.has(token.text) && minimumPrecedence <= 15) {
1228
1355
  advance();
1229
- operators.last = POSTFIX_PRECEDENCE;
1230
- state.left = withRange(
1356
+ lastOperator = POSTFIX_PRECEDENCE;
1357
+ left = withRange(
1231
1358
  {
1232
1359
  kind: "Apply",
1233
1360
  operator: token.text,
1234
1361
  spelling: token.spelling,
1235
- args: [state.left],
1362
+ args: [left],
1236
1363
  location,
1237
1364
  },
1238
1365
  start,
@@ -1243,22 +1370,18 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1243
1370
  advance();
1244
1371
  const args = withBracketLayout(() => parseSeparated(() => parseExpression()));
1245
1372
  withBracketLayout(() => expect("]"));
1246
- operators.last = FUNCTION_PRECEDENCE;
1247
- state.left = withRange(
1248
- { kind: "FunctionApplication", function: state.left, args, location },
1249
- start,
1250
- );
1373
+ lastOperator = FUNCTION_PRECEDENCE;
1374
+ left = withRange({ kind: "FunctionApplication", function: left, args, location }, start);
1251
1375
  continue;
1252
1376
  }
1253
1377
  if (token.text === "." && isFieldName(peek(1))) {
1254
1378
  advance();
1255
1379
  const field = advance().text;
1256
- state.left = withRange({ kind: "FieldAccess", record: state.left, field, location }, start);
1380
+ left = withRange({ kind: "FieldAccess", record: left, field, location }, start);
1257
1381
  continue;
1258
1382
  }
1259
1383
  const infix = INFIX_OPERATORS.get(token.text);
1260
1384
  if (!infix || infix.low < minimumPrecedence) break;
1261
- const previous = state.previous;
1262
1385
  if (previous) {
1263
1386
  const isOverlapping = !(previous.low > infix.high || previous.high < infix.low);
1264
1387
  const isChain = previous.text === token.text && infix.isAssociative;
@@ -1270,17 +1393,15 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1270
1393
  }
1271
1394
  }
1272
1395
  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("-")) {
1396
+ if (!isTlapm && infix.low > NEGATION_PRECEDENCE && isAt("-")) {
1275
1397
  throw createError(`Precedence conflict between ${token.text} and -`, peek());
1276
1398
  }
1277
- operators.last = operators.preceding = infix;
1399
+ lastOperator = precedingOperator = infix;
1278
1400
  const right = parseExpression(infix.high + 1);
1279
- const left = state.left;
1280
1401
  if (token.text === "/\\" || token.text === "\\/") {
1281
1402
  const kind = token.text === "/\\" ? "And" : "Or";
1282
1403
  const prefixEnds = [getRange(start).end];
1283
- state.left =
1404
+ left =
1284
1405
  left.kind === kind && previous?.text === token.text
1285
1406
  ? {
1286
1407
  ...left,
@@ -1289,12 +1410,12 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1289
1410
  }
1290
1411
  : { kind, operands: [left, right], prefixEnds, location };
1291
1412
  } else if (token.text === "\\X") {
1292
- state.left =
1413
+ left =
1293
1414
  left.kind === "Product" && previous?.text === "\\X"
1294
1415
  ? { ...left, factors: [...left.factors, right] }
1295
1416
  : { kind: "Product", factors: [left, right], location };
1296
1417
  } else {
1297
- state.left = {
1418
+ left = {
1298
1419
  kind: "Apply",
1299
1420
  operator: token.text,
1300
1421
  spelling: token.spelling,
@@ -1302,10 +1423,10 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1302
1423
  location,
1303
1424
  };
1304
1425
  }
1305
- state.left = withRange(state.left, start);
1306
- state.previous = { ...infix, text: token.text };
1426
+ left = withRange(left, start);
1427
+ previous = { ...infix, text: token.text };
1307
1428
  }
1308
- return state.left;
1429
+ return left;
1309
1430
  };
1310
1431
 
1311
1432
  const parseParams = () => {
@@ -1318,17 +1439,17 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1318
1439
  const parseBody = () => {
1319
1440
  const start = getLocation(peek());
1320
1441
  const body = parseExpression();
1321
- const last = tokens[cursor.index - 1];
1442
+ const last = tokens[cursor - 1];
1322
1443
  const end = { line: last.line, column: last.endColumn };
1323
1444
  return { body, bodyRange: { module: openModules[0].name, start, end } };
1324
1445
  };
1325
1446
 
1326
1447
  const parseDefinition = (isLocal: boolean): Definition | Instance => {
1327
- const start = cursor.index;
1448
+ const start = cursor;
1328
1449
  return withRange(parseDefinitionUnit(isLocal), start);
1329
1450
  };
1330
1451
 
1331
- const toParam = (named: { name: string; range: SourceRange }): OperatorParam => ({
1452
+ const toParam = (named: RangedName): OperatorParam => ({
1332
1453
  name: named.name,
1333
1454
  arity: 0,
1334
1455
  location: {
@@ -1340,11 +1461,13 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1340
1461
 
1341
1462
  const parseDefinitionUnit = (isLocal: boolean): Definition | Instance => {
1342
1463
  const token = peek();
1464
+ const start = cursor;
1343
1465
  const location = getLocation(token);
1344
1466
  const parseOperator = (name: string, params: OperatorParam[]): Definition => ({
1345
1467
  kind: "Operator",
1346
1468
  name,
1347
1469
  params,
1470
+ head: getRange(start, cursor - 2),
1348
1471
  ...parseBody(),
1349
1472
  isLocal,
1350
1473
  isRecursive: isRecursiveName(name),
@@ -1366,7 +1489,7 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1366
1489
  const isPrefixDefinition =
1367
1490
  token.kind !== "String" && DEFINABLE_PREFIX_OPERATORS.has(token.text);
1368
1491
  const isPostfixDefinition =
1369
- token.kind === "Identifier" && POSTFIX_OPERATORS.has(peek(1).text) && isAt("==", 2);
1492
+ token.kind === "Identifier" && DEFINABLE_POSTFIX_OPERATORS.has(peek(1).text) && isAt("==", 2);
1370
1493
  if (isPrefixDefinition || isPostfixDefinition) {
1371
1494
  const operator = isPrefixDefinition ? token.text : peek(1).text;
1372
1495
  if (isPrefixDefinition) advance();
@@ -1390,7 +1513,7 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1390
1513
  location,
1391
1514
  };
1392
1515
  }
1393
- const definitionStart = cursor.index;
1516
+ const definitionStart = cursor;
1394
1517
  const params = parseParams();
1395
1518
  expect("==");
1396
1519
  if (isAt("INSTANCE")) {
@@ -1406,12 +1529,12 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1406
1529
  isLocal: boolean,
1407
1530
  location: SourceLocation,
1408
1531
  ): Instance => {
1409
- const start = cursor.index;
1532
+ const start = cursor;
1410
1533
  expect("INSTANCE");
1411
1534
  const module = expectModuleName();
1412
1535
  const substitutions = accept("WITH")
1413
1536
  ? parseSeparated(() => {
1414
- const targetStart = cursor.index;
1537
+ const targetStart = cursor;
1415
1538
  const target = expectSubstitutionTarget();
1416
1539
  const nameRange = getRange(targetStart);
1417
1540
  expect("<-");
@@ -1431,7 +1554,7 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1431
1554
  };
1432
1555
 
1433
1556
  const parseDeclaration = (): Declaration => {
1434
- const start = cursor.index;
1557
+ const start = cursor;
1435
1558
  return withRange(parseDeclarationUnit(), start);
1436
1559
  };
1437
1560
 
@@ -1442,7 +1565,10 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1442
1565
  const name = advance().text;
1443
1566
  return { name, arity: accept("_") ? 2 : 1, location };
1444
1567
  }
1445
- if (peek().kind === "Operator" && isAt("_", 1)) {
1568
+ const isPrefixOperator =
1569
+ peek().kind !== "String" &&
1570
+ (DEFINABLE_PREFIX_OPERATORS.has(peek().text) || (isTlapm && peek().kind === "Operator"));
1571
+ if (isPrefixOperator && isAt("_", 1)) {
1446
1572
  const operator = advance().text;
1447
1573
  advance();
1448
1574
  return { name: operator === "-" ? "-." : operator, arity: 1, location };
@@ -1464,19 +1590,19 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1464
1590
  return declarations;
1465
1591
  };
1466
1592
 
1467
- const getClosingOffset = (offset: number) => {
1468
- const depth = { value: 0, offset };
1593
+ const getClosingOffset = (start: number) => {
1594
+ let depth = 0;
1595
+ let offset = start;
1469
1596
  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;
1597
+ const token = peek(offset);
1598
+ if (token.kind === "End") return offset;
1599
+ if (token.kind === "Operator" && OPENING_BRACKETS.has(token.text)) depth++;
1600
+ if (token.kind === "Operator" && CLOSING_BRACKETS.has(token.text)) depth--;
1601
+ offset++;
1602
+ } while (depth > 0);
1603
+ return offset;
1477
1604
  };
1478
1605
 
1479
- // SANY inserts a break before each definition, which ends the fact list or step before it.
1480
1606
  const isDefinitionStart = () => {
1481
1607
  const token = peek();
1482
1608
  const next = peek(1);
@@ -1489,14 +1615,14 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1489
1615
  );
1490
1616
  }
1491
1617
  if (isAt("(", 1) || isAt("[", 1)) return isAt("==", getClosingOffset(1));
1492
- if (next.kind === "Operator" && POSTFIX_OPERATORS.has(next.text)) return isAt("==", 2);
1618
+ if (next.kind === "Operator" && DEFINABLE_POSTFIX_OPERATORS.has(next.text))
1619
+ return isAt("==", 2);
1493
1620
  if (next.kind === "Operator" && INFIX_OPERATORS.has(next.text)) {
1494
1621
  return peek(2).kind === "Identifier" && isAt("==", 3);
1495
1622
  }
1496
1623
  return isAt("==", 1);
1497
1624
  };
1498
1625
 
1499
- // SANY's proof levels, one for each open proof, which stay -1 until a step sets them.
1500
1626
  const proofLevels: number[] = [];
1501
1627
 
1502
1628
  const getProofLevel = () => proofLevels[proofLevels.length - 1] ?? -1;
@@ -1509,9 +1635,9 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1509
1635
 
1510
1636
  const getStepLabel = (step: Token) => {
1511
1637
  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);
1638
+ let end = label.length;
1639
+ while (label[end - 1] === ".") end--;
1640
+ return label.slice(0, end);
1515
1641
  };
1516
1642
 
1517
1643
  const isStepReference = (step: Token) =>
@@ -1574,17 +1700,15 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1574
1700
  return !isDefinitionStart();
1575
1701
  };
1576
1702
 
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
1703
  const parseFact = (): Fact => {
1580
- const start = cursor.index;
1704
+ const start = cursor;
1581
1705
  const token = peek();
1582
1706
  if (
1583
1707
  token.kind === "Operator" &&
1584
1708
  !EXPRESSION_PREFIXES.has(token.text) &&
1585
1709
  isOperatorName(token.text)
1586
1710
  ) {
1587
- cursor.index++;
1711
+ cursor++;
1588
1712
  return withRange(
1589
1713
  {
1590
1714
  kind: "OperatorReference",
@@ -1619,9 +1743,8 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1619
1743
  module.variables.some((variable) => variable.name === name),
1620
1744
  );
1621
1745
 
1622
- // tlapm's definable: names and operators joined by !.
1623
1746
  const parseDefinable = (): Fact => {
1624
- const start = cursor.index;
1747
+ const start = cursor;
1625
1748
  const token = peek();
1626
1749
  const parts = parseSeparated(() => {
1627
1750
  const part = peek();
@@ -1629,7 +1752,7 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1629
1752
  if (!isName && part.kind !== "Operator") {
1630
1753
  throw createUnexpected(`Expected a definition name but found ${describeToken(part)}`, part);
1631
1754
  }
1632
- cursor.index++;
1755
+ cursor++;
1633
1756
  return part.text;
1634
1757
  }, "!");
1635
1758
  const location = getLocation(token);
@@ -1654,13 +1777,15 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1654
1777
  return defs;
1655
1778
  };
1656
1779
 
1657
- const parseFacts = () => ({
1658
- facts: isFactAhead() ? parseSeparated(parseFact) : [],
1659
- defs: accept("DEF") || accept("DEFS") ? parseDefs() : [],
1660
- });
1780
+ const parseFacts = () => {
1781
+ const facts = isFactAhead() ? parseSeparated(parseFact) : [];
1782
+ const isDef = accept("DEF") || accept("DEFS");
1783
+ if (isTlapm && facts.length === 0 && !isDef) throw createUnexpected("Expected a fact");
1784
+ return { facts, defs: isDef ? parseDefs() : [] };
1785
+ };
1661
1786
 
1662
1787
  const parseUseOrHide = (): UseOrHide => {
1663
- const start = cursor.index;
1788
+ const start = cursor;
1664
1789
  const keyword = advance();
1665
1790
  const isOnly = keyword.text === "USE" && accept("ONLY");
1666
1791
  const keywordRange = getRange(start);
@@ -1686,9 +1811,11 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1686
1811
  };
1687
1812
 
1688
1813
  const parseNewSymbol = (): NewSymbol => {
1689
- const start = cursor.index;
1690
- const location = getLocation(peek());
1814
+ const newStart = cursor;
1815
+ const newLocation = getLocation(peek());
1691
1816
  const isNew = accept("NEW");
1817
+ const start = isTlapm ? cursor : newStart;
1818
+ const location = isTlapm ? getLocation(peek()) : newLocation;
1692
1819
  const level = peek().kind === "Keyword" ? NEW_SYMBOL_LEVELS.get(peek().text) : undefined;
1693
1820
  if (!isNew && level === undefined) {
1694
1821
  throw createUnexpected(`Expected a declaration but found ${describeToken(peek())}`);
@@ -1732,9 +1859,13 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1732
1859
  };
1733
1860
 
1734
1861
  const parseAssumeProve = (): AssumeProve => {
1735
- const start = cursor.index;
1862
+ const start = cursor;
1736
1863
  const location = getLocation(expect("ASSUME"));
1737
1864
  const assumptions = parseSeparated(() => {
1865
+ if (peek().kind === "Identifier" && isAt("::", 1) && isAt("ASSUME", 2)) {
1866
+ advance();
1867
+ advance();
1868
+ }
1738
1869
  if (isAt("ASSUME")) return withProofScope(parseAssumeProve);
1739
1870
  if (peek().kind === "Keyword" && NEW_SYMBOL_STARTS.has(peek().text)) return parseNewSymbol();
1740
1871
  return parseExpression();
@@ -1747,11 +1878,11 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1747
1878
  };
1748
1879
 
1749
1880
  const isNameListAhead = (terminator: string) => {
1750
- const offset = { value: 0 };
1751
- while (peek(offset.value).kind === "Identifier" && isAt(",", offset.value + 1)) {
1752
- offset.value += 2;
1881
+ let offset = 0;
1882
+ while (peek(offset).kind === "Identifier" && isAt(",", offset + 1)) {
1883
+ offset += 2;
1753
1884
  }
1754
- return peek(offset.value).kind === "Identifier" && isAt(terminator, offset.value + 1);
1885
+ return peek(offset).kind === "Identifier" && isAt(terminator, offset + 1);
1755
1886
  };
1756
1887
 
1757
1888
  const declareProofSymbols = (names: string[], bounds: Bound[]) => {
@@ -1767,11 +1898,11 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1767
1898
  const token = peek();
1768
1899
  if (isAt("USE") || isAt("HIDE")) return parseUseOrHide();
1769
1900
  if (isAt("INSTANCE")) {
1770
- const start = cursor.index;
1901
+ const start = cursor;
1771
1902
  return withRange(parseInstance(undefined, [], false, getLocation(token)), start);
1772
1903
  }
1773
1904
  if (isAt("DEFINE") || isDefinitionStart()) {
1774
- const start = cursor.index;
1905
+ const start = cursor;
1775
1906
  accept("DEFINE");
1776
1907
  const definitions = [parseDefinition(false)];
1777
1908
  while (isDefinitionStart()) definitions.push(parseDefinition(false));
@@ -1819,19 +1950,17 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1819
1950
  if (!isCorrectLevel(step)) {
1820
1951
  throw createError(`${isQed ? "QED step" : "step"}'s number has bad level`, step);
1821
1952
  }
1822
- if (getStepLevel(step) < 0 && getStepName(step) !== undefined) {
1953
+ if (mode !== "sany" && getStepLevel(step) < 0 && getStepName(step) !== undefined) {
1823
1954
  throw createError("<*> and <+> cannot be used for a named step", step);
1824
1955
  }
1825
- cursor.index++;
1956
+ cursor++;
1826
1957
  return { name: getStepName(step), token: step.text, location: getLocation(step) };
1827
1958
  };
1828
1959
 
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
1960
  const parseStep = (): ProofStep => {
1832
- const start = cursor.index;
1961
+ const start = cursor;
1833
1962
  const step = parseStepStart(isAt("QED", 1));
1834
- const statementStart = cursor.index;
1963
+ const statementStart = cursor;
1835
1964
  const scope = new Set<string>();
1836
1965
  proofScopes.push(scope);
1837
1966
  const body: StepBody = accept("QED") ? { kind: "Qed" } : parseStepBody();
@@ -1847,56 +1976,223 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1847
1976
  return withRange({ ...step, body, head, statement, proof }, start);
1848
1977
  };
1849
1978
 
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);
1979
+ const parseLeafProof = (
1980
+ location: SourceLocation,
1981
+ ): Exclude<Proof, { kind: "Steps" }> | undefined => {
1982
+ if (accept("BY")) {
1983
+ const keyword = getRange(cursor - 1);
1856
1984
  return { kind: "By", isOnly: accept("ONLY"), ...parseFacts(), keyword, location };
1857
1985
  }
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
- }
1986
+ const terminal = peek();
1987
+ if (terminal.kind !== "Keyword" || (terminal.text !== "OBVIOUS" && terminal.text !== "OMITTED"))
1988
+ return undefined;
1989
+ advance();
1990
+ const keyword = getRange(cursor - 1);
1991
+ return { kind: terminal.text === "OBVIOUS" ? "Obvious" : "Omitted", keyword, location };
1992
+ };
1993
+
1994
+ const parseProofBody = (): Proof => {
1995
+ const location = getLocation(peek());
1868
1996
  accept("PROOF");
1997
+ const leaf = parseLeafProof(location);
1998
+ if (leaf) return leaf;
1869
1999
  const steps = [parseStep()];
1870
2000
  while (steps[steps.length - 1].body.kind !== "Qed") steps.push(parseStep());
1871
2001
  return { kind: "Steps", level: getProofLevel(), steps, location };
1872
2002
  };
1873
2003
 
1874
2004
  const parseProof = (): Proof => {
1875
- const start = cursor.index;
2005
+ const start = cursor;
1876
2006
  proofLevels.push(-1);
1877
2007
  const proof = withProofScope(parseProofBody);
1878
2008
  proofLevels.pop();
1879
2009
  return withRange(proof, start);
1880
2010
  };
1881
2011
 
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);
2012
+ const isPreproofStart = () =>
2013
+ peek().kind === "Step" || (peek().kind === "Keyword" && PROOF_STARTS.has(peek().text));
2014
+
2015
+ const getStepSpan = (head: SourceRange, body: StepBody) => {
2016
+ if (body.kind !== "Use" && body.kind !== "Hide") return getSpan(head);
2017
+ const lastDef = body.defs[body.defs.length - 1]?.location.range;
2018
+ return mergeSpans(getSpan({ ...head, end: head.start }), getSpan(lastDef ?? body.keyword));
2019
+ };
2020
+
2021
+ const parsePreproof = (): Preproof => {
2022
+ const first = cursor;
2023
+ const location = getLocation(peek());
2024
+ const isProof = accept("PROOF");
2025
+ const leaf = parseLeafProof(location);
2026
+ if (leaf) {
2027
+ const proof = withRange(leaf, first);
2028
+ return { kind: "Leaf", proof, span: getSpan(proof.keyword), first, end: cursor - 1 };
2029
+ }
2030
+ const token = peek();
2031
+ if (token.kind !== "Step") {
2032
+ throw createUnexpected(`Expected a step number but found ${describeToken(token)}`);
2033
+ }
2034
+ const start = cursor;
2035
+ advance();
2036
+ const statementStart = cursor;
2037
+ const body: StepBody = accept("QED") ? { kind: "Qed" } : parseStepBody();
2038
+ const head = getRange(start);
2039
+ return {
2040
+ kind: "Step",
2041
+ token,
2042
+ isProof,
2043
+ body,
2044
+ head,
2045
+ statement: getRange(statementStart),
2046
+ span: getStepSpan(head, body),
2047
+ first,
2048
+ start,
2049
+ end: cursor - 1,
2050
+ };
2051
+ };
2052
+
2053
+ const nestProof = (
2054
+ items: Preproof[],
2055
+ index: number,
2056
+ level: number,
2057
+ levelSpan: Span,
2058
+ ): NestedProof => {
2059
+ const item = items[index];
2060
+ if (!item) return { proof: undefined, span: levelSpan, next: index, end: undefined };
2061
+ if (item.kind === "Leaf")
2062
+ return { proof: item.proof, span: item.span, next: index + 1, end: item.end };
2063
+ const nested = nestSteps(items, index, level, levelSpan, true);
2064
+ if (!nested) return { proof: undefined, span: levelSpan, next: index, end: undefined };
2065
+ const location = {
2066
+ ...getLocation(tokens[item.first]),
2067
+ range: getRange(item.first, nested.end),
2068
+ };
2069
+ return {
2070
+ proof: { kind: "Steps", level: nested.level, steps: nested.steps, location },
2071
+ span: nested.span,
2072
+ next: nested.next,
2073
+ end: nested.end,
2074
+ };
2075
+ };
2076
+
2077
+ const nestSteps = (
2078
+ items: Preproof[],
2079
+ index: number,
2080
+ level: number,
2081
+ levelSpan: Span,
2082
+ isFirst: boolean,
2083
+ ): NestedSteps | undefined => {
2084
+ const item = items[index];
2085
+ if (!item) {
2086
+ throw createProofError(
2087
+ `Unexpected end of (sub)proof at level ${level} before QED step`,
2088
+ levelSpan,
2089
+ );
2090
+ }
2091
+ if (item.kind === "Leaf") {
2092
+ throw createProofError(
2093
+ `Expecting a proof step but found a${LEAF_NAMES[item.proof.kind]} leaf proof`,
2094
+ item.span,
2095
+ );
2096
+ }
2097
+ if (!isFirst && item.isProof) {
2098
+ throw createProofError("PROOF keyword found in step that does not begin subproof", item.span);
2099
+ }
2100
+ const implicit = item.token.text[1];
2101
+ if (implicit === "+" && !isFirst) {
2102
+ throw createProofError("<+> used but no subproof expected", item.span);
2103
+ }
2104
+ const stepLevel =
2105
+ implicit === "*"
2106
+ ? level - (isFirst && !item.isProof ? 1 : 0)
2107
+ : implicit === "+"
2108
+ ? level
2109
+ : getStepLevel(item.token);
2110
+ if (stepLevel < level || (!isFirst && stepLevel > level)) return undefined;
2111
+ const proof = PROVABLE_STEPS.has(item.body.kind)
2112
+ ? nestProof(items, index + 1, stepLevel + 1, item.span)
2113
+ : { proof: undefined, span: item.span, next: index + 1, end: undefined };
2114
+ const end = proof.end ?? item.end;
2115
+ const step: ProofStep = {
2116
+ name: getStepName(item.token),
2117
+ token: item.token.text,
2118
+ body: item.body,
2119
+ head: item.head,
2120
+ statement: item.statement,
2121
+ proof: proof.proof,
2122
+ location: { ...getLocation(item.token), range: getRange(item.start, end) },
2123
+ };
2124
+ const span = mergeSpans(item.span, proof.span);
2125
+ if (item.body.kind === "Qed") {
2126
+ return { level: stepLevel, steps: [step], span, next: proof.next, end };
2127
+ }
2128
+ const rest = nestSteps(
2129
+ items,
2130
+ proof.next,
2131
+ stepLevel,
2132
+ { start: span.stop, stop: span.stop },
2133
+ false,
2134
+ );
2135
+ return (
2136
+ rest && {
2137
+ ...rest,
2138
+ level: stepLevel,
2139
+ steps: [step, ...rest.steps],
2140
+ span: mergeSpans(span, rest.span),
2141
+ }
2142
+ );
2143
+ };
2144
+
2145
+ const parseTlapmProof = () => {
2146
+ if (!isPreproofStart()) return undefined;
2147
+ const items: Preproof[] = [];
2148
+ while (isPreproofStart()) items.push(parsePreproof());
2149
+ const first = items[0];
2150
+ if (first.kind === "Step") items[0] = { ...first, isProof: true };
2151
+ const nested = nestProof(items, 0, 0, first.span);
2152
+ const extra = items[nested.next];
2153
+ if (extra) {
2154
+ throw createProofError(
2155
+ "extra step(s) after finished proof",
2156
+ extra.span,
2157
+ "Proof.Parser.toplevel",
2158
+ );
2159
+ }
2160
+ return nested.proof;
2161
+ };
2162
+
2163
+ const addFactDefinition = (
2164
+ module: Module,
2165
+ name: string,
2166
+ body: Expression,
2167
+ location: SourceLocation,
2168
+ ) => {
2169
+ if (module.definitions.some((other) => other.name === name)) return;
2170
+ module.definitions.push({
2171
+ kind: "Operator",
2172
+ name,
2173
+ params: [],
2174
+ body,
2175
+ isLocal: false,
2176
+ isRecursive: false,
2177
+ location,
2178
+ });
2179
+ };
2180
+
2181
+ const parseFactName = () => {
2182
+ if (peek().kind !== "Identifier" || !isAt("==", 1)) return undefined;
2183
+ const name = expectIdentifier();
2184
+ factNames.add(name);
2185
+ advance();
2186
+ return name;
1887
2187
  };
1888
2188
 
1889
2189
  const parseTheorem = (module: Module) => {
1890
- const start = cursor.index;
2190
+ const start = cursor;
1891
2191
  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
- }
2192
+ const name = parseFactName();
1898
2193
  const parsed = withProofScope(() => {
1899
2194
  const statement = isAt("ASSUME") ? parseAssumeProve() : parseExpression();
2195
+ if (isTlapm) return { statement, proof: parseTlapmProof() };
1900
2196
  return { statement, proof: isProofStart(peek()) ? parseProof() : undefined };
1901
2197
  });
1902
2198
  const statement = parsed.statement;
@@ -1907,32 +2203,13 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1907
2203
  module.theorems.push(theorem);
1908
2204
  module.units.push({ kind: "Theorem", theorem });
1909
2205
  if (name === undefined || statement.kind === "AssumeProve") return;
1910
- addFactDefinition(
1911
- module,
1912
- withRange(
1913
- {
1914
- kind: "Operator",
1915
- name,
1916
- params: [],
1917
- body: statement,
1918
- isLocal: false,
1919
- isRecursive: false,
1920
- location: getLocation(keyword),
1921
- },
1922
- start,
1923
- ),
1924
- );
2206
+ addFactDefinition(module, name, statement, theorem.location);
1925
2207
  };
1926
2208
 
1927
2209
  const parseAssumption = (): Assumption => {
1928
- const start = cursor.index;
2210
+ const start = cursor;
1929
2211
  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
- }
2212
+ const name = parseFactName();
1936
2213
  return withRange(
1937
2214
  {
1938
2215
  name,
@@ -1968,14 +2245,14 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1968
2245
  recursiveScopes.push(new Set());
1969
2246
  if (accept("EXTENDS")) {
1970
2247
  parseSeparated(() => {
1971
- const start = cursor.index;
2248
+ const start = cursor;
1972
2249
  module.extends.push(expectModuleName());
1973
2250
  module.extendsRanges.push(getRange(start));
1974
2251
  });
1975
2252
  }
1976
2253
  while (true) {
1977
- const tokenIndex = cursor.index;
1978
- unitStart.index = tokenIndex;
2254
+ const tokenIndex = cursor;
2255
+ unitStart = tokenIndex;
1979
2256
  const token = peek();
1980
2257
  if (token.kind === "ModuleEnd") {
1981
2258
  location.range = {
@@ -2012,7 +2289,7 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
2012
2289
  case "VARIABLES": {
2013
2290
  const unitLocation = getLocation(advance());
2014
2291
  const declarations = parseSeparated(() => {
2015
- const start = cursor.index;
2292
+ const start = cursor;
2016
2293
  const location = getLocation(peek());
2017
2294
  return withRange({ name: expectIdentifier(), arity: 0, location }, start);
2018
2295
  });
@@ -2028,21 +2305,12 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
2028
2305
  module.assumptions.push(assumption);
2029
2306
  module.units.push({ kind: "Assumption", assumption });
2030
2307
  if (assumption.name !== undefined) {
2031
- addFactDefinition(module, {
2032
- kind: "Operator",
2033
- name: assumption.name,
2034
- params: [],
2035
- body: assumption.expression,
2036
- isLocal: false,
2037
- isRecursive: false,
2038
- location: assumption.location,
2039
- });
2308
+ addFactDefinition(module, assumption.name, assumption.expression, assumption.location);
2040
2309
  }
2041
2310
  continue;
2042
2311
  }
2043
2312
  case "USE":
2044
2313
  case "HIDE": {
2045
- // SANY's module body takes a USE only when ONLY doesn't follow it.
2046
2314
  if (isAt("USE") && isAt("ONLY", 1)) {
2047
2315
  throw createUnexpected(`Expected a module unit but found ${describeToken(token)}`);
2048
2316
  }
@@ -2051,10 +2319,13 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
2051
2319
  module.units.push({ kind: "Use", use });
2052
2320
  continue;
2053
2321
  }
2054
- case "RECURSIVE":
2055
- advance();
2056
- module.units.push({ kind: "Recursive", declarations: declareRecursive() });
2322
+ case "RECURSIVE": {
2323
+ const unitLocation = getLocation(advance());
2324
+ const declarations = declareRecursive();
2325
+ unitLocation.range = getRange(tokenIndex);
2326
+ module.units.push({ kind: "Recursive", declarations, location: unitLocation });
2057
2327
  continue;
2328
+ }
2058
2329
  case "INSTANCE":
2059
2330
  addDefinitionUnit(
2060
2331
  module,
@@ -2093,16 +2364,13 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
2093
2364
  };
2094
2365
 
2095
2366
  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;
2367
+ const sanyError = isKeywordModuleName ? getSanyParseError(source) : undefined;
2099
2368
  if (sanyError !== undefined) throw new TlaSyntaxError(sanyError);
2100
2369
  return module;
2101
2370
  };
2102
2371
 
2103
2372
  export const parseModule = (source: string) => parse(source, "tlc");
2104
2373
 
2105
- // Parses a module the caller has tokenized already.
2106
2374
  export const parseModuleTokens = (source: string, tokens: Token[]) => parse(source, "tlc", tokens);
2107
2375
 
2108
2376
  export const parseTlapmModule = (source: string) => parse(source, "tlapm");