tla-ts 0.0.9 → 0.0.10-dev.09e53c2a6

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 (625) hide show
  1. package/README.md +30 -1
  2. package/dist/compile.cjs +23 -0
  3. package/dist/compile.js +23 -0
  4. package/dist/deciders.cjs +41 -37
  5. package/dist/deciders.js +57 -53
  6. package/dist/index.cjs +1 -1
  7. package/dist/index.d.cts +109 -10
  8. package/dist/index.d.ts +109 -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 +2746 -410
  15. package/dist/prove.js +2745 -409
  16. package/dist/run.cjs +146 -31
  17. package/dist/run.js +146 -31
  18. package/dist/tlapm.cjs +2 -2
  19. package/dist/tlapm.js +2 -2
  20. package/dist/transfer.cjs +132 -104
  21. package/dist/transfer.js +132 -104
  22. package/dist/worker.cjs +6 -6
  23. package/dist/worker.js +6 -6
  24. package/package.json +3 -1
  25. package/src/ast.ts +45 -59
  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 +797 -782
  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 +433 -82
  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 +360 -0
  40. package/src/cli/tlc.ts +323 -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 +36 -54
  48. package/src/dfid.ts +618 -0
  49. package/src/environment-config.ts +315 -0
  50. package/src/environment.ts +178 -339
  51. package/src/errors.ts +100 -57
  52. package/src/evaluate.ts +598 -340
  53. package/src/exit-codes.ts +38 -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 +83 -101
  63. package/src/liveness-checker.ts +590 -311
  64. package/src/liveness.ts +180 -124
  65. package/src/obligations/action.ts +17 -44
  66. package/src/obligations/anonymize.ts +120 -95
  67. package/src/obligations/enabled-axioms.ts +218 -0
  68. package/src/obligations/equality.ts +1 -3
  69. package/src/obligations/expression.ts +37 -26
  70. package/src/obligations/format.ts +0 -10
  71. package/src/obligations/generate.ts +66 -64
  72. package/src/obligations/index.ts +38 -19
  73. package/src/obligations/levels.ts +27 -18
  74. package/src/obligations/module.ts +28 -55
  75. package/src/obligations/normalize.ts +30 -37
  76. package/src/obligations/operators.ts +0 -3
  77. package/src/obligations/pragma.ts +52 -24
  78. package/src/obligations/printer.ts +89 -58
  79. package/src/obligations/proof.ts +3 -6
  80. package/src/obligations/regroup.ts +0 -5
  81. package/src/obligations/simplify.ts +57 -63
  82. package/src/obligations/source.ts +119 -95
  83. package/src/obligations/subexpression.ts +49 -28
  84. package/src/obligations/substitution.ts +1 -5
  85. package/src/obligations/temporal.ts +12 -20
  86. package/src/obligations/tuples.ts +2 -10
  87. package/src/parallel-worker.ts +30 -60
  88. package/src/parallel.ts +59 -73
  89. package/src/parser.ts +1082 -399
  90. package/src/pcal/ast.ts +53 -86
  91. package/src/pcal/parse.ts +144 -219
  92. package/src/pcal/tokenize.ts +91 -131
  93. package/src/pcal/translate.ts +83 -130
  94. package/src/pcal/validate.ts +48 -68
  95. package/src/pretty-print.ts +7 -8
  96. package/src/prover/decide-pool.ts +8 -13
  97. package/src/prover/deciders.ts +12 -13
  98. package/src/prover/first-order.ts +0 -11
  99. package/src/prover/isabelle/decide.ts +3 -31
  100. package/src/prover/isabelle/encode.ts +82 -64
  101. package/src/prover/isabelle/isar/attrib.ts +250 -0
  102. package/src/prover/isabelle/isar/context.ts +335 -0
  103. package/src/prover/isabelle/isar/induct.ts +382 -0
  104. package/src/prover/isabelle/isar/inner-syntax.ts +262 -117
  105. package/src/prover/isabelle/isar/method.ts +510 -226
  106. package/src/prover/isabelle/isar/proof.ts +570 -23
  107. package/src/prover/isabelle/isar/rule-cases.ts +224 -0
  108. package/src/prover/isabelle/isar/theory.ts +488 -88
  109. package/src/prover/isabelle/isar/toplevel.ts +331 -0
  110. package/src/prover/isabelle/isar/type-check.ts +99 -38
  111. package/src/prover/isabelle/provers/blast/blast.ts +16 -105
  112. package/src/prover/isabelle/provers/blast/branch.ts +0 -33
  113. package/src/prover/isabelle/provers/blast/prove.ts +0 -36
  114. package/src/prover/isabelle/provers/blast/rules.ts +5 -45
  115. package/src/prover/isabelle/provers/blast/state.ts +1 -29
  116. package/src/prover/isabelle/provers/blast/term.ts +8 -37
  117. package/src/prover/isabelle/provers/clasimp.ts +0 -14
  118. package/src/prover/isabelle/provers/classical.ts +58 -61
  119. package/src/prover/isabelle/provers/hypsubst.ts +27 -52
  120. package/src/prover/isabelle/pure/bicompose.ts +24 -39
  121. package/src/prover/isabelle/pure/consts.ts +0 -8
  122. package/src/prover/isabelle/pure/conv.ts +2 -18
  123. package/src/prover/isabelle/pure/drule.ts +95 -45
  124. package/src/prover/isabelle/pure/envir.ts +2 -53
  125. package/src/prover/isabelle/pure/goal.ts +1 -9
  126. package/src/prover/isabelle/pure/interrupt.ts +0 -5
  127. package/src/prover/isabelle/pure/list.ts +0 -3
  128. package/src/prover/isabelle/pure/logic.ts +1 -16
  129. package/src/prover/isabelle/pure/name.ts +1 -10
  130. package/src/prover/isabelle/pure/net.ts +2 -60
  131. package/src/prover/isabelle/pure/object-logic.ts +15 -16
  132. package/src/prover/isabelle/pure/pattern.ts +1 -20
  133. package/src/prover/isabelle/pure/raw-simplifier.ts +16 -63
  134. package/src/prover/isabelle/pure/rewriter.ts +31 -74
  135. package/src/prover/isabelle/pure/search.ts +2 -11
  136. package/src/prover/isabelle/pure/seq.ts +0 -11
  137. package/src/prover/isabelle/pure/simplifier.ts +27 -16
  138. package/src/prover/isabelle/pure/table.ts +2 -33
  139. package/src/prover/isabelle/pure/tactic.ts +11 -23
  140. package/src/prover/isabelle/pure/tactical.ts +47 -48
  141. package/src/prover/isabelle/pure/term-ord.ts +1 -7
  142. package/src/prover/isabelle/pure/term.ts +1 -44
  143. package/src/prover/isabelle/pure/thm.ts +26 -48
  144. package/src/prover/isabelle/pure/type.ts +1 -16
  145. package/src/prover/isabelle/pure/unify.ts +19 -31
  146. package/src/prover/isabelle/pure/variable.ts +2 -8
  147. package/src/prover/isabelle/tla/classical-setup.ts +17 -25
  148. package/src/prover/isabelle/tla/context.ts +65 -26
  149. package/src/prover/isabelle/tla/logic-data.ts +1 -1
  150. package/src/prover/isabelle/tla/logic.ts +53 -32
  151. package/src/prover/isabelle/tla/simpdata.ts +45 -44
  152. package/src/prover/isabelle/tools/intuitionistic.ts +28 -21
  153. package/src/prover/ocaml.ts +4 -7
  154. package/src/prover/prep/action.ts +33 -66
  155. package/src/prover/prep/enabled-axioms.ts +22 -20
  156. package/src/prover/prep/fingerprint.ts +2 -21
  157. package/src/prover/prep/level-comparison.ts +8 -12
  158. package/src/prover/prep/md5.ts +0 -2
  159. package/src/prover/prep/methods.ts +189 -86
  160. package/src/prover/prep/normalize.ts +42 -37
  161. package/src/prover/prove-worker.ts +0 -2
  162. package/src/prover/prove.ts +398 -133
  163. package/src/prover/ptl/decide.ts +96 -56
  164. package/src/prover/ptl/encode.ts +15 -38
  165. package/src/prover/ptl/sat.ts +24 -32
  166. package/src/prover/ptl/tableau.ts +40 -28
  167. package/src/prover/smt/arithmetic.ts +310 -0
  168. package/src/prover/smt/axioms.ts +12 -15
  169. package/src/prover/smt/context.ts +60 -32
  170. package/src/prover/smt/data.ts +517 -401
  171. package/src/prover/smt/encode.ts +155 -85
  172. package/src/prover/smt/extensionality.ts +5 -13
  173. package/src/prover/smt/flatten.ts +7 -28
  174. package/src/prover/smt/format.ts +33 -14
  175. package/src/prover/smt/instances.ts +7 -11
  176. package/src/prover/smt/layout.ts +91 -0
  177. package/src/prover/smt/rewrite.ts +1026 -658
  178. package/src/prover/smt/simplify.ts +441 -0
  179. package/src/prover/smt/solver/ackermannize-bv-tactic.ts +61 -0
  180. package/src/prover/smt/solver/ackr-helper.ts +179 -0
  181. package/src/prover/smt/solver/ackr-model-converter.ts +105 -0
  182. package/src/prover/smt/solver/act-cache.ts +0 -16
  183. package/src/prover/smt/solver/add-bounds-tactic.ts +59 -0
  184. package/src/prover/smt/solver/aig-tactic.ts +52 -0
  185. package/src/prover/smt/solver/aig.ts +889 -0
  186. package/src/prover/smt/solver/arith-rewriter.ts +615 -53
  187. package/src/prover/smt/solver/arith-terms.ts +121 -0
  188. package/src/prover/smt/solver/array-decl-plugin.ts +175 -0
  189. package/src/prover/smt/solver/array-rewriter.ts +309 -0
  190. package/src/prover/smt/solver/array.ts +1 -3
  191. package/src/prover/smt/solver/asserted-formulas.ts +87 -58
  192. package/src/prover/smt/solver/ast-lt.ts +166 -22
  193. package/src/prover/smt/solver/ast-util.ts +160 -7
  194. package/src/prover/smt/solver/ast.ts +1424 -180
  195. package/src/prover/smt/solver/auf-solver.ts +7 -44
  196. package/src/prover/smt/solver/bit-blast-tactic.ts +582 -0
  197. package/src/prover/smt/solver/bit-blaster.ts +871 -0
  198. package/src/prover/smt/solver/bound-manager.ts +196 -0
  199. package/src/prover/smt/solver/bound-simplifier.ts +600 -0
  200. package/src/prover/smt/solver/bv-bound-chk.ts +492 -0
  201. package/src/prover/smt/solver/bv-decl-plugin.ts +338 -0
  202. package/src/prover/smt/solver/bv-divrem-bounds.ts +95 -0
  203. package/src/prover/smt/solver/bv-rewriter.ts +1901 -0
  204. package/src/prover/smt/solver/bv1-blast.ts +214 -0
  205. package/src/prover/smt/solver/bv2fpa-converter.ts +174 -0
  206. package/src/prover/smt/solver/bv2int-rewriter.ts +544 -0
  207. package/src/prover/smt/solver/bv2real-rewriter.ts +533 -0
  208. package/src/prover/smt/solver/card2bv.ts +110 -0
  209. package/src/prover/smt/solver/case-split-queue.ts +0 -10
  210. package/src/prover/smt/solver/cg-table.ts +39 -42
  211. package/src/prover/smt/solver/check-logic.ts +330 -0
  212. package/src/prover/smt/solver/clause.ts +0 -27
  213. package/src/prover/smt/solver/cofactor-elim-term-ite.ts +278 -0
  214. package/src/prover/smt/solver/conflict-resolution.ts +78 -11
  215. package/src/prover/smt/solver/context.ts +519 -175
  216. package/src/prover/smt/solver/ctx-simplify.ts +33 -50
  217. package/src/prover/smt/solver/ctx-solver-simplify.ts +122 -0
  218. package/src/prover/smt/solver/datatype-decl-plugin.ts +572 -0
  219. package/src/prover/smt/solver/datatype-rewriter.ts +82 -0
  220. package/src/prover/smt/solver/demodulator.ts +786 -0
  221. package/src/prover/smt/solver/dependent-expr-state.ts +81 -0
  222. package/src/prover/smt/solver/der.ts +39 -30
  223. package/src/prover/smt/solver/diff-neq.ts +206 -0
  224. package/src/prover/smt/solver/distribute-forall.ts +57 -0
  225. package/src/prover/smt/solver/dom-simplify.ts +511 -0
  226. package/src/prover/smt/solver/dt2bv-tactic.ts +260 -0
  227. package/src/prover/smt/solver/dyn-ack.ts +0 -11
  228. package/src/prover/smt/solver/e-matching.ts +9 -41
  229. package/src/prover/smt/solver/elim-small-bv-tactic.ts +129 -0
  230. package/src/prover/smt/solver/elim-uncnstr.ts +545 -0
  231. package/src/prover/smt/solver/enode.ts +100 -23
  232. package/src/prover/smt/solver/eq2bv-tactic.ts +218 -0
  233. package/src/prover/smt/solver/euf/arith-axioms.ts +403 -0
  234. package/src/prover/smt/solver/euf/arith-internalize.ts +653 -0
  235. package/src/prover/smt/solver/euf/arith-solver.ts +889 -0
  236. package/src/prover/smt/solver/euf/array-axioms.ts +527 -0
  237. package/src/prover/smt/solver/euf/array-internalize.ts +428 -0
  238. package/src/prover/smt/solver/euf/array-solver.ts +306 -0
  239. package/src/prover/smt/solver/euf/bv-ackerman.ts +162 -0
  240. package/src/prover/smt/solver/euf/bv-internalize.ts +748 -0
  241. package/src/prover/smt/solver/euf/bv-solver.ts +449 -0
  242. package/src/prover/smt/solver/euf/dt-solver.ts +618 -0
  243. package/src/prover/smt/solver/euf/egraph.ts +907 -0
  244. package/src/prover/smt/solver/euf/euf-solver.ts +1205 -0
  245. package/src/prover/smt/solver/euf/fpa-solver.ts +317 -0
  246. package/src/prover/smt/solver/euf/mam.ts +1050 -0
  247. package/src/prover/smt/solver/euf/q-ematch.ts +830 -0
  248. package/src/prover/smt/solver/euf/q-mbi.ts +587 -0
  249. package/src/prover/smt/solver/euf/q-model-fixer.ts +296 -0
  250. package/src/prover/smt/solver/euf/q-solver.ts +361 -0
  251. package/src/prover/smt/solver/euf/th-solver.ts +335 -0
  252. package/src/prover/smt/solver/euf/th-solvers.ts +30 -0
  253. package/src/prover/smt/solver/expr-ref.ts +0 -5
  254. package/src/prover/smt/solver/expr-safe-replace.ts +26 -7
  255. package/src/prover/smt/solver/expr2polynomial.ts +146 -0
  256. package/src/prover/smt/solver/factor.ts +141 -0
  257. package/src/prover/smt/solver/fd-solver.ts +265 -0
  258. package/src/prover/smt/solver/fingerprints.ts +15 -26
  259. package/src/prover/smt/solver/fix-dl-var.ts +148 -0
  260. package/src/prover/smt/solver/flat-literals.ts +0 -9
  261. package/src/prover/smt/solver/fm-tactic.ts +884 -0
  262. package/src/prover/smt/solver/fpa-decl-plugin.ts +618 -0
  263. package/src/prover/smt/solver/fpa-rewriter.ts +640 -0
  264. package/src/prover/smt/solver/fpa2bv-converter.ts +2249 -0
  265. package/src/prover/smt/solver/fpa2bv-rewriter.ts +348 -0
  266. package/src/prover/smt/solver/fpa2bv-tactic.ts +73 -0
  267. package/src/prover/smt/solver/goal.ts +176 -28
  268. package/src/prover/smt/solver/goal2nlsat.ts +189 -0
  269. package/src/prover/smt/solver/guard-set.ts +219 -0
  270. package/src/prover/smt/solver/hash.ts +0 -9
  271. package/src/prover/smt/solver/hashtable.ts +26 -23
  272. package/src/prover/smt/solver/inf-eps.ts +63 -0
  273. package/src/prover/smt/solver/inj-axiom.ts +101 -0
  274. package/src/prover/smt/solver/internalizer.ts +112 -132
  275. package/src/prover/smt/solver/lackr.ts +381 -0
  276. package/src/prover/smt/solver/lbool.ts +0 -2
  277. package/src/prover/smt/solver/lia2card.ts +268 -0
  278. package/src/prover/smt/solver/lia2pb.ts +154 -0
  279. package/src/prover/smt/solver/literal.ts +0 -4
  280. package/src/prover/smt/solver/logic-tactics.ts +345 -0
  281. package/src/prover/smt/solver/lp/bound-propagator.ts +7 -26
  282. package/src/prover/smt/solver/lp/constraints.ts +1 -8
  283. package/src/prover/smt/solver/lp/containers.ts +11 -30
  284. package/src/prover/smt/solver/lp/core-solver.ts +23 -29
  285. package/src/prover/smt/solver/lp/cross-nested.ts +5 -20
  286. package/src/prover/smt/solver/lp/dep-intervals.ts +6 -24
  287. package/src/prover/smt/solver/lp/dependency.ts +0 -5
  288. package/src/prover/smt/solver/lp/dioph-eq.ts +8 -103
  289. package/src/prover/smt/solver/lp/explanation.ts +0 -6
  290. package/src/prover/smt/solver/lp/gomory.ts +8 -22
  291. package/src/prover/smt/solver/lp/hnf-cutter.ts +16 -23
  292. package/src/prover/smt/solver/lp/hnf.ts +10 -28
  293. package/src/prover/smt/solver/lp/int-cube.ts +17 -39
  294. package/src/prover/smt/solver/lp/int-solver.ts +3 -35
  295. package/src/prover/smt/solver/lp/lar-solver.ts +69 -82
  296. package/src/prover/smt/solver/lp/lar-term.ts +0 -5
  297. package/src/prover/smt/solver/lp/lp-settings.ts +0 -14
  298. package/src/prover/smt/solver/lp/maximize-term.ts +76 -52
  299. package/src/prover/smt/solver/lp/nex-creator.ts +4 -28
  300. package/src/prover/smt/solver/lp/nex.ts +0 -6
  301. package/src/prover/smt/solver/lp/nla-backoff.ts +0 -5
  302. package/src/prover/smt/solver/lp/nla-basics.ts +48 -30
  303. package/src/prover/smt/solver/lp/nla-core.ts +91 -135
  304. package/src/prover/smt/solver/lp/nla-divisions.ts +31 -43
  305. package/src/prover/smt/solver/lp/nla-emonics.ts +3 -21
  306. package/src/prover/smt/solver/lp/nla-factorization.ts +0 -4
  307. package/src/prover/smt/solver/lp/nla-grobner.ts +22 -72
  308. package/src/prover/smt/solver/lp/nla-horner.ts +2 -12
  309. package/src/prover/smt/solver/lp/nla-intervals.ts +1 -12
  310. package/src/prover/smt/solver/lp/nla-monomial-bounds.ts +15 -42
  311. package/src/prover/smt/solver/lp/nla-monotone.ts +1 -6
  312. package/src/prover/smt/solver/lp/nla-order.ts +0 -13
  313. package/src/prover/smt/solver/lp/nla-patcher.ts +3 -7
  314. package/src/prover/smt/solver/lp/nla-powers.ts +220 -0
  315. package/src/prover/smt/solver/lp/nla-tangents.ts +0 -10
  316. package/src/prover/smt/solver/lp/nla-throttle.ts +0 -6
  317. package/src/prover/smt/solver/lp/nla-transcendentals.ts +324 -0
  318. package/src/prover/smt/solver/lp/nla-types.ts +0 -12
  319. package/src/prover/smt/solver/lp/nla-var-eqs.ts +4 -26
  320. package/src/prover/smt/solver/lp/nra-solver.ts +123 -112
  321. package/src/prover/smt/solver/lp/numeric-pair.ts +0 -4
  322. package/src/prover/smt/solver/lp/pdd-interval.ts +0 -3
  323. package/src/prover/smt/solver/lp/pdd-simplifier.ts +1 -14
  324. package/src/prover/smt/solver/lp/pdd-solver.ts +2 -33
  325. package/src/prover/smt/solver/lp/pdd.ts +7 -70
  326. package/src/prover/smt/solver/lp/random-updater.ts +0 -9
  327. package/src/prover/smt/solver/lp/static-matrix.ts +8 -19
  328. package/src/prover/smt/solver/lp/union-find.ts +5 -5
  329. package/src/prover/smt/solver/macro-finder.ts +530 -0
  330. package/src/prover/smt/solver/mam-compiler.ts +129 -139
  331. package/src/prover/smt/solver/mam-interpreter.ts +0 -21
  332. package/src/prover/smt/solver/max-bv-sharing-tactic.ts +17 -0
  333. package/src/prover/smt/solver/max-cliques.ts +105 -0
  334. package/src/prover/smt/solver/maxcore.ts +309 -0
  335. package/src/prover/smt/solver/maximize-ac-sharing.ts +8 -21
  336. package/src/prover/smt/solver/maxlex.ts +115 -0
  337. package/src/prover/smt/solver/maxsmt-base.ts +105 -0
  338. package/src/prover/smt/solver/maxsmt.ts +92 -0
  339. package/src/prover/smt/solver/mbp/mbp-arith.ts +467 -0
  340. package/src/prover/smt/solver/mbp/mbp-basic-tg.ts +101 -0
  341. package/src/prover/smt/solver/mbp/mbp-plugin.ts +287 -0
  342. package/src/prover/smt/solver/mbp/mbp-qel.ts +48 -0
  343. package/src/prover/smt/solver/mbp/mbp-solve-plugin.ts +271 -0
  344. package/src/prover/smt/solver/mbp/mbp-term-graph.ts +606 -0
  345. package/src/prover/smt/solver/model-based-opt.ts +844 -0
  346. package/src/prover/smt/solver/model-checker.ts +19 -62
  347. package/src/prover/smt/solver/model-evaluator.ts +190 -40
  348. package/src/prover/smt/solver/model-finder.ts +14 -32
  349. package/src/prover/smt/solver/model-generator.ts +56 -40
  350. package/src/prover/smt/solver/model-macro-solver.ts +60 -114
  351. package/src/prover/smt/solver/model-printer.ts +214 -0
  352. package/src/prover/smt/solver/mpf.ts +711 -0
  353. package/src/prover/smt/solver/mus.ts +51 -0
  354. package/src/prover/smt/solver/muz/dl-context.ts +404 -0
  355. package/src/prover/smt/solver/muz/dl-mk-bit-blast.ts +97 -0
  356. package/src/prover/smt/solver/muz/dl-mk-coi-filter.ts +167 -0
  357. package/src/prover/smt/solver/muz/dl-mk-elim-term-ite.ts +125 -0
  358. package/src/prover/smt/solver/muz/dl-mk-interp-tail-simplifier.ts +299 -0
  359. package/src/prover/smt/solver/muz/dl-mk-rule-inliner.ts +455 -0
  360. package/src/prover/smt/solver/muz/dl-mk-slice.ts +340 -0
  361. package/src/prover/smt/solver/muz/dl-mk-subsumption-checker.ts +163 -0
  362. package/src/prover/smt/solver/muz/dl-rule-set.ts +273 -0
  363. package/src/prover/smt/solver/muz/dl-rule-transformer.ts +123 -0
  364. package/src/prover/smt/solver/muz/dl-rule.ts +496 -0
  365. package/src/prover/smt/solver/muz/hnf.ts +201 -0
  366. package/src/prover/smt/solver/muz/horn-subsume-model-converter.ts +176 -0
  367. package/src/prover/smt/solver/muz/horn-tactic.ts +201 -0
  368. package/src/prover/smt/solver/muz/rule-properties.ts +337 -0
  369. package/src/prover/smt/solver/muz/spacer-context.ts +1406 -0
  370. package/src/prover/smt/solver/muz/spacer-dl-interface.ts +52 -0
  371. package/src/prover/smt/solver/muz/spacer-generalizers.ts +241 -0
  372. package/src/prover/smt/solver/muz/spacer-manager.ts +127 -0
  373. package/src/prover/smt/solver/muz/spacer-pdr.ts +218 -0
  374. package/src/prover/smt/solver/muz/spacer-prop-solver.ts +333 -0
  375. package/src/prover/smt/solver/muz/spacer-util.ts +282 -0
  376. package/src/prover/smt/solver/muz/substitution.ts +203 -0
  377. package/src/prover/smt/solver/nla2bv-tactic.ts +285 -0
  378. package/src/prover/smt/solver/nlqsat.ts +484 -0
  379. package/src/prover/smt/solver/nlsat/algebraic.ts +177 -160
  380. package/src/prover/smt/solver/nlsat/atoms.ts +24 -24
  381. package/src/prover/smt/solver/nlsat/evaluator.ts +16 -22
  382. package/src/prover/smt/solver/nlsat/explain.ts +65 -69
  383. package/src/prover/smt/solver/nlsat/interval-set.ts +9 -51
  384. package/src/prover/smt/solver/nlsat/levelwise.ts +48 -135
  385. package/src/prover/smt/solver/nlsat/mpbq.ts +47 -14
  386. package/src/prover/smt/solver/nlsat/polynomial.ts +29 -161
  387. package/src/prover/smt/solver/nlsat/solver.ts +241 -110
  388. package/src/prover/smt/solver/nlsat/transcendental-eval.ts +310 -0
  389. package/src/prover/smt/solver/nlsat/transcendentals.ts +367 -0
  390. package/src/prover/smt/solver/nlsat/types.ts +0 -9
  391. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +1 -47
  392. package/src/prover/smt/solver/nlsat/upolynomial.ts +10 -93
  393. package/src/prover/smt/solver/nlsat-tactic.ts +82 -0
  394. package/src/prover/smt/solver/nnf.ts +107 -60
  395. package/src/prover/smt/solver/normalize-bounds.ts +53 -0
  396. package/src/prover/smt/solver/occf.ts +97 -0
  397. package/src/prover/smt/solver/opt-context.ts +787 -0
  398. package/src/prover/smt/solver/opt-nlsat.ts +375 -0
  399. package/src/prover/smt/solver/opt-pareto.ts +282 -0
  400. package/src/prover/smt/solver/opt-preprocess.ts +101 -0
  401. package/src/prover/smt/solver/opt-solver.ts +308 -0
  402. package/src/prover/smt/solver/opt-value.ts +55 -0
  403. package/src/prover/smt/solver/optsmt.ts +692 -0
  404. package/src/prover/smt/solver/parallel-tactic.ts +299 -0
  405. package/src/prover/smt/solver/pattern-inference.ts +21 -26
  406. package/src/prover/smt/solver/pb-rewriter.ts +284 -0
  407. package/src/prover/smt/solver/pb2bv-tactic.ts +540 -0
  408. package/src/prover/smt/solver/poly-rewriter.ts +204 -79
  409. package/src/prover/smt/solver/probes.ts +512 -0
  410. package/src/prover/smt/solver/propagate-values.ts +37 -30
  411. package/src/prover/smt/solver/proto-model.ts +650 -66
  412. package/src/prover/smt/solver/pull-quant.ts +28 -23
  413. package/src/prover/smt/solver/purify-arith.ts +632 -0
  414. package/src/prover/smt/solver/qe-arith-plugin.ts +1098 -0
  415. package/src/prover/smt/solver/qe-lite-der.ts +2 -31
  416. package/src/prover/smt/solver/qe-lite-fm.ts +4 -28
  417. package/src/prover/smt/solver/qe-lite.ts +39 -49
  418. package/src/prover/smt/solver/qe-mbp.ts +270 -0
  419. package/src/prover/smt/solver/qe.ts +1498 -0
  420. package/src/prover/smt/solver/qel.ts +25 -0
  421. package/src/prover/smt/solver/qi-queue.ts +0 -16
  422. package/src/prover/smt/solver/qsat.ts +814 -0
  423. package/src/prover/smt/solver/quant-hoist.ts +196 -0
  424. package/src/prover/smt/solver/quant-tactics.ts +17 -74
  425. package/src/prover/smt/solver/quantifier-analyzer.ts +26 -47
  426. package/src/prover/smt/solver/quantifier-manager.ts +8 -23
  427. package/src/prover/smt/solver/quasi-macros.ts +243 -0
  428. package/src/prover/smt/solver/random-gen.ts +0 -2
  429. package/src/prover/smt/solver/rational.ts +45 -8
  430. package/src/prover/smt/solver/recfun-decl-plugin.ts +261 -0
  431. package/src/prover/smt/solver/recfun-rewriter.ts +107 -0
  432. package/src/prover/smt/solver/reduce-args.ts +225 -0
  433. package/src/prover/smt/solver/reduce-bv-size.ts +119 -0
  434. package/src/prover/smt/solver/ref-vector.ts +0 -6
  435. package/src/prover/smt/solver/relevancy.ts +2 -16
  436. package/src/prover/smt/solver/rewriter-tpl.ts +52 -129
  437. package/src/prover/smt/solver/rewriter.ts +477 -120
  438. package/src/prover/smt/solver/rlimit.ts +39 -21
  439. package/src/prover/smt/solver/sat/asymm-branch.ts +325 -0
  440. package/src/prover/smt/solver/sat/big.ts +177 -0
  441. package/src/prover/smt/solver/sat/clause-use-list.ts +71 -0
  442. package/src/prover/smt/solver/sat/clause.ts +203 -0
  443. package/src/prover/smt/solver/sat/cleaner.ts +94 -0
  444. package/src/prover/smt/solver/sat/config.ts +122 -0
  445. package/src/prover/smt/solver/sat/consequences.ts +203 -0
  446. package/src/prover/smt/solver/sat/elim-eqs.ts +142 -0
  447. package/src/prover/smt/solver/sat/goal2sat.ts +526 -0
  448. package/src/prover/smt/solver/sat/inc-sat-solver.ts +378 -0
  449. package/src/prover/smt/solver/sat/model-converter.ts +136 -0
  450. package/src/prover/smt/solver/sat/pb-constraint.ts +261 -0
  451. package/src/prover/smt/solver/sat/pb-solver.ts +1577 -0
  452. package/src/prover/smt/solver/sat/probing.ts +170 -0
  453. package/src/prover/smt/solver/sat/sat-tactic.ts +43 -0
  454. package/src/prover/smt/solver/sat/sat2goal.ts +165 -0
  455. package/src/prover/smt/solver/sat/scc.ts +142 -0
  456. package/src/prover/smt/solver/sat/simplifier.ts +1618 -0
  457. package/src/prover/smt/solver/sat/solver.ts +2127 -0
  458. package/src/prover/smt/solver/sat/var-queue.ts +117 -0
  459. package/src/prover/smt/solver/sat/watch-list.ts +140 -0
  460. package/src/prover/smt/solver/search-tree.ts +284 -0
  461. package/src/prover/smt/solver/seq-axioms.ts +1010 -0
  462. package/src/prover/smt/solver/seq-decl-plugin.ts +819 -0
  463. package/src/prover/smt/solver/seq-derive.ts +1301 -0
  464. package/src/prover/smt/solver/seq-eq-approx.ts +236 -0
  465. package/src/prover/smt/solver/seq-eq-solver.ts +439 -0
  466. package/src/prover/smt/solver/seq-factory.ts +89 -0
  467. package/src/prover/smt/solver/seq-monadic.ts +728 -0
  468. package/src/prover/smt/solver/seq-range-predicate.ts +235 -0
  469. package/src/prover/smt/solver/seq-re-rewriter.ts +1170 -0
  470. package/src/prover/smt/solver/seq-re-util.ts +758 -0
  471. package/src/prover/smt/solver/seq-regex-bisim.ts +144 -0
  472. package/src/prover/smt/solver/seq-regex-live.ts +200 -0
  473. package/src/prover/smt/solver/seq-rewriter.ts +2402 -0
  474. package/src/prover/smt/solver/seq-skolem.ts +317 -0
  475. package/src/prover/smt/solver/seq-subset.ts +165 -0
  476. package/src/prover/smt/solver/seq-view-witness.ts +353 -0
  477. package/src/prover/smt/solver/smt-consequences.ts +297 -0
  478. package/src/prover/smt/solver/smt-kernel.ts +83 -0
  479. package/src/prover/smt/solver/smt-logics.ts +66 -0
  480. package/src/prover/smt/solver/smt-setup.ts +496 -0
  481. package/src/prover/smt/solver/smt2-printer.ts +765 -0
  482. package/src/prover/smt/solver/smtlib-parser.ts +3140 -365
  483. package/src/prover/smt/solver/smtlib-script.ts +1631 -0
  484. package/src/prover/smt/solver/solve-eqs.ts +929 -0
  485. package/src/prover/smt/solver/solver.ts +119 -39
  486. package/src/prover/smt/solver/sort.ts +1 -5
  487. package/src/prover/smt/solver/static-features.ts +314 -0
  488. package/src/prover/smt/solver/sticky-generations.ts +0 -6
  489. package/src/prover/smt/solver/tactic.ts +1986 -0
  490. package/src/prover/smt/solver/term-enumeration.ts +205 -0
  491. package/src/prover/smt/solver/theory-array.ts +1240 -0
  492. package/src/prover/smt/solver/theory-bv.ts +1200 -0
  493. package/src/prover/smt/solver/theory-char.ts +355 -0
  494. package/src/prover/smt/solver/theory-datatype.ts +598 -0
  495. package/src/prover/smt/solver/theory-finite-set.ts +30 -0
  496. package/src/prover/smt/solver/theory-fpa.ts +389 -0
  497. package/src/prover/smt/solver/theory-lra-axioms.ts +55 -25
  498. package/src/prover/smt/solver/theory-lra-bounds.ts +31 -11
  499. package/src/prover/smt/solver/theory-lra-final-check.ts +59 -91
  500. package/src/prover/smt/solver/theory-lra-internalize.ts +94 -53
  501. package/src/prover/smt/solver/theory-lra-model.ts +23 -53
  502. package/src/prover/smt/solver/theory-lra-propagate.ts +24 -40
  503. package/src/prover/smt/solver/theory-lra-state.ts +6 -27
  504. package/src/prover/smt/solver/theory-lra.ts +188 -8
  505. package/src/prover/smt/solver/theory-pb.ts +934 -0
  506. package/src/prover/smt/solver/theory-polymorphism.ts +58 -0
  507. package/src/prover/smt/solver/theory-recfun.ts +307 -0
  508. package/src/prover/smt/solver/theory-seq-regex.ts +867 -0
  509. package/src/prover/smt/solver/theory-seq-solve.ts +1373 -0
  510. package/src/prover/smt/solver/theory-seq-state.ts +871 -0
  511. package/src/prover/smt/solver/theory-seq.ts +961 -0
  512. package/src/prover/smt/solver/theory.ts +189 -0
  513. package/src/prover/smt/solver/tseitin-cnf.ts +485 -0
  514. package/src/prover/smt/solver/var-subst.ts +37 -39
  515. package/src/prover/smt/table.ts +3 -10
  516. package/src/prover/smt/types.ts +146 -0
  517. package/src/prover/tlapm/cache.ts +67 -41
  518. package/src/prover/tlapm/ocaml-marshal.ts +19 -21
  519. package/src/prover/tlapm/tlapm.ts +21 -20
  520. package/src/prover/tlapm-library.ts +3208 -0
  521. package/src/prover/verdict.ts +9 -2
  522. package/src/prover/zenon/check/check.ts +1 -11
  523. package/src/prover/zenon/check/definitions.ts +5 -15
  524. package/src/prover/zenon/check/equality.ts +0 -8
  525. package/src/prover/zenon/check/functions.ts +0 -4
  526. package/src/prover/zenon/check/keys.ts +0 -7
  527. package/src/prover/zenon/check/propositional.ts +0 -3
  528. package/src/prover/zenon/check/records.ts +1 -6
  529. package/src/prover/zenon/check/relations.ts +2 -14
  530. package/src/prover/zenon/check/rewrites.ts +2 -21
  531. package/src/prover/zenon/check/sets.ts +40 -61
  532. package/src/prover/zenon/check/terms.ts +1 -19
  533. package/src/prover/zenon/check/tla.ts +0 -6
  534. package/src/prover/zenon/decide.ts +10 -19
  535. package/src/prover/zenon/encode.ts +0 -9
  536. package/src/prover/zenon/eqrel.ts +2 -15
  537. package/src/prover/zenon/equality-rules.ts +0 -6
  538. package/src/prover/zenon/expr.ts +8 -28
  539. package/src/prover/zenon/index-table.ts +26 -59
  540. package/src/prover/zenon/isar-case.ts +8 -20
  541. package/src/prover/zenon/isar.ts +35 -65
  542. package/src/prover/zenon/limits.ts +0 -4
  543. package/src/prover/zenon/llproof.ts +2 -22
  544. package/src/prover/zenon/mltoll.ts +66 -106
  545. package/src/prover/zenon/node.ts +20 -15
  546. package/src/prover/zenon/ocaml.ts +1 -17
  547. package/src/prover/zenon/parse.ts +9 -13
  548. package/src/prover/zenon/phrase.ts +1 -13
  549. package/src/prover/zenon/proof.ts +0 -11
  550. package/src/prover/zenon/propositional-rules.ts +0 -7
  551. package/src/prover/zenon/rules.ts +2 -8
  552. package/src/prover/zenon/search.ts +11 -35
  553. package/src/prover/zenon/tla/functions.ts +59 -33
  554. package/src/prover/zenon/tla/llproof.ts +67 -78
  555. package/src/prover/zenon/tla/records.ts +57 -35
  556. package/src/prover/zenon/tla/rewrites.ts +12 -21
  557. package/src/prover/zenon/tla/sets.ts +88 -59
  558. package/src/prover/zenon/tla/terms.ts +0 -8
  559. package/src/prover/zenon/tla/tla.ts +66 -66
  560. package/src/randomization.ts +81 -35
  561. package/src/resolve.ts +67 -185
  562. package/src/runtime.ts +26 -22
  563. package/src/sany/builtins.ts +2 -5
  564. package/src/sany/generation.ts +394 -0
  565. package/src/sany/generator-def-entries.ts +210 -0
  566. package/src/sany/generator-definitions.ts +686 -0
  567. package/src/sany/generator-expressions.ts +1100 -0
  568. package/src/sany/generator-proofs.ts +662 -0
  569. package/src/sany/generator.ts +191 -2764
  570. package/src/sany/levels.ts +5 -35
  571. package/src/sany/lexer.ts +58 -77
  572. package/src/sany/linter.ts +0 -10
  573. package/src/sany/modules.ts +1 -5
  574. package/src/sany/nodes.ts +5 -43
  575. package/src/sany/parse-error.ts +39 -117
  576. package/src/sany/report.ts +32 -69
  577. package/src/sany/selectors.ts +49 -76
  578. package/src/sany/source.ts +1 -17
  579. package/src/sany/xml.ts +35 -117
  580. package/src/search.ts +671 -169
  581. package/src/simulate.ts +712 -0
  582. package/src/spec-description.ts +192 -100
  583. package/src/standard-definitions.ts +4 -4
  584. package/src/standard-modules.ts +264 -95
  585. package/src/state-graph.ts +52 -33
  586. package/src/subexpressions.ts +69 -52
  587. package/src/substitution-levels.ts +7 -7
  588. package/src/successors.ts +267 -100
  589. package/src/symmetry.ts +35 -27
  590. package/src/tableau.ts +29 -26
  591. package/src/tlc/fingerprint.ts +267 -79
  592. package/src/tlc/jar-data.ts +112 -6
  593. package/src/tlc/messages.ts +125 -54
  594. package/src/tlc/order.ts +39 -69
  595. package/src/tlc/random.ts +37 -49
  596. package/src/tlc/replay.ts +553 -228
  597. package/src/tlc/summary.ts +64 -60
  598. package/src/tlc/tlc-operators.ts +78 -44
  599. package/src/tlc/tlcext-operators.ts +171 -122
  600. package/src/tlc/trace-spec.ts +249 -0
  601. package/src/tlc/value-stream.ts +139 -0
  602. package/src/tlc/version.ts +1 -4
  603. package/src/transfer.ts +22 -25
  604. package/src/typed-tier.ts +6535 -0
  605. package/src/typescript/actions.ts +479 -0
  606. package/src/typescript/collections.ts +614 -0
  607. package/src/typescript/compile.ts +63 -0
  608. package/src/typescript/context.ts +94 -0
  609. package/src/typescript/emit.ts +121 -0
  610. package/src/typescript/expressions.ts +496 -0
  611. package/src/typescript/formula.ts +154 -0
  612. package/src/typescript/functions.ts +284 -0
  613. package/src/typescript/model.ts +162 -0
  614. package/src/typescript/names.ts +114 -0
  615. package/src/typescript/program.ts +48 -0
  616. package/src/typescript/properties.ts +139 -0
  617. package/src/typescript/scope.ts +112 -0
  618. package/src/typescript/steps.ts +167 -0
  619. package/src/typescript/types.ts +171 -0
  620. package/src/values.ts +832 -484
  621. package/src/worker.ts +7 -8
  622. package/src/prover/isabelle/isar/statement.ts +0 -57
  623. package/src/prover/smt/solver/z3-license.txt +0 -10
  624. package/src/prover/tlaps-module.ts +0 -510
  625. package/src/prover/zenon/LICENSE +0 -32
package/src/parser.ts CHANGED
@@ -35,16 +35,26 @@ 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;
38
+ interface TlapmOperand {
39
+ start: number;
40
+ end: number;
41
+ expression: Expression;
42
+ joinedBy?: string;
43
43
  }
44
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 };
45
+ interface TlapmOperator extends Precedence {
46
+ start: number;
47
+ end: number;
48
+ fixity: "Prefix" | "Infix" | "Postfix";
49
+ isLeft: boolean;
50
+ joins?: string;
51
+ apply: (operands: TlapmOperand[]) => Expression;
52
+ }
53
+
54
+ type TlapmItem = TlapmOperand | TlapmOperator;
55
+
56
+ const POSTFIX_PRECEDENCE = { low: 15, high: 15 };
57
+ const FUNCTION_PRECEDENCE = { low: 16, high: 16 };
48
58
 
49
59
  const createInfix = (low: number, high: number, isAssociative: boolean) => ({
50
60
  low,
@@ -152,11 +162,55 @@ const INFIX_OPERATORS = new Map<string, InfixOperator>([
152
162
 
153
163
  const NEGATION_PRECEDENCE = 12;
154
164
 
165
+ // tlapm's Optable has SANY's infix precedences, groups % and \X to the left with the operators
166
+ // SANY takes as associative, and has these prefix precedences. A function application and a field
167
+ // bind above every operator.
168
+ const isTlapmLeft = (text: string, infix: InfixOperator) =>
169
+ infix.isAssociative || text === "%" || text === "\\X";
170
+
171
+ const TLAPM_PREFIX_OPERATORS = new Map<string, Precedence>([
172
+ ["~", { low: 4, high: 4 }],
173
+ ["[]", { low: 4, high: 15 }],
174
+ ["<>", { low: 4, high: 15 }],
175
+ ["ENABLED", { low: 4, high: 15 }],
176
+ ["UNCHANGED", { low: 4, high: 15 }],
177
+ ["SUBSET", { low: 8, high: 8 }],
178
+ ["UNION", { low: 8, high: 8 }],
179
+ ["DOMAIN", { low: 9, high: 9 }],
180
+ ["-", { low: 12, high: 12 }],
181
+ ["-.", { low: 12, high: 12 }],
182
+ ]);
183
+
184
+ const TLAPM_SELECTION_PRECEDENCE = { low: 17, high: 17 };
185
+
186
+ const TLAPM_ATOM_STARTS = new Set([
187
+ "(",
188
+ "[",
189
+ "{",
190
+ "<<",
191
+ "@",
192
+ "\\A",
193
+ "\\E",
194
+ "\\AA",
195
+ "\\EE",
196
+ "IF",
197
+ "CASE",
198
+ "LET",
199
+ "CHOOSE",
200
+ "LAMBDA",
201
+ "WF_",
202
+ "SF_",
203
+ ]);
204
+
205
+ // The brackets whose contents tlapm reads without committing, so a failure in them backtracks.
206
+ const TLAPM_OPEN_BRACKETS = new Set(["(", "{", "<<"]);
207
+
155
208
  const POSTFIX_OPERATORS = new Set(["^+", "^*", "^#"]);
156
209
 
210
+ const DEFINABLE_POSTFIX_OPERATORS = new Set([...POSTFIX_OPERATORS, "'"]);
211
+
157
212
  const PREFIX_OPERATOR_REFERENCES = new Set(["-", "~", "-."]);
158
213
 
159
- // The prefix operators SANY reads in a definition's left-hand side, built-in ones included.
160
214
  const DEFINABLE_PREFIX_OPERATORS = new Set([
161
215
  "-.",
162
216
  "~",
@@ -193,8 +247,7 @@ const OPERATOR_ARGUMENTS = new Set([
193
247
  "UNCHANGED",
194
248
  "[]",
195
249
  "<>",
196
- "'",
197
- ...POSTFIX_OPERATORS,
250
+ ...DEFINABLE_POSTFIX_OPERATORS,
198
251
  ]);
199
252
 
200
253
  const SELECTOR_SYMBOLS = new Set(["<<", ">>", ":", "@", "("]);
@@ -259,6 +312,96 @@ const TLAPM_PUNCTUATION = new Set([
259
312
 
260
313
  const UNNAMED_STEP_LABELS = new Set(["", "*", "-"]);
261
314
 
315
+ interface Point {
316
+ line: number;
317
+ column: number;
318
+ }
319
+
320
+ interface Span {
321
+ start: Point;
322
+ stop: Point;
323
+ }
324
+
325
+ interface RangedName {
326
+ name: string;
327
+ range: SourceRange;
328
+ }
329
+
330
+ type Preproof =
331
+ | { kind: "Leaf"; proof: Proof; span: Span; first: number; end: number }
332
+ | {
333
+ kind: "Step";
334
+ token: Token;
335
+ isProof: boolean;
336
+ body: StepBody;
337
+ head: SourceRange;
338
+ statement: SourceRange;
339
+ span: Span;
340
+ first: number;
341
+ start: number;
342
+ end: number;
343
+ };
344
+
345
+ interface NestedProof {
346
+ proof: Proof | undefined;
347
+ span: Span;
348
+ next: number;
349
+ end: number | undefined;
350
+ }
351
+
352
+ interface NestedSteps {
353
+ level: number;
354
+ steps: ProofStep[];
355
+ span: Span;
356
+ next: number;
357
+ end: number;
358
+ }
359
+
360
+ const LEAF_NAMES: Record<string, string> = {
361
+ Obvious: "n OBVIOUS",
362
+ Omitted: "n OMITTED",
363
+ By: " BY",
364
+ };
365
+
366
+ const comparePoints = (left: Point, right: Point) =>
367
+ left.line - right.line || left.column - right.column;
368
+
369
+ const mergeSpans = (left: Span, right: Span): Span => ({
370
+ start: comparePoints(left.start, right.start) <= 0 ? left.start : right.start,
371
+ stop: comparePoints(left.stop, right.stop) >= 0 ? left.stop : right.stop,
372
+ });
373
+
374
+ const getSpan = (range: SourceRange): Span => ({
375
+ start: { line: range.start.line, column: range.start.column },
376
+ stop: { line: range.end.line, column: range.end.column + 1 },
377
+ });
378
+
379
+ interface ProofErrorEnds {
380
+ printed: string;
381
+ set: string;
382
+ }
383
+
384
+ const NO_NEWLINES: ProofErrorEnds = { printed: "", set: "" };
385
+
386
+ const PRINTED_NEWLINE: ProofErrorEnds = { printed: "\n", set: "" };
387
+
388
+ const NEWLINES: ProofErrorEnds = { printed: "\n", set: "\n" };
389
+
390
+ // p_parser.ml ends some of the messages it prints, and of those it sets, with a newline.
391
+ const createProofError = (
392
+ message: string,
393
+ span: Span,
394
+ ends: ProofErrorEnds,
395
+ exception = "Proof.Parser",
396
+ ) =>
397
+ new TlaSyntaxError(message, undefined, {
398
+ reason: `${message}${ends.set}`,
399
+ line: span.start.line,
400
+ column: span.start.column,
401
+ isEnd: false,
402
+ proof: { stop: span.stop, exception, printed: `${message}${ends.printed}` },
403
+ });
404
+
262
405
  const FACT_KEYWORDS = new Set([
263
406
  "CASE",
264
407
  "CHOOSE",
@@ -297,7 +440,6 @@ const BUILTIN_CONSTANTS = new Set(["TRUE", "FALSE", "BOOLEAN", "STRING"]);
297
440
 
298
441
  const NO_OFFSIDE = -1;
299
442
 
300
- // A SANY InfixExpr or PostfixExpr.
301
443
  const isOperatorExpression = (expression: Expression) =>
302
444
  expression.kind === "Prime" ||
303
445
  expression.kind === "Product" ||
@@ -307,6 +449,11 @@ const isOperatorExpression = (expression: Expression) =>
307
449
  ? INFIX_OPERATORS.has(expression.operator)
308
450
  : POSTFIX_OPERATORS.has(expression.operator)));
309
451
 
452
+ const isBullet = (token: Token) =>
453
+ (token.text === "/\\" || token.text === "\\/") &&
454
+ token.spelling !== "\\land" &&
455
+ token.spelling !== "\\lor";
456
+
310
457
  const isOperatorName = (text: string) =>
311
458
  INFIX_OPERATORS.has(text) || POSTFIX_OPERATORS.has(text) || text === "-.";
312
459
 
@@ -331,34 +478,37 @@ const getOperatorApplication = (
331
478
  }
332
479
  };
333
480
 
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
481
  export const extractModule = (source: string, name: string) => {
337
482
  const header = new RegExp(`^-{4,}\\s*MODULE\\s+${name}\\s*-{3,}$`);
338
- const lines = source.split(/\r?\n/);
483
+ const lines = source.replace(/\r?\n$/, "").split(/\r?\n/);
339
484
  const start = lines.findIndex((line) => header.test(line));
340
485
  if (start === -1) return undefined;
341
486
  const end = lines.findIndex((line, index) => index > start && line.startsWith("===="));
342
487
  return `${lines.slice(start, end === -1 ? undefined : end + 1).join("\n")}\n`;
343
488
  };
344
489
 
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
490
  type ParseMode = "tlc" | "tlapm" | "sany";
349
491
 
350
- const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source)): Module => {
492
+ const parse = (
493
+ source: string,
494
+ mode: ParseMode,
495
+ sourceTokens = tokenize(source, mode === "tlapm"),
496
+ ): Module => {
351
497
  const isTlapm = mode === "tlapm";
352
498
  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.
499
+ let cursor = 0;
500
+ const offsideColumns: number[] = [];
501
+ let lastOperator: Precedence | undefined;
502
+ let precedingOperator: Precedence | undefined;
356
503
  const recursiveScopes: Set<string>[] = [];
357
504
  const factNames = new Set<string>();
358
- // The NEW, TAKE, and PICK names in scope, which a DEF clause cannot cite.
359
505
  const proofScopes: Set<string>[] = [];
360
- // SANY reports a location in a nested module as one in the module of its file.
361
506
  const openModules: Module[] = [];
507
+ // Pco's backtracking: a failure not past a commit rewinds to its attempt's frame.
508
+ let attemptFrame: number | undefined;
509
+ let attemptCount = 0;
510
+ const restorePoints: number[] = [];
511
+ const backtracks = new WeakMap<TlaSyntaxError, number>();
362
512
 
363
513
  const isRecursiveName = (name: string) => recursiveScopes[recursiveScopes.length - 1].has(name);
364
514
 
@@ -372,7 +522,7 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
372
522
  const tokenEnds: SourceLocation[] = [];
373
523
  const tokenRanges: SourceRange[] = [];
374
524
 
375
- const getRange = (startIndex: number, endIndex = cursor.index - 1) => {
525
+ const getRange = (startIndex: number, endIndex = cursor - 1) => {
376
526
  const cached = startIndex === endIndex ? tokenRanges[startIndex] : undefined;
377
527
  if (cached) return cached;
378
528
  const last = tokens[endIndex];
@@ -387,17 +537,16 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
387
537
  return range;
388
538
  };
389
539
 
390
- // Each node gets its own location object from getLocation, so the range can be set in place.
391
540
  const withRange = <Node extends { location: SourceLocation }>(node: Node, startIndex: number) => {
392
541
  node.location.range = getRange(startIndex);
393
542
  return node;
394
543
  };
395
544
 
396
- const peekRaw = (offset = 0) => tokens[Math.min(cursor.index + offset, tokens.length - 1)];
545
+ const peekRaw = (offset = 0) => tokens[Math.min(cursor + offset, tokens.length - 1)];
397
546
 
398
547
  const peek = (offset = 0) => {
399
548
  const token = peekRaw(offset);
400
- const offsideColumn = cursor.offsideColumns[cursor.offsideColumns.length - 1];
549
+ const offsideColumn = offsideColumns[offsideColumns.length - 1];
401
550
  if (offsideColumn === undefined || offsideColumn === NO_OFFSIDE || token.kind === "End") {
402
551
  return token;
403
552
  }
@@ -407,20 +556,10 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
407
556
  const describeToken = (token: Token) =>
408
557
  token.kind === "End" ? "end of input" : JSON.stringify(token.text);
409
558
 
410
- const unitStart = { index: 0 };
411
-
412
- const getDefinitionEnd = (fallback: { line: number; column: number }) => {
413
- const equals = tokens
414
- .slice(unitStart.index, cursor.index)
415
- .find((token) => token.text === "==" && token.kind !== "String");
416
- return equals ? { line: equals.line, column: equals.endColumn + 1 } : fallback;
417
- };
418
-
419
- // tlapm reads TRUE, FALSE, BOOLEAN, STRING and the other keywords only as keywords.
420
559
  const isTlapmKeyword = (token: Token) =>
421
560
  isTlapm && (token.kind === "Keyword" || BUILTIN_CONSTANTS.has(token.text));
422
561
 
423
- const getPreviousEnd = (position: { line: number; column: number }) => {
562
+ const getPreviousEnd = (position: Point) => {
424
563
  const previous = tokens.findLast(
425
564
  (token) =>
426
565
  token.kind !== "End" &&
@@ -431,53 +570,89 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
431
570
  };
432
571
 
433
572
  const getTlapmName = (token: Token) => {
573
+ if (token.kind === "End") return "EOF";
434
574
  if (/^-{4,}$/.test(token.text)) return "----";
435
575
  if (/^={4,}$/.test(token.text)) return "====";
436
576
  if (TLAPM_PUNCTUATION.has(token.text) || token.kind === "Number" || token.kind === "Decimal")
437
577
  return token.text;
438
578
  if (token.kind === "String") return JSON.stringify(token.text);
579
+ if (token.kind === "Step") return token.text;
439
580
  if (isTlapmKeyword(token)) return `keyword ${token.text}`;
440
581
  return token.kind === "Identifier" ? `identifier ${token.text}` : `operator ${token.text}`;
441
582
  };
442
583
 
443
- const createError = (
444
- message: string,
445
- token: { line: number; column: number } = peekRaw(),
446
- unexpected?: Token,
447
- ) => {
584
+ const createError = (message: string, token: Point = peekRaw(), unexpected?: Token) => {
448
585
  const end = tokens[tokens.length - 1];
449
586
  const isEnd = token.line === end.line && token.column === end.column;
450
- return new TlaSyntaxError(
587
+ const error = new TlaSyntaxError(
451
588
  `${message} at line ${token.line}, column ${token.column}`,
452
589
  undefined,
453
590
  getFailure(message, token, isEnd, unexpected),
454
591
  );
592
+ if (attemptFrame !== undefined) backtracks.set(error, attemptFrame);
593
+ return error;
455
594
  };
456
595
 
596
+ // tlapm reports a failure after the last token it read before the outermost attempt around it.
457
597
  const getFailure = (
458
598
  message: string,
459
- token: { line: number; column: number },
599
+ token: Point,
460
600
  isEnd: boolean,
461
601
  unexpected: Token | undefined,
462
602
  ) => {
463
- if (isTlapm && isEnd) {
464
- const end = tokens[tokens.length - 1];
465
- return { reason: "Unexpected EOF", ...getDefinitionEnd(getPreviousEnd(end)), isEnd };
466
- }
467
- if (isTlapm && unexpected) {
468
- return {
469
- reason: `Unexpected ${getTlapmName(unexpected)}`,
470
- ...getPreviousEnd(unexpected),
471
- isEnd,
472
- };
473
- }
474
- return { reason: message, line: token.line, column: token.column, isEnd };
603
+ if (!isTlapm) return { reason: message, line: token.line, column: token.column, isEnd };
604
+ const restored = tokens[restorePoints[0] - 1];
605
+ const reason = unexpected ? `Unexpected ${getTlapmName(unexpected)}` : message;
606
+ if (restored) return { reason, line: restored.line, column: restored.endColumn + 1, isEnd };
607
+ const position = unexpected ? getPreviousEnd(unexpected) : token;
608
+ return { reason, line: position.line, column: position.column, isEnd };
475
609
  };
476
610
 
477
611
  const createUnexpected = (message: string, token: Token = peekRaw()) =>
478
612
  createError(message, token, token);
479
613
 
480
- // TLAplusParser.isFieldNameToken: a keyword or an underscore names a field or a module too.
614
+ // Pco.attempt: a failure that backtracks to it leaves the input as it was, and gives undefined.
615
+ const attempt = <Result>(parse: () => Result): Result | undefined => {
616
+ const saved = {
617
+ cursor,
618
+ frame: attemptFrame,
619
+ restorePoints: restorePoints.length,
620
+ offsideColumns: offsideColumns.length,
621
+ recursiveScopes: recursiveScopes.length,
622
+ };
623
+ const frame = ++attemptCount;
624
+ attemptFrame = frame;
625
+ try {
626
+ const result = parse();
627
+ attemptFrame = saved.frame;
628
+ return result;
629
+ } catch (error) {
630
+ if (!(error instanceof TlaSyntaxError) || backtracks.get(error) !== frame) throw error;
631
+ cursor = saved.cursor;
632
+ attemptFrame = saved.frame;
633
+ restorePoints.length = saved.restorePoints;
634
+ offsideColumns.length = saved.offsideColumns;
635
+ recursiveScopes.length = saved.recursiveScopes;
636
+ return undefined;
637
+ }
638
+ };
639
+
640
+ // Pco.commit: a failure in parse no longer backtracks.
641
+ const commit = <Result>(parse: () => Result) => {
642
+ const frame = attemptFrame;
643
+ attemptFrame = undefined;
644
+ const result = parse();
645
+ attemptFrame = frame;
646
+ return result;
647
+ };
648
+
649
+ const withRestorePoint = <Result>(parse: () => Result) => {
650
+ restorePoints.push(cursor);
651
+ const result = parse();
652
+ restorePoints.pop();
653
+ return result;
654
+ };
655
+
481
656
  const isFieldName = (token: Token) =>
482
657
  (token.kind === "Identifier" ||
483
658
  token.kind === "Keyword" ||
@@ -491,14 +666,14 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
491
666
 
492
667
  const advance = () => {
493
668
  const token = peek();
494
- if (token.kind === "End") throw createError("Unexpected end of expression");
495
- cursor.index++;
669
+ if (token.kind === "End") throw createUnexpected("Unexpected end of expression");
670
+ cursor++;
496
671
  return token;
497
672
  };
498
673
 
499
674
  const accept = (text: string) => {
500
675
  if (!isAt(text)) return false;
501
- cursor.index++;
676
+ cursor++;
502
677
  return true;
503
678
  };
504
679
 
@@ -514,49 +689,44 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
514
689
  throw createUnexpected(`Expected an identifier but found ${describeToken(token)}`);
515
690
  }
516
691
  if (isTlapmKeyword(token)) throw createUnexpected(`Unexpected keyword ${token.text}`);
517
- cursor.index++;
692
+ cursor++;
518
693
  return token.text;
519
694
  };
520
695
 
521
696
  const expectName = () => {
522
- const start = cursor.index;
697
+ const start = cursor;
523
698
  return { name: expectIdentifier(), range: getRange(start) };
524
699
  };
525
700
 
526
- const getNames = (names: { name: string; range: SourceRange }[]) => ({
527
- names: names.map((item) => item.name),
528
- ranges: names.map((item) => item.range),
701
+ const getNames = (names: RangedName[]) => ({
702
+ names: names.map((named) => named.name),
703
+ ranges: names.map((named) => named.range),
529
704
  });
530
705
 
531
- // TLAplusParser.Substitution: an identifier, or a prefix, infix or postfix operator.
532
706
  const expectSubstitutionTarget = () => {
533
707
  const token = peek();
534
708
  const isOperator =
535
709
  token.kind !== "String" &&
536
710
  (DEFINABLE_PREFIX_OPERATORS.has(token.text) ||
537
711
  INFIX_OPERATORS.has(token.text) ||
538
- POSTFIX_OPERATORS.has(token.text) ||
539
- token.text === "'");
712
+ DEFINABLE_POSTFIX_OPERATORS.has(token.text));
540
713
  if (!isOperator) return expectIdentifier();
541
- cursor.index++;
714
+ cursor++;
542
715
  return token.text;
543
716
  };
544
717
 
545
- // SANY takes a keyword for the name of a module, as it does for a field.
546
- const keywordModuleName = { isUsed: false };
718
+ let isKeywordModuleName = false;
547
719
  const expectModuleName = () => {
548
720
  if (peek().kind === "Identifier" || !isFieldName(peek())) return expectIdentifier();
549
- keywordModuleName.isUsed = true;
721
+ isKeywordModuleName = true;
550
722
  return advance().text;
551
723
  };
552
724
 
553
- // tlapm reads a bracketed expression apart from the junction list around it, whose alignment
554
- // SANY keeps applying.
555
725
  const withBracketLayout = <Result>(parse: () => Result) => {
556
726
  if (!isTlapm) return parse();
557
- cursor.offsideColumns.push(NO_OFFSIDE);
727
+ offsideColumns.push(NO_OFFSIDE);
558
728
  const result = parse();
559
- cursor.offsideColumns.pop();
729
+ offsideColumns.pop();
560
730
  return result;
561
731
  };
562
732
 
@@ -566,17 +736,17 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
566
736
  return items;
567
737
  };
568
738
 
569
- const isBoundAhead = () => {
570
- 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);
739
+ const isBoundAhead = (start = 0) => {
740
+ if (isAt("<<", start)) {
741
+ let offset = start + 1;
742
+ while (peek(offset).kind === "Identifier" || isAt(",", offset)) offset++;
743
+ return isAt(">>", offset) && isAt("\\in", offset + 1);
574
744
  }
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;
745
+ let offset = start;
746
+ while (peek(offset).kind === "Identifier") {
747
+ if (isAt("\\in", offset + 1)) return true;
748
+ if (!isAt(",", offset + 1)) return false;
749
+ offset += 2;
580
750
  }
581
751
  return false;
582
752
  };
@@ -584,14 +754,9 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
584
754
  const isLabelAhead = () => {
585
755
  if (isAt("::")) return true;
586
756
  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
- );
757
+ let offset = 1;
758
+ while (peek(offset).kind === "Identifier" && isAt(",", offset + 1)) offset += 2;
759
+ return peek(offset).kind === "Identifier" && isAt(")", offset + 1) && isAt("::", offset + 2);
595
760
  };
596
761
 
597
762
  const parsePattern = (): BoundPattern => {
@@ -599,34 +764,80 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
599
764
  const named = expectName();
600
765
  return { kind: "Name", name: named.name, ranges: [named.range] };
601
766
  }
602
- const names = getNames(parseSeparated(expectName));
767
+ const names = getNames(isAt(">>") ? [] : parseSeparated(expectName));
603
768
  expect(">>");
604
769
  return { kind: "Tuple", names: names.names, ranges: names.ranges };
605
770
  };
606
771
 
607
- const parseBounds = () =>
608
- parseSeparated(() => {
772
+ // tlapm's func_boundeds reads another bound only where names and \in follow the comma.
773
+ const parseBounds = () => {
774
+ const parseBound = () => {
609
775
  const patterns = parseSeparated(parsePattern);
610
776
  expect("\\in");
611
- const set = parseExpression();
777
+ const set = commit(parseExpression);
612
778
  return patterns.map((pattern) => ({ pattern, set }));
613
- }).flat();
779
+ };
780
+ const bounds = [parseBound()];
781
+ while (isAt(",") && (!isTlapm || isBoundAhead(1))) {
782
+ advance();
783
+ bounds.push(parseBound());
784
+ }
785
+ return bounds.flat();
786
+ };
614
787
 
615
- const parseSubscript = (): Expression => {
788
+ const parseSubscript = (): { subscript: Expression; lastArgs: Expression[] } => {
616
789
  const token = peek();
790
+ if (isTlapm && BUILTIN_CONSTANTS.has(token.text)) {
791
+ const start = cursor;
792
+ advance();
793
+ const constant: Expression = {
794
+ kind: "Identifier",
795
+ name: token.text,
796
+ location: getLocation(token),
797
+ };
798
+ return { subscript: withRange(constant, start), lastArgs: [] };
799
+ }
800
+ const isTlapmAtom =
801
+ isTlapm && (token.kind === "Number" || token.kind === "String" || isAt("@"));
617
802
  if (token.kind === "Identifier") {
618
- const start = cursor.index;
619
- const names = [advance().text];
803
+ const start = cursor;
804
+ const names: string[] = [];
805
+ const selectorRanges: SourceRange[] = [];
806
+ const parseElement = (isApplicable: boolean) => {
807
+ selectorRanges.push(getRange(cursor, cursor));
808
+ names.push(expectIdentifier());
809
+ return isApplicable && isAt("(") ? parseArguments() : [];
810
+ };
811
+ const elementArgs = [parseElement(!isTlapm)];
620
812
  while (isAt("!") && peek(1).kind === "Identifier") {
621
813
  advance();
622
- names.push(expectIdentifier());
814
+ elementArgs.push(parseElement(true));
623
815
  }
624
- return withRange(
625
- { kind: "Identifier", name: names.join("!"), location: getLocation(token) },
626
- start,
627
- );
816
+ const prefixArgs = elementArgs.slice(0, -1);
817
+ const location = getLocation(token);
818
+ location.range = { ...getRange(start), end: selectorRanges[selectorRanges.length - 1].end };
819
+ const name = names.join("!");
820
+ const subscript: Expression = prefixArgs.every((args) => args.length === 0)
821
+ ? { kind: "Identifier", name, location }
822
+ : {
823
+ kind: "Apply",
824
+ operator: name,
825
+ args: prefixArgs.flat(),
826
+ argumentCounts: [...prefixArgs.map((args) => args.length), 0],
827
+ argumentsRange: location.range,
828
+ selectorRanges,
829
+ location,
830
+ };
831
+ return { subscript, lastArgs: elementArgs[elementArgs.length - 1] };
832
+ }
833
+ if (isAt("<<") || isAt("(") || isAt("{") || isAt("[") || isTlapmAtom) {
834
+ const start = cursor;
835
+ const subscript = parsePrimary();
836
+ return {
837
+ subscript: subscript.location.range ? subscript : withRange(subscript, start),
838
+ lastArgs: [],
839
+ };
628
840
  }
629
- if (isAt("<<") || isAt("(")) return parsePrimary();
630
841
  throw createUnexpected(`Expected a subscript but found ${describeToken(token)}`);
631
842
  };
632
843
 
@@ -640,12 +851,11 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
640
851
  token.kind === "Identifier" &&
641
852
  (next.text === "(" ||
642
853
  next.text === "[" ||
643
- (next.kind === "Operator" && isAt("==", POSTFIX_OPERATORS.has(next.text) ? 3 : 4)))
854
+ (next.kind === "Operator" &&
855
+ isAt("==", DEFINABLE_POSTFIX_OPERATORS.has(next.text) ? 3 : 4)))
644
856
  );
645
857
  };
646
858
 
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
859
  const isStandalone = (operator: Token) => {
650
860
  const token = peek(1);
651
861
  return (
@@ -665,8 +875,6 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
665
875
  token.kind === "Operator" &&
666
876
  (INFIX_OPERATORS.has(token.text) || PREFIX_OPERATOR_REFERENCES.has(token.text)) &&
667
877
  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
878
  const isTlapmIncomplete =
671
879
  isTlapm &&
672
880
  token.kind !== "String" &&
@@ -682,8 +890,11 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
682
890
  peek(1).line === token.line &&
683
891
  peek(1).column === token.endColumn + 1));
684
892
  if (isTlapmIncomplete && isStandalone(token)) throw createError("incomplete expression", token);
893
+ if (isOperatorAlone && !isTlapm && token.text === "\\X" && token.spelling !== "×") {
894
+ throw createError("\\X may not be used as an infix operator", token);
895
+ }
685
896
  if (isOperatorAlone) {
686
- cursor.index++;
897
+ cursor++;
687
898
  return withRange(
688
899
  {
689
900
  kind: "OperatorReference",
@@ -691,18 +902,18 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
691
902
  spelling: token.spelling,
692
903
  location: getLocation(token),
693
904
  },
694
- cursor.index - 1,
905
+ cursor - 1,
695
906
  );
696
907
  }
697
908
  const isPrefixAlone =
698
909
  token.kind !== "String" && OPERATOR_ARGUMENTS.has(token.text) && isStandalone(token);
699
910
  if (isPrefixAlone) {
700
- cursor.index++;
911
+ cursor++;
701
912
  const location = getLocation(token);
702
913
  if (POSTFIX_OPERATORS.has(token.text)) {
703
914
  return withRange(
704
915
  { kind: "OperatorReference", operator: token.text, spelling: token.spelling, location },
705
- cursor.index - 1,
916
+ cursor - 1,
706
917
  );
707
918
  }
708
919
  const argument: Expression = { kind: "Identifier", name: "argument", location };
@@ -714,11 +925,11 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
714
925
  operator: token.text,
715
926
  location: getLocation(token),
716
927
  },
717
- cursor.index - 1,
928
+ cursor - 1,
718
929
  );
719
930
  }
720
931
  if (isAt("LAMBDA")) {
721
- const start = cursor.index;
932
+ const start = cursor;
722
933
  advance();
723
934
  const params = getNames(parseSeparated(expectName));
724
935
  expect(":");
@@ -734,30 +945,43 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
734
945
  start,
735
946
  );
736
947
  }
737
- return parseExpression();
948
+ if (!isTlapm) return parseExpression();
949
+ // tlapm's oparg reads an operator where an expression doesn't start, and fails otherwise.
950
+ const argument = attempt(parseExpression);
951
+ if (argument) return argument;
952
+ throw createUnexpected(`Unexpected ${describeToken(peek())}`);
738
953
  };
739
954
 
740
- const lastArguments: { range: SourceRange | undefined } = { range: undefined };
955
+ let lastArgumentsRange: SourceRange | undefined;
741
956
 
742
957
  const parseArguments = () =>
743
958
  withBracketLayout(() => {
744
- const start = cursor.index;
959
+ const start = cursor;
745
960
  expect("(");
746
961
  const args = parseSeparated(parseArgument);
747
962
  expect(")");
748
- lastArguments.range = getRange(start);
963
+ lastArgumentsRange = getRange(start);
749
964
  return args;
750
965
  });
751
966
 
752
967
  const parseJunctionList = (): Expression => {
753
968
  const bullet = advance();
754
- cursor.offsideColumns.push(bullet.column);
969
+ offsideColumns.push(bullet.column);
755
970
  const operands = [parseExpression()];
756
- while (peekRaw().text === bullet.text && peekRaw().column === bullet.column) {
757
- cursor.index++;
758
- operands.push(parseExpression());
759
- }
760
- cursor.offsideColumns.pop();
971
+ const parseItems = () => {
972
+ while (
973
+ isBullet(peekRaw()) &&
974
+ peekRaw().text === bullet.text &&
975
+ peekRaw().column === bullet.column
976
+ ) {
977
+ cursor++;
978
+ operands.push(parseExpression());
979
+ }
980
+ };
981
+ // bulleted_list: a first item that fails leaves expr_or_op's other readings to fail after it.
982
+ if (isTlapm) commit(parseItems);
983
+ else parseItems();
984
+ offsideColumns.pop();
761
985
  return {
762
986
  kind: bullet.text === "/\\" ? "And" : "Or",
763
987
  operands,
@@ -769,13 +993,12 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
769
993
  const parseBracket = (start: Token): Expression =>
770
994
  withBracketLayout(() => {
771
995
  const location = getLocation(start);
772
- // SANY takes a keyword for the first field of a record, as it does for a selected field.
773
996
  const isIdentifier = peek().kind === "Identifier";
774
997
  const isRecord = isAt("|->", 1) && (isIdentifier || isFieldName(peek()));
775
998
  if (isRecord || (isIdentifier && isAt(":", 1))) {
776
999
  const kind = isRecord ? "Record" : "RecordSet";
777
1000
  const parseField = (readName: () => string) => {
778
- const fieldStart = cursor.index;
1001
+ const fieldStart = cursor;
779
1002
  const fieldLocation = getLocation(peek());
780
1003
  const name = readName();
781
1004
  fieldLocation.range = getRange(fieldStart);
@@ -790,11 +1013,15 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
790
1013
  return { kind, fields, location };
791
1014
  }
792
1015
  if (isBoundAhead()) {
1016
+ const checkpoint = cursor;
793
1017
  const bounds = parseBounds();
794
- expect("|->");
795
- const body = parseExpression();
796
- expect("]");
797
- return { kind: "FunctionConstruction", bounds, body, location };
1018
+ if (!isTlapm || isAt("|->")) {
1019
+ expect("|->");
1020
+ const body = parseExpression();
1021
+ expect("]");
1022
+ return { kind: "FunctionConstruction", bounds, body, location };
1023
+ }
1024
+ cursor = checkpoint;
798
1025
  }
799
1026
  const expression = parseExpression();
800
1027
  if (accept("->")) {
@@ -810,6 +1037,7 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
810
1037
  if (accept(".")) {
811
1038
  if (!isFieldName(peek()))
812
1039
  throw createUnexpected(`Expected a field name but found ${describeToken(peek())}`);
1040
+ if (!isTlapm && isAt("@")) throw createUnexpected("@ used in !.@");
813
1041
  path.push({ kind: "Field", name: advance().text });
814
1042
  continue;
815
1043
  }
@@ -830,16 +1058,20 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
830
1058
  return { kind: "Bracket", args, location };
831
1059
  }
832
1060
  expect("]_");
833
- return { kind: "BoxAction", action: expression, subscript: parseSubscript(), location };
1061
+ return {
1062
+ kind: "BoxAction",
1063
+ action: expression,
1064
+ subscript: parseSubscript().subscript,
1065
+ location,
1066
+ };
834
1067
  });
835
1068
 
836
- // SANY reads the set after the \in of {x \in S} as a whole expression, whatever operators it has.
837
1069
  const parseSetMembership = (): Expression => {
838
- const start = cursor.index;
1070
+ const start = cursor;
839
1071
  const element = withRange(parsePrefix(), start);
840
1072
  const location = getLocation(advance());
841
1073
  return withRange(
842
- { kind: "Apply", operator: "\\in", args: [element, parseExpression()], location },
1074
+ { kind: "Apply", operator: "\\in", args: [element, commit(parseExpression)], location },
843
1075
  start,
844
1076
  );
845
1077
  };
@@ -849,16 +1081,16 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
849
1081
  const location = getLocation(start);
850
1082
  if (accept("}")) return { kind: "SetEnumeration", elements: [], location };
851
1083
  if (isBoundAhead() && (peek(1).text === "\\in" || isAt("<<"))) {
852
- const checkpoint = cursor.index;
1084
+ const checkpoint = cursor;
853
1085
  const pattern = parsePattern();
854
1086
  expect("\\in");
855
- const set = parseExpression();
1087
+ const set = commit(parseExpression);
856
1088
  if (accept(":")) {
857
- const predicate = parseExpression();
1089
+ const predicate = commit(parseExpression);
858
1090
  expect("}");
859
1091
  return { kind: "SetFilter", bound: { pattern, set }, predicate, location };
860
1092
  }
861
- cursor.index = checkpoint;
1093
+ cursor = checkpoint;
862
1094
  }
863
1095
  const first =
864
1096
  peek().kind === "Identifier" && isAt("\\in", 1) ? parseSetMembership() : parseExpression();
@@ -881,7 +1113,12 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
881
1113
  if (accept(">>_")) {
882
1114
  if (elements.length !== 1)
883
1115
  throw createError("Expected a single action inside <<A>>_v", start);
884
- return { kind: "AngleAction", action: elements[0], subscript: parseSubscript(), location };
1116
+ return {
1117
+ kind: "AngleAction",
1118
+ action: elements[0],
1119
+ subscript: commit(parseSubscript).subscript,
1120
+ location,
1121
+ };
885
1122
  }
886
1123
  expect(">>");
887
1124
  return { kind: "Tuple", elements, location };
@@ -912,9 +1149,17 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
912
1149
  const parseCase = (start: Token): Expression => {
913
1150
  const arms: CaseArm[] = [];
914
1151
  do {
1152
+ const otherStart = cursor;
915
1153
  if (accept("OTHER")) {
916
1154
  expect("->");
917
- return { kind: "Case", arms, other: parseExpression(), location: getLocation(start) };
1155
+ const other = parseExpression();
1156
+ return {
1157
+ kind: "Case",
1158
+ arms,
1159
+ other,
1160
+ otherRange: getRange(otherStart),
1161
+ location: getLocation(start),
1162
+ };
918
1163
  }
919
1164
  const condition = parseExpression();
920
1165
  expect("->");
@@ -931,9 +1176,9 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
931
1176
  next.kind === "Number" ||
932
1177
  SELECTOR_SYMBOLS.has(next.text) ||
933
1178
  (next.kind === "Operator" &&
934
- (INFIX_OPERATORS.has(next.text) ||
935
- POSTFIX_OPERATORS.has(next.text) ||
936
- PREFIX_OPERATOR_REFERENCES.has(next.text))))
1179
+ (INFIX_OPERATORS.has(next.text) || DEFINABLE_POSTFIX_OPERATORS.has(next.text))) ||
1180
+ ((next.kind === "Operator" || next.kind === "Keyword") &&
1181
+ DEFINABLE_PREFIX_OPERATORS.has(next.text)))
937
1182
  );
938
1183
  };
939
1184
 
@@ -949,7 +1194,7 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
949
1194
  case "@":
950
1195
  return { kind: "At" };
951
1196
  case "(": {
952
- cursor.index--;
1197
+ cursor--;
953
1198
  return { kind: "Bound", args: parseArguments() };
954
1199
  }
955
1200
  }
@@ -957,7 +1202,7 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
957
1202
  };
958
1203
 
959
1204
  const parsePrimary = (preceding?: Precedence): Expression => {
960
- const start = cursor.index;
1205
+ const start = cursor;
961
1206
  const token = advance();
962
1207
  const location = getLocation(token);
963
1208
  if (isTlapm && token.kind === "Keyword" && token.text === "LAMBDA") {
@@ -965,14 +1210,12 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
965
1210
  expect(":");
966
1211
  return { kind: "Lambda", params, body: parseExpression(), location };
967
1212
  }
968
- if (token.kind === "Number") {
969
- if (isTlapm && /^\\[BOH]/.test(token.text)) throw createError("incomplete expression", token);
1213
+ if (token.kind === "Number")
970
1214
  return { kind: "Number", value: getNumeralValue(token.text), text: token.text, location };
971
- }
972
1215
  if (token.kind === "Decimal") return { kind: "Decimal", text: token.text, location };
973
1216
  if (token.kind === "String") return { kind: "String", value: token.text, location };
974
1217
  const isStep = token.kind === "Step" && isStepReference(token);
975
- if (isStep && getProofLevel() < 0 && proofLevels.length <= 1) {
1218
+ if (!isTlapm && isStep && getProofLevel() < 0 && proofLevels.length <= 1) {
976
1219
  throw createError("Step number used outside proof", token);
977
1220
  }
978
1221
  if (isStep && token.text[1] === "+") {
@@ -984,14 +1227,14 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
984
1227
  const params = getNames(accept("(") ? parseSeparated(expectName) : []);
985
1228
  if (params.names.length > 0) expect(")");
986
1229
  expect("::");
1230
+ const head = getRange(start);
987
1231
  const body = parseExpression();
988
- // TLAplusParser.labelDoesNotChangeParse.
989
1232
  if (
990
1233
  !isTlapm &&
991
1234
  preceding !== undefined &&
992
- operators.last !== undefined &&
1235
+ lastOperator !== undefined &&
993
1236
  isOperatorExpression(body) &&
994
- preceding.high >= operators.last.low
1237
+ preceding.high >= lastOperator.low
995
1238
  ) {
996
1239
  throw createError("Removing the label would change expression parsing", token);
997
1240
  }
@@ -1000,6 +1243,7 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1000
1243
  name,
1001
1244
  params: params.names,
1002
1245
  paramRanges: params.ranges,
1246
+ head,
1003
1247
  body,
1004
1248
  location,
1005
1249
  };
@@ -1008,20 +1252,20 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1008
1252
  if (name === "@" && !hasArguments && !isSelectorAhead())
1009
1253
  return { kind: "ExceptAt", location };
1010
1254
  const args = hasArguments ? parseArguments() : [];
1011
- const argumentRanges = [hasArguments ? lastArguments.range : undefined];
1255
+ const argumentRanges = [hasArguments ? lastArgumentsRange : undefined];
1012
1256
  if (!isSelectorAhead()) {
1013
1257
  return hasArguments
1014
- ? { kind: "Apply", operator: name, args, argumentsRange: lastArguments.range, location }
1258
+ ? { kind: "Apply", operator: name, args, argumentsRange: lastArgumentsRange, location }
1015
1259
  : { kind: "Identifier", name, location };
1016
1260
  }
1017
1261
  const selectors: Selector[] = [{ kind: "Name", name, args }];
1018
1262
  const selectorRanges = [getRange(start, start)];
1019
1263
  while (isSelectorAhead()) {
1020
1264
  advance();
1021
- selectorRanges.push(getRange(cursor.index, cursor.index));
1022
- lastArguments.range = undefined;
1265
+ selectorRanges.push(getRange(cursor, cursor));
1266
+ lastArgumentsRange = undefined;
1023
1267
  selectors.push(parseSelector());
1024
- argumentRanges.push(lastArguments.range);
1268
+ argumentRanges.push(lastArgumentsRange);
1025
1269
  }
1026
1270
  const names = selectors.flatMap((selector) =>
1027
1271
  selector.kind === "Name" ? [selector.name] : [],
@@ -1049,15 +1293,12 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1049
1293
  location,
1050
1294
  };
1051
1295
  }
1052
- // SANY reads an infix or postfix operator as a primary expression, with or without arguments.
1053
1296
  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
- };
1297
+ const args = parseArguments();
1298
+ // Deviation from TLC: SANY's built-in \X has no definition for TLC to evaluate, a TLC bug.
1299
+ return mode === "tlc" && token.text === "\\X" && args.length === 2
1300
+ ? { kind: "Product", factors: args, location }
1301
+ : { kind: "Apply", operator: token.text, spelling: token.spelling, args, location };
1061
1302
  }
1062
1303
  if (token.kind === "Operator" && isOperatorName(token.text) && !isTlapm) {
1063
1304
  return { kind: "Identifier", name: token.text, spelling: token.spelling, location };
@@ -1095,13 +1336,12 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1095
1336
  const instances: Instance[] = [];
1096
1337
  recursiveScopes.push(new Set());
1097
1338
  while (!accept("IN")) {
1098
- if (isTlapm && isAt("RECURSIVE"))
1099
- throw createError("Unexpected keyword RECURSIVE", getDefinitionEnd(peekRaw()));
1339
+ if (isTlapm && isAt("RECURSIVE")) throw createUnexpected("Unexpected keyword RECURSIVE");
1100
1340
  if (accept("RECURSIVE")) {
1101
1341
  declareRecursive();
1102
1342
  continue;
1103
1343
  }
1104
- const unit = parseDefinition(false);
1344
+ const unit = parseDefinition(!isTlapm && accept("LOCAL"));
1105
1345
  if (unit.kind === "Instance") instances.push(unit);
1106
1346
  else definitions.push(unit);
1107
1347
  }
@@ -1120,15 +1360,18 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1120
1360
  case "WF_":
1121
1361
  case "SF_": {
1122
1362
  const subscript = parseSubscript();
1123
- const action = withBracketLayout(() => {
1124
- expect("(");
1125
- const expression = parseExpression();
1126
- expect(")");
1127
- return expression;
1128
- });
1363
+ const action =
1364
+ !isAt("(") && subscript.lastArgs.length === 1
1365
+ ? subscript.lastArgs[0]
1366
+ : withBracketLayout(() => {
1367
+ expect("(");
1368
+ const expression = parseExpression();
1369
+ expect(")");
1370
+ return expression;
1371
+ });
1129
1372
  return {
1130
1373
  kind: token.text === "WF_" ? "WeakFairness" : "StrongFairness",
1131
- subscript,
1374
+ subscript: subscript.subscript,
1132
1375
  action,
1133
1376
  location,
1134
1377
  };
@@ -1137,28 +1380,25 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1137
1380
  throw createUnexpected(`Unexpected ${describeToken(token)}`, token);
1138
1381
  };
1139
1382
 
1140
- // SANY rejects the operator after a prefix operator's operand unless it binds looser than the
1141
- // prefix operator.
1142
1383
  const parsePrefixOperand = (operator: Token, low: number, high: number) => {
1143
- operators.last = operators.preceding = { low, high };
1384
+ lastOperator = precedingOperator = { low, high };
1144
1385
  const operand = parseExpression(high + 1);
1145
1386
  const next = peek();
1146
- const nextHigh =
1147
- next.text === "'" || POSTFIX_OPERATORS.has(next.text)
1148
- ? POSTFIX_PRECEDENCE.high
1149
- : INFIX_OPERATORS.get(next.text)?.high;
1150
- if (!isTlapm && next.kind === "Operator" && nextHigh !== undefined && nextHigh >= low) {
1387
+ const nextHigh = DEFINABLE_POSTFIX_OPERATORS.has(next.text)
1388
+ ? POSTFIX_PRECEDENCE.high
1389
+ : INFIX_OPERATORS.get(next.text)?.high;
1390
+ if (next.kind === "Operator" && nextHigh !== undefined && nextHigh >= low) {
1151
1391
  throw createError(`Precedence conflict between ${operator.text} and ${next.text}`, next);
1152
1392
  }
1153
1393
  return operand;
1154
1394
  };
1155
1395
 
1156
1396
  const parsePrefix = (): Expression => {
1157
- const preceding = operators.preceding;
1158
- operators.preceding = undefined;
1397
+ const preceding = precedingOperator;
1398
+ precedingOperator = undefined;
1159
1399
  const token = peek();
1160
1400
  const location = getLocation(token);
1161
- if (token.kind === "Operator" && (token.text === "/\\" || token.text === "\\/")) {
1401
+ if (token.kind === "Operator" && isBullet(token)) {
1162
1402
  return parseJunctionList();
1163
1403
  }
1164
1404
  if (token.kind === "Operator" || token.kind === "Keyword") {
@@ -1180,17 +1420,11 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1180
1420
  location,
1181
1421
  };
1182
1422
  case "[]":
1183
- advance();
1184
- return { kind: "Always", expression: parsePrefixOperand(token, 4, 15), location };
1185
1423
  case "<>":
1186
- advance();
1187
- return { kind: "Eventually", expression: parsePrefixOperand(token, 4, 15), location };
1188
1424
  case "ENABLED":
1189
- advance();
1190
- return { kind: "Enabled", expression: parsePrefixOperand(token, 4, 15), location };
1191
1425
  case "UNCHANGED":
1192
1426
  advance();
1193
- return { kind: "Unchanged", expression: parsePrefixOperand(token, 4, 15), location };
1427
+ return getOperatorApplication(token.text, parsePrefixOperand(token, 4, 15), location);
1194
1428
  case "SUBSET":
1195
1429
  case "UNION":
1196
1430
  case "DOMAIN":
@@ -1198,8 +1432,7 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1198
1432
  return {
1199
1433
  kind: "Apply",
1200
1434
  operator: token.text,
1201
- // tlapm gives these operators the precedence 8 of the TLA+ book, and SANY 10-13.
1202
- args: [isTlapm ? parseExpression(9) : parsePrefixOperand(token, 10, 13)],
1435
+ args: [parsePrefixOperand(token, 10, 13)],
1203
1436
  location,
1204
1437
  };
1205
1438
  }
@@ -1207,58 +1440,85 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1207
1440
  return parsePrimary(preceding);
1208
1441
  };
1209
1442
 
1210
- const parseExpression = (minimumPrecedence = 0): Expression => {
1211
- const start = cursor.index;
1212
- const prefix = parsePrefix();
1213
- const state = {
1214
- left: prefix.location.range ? prefix : withRange(prefix, start),
1215
- previous: undefined as (InfixOperator & { text: string }) | undefined,
1443
+ const getInfixApplication = (
1444
+ token: Token,
1445
+ left: Expression,
1446
+ right: Expression,
1447
+ isChained: boolean,
1448
+ prefixEnd: Point,
1449
+ ): Expression => {
1450
+ const location = getLocation(token);
1451
+ if (token.text === "/\\" || token.text === "\\/") {
1452
+ const kind = token.text === "/\\" ? "And" : "Or";
1453
+ return left.kind === kind && isChained
1454
+ ? {
1455
+ ...left,
1456
+ operands: [...left.operands, right],
1457
+ prefixEnds: [...(left.prefixEnds ?? []), prefixEnd],
1458
+ }
1459
+ : { kind, operands: [left, right], prefixEnds: [prefixEnd], location };
1460
+ }
1461
+ if (token.text === "\\X") {
1462
+ return left.kind === "Product" && isChained
1463
+ ? { ...left, factors: [...left.factors, right] }
1464
+ : { kind: "Product", factors: [left, right], location };
1465
+ }
1466
+ return {
1467
+ kind: "Apply",
1468
+ operator: token.text,
1469
+ spelling: token.spelling,
1470
+ args: [left, right],
1471
+ location,
1216
1472
  };
1473
+ };
1474
+
1475
+ const getPostfixApplication = (token: Token, operand: Expression): Expression =>
1476
+ token.text === "'"
1477
+ ? { kind: "Prime", expression: operand, location: getLocation(token) }
1478
+ : {
1479
+ kind: "Apply",
1480
+ operator: token.text,
1481
+ spelling: token.spelling,
1482
+ args: [operand],
1483
+ location: getLocation(token),
1484
+ };
1485
+
1486
+ const parseFunctionArguments = () => {
1487
+ advance();
1488
+ const args = withBracketLayout(() => parseSeparated(() => parseExpression()));
1489
+ withBracketLayout(() => expect("]"));
1490
+ return args;
1491
+ };
1492
+
1493
+ const parseSanyExpression = (minimumPrecedence: number): Expression => {
1494
+ const start = cursor;
1495
+ const prefix = parsePrefix();
1496
+ let left = prefix.location.range ? prefix : withRange(prefix, start);
1497
+ let previous: (InfixOperator & { text: string }) | undefined;
1217
1498
  while (true) {
1218
1499
  const token = peek();
1219
1500
  if (token.kind !== "Operator") break;
1220
1501
  const location = getLocation(token);
1221
- if (token.text === "'" && minimumPrecedence <= 15) {
1222
- advance();
1223
- operators.last = POSTFIX_PRECEDENCE;
1224
- state.left = withRange({ kind: "Prime", expression: state.left, location }, start);
1225
- continue;
1226
- }
1227
- if (POSTFIX_OPERATORS.has(token.text) && minimumPrecedence <= 15) {
1502
+ if (DEFINABLE_POSTFIX_OPERATORS.has(token.text) && minimumPrecedence <= 15) {
1228
1503
  advance();
1229
- operators.last = POSTFIX_PRECEDENCE;
1230
- state.left = withRange(
1231
- {
1232
- kind: "Apply",
1233
- operator: token.text,
1234
- spelling: token.spelling,
1235
- args: [state.left],
1236
- location,
1237
- },
1238
- start,
1239
- );
1504
+ lastOperator = POSTFIX_PRECEDENCE;
1505
+ left = withRange(getPostfixApplication(token, left), start);
1240
1506
  continue;
1241
1507
  }
1242
1508
  if (token.text === "[") {
1243
- advance();
1244
- const args = withBracketLayout(() => parseSeparated(() => parseExpression()));
1245
- withBracketLayout(() => expect("]"));
1246
- operators.last = FUNCTION_PRECEDENCE;
1247
- state.left = withRange(
1248
- { kind: "FunctionApplication", function: state.left, args, location },
1249
- start,
1250
- );
1509
+ const args = parseFunctionArguments();
1510
+ lastOperator = FUNCTION_PRECEDENCE;
1511
+ left = withRange({ kind: "FunctionApplication", function: left, args, location }, start);
1251
1512
  continue;
1252
1513
  }
1253
1514
  if (token.text === "." && isFieldName(peek(1))) {
1254
1515
  advance();
1255
1516
  const field = advance().text;
1256
- state.left = withRange({ kind: "FieldAccess", record: state.left, field, location }, start);
1517
+ left = withRange({ kind: "FieldAccess", record: left, field, location }, start);
1257
1518
  continue;
1258
1519
  }
1259
1520
  const infix = INFIX_OPERATORS.get(token.text);
1260
1521
  if (!infix || infix.low < minimumPrecedence) break;
1261
- const previous = state.previous;
1262
1522
  if (previous) {
1263
1523
  const isOverlapping = !(previous.low > infix.high || previous.high < infix.low);
1264
1524
  const isChain = previous.text === token.text && infix.isAssociative;
@@ -1270,44 +1530,260 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1270
1530
  }
1271
1531
  }
1272
1532
  advance();
1273
- // SANY reads - after an infix operator as prefix -, and rejects it after one that binds tighter.
1274
1533
  if (infix.low > NEGATION_PRECEDENCE && isAt("-")) {
1275
1534
  throw createError(`Precedence conflict between ${token.text} and -`, peek());
1276
1535
  }
1277
- operators.last = operators.preceding = infix;
1536
+ lastOperator = precedingOperator = infix;
1278
1537
  const right = parseExpression(infix.high + 1);
1279
- const left = state.left;
1280
- if (token.text === "/\\" || token.text === "\\/") {
1281
- const kind = token.text === "/\\" ? "And" : "Or";
1282
- const prefixEnds = [getRange(start).end];
1283
- state.left =
1284
- left.kind === kind && previous?.text === token.text
1285
- ? {
1286
- ...left,
1287
- operands: [...left.operands, right],
1288
- prefixEnds: [...(left.prefixEnds ?? []), ...prefixEnds],
1289
- }
1290
- : { kind, operands: [left, right], prefixEnds, location };
1291
- } else if (token.text === "\\X") {
1292
- state.left =
1293
- left.kind === "Product" && previous?.text === "\\X"
1294
- ? { ...left, factors: [...left.factors, right] }
1295
- : { kind: "Product", factors: [left, right], location };
1296
- } else {
1297
- state.left = {
1298
- kind: "Apply",
1299
- operator: token.text,
1300
- spelling: token.spelling,
1301
- args: [left, right],
1538
+ const isChained = previous?.text === token.text;
1539
+ left = withRange(
1540
+ getInfixApplication(token, left, right, isChained, getRange(start).end),
1541
+ start,
1542
+ );
1543
+ previous = { ...infix, text: token.text };
1544
+ }
1545
+ return left;
1546
+ };
1547
+
1548
+ const isTlapmAtomStart = (token: Token) =>
1549
+ token.kind === "Number" ||
1550
+ token.kind === "Decimal" ||
1551
+ token.kind === "String" ||
1552
+ token.kind === "Identifier" ||
1553
+ (token.kind === "Step" && isStepReference(token) && /^<\d/.test(token.text)) ||
1554
+ ((token.kind === "Operator" || token.kind === "Keyword") && TLAPM_ATOM_STARTS.has(token.text));
1555
+
1556
+ const getTlapmOperand = (expression: Expression, start: number): TlapmOperand => ({
1557
+ start,
1558
+ end: cursor - 1,
1559
+ expression: expression.location.range ? expression : withRange(expression, start),
1560
+ });
1561
+
1562
+ const getTlapmOperator = (
1563
+ start: number,
1564
+ fixity: TlapmOperator["fixity"],
1565
+ precedence: Precedence,
1566
+ apply: TlapmOperator["apply"],
1567
+ ): TlapmOperator => ({
1568
+ ...precedence,
1569
+ start,
1570
+ end: cursor - 1,
1571
+ fixity,
1572
+ isLeft: false,
1573
+ apply,
1574
+ });
1575
+
1576
+ // expr_or_op's non_test: a postfix operator before an expression in parentheses is an atom.
1577
+ const parseTlapmNonfixPostfix = (token: Token) =>
1578
+ token.kind === "Operator" && DEFINABLE_POSTFIX_OPERATORS.has(token.text) && isAt("(", 1)
1579
+ ? attempt(() =>
1580
+ withBracketLayout(() => {
1581
+ advance();
1582
+ advance();
1583
+ const operand = parseExpression();
1584
+ const end = cursor - 1;
1585
+ expect(")");
1586
+ return { end, expression: getPostfixApplication(token, operand) };
1587
+ }),
1588
+ )
1589
+ : undefined;
1590
+
1591
+ // A comma directly inside the parentheses after the operator, without which non_test's
1592
+ // attempt at `(e, f)` fails. A selector's << or >> isn't a bracket.
1593
+ const hasNonfixComma = () => {
1594
+ let depth = 0;
1595
+ for (let index = cursor + 1; index < tokens.length; index++) {
1596
+ const token = tokens[index];
1597
+ if (token.kind !== "Operator") continue;
1598
+ if (depth === 1 && token.text === ",") return true;
1599
+ if (tokens[index - 1].text === "!") continue;
1600
+ if (OPENING_BRACKETS.has(token.text)) depth++;
1601
+ if (CLOSING_BRACKETS.has(token.text) && --depth === 0) return false;
1602
+ }
1603
+ return false;
1604
+ };
1605
+
1606
+ // expr_or_op's non_test: an infix operator before two expressions in parentheses is an atom.
1607
+ const parseTlapmNonfixInfix = (token: Token) =>
1608
+ isAt("(", 1) && hasNonfixComma()
1609
+ ? attempt(() =>
1610
+ withBracketLayout((): Expression => {
1611
+ advance();
1612
+ advance();
1613
+ const left = parseExpression();
1614
+ expect(",");
1615
+ const right = parseExpression();
1616
+ expect(")");
1617
+ return {
1618
+ kind: "Apply",
1619
+ operator: token.text,
1620
+ args: [left, right],
1621
+ location: getLocation(token),
1622
+ };
1623
+ }),
1624
+ )
1625
+ : undefined;
1626
+
1627
+ const parseTlapmItem = (isStart: boolean): TlapmItem | undefined => {
1628
+ const start = cursor;
1629
+ const token = peek();
1630
+ const location = getLocation(token);
1631
+ const isOperator = token.kind === "Operator" || token.kind === "Keyword";
1632
+ const infix = isOperator ? INFIX_OPERATORS.get(token.text) : undefined;
1633
+ if (!isStart) {
1634
+ if (isAt("[")) {
1635
+ const args = parseFunctionArguments();
1636
+ return getTlapmOperator(start, "Postfix", TLAPM_SELECTION_PRECEDENCE, (operands) => ({
1637
+ kind: "FunctionApplication",
1638
+ function: operands[0].expression,
1639
+ args,
1302
1640
  location,
1641
+ }));
1642
+ }
1643
+ if (isAt(".") && isFieldName(peek(1))) {
1644
+ advance();
1645
+ const field = advance().text;
1646
+ return getTlapmOperator(start, "Postfix", TLAPM_SELECTION_PRECEDENCE, (operands) => ({
1647
+ kind: "FieldAccess",
1648
+ record: operands[0].expression,
1649
+ field,
1650
+ location,
1651
+ }));
1652
+ }
1653
+ if (infix) {
1654
+ // Pco.resolve has no operator to put before that atom, so the expression ends here.
1655
+ if (parseTlapmNonfixInfix(token)) {
1656
+ cursor = start;
1657
+ return undefined;
1658
+ }
1659
+ advance();
1660
+ return {
1661
+ ...getTlapmOperator(start, "Infix", infix, (operands) =>
1662
+ getInfixApplication(
1663
+ token,
1664
+ operands[0].expression,
1665
+ operands[1].expression,
1666
+ operands[0].joinedBy === token.text,
1667
+ getRange(operands[0].start, operands[1].end).end,
1668
+ ),
1669
+ ),
1670
+ isLeft: isTlapmLeft(token.text, infix),
1671
+ joins: token.text,
1303
1672
  };
1304
1673
  }
1305
- state.left = withRange(state.left, start);
1306
- state.previous = { ...infix, text: token.text };
1674
+ if (token.kind !== "Operator" || !DEFINABLE_POSTFIX_OPERATORS.has(token.text))
1675
+ return undefined;
1676
+ // Pco.resolve has no operator to put before that atom, so the expression ends here.
1677
+ if (parseTlapmNonfixPostfix(token)) {
1678
+ cursor = start;
1679
+ return undefined;
1680
+ }
1681
+ advance();
1682
+ return getTlapmOperator(start, "Postfix", POSTFIX_PRECEDENCE, (operands) =>
1683
+ getPostfixApplication(token, operands[0].expression),
1684
+ );
1685
+ }
1686
+ if (token.kind === "Operator" && isBullet(token))
1687
+ return getTlapmOperand(parseJunctionList(), start);
1688
+ const nonfix = infix ? parseTlapmNonfixInfix(token) : undefined;
1689
+ if (nonfix) return getTlapmOperand(nonfix, start);
1690
+ const nonfixPostfix = parseTlapmNonfixPostfix(token);
1691
+ if (nonfixPostfix) {
1692
+ nonfixPostfix.expression.location.range = getRange(start, nonfixPostfix.end);
1693
+ return { start, end: nonfixPostfix.end, expression: nonfixPostfix.expression };
1307
1694
  }
1308
- return state.left;
1695
+ const prefix = isOperator ? TLAPM_PREFIX_OPERATORS.get(token.text) : undefined;
1696
+ if (prefix) {
1697
+ advance();
1698
+ return getTlapmOperator(start, "Prefix", prefix, (operands) =>
1699
+ getOperatorApplication(
1700
+ token.text === "-" ? "-." : token.text,
1701
+ operands[0].expression,
1702
+ location,
1703
+ ),
1704
+ );
1705
+ }
1706
+ if (!isTlapmAtomStart(token)) return undefined;
1707
+ const isTransparent = token.kind === "Operator" && TLAPM_OPEN_BRACKETS.has(token.text);
1708
+ return getTlapmOperand(isTransparent ? parsePrimary() : commit(parsePrimary), start);
1709
+ };
1710
+
1711
+ const isTlapmOperator = (item: TlapmItem | undefined): item is TlapmOperator =>
1712
+ item !== undefined && "fixity" in item;
1713
+
1714
+ const isTlapmOperand = (item: TlapmItem | undefined): item is TlapmOperand =>
1715
+ item !== undefined && !("fixity" in item);
1716
+
1717
+ const applyTlapmOperator = (operator: TlapmOperator, operands: TlapmOperand[]) => {
1718
+ const start = Math.min(operator.start, operands[0].start);
1719
+ const end = Math.max(operator.end, operands[operands.length - 1].end);
1720
+ const expression = operator.apply(operands);
1721
+ expression.location.range = getRange(start, end);
1722
+ return { start, end, expression, joinedBy: operator.joins };
1723
+ };
1724
+
1725
+ const reduceTlapmItems = (stack: TlapmItem[]) => {
1726
+ const right = stack.pop();
1727
+ const operator = stack.pop();
1728
+ if (!isTlapmOperand(right) || !isTlapmOperator(operator)) {
1729
+ throw createError("incomplete expression");
1730
+ }
1731
+ const left = operator.fixity === "Infix" ? stack.pop() : undefined;
1732
+ stack.push(applyTlapmOperator(operator, isTlapmOperand(left) ? [left, right] : [right]));
1733
+ };
1734
+
1735
+ const getPreviousOperator = (stack: TlapmItem[]) => {
1736
+ const previous = stack[stack.length - 2];
1737
+ return isTlapmOperator(previous) ? previous : undefined;
1309
1738
  };
1310
1739
 
1740
+ const isBelow = (left: Precedence, right: Precedence | undefined) =>
1741
+ right !== undefined && left.high < right.low;
1742
+
1743
+ // Port of Pco.resolve. A failure after the first item backtracks no further than its attempt.
1744
+ const parseTlapmExpression = (): Expression =>
1745
+ withRestorePoint(() => {
1746
+ const first = attempt(() => parseTlapmItem(true));
1747
+ if (first === undefined) {
1748
+ const token = peekRaw();
1749
+ throw token.kind === "End"
1750
+ ? createUnexpected("Unexpected end of expression", token)
1751
+ : createError(`required expressions(s) missing before '${getTlapmName(token)}'`, token);
1752
+ }
1753
+ return commit(() => {
1754
+ const stack = [first];
1755
+ while (true) {
1756
+ const item = attempt(() => parseTlapmItem(isTlapmOperator(stack[stack.length - 1])));
1757
+ if (item === undefined) break;
1758
+ if (isTlapmOperand(item) || item.fixity === "Prefix") {
1759
+ stack.push(item);
1760
+ continue;
1761
+ }
1762
+ while (isBelow(item, getPreviousOperator(stack))) reduceTlapmItems(stack);
1763
+ const operand = stack[stack.length - 1];
1764
+ if (item.fixity === "Postfix" && isTlapmOperand(operand)) {
1765
+ stack.splice(-1, 1, applyTlapmOperator(item, [operand]));
1766
+ continue;
1767
+ }
1768
+ const previous = getPreviousOperator(stack);
1769
+ const isLeftChain =
1770
+ previous?.fixity === "Infix" &&
1771
+ previous.isLeft &&
1772
+ item.isLeft &&
1773
+ !isBelow(previous, item);
1774
+ if (isLeftChain) reduceTlapmItems(stack);
1775
+ stack.push(item);
1776
+ }
1777
+ while (stack.length > 1) reduceTlapmItems(stack);
1778
+ const result = stack[0];
1779
+ if (!isTlapmOperand(result)) throw createError("incomplete expression");
1780
+ return result.expression;
1781
+ });
1782
+ });
1783
+
1784
+ const parseExpression = (minimumPrecedence = 0) =>
1785
+ isTlapm ? parseTlapmExpression() : parseSanyExpression(minimumPrecedence);
1786
+
1311
1787
  const parseParams = () => {
1312
1788
  if (!accept("(")) return [];
1313
1789
  const params = parseDeclarations();
@@ -1318,17 +1794,17 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1318
1794
  const parseBody = () => {
1319
1795
  const start = getLocation(peek());
1320
1796
  const body = parseExpression();
1321
- const last = tokens[cursor.index - 1];
1797
+ const last = tokens[cursor - 1];
1322
1798
  const end = { line: last.line, column: last.endColumn };
1323
1799
  return { body, bodyRange: { module: openModules[0].name, start, end } };
1324
1800
  };
1325
1801
 
1326
1802
  const parseDefinition = (isLocal: boolean): Definition | Instance => {
1327
- const start = cursor.index;
1803
+ const start = cursor;
1328
1804
  return withRange(parseDefinitionUnit(isLocal), start);
1329
1805
  };
1330
1806
 
1331
- const toParam = (named: { name: string; range: SourceRange }): OperatorParam => ({
1807
+ const toParam = (named: RangedName): OperatorParam => ({
1332
1808
  name: named.name,
1333
1809
  arity: 0,
1334
1810
  location: {
@@ -1340,11 +1816,13 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1340
1816
 
1341
1817
  const parseDefinitionUnit = (isLocal: boolean): Definition | Instance => {
1342
1818
  const token = peek();
1819
+ const start = cursor;
1343
1820
  const location = getLocation(token);
1344
1821
  const parseOperator = (name: string, params: OperatorParam[]): Definition => ({
1345
1822
  kind: "Operator",
1346
1823
  name,
1347
1824
  params,
1825
+ head: getRange(start, cursor - 2),
1348
1826
  ...parseBody(),
1349
1827
  isLocal,
1350
1828
  isRecursive: isRecursiveName(name),
@@ -1366,7 +1844,7 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1366
1844
  const isPrefixDefinition =
1367
1845
  token.kind !== "String" && DEFINABLE_PREFIX_OPERATORS.has(token.text);
1368
1846
  const isPostfixDefinition =
1369
- token.kind === "Identifier" && POSTFIX_OPERATORS.has(peek(1).text) && isAt("==", 2);
1847
+ token.kind === "Identifier" && DEFINABLE_POSTFIX_OPERATORS.has(peek(1).text) && isAt("==", 2);
1370
1848
  if (isPrefixDefinition || isPostfixDefinition) {
1371
1849
  const operator = isPrefixDefinition ? token.text : peek(1).text;
1372
1850
  if (isPrefixDefinition) advance();
@@ -1390,7 +1868,7 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1390
1868
  location,
1391
1869
  };
1392
1870
  }
1393
- const definitionStart = cursor.index;
1871
+ const definitionStart = cursor;
1394
1872
  const params = parseParams();
1395
1873
  expect("==");
1396
1874
  if (isAt("INSTANCE")) {
@@ -1406,12 +1884,12 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1406
1884
  isLocal: boolean,
1407
1885
  location: SourceLocation,
1408
1886
  ): Instance => {
1409
- const start = cursor.index;
1887
+ const start = cursor;
1410
1888
  expect("INSTANCE");
1411
1889
  const module = expectModuleName();
1412
1890
  const substitutions = accept("WITH")
1413
1891
  ? parseSeparated(() => {
1414
- const targetStart = cursor.index;
1892
+ const targetStart = cursor;
1415
1893
  const target = expectSubstitutionTarget();
1416
1894
  const nameRange = getRange(targetStart);
1417
1895
  expect("<-");
@@ -1431,7 +1909,7 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1431
1909
  };
1432
1910
 
1433
1911
  const parseDeclaration = (): Declaration => {
1434
- const start = cursor.index;
1912
+ const start = cursor;
1435
1913
  return withRange(parseDeclarationUnit(), start);
1436
1914
  };
1437
1915
 
@@ -1442,7 +1920,10 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1442
1920
  const name = advance().text;
1443
1921
  return { name, arity: accept("_") ? 2 : 1, location };
1444
1922
  }
1445
- if (peek().kind === "Operator" && isAt("_", 1)) {
1923
+ const isPrefixOperator =
1924
+ peek().kind !== "String" &&
1925
+ (DEFINABLE_PREFIX_OPERATORS.has(peek().text) || (isTlapm && peek().kind === "Operator"));
1926
+ if (isPrefixOperator && isAt("_", 1)) {
1446
1927
  const operator = advance().text;
1447
1928
  advance();
1448
1929
  return { name: operator === "-" ? "-." : operator, arity: 1, location };
@@ -1464,19 +1945,19 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1464
1945
  return declarations;
1465
1946
  };
1466
1947
 
1467
- const getClosingOffset = (offset: number) => {
1468
- const depth = { value: 0, offset };
1948
+ const getClosingOffset = (start: number) => {
1949
+ let depth = 0;
1950
+ let offset = start;
1469
1951
  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;
1952
+ const token = peek(offset);
1953
+ if (token.kind === "End") return offset;
1954
+ if (token.kind === "Operator" && OPENING_BRACKETS.has(token.text)) depth++;
1955
+ if (token.kind === "Operator" && CLOSING_BRACKETS.has(token.text)) depth--;
1956
+ offset++;
1957
+ } while (depth > 0);
1958
+ return offset;
1477
1959
  };
1478
1960
 
1479
- // SANY inserts a break before each definition, which ends the fact list or step before it.
1480
1961
  const isDefinitionStart = () => {
1481
1962
  const token = peek();
1482
1963
  const next = peek(1);
@@ -1489,14 +1970,14 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1489
1970
  );
1490
1971
  }
1491
1972
  if (isAt("(", 1) || isAt("[", 1)) return isAt("==", getClosingOffset(1));
1492
- if (next.kind === "Operator" && POSTFIX_OPERATORS.has(next.text)) return isAt("==", 2);
1973
+ if (next.kind === "Operator" && DEFINABLE_POSTFIX_OPERATORS.has(next.text))
1974
+ return isAt("==", 2);
1493
1975
  if (next.kind === "Operator" && INFIX_OPERATORS.has(next.text)) {
1494
1976
  return peek(2).kind === "Identifier" && isAt("==", 3);
1495
1977
  }
1496
1978
  return isAt("==", 1);
1497
1979
  };
1498
1980
 
1499
- // SANY's proof levels, one for each open proof, which stay -1 until a step sets them.
1500
1981
  const proofLevels: number[] = [];
1501
1982
 
1502
1983
  const getProofLevel = () => proofLevels[proofLevels.length - 1] ?? -1;
@@ -1509,9 +1990,9 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1509
1990
 
1510
1991
  const getStepLabel = (step: Token) => {
1511
1992
  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);
1993
+ let end = label.length;
1994
+ while (label[end - 1] === ".") end--;
1995
+ return label.slice(0, end);
1515
1996
  };
1516
1997
 
1517
1998
  const isStepReference = (step: Token) =>
@@ -1574,17 +2055,15 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1574
2055
  return !isDefinitionStart();
1575
2056
  };
1576
2057
 
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
2058
  const parseFact = (): Fact => {
1580
- const start = cursor.index;
2059
+ const start = cursor;
1581
2060
  const token = peek();
1582
2061
  if (
1583
2062
  token.kind === "Operator" &&
1584
2063
  !EXPRESSION_PREFIXES.has(token.text) &&
1585
2064
  isOperatorName(token.text)
1586
2065
  ) {
1587
- cursor.index++;
2066
+ cursor++;
1588
2067
  return withRange(
1589
2068
  {
1590
2069
  kind: "OperatorReference",
@@ -1619,9 +2098,8 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1619
2098
  module.variables.some((variable) => variable.name === name),
1620
2099
  );
1621
2100
 
1622
- // tlapm's definable: names and operators joined by !.
1623
2101
  const parseDefinable = (): Fact => {
1624
- const start = cursor.index;
2102
+ const start = cursor;
1625
2103
  const token = peek();
1626
2104
  const parts = parseSeparated(() => {
1627
2105
  const part = peek();
@@ -1629,7 +2107,7 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1629
2107
  if (!isName && part.kind !== "Operator") {
1630
2108
  throw createUnexpected(`Expected a definition name but found ${describeToken(part)}`, part);
1631
2109
  }
1632
- cursor.index++;
2110
+ cursor++;
1633
2111
  return part.text;
1634
2112
  }, "!");
1635
2113
  const location = getLocation(token);
@@ -1654,13 +2132,33 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1654
2132
  return defs;
1655
2133
  };
1656
2134
 
1657
- const parseFacts = () => ({
1658
- facts: isFactAhead() ? parseSeparated(parseFact) : [],
1659
- defs: accept("DEF") || accept("DEFS") ? parseDefs() : [],
1660
- });
2135
+ // tlapm's usebody reads facts while an expression starts after the comma.
2136
+ const parseTlapmFacts = (): Fact[] => {
2137
+ const first = attempt(parseExpression);
2138
+ if (!first) return [];
2139
+ const facts = [first];
2140
+ withRestorePoint(() => {
2141
+ while (isAt(",")) {
2142
+ const fact = attempt(() => {
2143
+ advance();
2144
+ return parseExpression();
2145
+ });
2146
+ if (!fact) return;
2147
+ facts.push(fact);
2148
+ }
2149
+ });
2150
+ return facts;
2151
+ };
2152
+
2153
+ const parseFacts = () => {
2154
+ const facts = isTlapm ? parseTlapmFacts() : isFactAhead() ? parseSeparated(parseFact) : [];
2155
+ const isDef = accept("DEF") || accept("DEFS");
2156
+ if (isTlapm && facts.length === 0 && !isDef) throw createUnexpected("Expected a fact");
2157
+ return { facts, defs: isDef ? parseDefs() : [] };
2158
+ };
1661
2159
 
1662
2160
  const parseUseOrHide = (): UseOrHide => {
1663
- const start = cursor.index;
2161
+ const start = cursor;
1664
2162
  const keyword = advance();
1665
2163
  const isOnly = keyword.text === "USE" && accept("ONLY");
1666
2164
  const keywordRange = getRange(start);
@@ -1686,9 +2184,11 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1686
2184
  };
1687
2185
 
1688
2186
  const parseNewSymbol = (): NewSymbol => {
1689
- const start = cursor.index;
1690
- const location = getLocation(peek());
2187
+ const newStart = cursor;
2188
+ const newLocation = getLocation(peek());
1691
2189
  const isNew = accept("NEW");
2190
+ const start = isTlapm ? cursor : newStart;
2191
+ const location = isTlapm ? getLocation(peek()) : newLocation;
1692
2192
  const level = peek().kind === "Keyword" ? NEW_SYMBOL_LEVELS.get(peek().text) : undefined;
1693
2193
  if (!isNew && level === undefined) {
1694
2194
  throw createUnexpected(`Expected a declaration but found ${describeToken(peek())}`);
@@ -1731,27 +2231,58 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1731
2231
  );
1732
2232
  };
1733
2233
 
2234
+ const parseHypothesis = () => {
2235
+ if (peek().kind === "Identifier" && isAt("::", 1) && isAt("ASSUME", 2)) {
2236
+ advance();
2237
+ advance();
2238
+ }
2239
+ if (isAt("ASSUME")) return withProofScope(parseAssumeProve);
2240
+ if (peek().kind === "Keyword" && NEW_SYMBOL_STARTS.has(peek().text))
2241
+ return isTlapm ? commit(parseNewSymbol) : parseNewSymbol();
2242
+ if (!isTlapm) return parseExpression();
2243
+ // expr_or_sequent: where no expression starts, the sequent's ASSUME fails last.
2244
+ const expression = attempt(parseExpression);
2245
+ if (expression === undefined) throw createUnexpected("Expected a hypothesis");
2246
+ return expression;
2247
+ };
2248
+
2249
+ // comma1 (hyp b): Pco.star attempts the hypotheses after the first, each inside the one before,
2250
+ // so a failure that backtracks ends the list, and tlapm reports any other before the first comma.
2251
+ const parseTlapmHypotheses = () => {
2252
+ const assumptions = [parseHypothesis()];
2253
+ withRestorePoint(() => {
2254
+ while (true) {
2255
+ const assumption = attempt(() => {
2256
+ expect(",");
2257
+ return parseHypothesis();
2258
+ });
2259
+ if (assumption === undefined) break;
2260
+ assumptions.push(assumption);
2261
+ }
2262
+ });
2263
+ return assumptions;
2264
+ };
2265
+
1734
2266
  const parseAssumeProve = (): AssumeProve => {
1735
- const start = cursor.index;
2267
+ const start = cursor;
1736
2268
  const location = getLocation(expect("ASSUME"));
1737
- const assumptions = parseSeparated(() => {
1738
- if (isAt("ASSUME")) return withProofScope(parseAssumeProve);
1739
- if (peek().kind === "Keyword" && NEW_SYMBOL_STARTS.has(peek().text)) return parseNewSymbol();
1740
- return parseExpression();
1741
- });
1742
- expect("PROVE");
1743
- return withRange(
1744
- { kind: "AssumeProve", assumptions, conclusion: parseExpression(), location },
1745
- start,
1746
- );
2269
+ const parseSequent = (): AssumeProve => {
2270
+ const assumptions = isTlapm ? parseTlapmHypotheses() : parseSeparated(parseHypothesis);
2271
+ expect("PROVE");
2272
+ return withRange(
2273
+ { kind: "AssumeProve", assumptions, conclusion: parseExpression(), location },
2274
+ start,
2275
+ );
2276
+ };
2277
+ return isTlapm ? commit(parseSequent) : parseSequent();
1747
2278
  };
1748
2279
 
1749
2280
  const isNameListAhead = (terminator: string) => {
1750
- const offset = { value: 0 };
1751
- while (peek(offset.value).kind === "Identifier" && isAt(",", offset.value + 1)) {
1752
- offset.value += 2;
2281
+ let offset = 0;
2282
+ while (peek(offset).kind === "Identifier" && isAt(",", offset + 1)) {
2283
+ offset += 2;
1753
2284
  }
1754
- return peek(offset.value).kind === "Identifier" && isAt(terminator, offset.value + 1);
2285
+ return peek(offset).kind === "Identifier" && isAt(terminator, offset + 1);
1755
2286
  };
1756
2287
 
1757
2288
  const declareProofSymbols = (names: string[], bounds: Bound[]) => {
@@ -1766,12 +2297,12 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1766
2297
  const parseStepBody = (): StepBody => {
1767
2298
  const token = peek();
1768
2299
  if (isAt("USE") || isAt("HIDE")) return parseUseOrHide();
1769
- if (isAt("INSTANCE")) {
1770
- const start = cursor.index;
2300
+ if (!isTlapm && isAt("INSTANCE")) {
2301
+ const start = cursor;
1771
2302
  return withRange(parseInstance(undefined, [], false, getLocation(token)), start);
1772
2303
  }
1773
2304
  if (isAt("DEFINE") || isDefinitionStart()) {
1774
- const start = cursor.index;
2305
+ const start = cursor;
1775
2306
  accept("DEFINE");
1776
2307
  const definitions = [parseDefinition(false)];
1777
2308
  while (isDefinitionStart()) definitions.push(parseDefinition(false));
@@ -1819,19 +2350,17 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1819
2350
  if (!isCorrectLevel(step)) {
1820
2351
  throw createError(`${isQed ? "QED step" : "step"}'s number has bad level`, step);
1821
2352
  }
1822
- if (getStepLevel(step) < 0 && getStepName(step) !== undefined) {
2353
+ if (mode !== "sany" && getStepLevel(step) < 0 && getStepName(step) !== undefined) {
1823
2354
  throw createError("<*> and <+> cannot be used for a named step", step);
1824
2355
  }
1825
- cursor.index++;
2356
+ cursor++;
1826
2357
  return { name: getStepName(step), token: step.text, location: getLocation(step) };
1827
2358
  };
1828
2359
 
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
2360
  const parseStep = (): ProofStep => {
1832
- const start = cursor.index;
2361
+ const start = cursor;
1833
2362
  const step = parseStepStart(isAt("QED", 1));
1834
- const statementStart = cursor.index;
2363
+ const statementStart = cursor;
1835
2364
  const scope = new Set<string>();
1836
2365
  proofScopes.push(scope);
1837
2366
  const body: StepBody = accept("QED") ? { kind: "Qed" } : parseStepBody();
@@ -1847,56 +2376,239 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1847
2376
  return withRange({ ...step, body, head, statement, proof }, start);
1848
2377
  };
1849
2378
 
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);
2379
+ const parseLeafProof = (
2380
+ location: SourceLocation,
2381
+ ): Exclude<Proof, { kind: "Steps" }> | undefined => {
2382
+ if (accept("BY")) {
2383
+ const keyword = getRange(cursor - 1);
1856
2384
  return { kind: "By", isOnly: accept("ONLY"), ...parseFacts(), keyword, location };
1857
2385
  }
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
- }
2386
+ const terminal = peek();
2387
+ if (terminal.kind !== "Keyword" || (terminal.text !== "OBVIOUS" && terminal.text !== "OMITTED"))
2388
+ return undefined;
2389
+ advance();
2390
+ const keyword = getRange(cursor - 1);
2391
+ return { kind: terminal.text === "OBVIOUS" ? "Obvious" : "Omitted", keyword, location };
2392
+ };
2393
+
2394
+ const parseProofBody = (): Proof => {
2395
+ const location = getLocation(peek());
1868
2396
  accept("PROOF");
2397
+ const leaf = parseLeafProof(location);
2398
+ if (leaf) return leaf;
1869
2399
  const steps = [parseStep()];
1870
2400
  while (steps[steps.length - 1].body.kind !== "Qed") steps.push(parseStep());
1871
2401
  return { kind: "Steps", level: getProofLevel(), steps, location };
1872
2402
  };
1873
2403
 
1874
2404
  const parseProof = (): Proof => {
1875
- const start = cursor.index;
2405
+ const start = cursor;
1876
2406
  proofLevels.push(-1);
1877
2407
  const proof = withProofScope(parseProofBody);
1878
2408
  proofLevels.pop();
1879
2409
  return withRange(proof, start);
1880
2410
  };
1881
2411
 
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);
2412
+ const isPreproofStart = () =>
2413
+ peek().kind === "Step" || (peek().kind === "Keyword" && PROOF_STARTS.has(peek().text));
2414
+
2415
+ const getStepSpan = (head: SourceRange, body: StepBody) => {
2416
+ if (body.kind !== "Use" && body.kind !== "Hide") return getSpan(head);
2417
+ const lastDef = body.defs[body.defs.length - 1]?.location.range;
2418
+ return mergeSpans(getSpan({ ...head, end: head.start }), getSpan(lastDef ?? body.keyword));
2419
+ };
2420
+
2421
+ const parsePreproof = (): Preproof => {
2422
+ const first = cursor;
2423
+ const location = getLocation(peek());
2424
+ const isProof = accept("PROOF");
2425
+ const leaf = parseLeafProof(location);
2426
+ if (leaf) {
2427
+ const proof = withRange(leaf, first);
2428
+ return { kind: "Leaf", proof, span: getSpan(proof.keyword), first, end: cursor - 1 };
2429
+ }
2430
+ const token = peek();
2431
+ if (token.kind !== "Step") {
2432
+ throw createUnexpected(`Expected a step number but found ${describeToken(token)}`);
2433
+ }
2434
+ const start = cursor;
2435
+ advance();
2436
+ const statementStart = cursor;
2437
+ const body: StepBody = accept("QED") ? { kind: "Qed" } : parseStepBody();
2438
+ const head = getRange(start);
2439
+ return {
2440
+ kind: "Step",
2441
+ token,
2442
+ isProof,
2443
+ body,
2444
+ head,
2445
+ statement: getRange(statementStart),
2446
+ span: getStepSpan(head, body),
2447
+ first,
2448
+ start,
2449
+ end: cursor - 1,
2450
+ };
2451
+ };
2452
+
2453
+ const nestProof = (
2454
+ items: Preproof[],
2455
+ index: number,
2456
+ level: number,
2457
+ levelSpan: Span,
2458
+ ): NestedProof => {
2459
+ const item = items[index];
2460
+ if (!item) return { proof: undefined, span: levelSpan, next: index, end: undefined };
2461
+ if (item.kind === "Leaf")
2462
+ return { proof: item.proof, span: item.span, next: index + 1, end: item.end };
2463
+ const nested = nestSteps(items, index, level, levelSpan, true);
2464
+ if (!nested) return { proof: undefined, span: levelSpan, next: index, end: undefined };
2465
+ const location = {
2466
+ ...getLocation(tokens[item.first]),
2467
+ range: getRange(item.first, nested.end),
2468
+ };
2469
+ return {
2470
+ proof: { kind: "Steps", level: nested.level, steps: nested.steps, location },
2471
+ span: nested.span,
2472
+ next: nested.next,
2473
+ end: nested.end,
2474
+ };
2475
+ };
2476
+
2477
+ const nestSteps = (
2478
+ items: Preproof[],
2479
+ index: number,
2480
+ level: number,
2481
+ levelSpan: Span,
2482
+ isFirst: boolean,
2483
+ ): NestedSteps | undefined => {
2484
+ const item = items[index];
2485
+ if (!item) {
2486
+ throw createProofError(
2487
+ `Unexpected end of (sub)proof at level ${level} before QED step`,
2488
+ levelSpan,
2489
+ NEWLINES,
2490
+ );
2491
+ }
2492
+ if (item.kind === "Leaf") {
2493
+ throw createProofError(
2494
+ `Expecting a proof step but found a${LEAF_NAMES[item.proof.kind]} leaf proof`,
2495
+ item.span,
2496
+ NEWLINES,
2497
+ );
2498
+ }
2499
+ if (!isFirst && item.isProof) {
2500
+ throw createProofError(
2501
+ "PROOF keyword found in step that does not begin subproof",
2502
+ item.span,
2503
+ PRINTED_NEWLINE,
2504
+ );
2505
+ }
2506
+ const implicit = item.token.text[1];
2507
+ if (implicit === "+" && !isFirst) {
2508
+ throw createProofError("<+> used but no subproof expected", item.span, PRINTED_NEWLINE);
2509
+ }
2510
+ const stepLevel =
2511
+ implicit === "*"
2512
+ ? level - (isFirst && !item.isProof ? 1 : 0)
2513
+ : implicit === "+"
2514
+ ? level
2515
+ : getStepLevel(item.token);
2516
+ if (stepLevel < level || (!isFirst && stepLevel > level)) return undefined;
2517
+ const proof = PROVABLE_STEPS.has(item.body.kind)
2518
+ ? nestProof(items, index + 1, stepLevel + 1, item.span)
2519
+ : { proof: undefined, span: item.span, next: index + 1, end: undefined };
2520
+ const end = proof.end ?? item.end;
2521
+ const step: ProofStep = {
2522
+ name: getStepName(item.token),
2523
+ token: item.token.text,
2524
+ body: item.body,
2525
+ head: item.head,
2526
+ statement: item.statement,
2527
+ proof: proof.proof,
2528
+ location: { ...getLocation(item.token), range: getRange(item.start, end) },
2529
+ };
2530
+ const span = mergeSpans(item.span, proof.span);
2531
+ if (item.body.kind === "Qed") {
2532
+ return { level: stepLevel, steps: [step], span, next: proof.next, end };
2533
+ }
2534
+ const rest = nestSteps(
2535
+ items,
2536
+ proof.next,
2537
+ stepLevel,
2538
+ { start: span.stop, stop: span.stop },
2539
+ false,
2540
+ );
2541
+ return (
2542
+ rest && {
2543
+ ...rest,
2544
+ level: stepLevel,
2545
+ steps: [step, ...rest.steps],
2546
+ span: mergeSpans(span, rest.span),
2547
+ }
2548
+ );
2549
+ };
2550
+
2551
+ const parseTlapmProof = () => {
2552
+ if (!isPreproofStart()) return undefined;
2553
+ const items: Preproof[] = [];
2554
+ while (isPreproofStart()) items.push(parsePreproof());
2555
+ const first = items[0];
2556
+ if (first.kind === "Step") items[0] = { ...first, isProof: true };
2557
+ const nested = nestProof(items, 0, 0, first.span);
2558
+ const extra = items[nested.next];
2559
+ if (extra) {
2560
+ throw createProofError(
2561
+ "extra step(s) after finished proof",
2562
+ extra.span,
2563
+ NO_NEWLINES,
2564
+ "Proof.Parser.toplevel",
2565
+ );
2566
+ }
2567
+ return nested.proof;
2568
+ };
2569
+
2570
+ const addFactDefinition = (
2571
+ module: Module,
2572
+ name: string,
2573
+ body: Expression,
2574
+ location: SourceLocation,
2575
+ ) => {
2576
+ if (module.definitions.some((other) => other.name === name)) return;
2577
+ module.definitions.push({
2578
+ kind: "Operator",
2579
+ name,
2580
+ params: [],
2581
+ body,
2582
+ isLocal: false,
2583
+ isRecursive: false,
2584
+ location,
2585
+ });
2586
+ };
2587
+
2588
+ const parseFactName = () => {
2589
+ if (peek().kind !== "Identifier" || !isAt("==", 1)) return undefined;
2590
+ const name = expectIdentifier();
2591
+ factNames.add(name);
2592
+ advance();
2593
+ return name;
2594
+ };
2595
+
2596
+ // A theorem whose statement fails to start backtracks in tlapm, whose module ends there.
2597
+ const parseTheoremExpression = () => {
2598
+ if (!isTlapm) return parseExpression();
2599
+ const token = peekRaw();
2600
+ const statement = attempt(parseExpression);
2601
+ if (statement) return statement;
2602
+ throw createUnexpected(`Expected "====" but found ${describeToken(token)}`, token);
1887
2603
  };
1888
2604
 
1889
2605
  const parseTheorem = (module: Module) => {
1890
- const start = cursor.index;
2606
+ const start = cursor;
1891
2607
  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
- }
2608
+ const name = parseFactName();
1898
2609
  const parsed = withProofScope(() => {
1899
- const statement = isAt("ASSUME") ? parseAssumeProve() : parseExpression();
2610
+ const statement = isAt("ASSUME") ? parseAssumeProve() : parseTheoremExpression();
2611
+ if (isTlapm) return { statement, proof: parseTlapmProof() };
1900
2612
  return { statement, proof: isProofStart(peek()) ? parseProof() : undefined };
1901
2613
  });
1902
2614
  const statement = parsed.statement;
@@ -1907,32 +2619,13 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1907
2619
  module.theorems.push(theorem);
1908
2620
  module.units.push({ kind: "Theorem", theorem });
1909
2621
  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
- );
2622
+ addFactDefinition(module, name, statement, theorem.location);
1925
2623
  };
1926
2624
 
1927
2625
  const parseAssumption = (): Assumption => {
1928
- const start = cursor.index;
2626
+ const start = cursor;
1929
2627
  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
- }
2628
+ const name = parseFactName();
1936
2629
  return withRange(
1937
2630
  {
1938
2631
  name,
@@ -1968,14 +2661,13 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
1968
2661
  recursiveScopes.push(new Set());
1969
2662
  if (accept("EXTENDS")) {
1970
2663
  parseSeparated(() => {
1971
- const start = cursor.index;
2664
+ const start = cursor;
1972
2665
  module.extends.push(expectModuleName());
1973
2666
  module.extendsRanges.push(getRange(start));
1974
2667
  });
1975
2668
  }
1976
2669
  while (true) {
1977
- const tokenIndex = cursor.index;
1978
- unitStart.index = tokenIndex;
2670
+ const tokenIndex = cursor;
1979
2671
  const token = peek();
1980
2672
  if (token.kind === "ModuleEnd") {
1981
2673
  location.range = {
@@ -2012,7 +2704,7 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
2012
2704
  case "VARIABLES": {
2013
2705
  const unitLocation = getLocation(advance());
2014
2706
  const declarations = parseSeparated(() => {
2015
- const start = cursor.index;
2707
+ const start = cursor;
2016
2708
  const location = getLocation(peek());
2017
2709
  return withRange({ name: expectIdentifier(), arity: 0, location }, start);
2018
2710
  });
@@ -2028,21 +2720,12 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
2028
2720
  module.assumptions.push(assumption);
2029
2721
  module.units.push({ kind: "Assumption", assumption });
2030
2722
  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
- });
2723
+ addFactDefinition(module, assumption.name, assumption.expression, assumption.location);
2040
2724
  }
2041
2725
  continue;
2042
2726
  }
2043
2727
  case "USE":
2044
2728
  case "HIDE": {
2045
- // SANY's module body takes a USE only when ONLY doesn't follow it.
2046
2729
  if (isAt("USE") && isAt("ONLY", 1)) {
2047
2730
  throw createUnexpected(`Expected a module unit but found ${describeToken(token)}`);
2048
2731
  }
@@ -2051,10 +2734,13 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
2051
2734
  module.units.push({ kind: "Use", use });
2052
2735
  continue;
2053
2736
  }
2054
- case "RECURSIVE":
2055
- advance();
2056
- module.units.push({ kind: "Recursive", declarations: declareRecursive() });
2737
+ case "RECURSIVE": {
2738
+ const unitLocation = getLocation(advance());
2739
+ const declarations = declareRecursive();
2740
+ unitLocation.range = getRange(tokenIndex);
2741
+ module.units.push({ kind: "Recursive", declarations, location: unitLocation });
2057
2742
  continue;
2743
+ }
2058
2744
  case "INSTANCE":
2059
2745
  addDefinitionUnit(
2060
2746
  module,
@@ -2093,16 +2779,13 @@ const parse = (source: string, mode: ParseMode, sourceTokens = tokenize(source))
2093
2779
  };
2094
2780
 
2095
2781
  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;
2782
+ const sanyError = isKeywordModuleName ? getSanyParseError(source) : undefined;
2099
2783
  if (sanyError !== undefined) throw new TlaSyntaxError(sanyError);
2100
2784
  return module;
2101
2785
  };
2102
2786
 
2103
2787
  export const parseModule = (source: string) => parse(source, "tlc");
2104
2788
 
2105
- // Parses a module the caller has tokenized already.
2106
2789
  export const parseModuleTokens = (source: string, tokens: Token[]) => parse(source, "tlc", tokens);
2107
2790
 
2108
2791
  export const parseTlapmModule = (source: string) => parse(source, "tlapm");