tla-ts 0.0.10-dev.d618a2d79 → 0.0.10-dev.e3e5dd576

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 (252) hide show
  1. package/dist/compile.cjs +3 -3
  2. package/dist/compile.js +1 -1
  3. package/dist/deciders.cjs +36 -36
  4. package/dist/deciders.js +53 -53
  5. package/dist/index.cjs +1 -1
  6. package/dist/index.d.cts +18 -4
  7. package/dist/index.d.ts +18 -4
  8. package/dist/index.js +1 -1
  9. package/dist/parallel-worker.cjs +1 -1
  10. package/dist/parallel-worker.js +1 -1
  11. package/dist/prove-worker.cjs +1 -1
  12. package/dist/prove-worker.js +1 -1
  13. package/dist/prove.cjs +56 -56
  14. package/dist/prove.js +78 -78
  15. package/dist/run.cjs +40 -44
  16. package/dist/run.js +42 -46
  17. package/dist/tlapm.cjs +1 -1
  18. package/dist/tlapm.js +2 -2
  19. package/dist/transfer.cjs +49 -44
  20. package/dist/transfer.js +48 -43
  21. package/dist/worker.cjs +7 -7
  22. package/dist/worker.js +7 -7
  23. package/package.json +1 -1
  24. package/src/ast.ts +14 -2
  25. package/src/bags.ts +50 -29
  26. package/src/builtins.ts +4 -3
  27. package/src/check-failure.ts +13 -11
  28. package/src/check-trace.ts +116 -64
  29. package/src/check.ts +516 -280
  30. package/src/cli/runtime-invariants.ts +20 -56
  31. package/src/cli/tlc-arguments.ts +2 -2
  32. package/src/cli/tlc-output.ts +18 -4
  33. package/src/cli/tlc.ts +18 -12
  34. package/src/cli/xml-exporter.ts +1 -1
  35. package/src/codegen.ts +23 -10
  36. package/src/coverage.ts +190 -1
  37. package/src/dependencies.ts +68 -15
  38. package/src/dfid.ts +101 -36
  39. package/src/environment.ts +123 -38
  40. package/src/errors.ts +7 -0
  41. package/src/evaluate.ts +370 -99
  42. package/src/exit-codes.ts +28 -14
  43. package/src/instances.ts +135 -11
  44. package/src/java-hash.ts +14 -0
  45. package/src/java-overrides.ts +2 -2
  46. package/src/levels.ts +675 -236
  47. package/src/lexer.ts +12 -2
  48. package/src/liveness-checker.ts +179 -60
  49. package/src/liveness.ts +51 -10
  50. package/src/obligations/index.ts +1 -1
  51. package/src/obligations/normalize.ts +1 -4
  52. package/src/obligations/printer.ts +5 -5
  53. package/src/obligations/source.ts +2 -0
  54. package/src/parallel-worker.ts +8 -2
  55. package/src/parallel.ts +5 -0
  56. package/src/parser.ts +180 -149
  57. package/src/prover/isabelle/isar/attrib.ts +4 -4
  58. package/src/prover/isabelle/isar/rule-cases.ts +8 -6
  59. package/src/prover/isabelle/provers/clasimp.ts +1 -1
  60. package/src/prover/isabelle/provers/hypsubst.ts +2 -2
  61. package/src/prover/isabelle/pure/rewriter.ts +3 -3
  62. package/src/prover/isabelle/pure/term.ts +3 -3
  63. package/src/prover/prep/md5.ts +26 -29
  64. package/src/prover/smt/rewrite.ts +2 -7
  65. package/src/prover/smt/simplify.ts +1 -1
  66. package/src/prover/smt/solver/arith-rewriter.ts +11 -3
  67. package/src/prover/smt/solver/array-rewriter.ts +12 -2
  68. package/src/prover/smt/solver/asserted-formulas.ts +171 -58
  69. package/src/prover/smt/solver/ast-lt.ts +1 -1
  70. package/src/prover/smt/solver/ast.ts +66 -14
  71. package/src/prover/smt/solver/auf-solver.ts +23 -12
  72. package/src/prover/smt/solver/bit-blast-tactic.ts +27 -1
  73. package/src/prover/smt/solver/blast-term-ite.ts +47 -0
  74. package/src/prover/smt/solver/bound-simplifier.ts +11 -13
  75. package/src/prover/smt/solver/bv-decl-plugin.ts +13 -10
  76. package/src/prover/smt/solver/bv-rewriter.ts +1 -1
  77. package/src/prover/smt/solver/card2bv.ts +35 -18
  78. package/src/prover/smt/solver/cofactor-elim-term-ite.ts +39 -24
  79. package/src/prover/smt/solver/context.ts +84 -15
  80. package/src/prover/smt/solver/ctx-simplify.ts +1 -2
  81. package/src/prover/smt/solver/datatype-decl-plugin.ts +15 -7
  82. package/src/prover/smt/solver/dependent-expr-state.ts +28 -16
  83. package/src/prover/smt/solver/diff-neq.ts +1 -2
  84. package/src/prover/smt/solver/dt2bv-tactic.ts +57 -21
  85. package/src/prover/smt/solver/elim-bounds.ts +89 -0
  86. package/src/prover/smt/solver/elim-term-ite-tactic.ts +48 -0
  87. package/src/prover/smt/solver/elim-uncnstr.ts +5 -8
  88. package/src/prover/smt/solver/euf/arith-internalize.ts +1 -1
  89. package/src/prover/smt/solver/euf/array-internalize.ts +1 -1
  90. package/src/prover/smt/solver/euf/bv-internalize.ts +1 -1
  91. package/src/prover/smt/solver/euf/egraph.ts +4 -11
  92. package/src/prover/smt/solver/euf/euf-solver.ts +1 -2
  93. package/src/prover/smt/solver/euf/mam.ts +1 -5
  94. package/src/prover/smt/solver/euf/q-ematch.ts +1 -2
  95. package/src/prover/smt/solver/euf/th-solver.ts +0 -7
  96. package/src/prover/smt/solver/expr2polynomial.ts +204 -79
  97. package/src/prover/smt/solver/factor.ts +36 -14
  98. package/src/prover/smt/solver/fd-solver.ts +608 -139
  99. package/src/prover/smt/solver/fix-dl-var.ts +1 -2
  100. package/src/prover/smt/solver/fpa-rewriter.ts +1 -2
  101. package/src/prover/smt/solver/fpa2bv-converter.ts +3 -1
  102. package/src/prover/smt/solver/fpa2bv-rewriter.ts +1 -0
  103. package/src/prover/smt/solver/goal.ts +6 -3
  104. package/src/prover/smt/solver/goal2nlsat.ts +57 -30
  105. package/src/prover/smt/solver/hashtable.ts +4 -0
  106. package/src/prover/smt/solver/internalizer.ts +1 -1
  107. package/src/prover/smt/solver/logic-tactics.ts +15 -5
  108. package/src/prover/smt/solver/lp/core-solver.ts +12 -8
  109. package/src/prover/smt/solver/lp/lar-solver.ts +1 -1
  110. package/src/prover/smt/solver/lp/lp-settings.ts +6 -2
  111. package/src/prover/smt/solver/lp/nla-core.ts +1 -1
  112. package/src/prover/smt/solver/lp/nla-grobner.ts +158 -80
  113. package/src/prover/smt/solver/lp/nra-solver.ts +45 -39
  114. package/src/prover/smt/solver/lp/pdd-interval.ts +6 -2
  115. package/src/prover/smt/solver/lp/pdd-simplifier.ts +60 -20
  116. package/src/prover/smt/solver/lp/pdd-solver.ts +72 -39
  117. package/src/prover/smt/solver/lp/pdd.ts +725 -290
  118. package/src/prover/smt/solver/lp/union-find.ts +1 -1
  119. package/src/prover/smt/solver/mam-compiler.ts +1 -1
  120. package/src/prover/smt/solver/maxcore.ts +2 -1
  121. package/src/prover/smt/solver/maxsmt-base.ts +1 -0
  122. package/src/prover/smt/solver/model-based-opt.ts +1 -1
  123. package/src/prover/smt/solver/model-checker.ts +1 -1
  124. package/src/prover/smt/solver/model-evaluator.ts +2 -0
  125. package/src/prover/smt/solver/model-generator.ts +85 -43
  126. package/src/prover/smt/solver/mpf.ts +2 -4
  127. package/src/prover/smt/solver/mus.ts +2 -3
  128. package/src/prover/smt/solver/muz/dl-context.ts +22 -44
  129. package/src/prover/smt/solver/muz/dl-mk-coi-filter.ts +1 -1
  130. package/src/prover/smt/solver/muz/dl-mk-slice.ts +3 -3
  131. package/src/prover/smt/solver/muz/dl-rule.ts +8 -9
  132. package/src/prover/smt/solver/muz/hnf.ts +2 -2
  133. package/src/prover/smt/solver/muz/horn-subsume-model-converter.ts +1 -1
  134. package/src/prover/smt/solver/muz/horn-tactic.ts +15 -2
  135. package/src/prover/smt/solver/muz/rule-properties.ts +22 -0
  136. package/src/prover/smt/solver/muz/spacer-context.ts +2 -4
  137. package/src/prover/smt/solver/muz/spacer-pdr.ts +1 -0
  138. package/src/prover/smt/solver/muz/spacer-prop-solver.ts +1 -1
  139. package/src/prover/smt/solver/nlqsat.ts +1 -1
  140. package/src/prover/smt/solver/nlsat/algebraic.ts +196 -92
  141. package/src/prover/smt/solver/nlsat/atoms.ts +52 -33
  142. package/src/prover/smt/solver/nlsat/explain.ts +375 -217
  143. package/src/prover/smt/solver/nlsat/levelwise.ts +460 -240
  144. package/src/prover/smt/solver/nlsat/polynomial.ts +2366 -681
  145. package/src/prover/smt/solver/nlsat/solver.ts +74 -64
  146. package/src/prover/smt/solver/nlsat/transcendentals.ts +41 -17
  147. package/src/prover/smt/solver/nlsat/upolynomial-factorization.ts +8 -4
  148. package/src/prover/smt/solver/nlsat/upolynomial.ts +41 -18
  149. package/src/prover/smt/solver/nlsat-tactic.ts +1 -1
  150. package/src/prover/smt/solver/nnf.ts +6 -2
  151. package/src/prover/smt/solver/opt-context.ts +21 -7
  152. package/src/prover/smt/solver/opt-nlsat.ts +29 -18
  153. package/src/prover/smt/solver/opt-pareto.ts +19 -0
  154. package/src/prover/smt/solver/opt-preprocess.ts +1 -1
  155. package/src/prover/smt/solver/opt-solver.ts +10 -6
  156. package/src/prover/smt/solver/optsmt.ts +1 -1
  157. package/src/prover/smt/solver/parallel-tactic.ts +1 -1
  158. package/src/prover/smt/solver/pb-rewriter.ts +1 -4
  159. package/src/prover/smt/solver/poly-rewriter.ts +75 -18
  160. package/src/prover/smt/solver/probes.ts +88 -23
  161. package/src/prover/smt/solver/proto-model.ts +8 -8
  162. package/src/prover/smt/solver/push-app-ite.ts +37 -0
  163. package/src/prover/smt/solver/qe-arith-plugin.ts +2 -4
  164. package/src/prover/smt/solver/qe-lite.ts +2 -2
  165. package/src/prover/smt/solver/qe.ts +3 -2
  166. package/src/prover/smt/solver/qsat.ts +23 -8
  167. package/src/prover/smt/solver/quantifier-manager.ts +14 -9
  168. package/src/prover/smt/solver/recfun-decl-plugin.ts +2 -1
  169. package/src/prover/smt/solver/rewriter-tpl.ts +7 -6
  170. package/src/prover/smt/solver/rewriter.ts +31 -25
  171. package/src/prover/smt/solver/rlimit.ts +7 -3
  172. package/src/prover/smt/solver/sat/config.ts +1 -1
  173. package/src/prover/smt/solver/sat/goal2sat.ts +65 -12
  174. package/src/prover/smt/solver/sat/inc-sat-solver.ts +129 -43
  175. package/src/prover/smt/solver/sat/model-converter.ts +1 -1
  176. package/src/prover/smt/solver/sat/pb-constraint.ts +7 -0
  177. package/src/prover/smt/solver/sat/pb-solver.ts +26 -7
  178. package/src/prover/smt/solver/sat/sat-tactic.ts +17 -7
  179. package/src/prover/smt/solver/sat/sat2goal.ts +72 -48
  180. package/src/prover/smt/solver/sat/simplifier.ts +1 -1
  181. package/src/prover/smt/solver/sat/solver.ts +27 -47
  182. package/src/prover/smt/solver/seq-axioms.ts +20 -35
  183. package/src/prover/smt/solver/seq-decl-plugin.ts +1 -1
  184. package/src/prover/smt/solver/seq-derive.ts +2 -2
  185. package/src/prover/smt/solver/seq-eq-solver.ts +2 -2
  186. package/src/prover/smt/solver/seq-monadic.ts +7 -5
  187. package/src/prover/smt/solver/seq-re-rewriter.ts +2 -1
  188. package/src/prover/smt/solver/seq-re-util.ts +1 -1
  189. package/src/prover/smt/solver/seq-regex-bisim.ts +1 -1
  190. package/src/prover/smt/solver/seq-regex-live.ts +2 -2
  191. package/src/prover/smt/solver/seq-rewriter.ts +31 -29
  192. package/src/prover/smt/solver/seq-skolem.ts +0 -23
  193. package/src/prover/smt/solver/seq-view-witness.ts +4 -4
  194. package/src/prover/smt/solver/smt-consequences.ts +1 -1
  195. package/src/prover/smt/solver/smt-kernel.ts +48 -7
  196. package/src/prover/smt/solver/smt-setup.ts +106 -13
  197. package/src/prover/smt/solver/smtlib-parser.ts +589 -224
  198. package/src/prover/smt/solver/smtlib-script.ts +713 -210
  199. package/src/prover/smt/solver/solve-eqs.ts +36 -37
  200. package/src/prover/smt/solver/solver.ts +18 -3
  201. package/src/prover/smt/solver/tactic.ts +350 -195
  202. package/src/prover/smt/solver/theory-bv.ts +13 -3
  203. package/src/prover/smt/solver/theory-fpa.ts +1 -1
  204. package/src/prover/smt/solver/theory-lra-final-check.ts +1 -0
  205. package/src/prover/smt/solver/theory-lra-internalize.ts +2 -0
  206. package/src/prover/smt/solver/theory-lra-propagate.ts +11 -3
  207. package/src/prover/smt/solver/theory-lra-state.ts +1 -1
  208. package/src/prover/smt/solver/theory-lra.ts +1 -1
  209. package/src/prover/smt/solver/theory-pb.ts +24 -7
  210. package/src/prover/smt/solver/theory-seq-solve.ts +1 -1
  211. package/src/prover/smt/solver/theory-seq-state.ts +2 -21
  212. package/src/prover/smt/solver/theory-without-terms.ts +24 -0
  213. package/src/prover/smt/solver/tseitin-cnf.ts +1 -0
  214. package/src/prover/tlapm/cache.ts +8 -8
  215. package/src/prover/zenon/index-table.ts +5 -2
  216. package/src/prover/zenon/isar-case.ts +1 -1
  217. package/src/prover/zenon/isar.ts +2 -2
  218. package/src/prover/zenon/phrase.ts +1 -1
  219. package/src/resolve.ts +1274 -257
  220. package/src/runtime.ts +7 -1
  221. package/src/sany/builtins.ts +10 -10
  222. package/src/sany/generation.ts +5 -15
  223. package/src/sany/generator-def-entries.ts +123 -36
  224. package/src/sany/generator-definitions.ts +5 -3
  225. package/src/sany/generator-expressions.ts +60 -37
  226. package/src/sany/generator-proofs.ts +18 -12
  227. package/src/sany/generator.ts +12 -6
  228. package/src/sany/lexer.ts +15 -7
  229. package/src/sany/modules.ts +4 -2
  230. package/src/sany/nodes.ts +1 -1
  231. package/src/sany/selectors.ts +11 -6
  232. package/src/sany/xml.ts +2 -3
  233. package/src/search.ts +319 -135
  234. package/src/simulate.ts +235 -182
  235. package/src/spec-description.ts +8 -6
  236. package/src/standard-definitions.ts +1 -0
  237. package/src/standard-modules.ts +56 -22
  238. package/src/subexpressions.ts +564 -138
  239. package/src/successors.ts +37 -13
  240. package/src/symmetry.ts +2 -1
  241. package/src/tlc/jar-data.ts +10 -0
  242. package/src/tlc/messages.ts +3 -3
  243. package/src/tlc/order.ts +14 -3
  244. package/src/tlc/random.ts +2 -1
  245. package/src/tlc/replay.ts +67 -43
  246. package/src/tlc/tlc-operators.ts +10 -8
  247. package/src/tlc/tlcext-operators.ts +44 -15
  248. package/src/tlc/trace-spec.ts +9 -22
  249. package/src/trace-liveness.ts +529 -0
  250. package/src/typed-tier.ts +52 -31
  251. package/src/typescript/types.ts +2 -2
  252. package/src/values.ts +150 -79
package/dist/run.js CHANGED
@@ -6,46 +6,42 @@
6
6
  * This source code is licensed under the MIT license found in the
7
7
  * LICENSE file in the root directory of this source tree.
8
8
  */
9
- import{t as e}from"./tlapm.js";import{$ as t,A as n,B as r,C as i,D as a,F as o,G as s,I as c,L as l,M as u,O as d,P as f,Q as p,T as m,V as h,W as g,_,at as v,b as y,c as b,g as x,it as S,j as C,k as w,nt as T,o as E,ot as ee,s as D,tt as O,x as k,y as A}from"./worker.js";import{$ as te,At as ne,E as re,Ft as ie,G as ae,K as oe,M as se,O as ce,Pt as le,Q as ue,S as de,Vt as j,Zt as fe,_n as pe,an as me,b as he,bn as ge,cn as _e,ct as ve,dn as ye,dt as be,en as M,fn as xe,gn as Se,h as Ce,hn as we,ht as Te,i as Ee,in as De,kt as Oe,lt as ke,m as Ae,mn as je,mt as Me,nn as N,o as Ne,on as P,ot as Pe,p as Fe,pn as Ie,pt as Le,qt as Re,r as ze,rn as Be,s as Ve,sn as He,tn as F,un as Ue,ut as We,vn as Ge,vt as Ke,w as qe,x as Je,yn as Ye}from"./transfer.js";import{S as Xe,_ as Ze,a as Qe,b as $e,c as et,d as tt,f as nt,g as rt,h as it,i as at,l as ot,m as st,n as ct,p as lt,r as ut,s as dt,t as ft,u as pt,v as mt,x as ht,y as gt}from"./prove.js";import{basename as _t,delimiter as vt,dirname as yt,isAbsolute as bt,join as xt,resolve as St}from"node:path";import{appendFileSync as Ct,closeSync as wt,cpSync as Tt,existsSync as I,globSync as Et,mkdirSync as Dt,openSync as Ot,readFileSync as kt,readSync as At,readdirSync as jt,realpathSync as Mt,renameSync as Nt,rmSync as Pt,statSync as Ft,writeFileSync as It}from"node:fs";import{pathToFileURL as Lt}from"node:url";import{spawnSync as Rt}from"node:child_process";import{arch as zt,availableParallelism as Bt,release as Vt,tmpdir as Ht,type as Ut}from"node:os";import{getHeapStatistics as Wt}from"node:v8";const Gt=`META-INF/MANIFEST.MF`,Kt=async e=>{if(e===void 0||!I(e))return`master`;let t=await import(`fflate`),n=t.unzipSync(kt(e),{filter:e=>e.name===Gt})[Gt];return(n&&/^X-Git-Tag: *(\S*)/m.exec(t.strFromU8(n))?.[1])===`v1.7.4`?`1.7.4`:`master`},qt=/[*?[{]/,Jt=e=>e.flatMap(e=>qt.test(e)?Et(e).sort().map(e=>({path:e,isGlobbed:!0})):[{path:e,isGlobbed:!1}]),Yt=(e,t)=>e.map(e=>xt(e,`${t}.tla`)).find(I),Xt=e=>t=>{let n=Yt(e,t);return n===void 0?void 0:kt(n,`utf8`)},Zt=(e,t,n)=>console.error(`File does not exist: ${e}/${t} while looking in these directories: ${e}, ${n.join(`, `)}, classpath:/tla2sany/StandardModules, classpath:/`),Qt=e=>`jar:file:${Lt(St(e)).pathname}!/tla2sany/StandardModules/`,$t=e=>e instanceof h?S(e.code):p(e),en=(e,t)=>{if(e instanceof _||e instanceof y){let n=He(e.message),r=e instanceof h?e.code:n&&!n.isEvalException?n.code:M.general;return t.print(r,F.error,Be(r,e.message,t.isTool))}console.error(`${e.name}: ${e.message}`)},tn=async(e,t=N({isTool:!1}))=>{try{return await e()}catch(e){if(!(e instanceof A))throw e;return en(e,t),$t(e)}},nn=(e,t,n)=>console.error(`File does not exist: ${bt(e)?e:`${process.cwd()}/${e}`} while looking in these directories: ${[...t,...n===void 0?[]:[Qt(n)]].join(`, `)}`),rn=e=>e.endsWith(`/`)?e:`${e}/`,an=(e,t)=>n=>{let r=e(n);return r===void 0&&!ve.has(n)&&t(`${n}.tla`),r},on=e=>e.classPath?.split(vt).find(e=>e.endsWith(`.jar`));var sn=`0.0.10-dev.d618a2d79`;const cn=2224400062,ln={int8:0,int16:1,int32:2,shared8:4,shared16:5,shared32:6,block32:8,string8:9,string32:10,doubleLittle:12},un={smallInt:64,smallString:32,smallBlock:128},L=(e,...t)=>({tag:e,fields:t}),dn=e=>typeof e==`object`&&`tag`in e,fn=(e,t)=>{let r=new DataView(e.buffer,e.byteOffset,e.byteLength);if(e.length<t+20||r.getUint32(t)!==cn)throw new n(`corrupted fingerprint file`);let i=t+20+r.getUint32(t+4),a=[],o=t+20,s=e=>{let t=o;if(o+=e,o>i)throw new n(`corrupted fingerprint file`);return t},c=new TextDecoder,l=t=>{let n=s(t),r=c.decode(e.subarray(n,n+t));return a.push(r),r},u=(e,t)=>{let n=L(e);t>0&&a.push(n);for(let e=0;e<t;e++)n.fields.push(f());return n},d=e=>a[a.length-e],f=()=>{let t=e[s(1)];if(t>=un.smallBlock)return u(t&15,t>>4&7);if(t>=un.smallInt)return t&63;if(t>=un.smallString)return l(t&31);switch(t){case ln.int8:return r.getInt8(s(1));case ln.int16:return r.getInt16(s(2));case ln.int32:return r.getInt32(s(4));case ln.shared8:return d(r.getUint8(s(1)));case ln.shared16:return d(r.getUint16(s(2)));case ln.shared32:return d(r.getUint32(s(4)));case ln.block32:{let e=r.getUint32(s(4));return u(e&255,e>>>10)}case ln.string8:return l(r.getUint8(s(1)));case ln.string32:return l(r.getUint32(s(4)));case ln.doubleLittle:{let e={float:r.getFloat64(s(8),!0)};return a.push(e),e}}throw new n(`corrupted fingerprint file`)};return{value:f(),next:i}},pn=e=>{let t=[],n=0,r=0,i=0,a=(e,n)=>{for(let r=(n-1)*8;r>=0;r-=8)t.push(e>>>r&255)},o=new TextEncoder,s=e=>{if(typeof e==`number`)return e>=0&&e<64?t.push(un.smallInt+e):e>=-128&&e<128?t.push(ln.int8,e&255):e>=-32768&&e<32768?(t.push(ln.int16),a(e,2)):(t.push(ln.int32),a(e,4));if(n++,typeof e==`string`){let n=o.encode(e);n.length<32?t.push(un.smallString+n.length):n.length<256?t.push(ln.string8,n.length):(t.push(ln.string32),a(n.length,4)),t.push(...n),r+=1+Math.floor((n.length+4)/4),i+=1+Math.floor((n.length+8)/8);return}if(!dn(e)){let n=/* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8));n.setFloat64(0,e.float,!0),t.push(ln.doubleLittle,...new Uint8Array(n.buffer)),r+=3,i+=2;return}let c=e.fields.length;c===0?n--:(r+=1+c,i+=1+c),e.tag<16&&c<8?t.push(un.smallBlock+e.tag+(c<<4)):(t.push(ln.block32),a(c*1024+e.tag,4)),e.fields.forEach(s)};s(e);let c=/* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(20));return[cn,t.length,n,r,i].forEach((e,t)=>c.setUint32(t*4,e)),new Uint8Array([...new Uint8Array(c.buffer),...t])},mn=20210223,hn=[...et,`cooper`,`expandenabled`,`expandcdot`,`lambdify`,`enabledaxioms`,`levelcomparison`],gn={zenon:{field:1,tag:1},isabelle:{field:2,tag:0},cooper:{field:4,tag:3,isConstant:!0},smt:{field:10,tag:8},z3:{field:11,tag:9},ls4:{field:17,tag:16},expandenabled:{field:18,tag:6,isConstant:!0},expandcdot:{field:19,tag:8,isConstant:!0},lambdify:{field:20,tag:9,isConstant:!0},enabledaxioms:{field:21,tag:10,isConstant:!0},levelcomparison:{field:22,tag:11,isConstant:!0}},_n=[`false`,`timeout`],vn=`tla-ts ${sn}`,yn=/* @__PURE__ */ new Map([[gn.zenon.field,3],[gn.isabelle.field,4]]),bn=(e,t)=>e!==void 0&&dn(e)?e.fields[t]:void 0,xn=e=>e!==void 0&&typeof e==`object`&&`float`in e?e.float:1/0,Sn=e=>{let t=new TextEncoder().encode(e),n=(e,t)=>e<<t|e>>>32-t,r=Array.from({length:Math.ceil(t.length/4)},(e,n)=>t[n*4]|t[n*4+1]<<8|t[n*4+2]<<16|t[n*4+3]<<24).reduce((e,t)=>{let r=Math.imul(n(Math.imul(t,3432918353),15),461845907);return Math.imul(n(e^r,13),5)+3864292196|0},0),i=Math.imul(r^t.length^(r^t.length)>>>16,2246822507),a=Math.imul(i^i>>>13,3266489909);return(a^a>>>16)&1073741823},Cn=e=>e!==void 0&&dn(e)?[[e.fields[0],e.fields[1]],...Cn(e.fields[2])]:[],wn=(e,t,r)=>{let i=kt(t),a=fn(i,0),o=fn(i,a.next).value;if(a.value!==mn||!dn(o)||o.tag!==0)throw new n(`corrupted fingerprint file`);let s=bn(bn(o,0),1),c=(e,t)=>{let n=yn.get(t);return!r||n===void 0||bn(bn(e,0),n)===vn};e.clear(),(s!==void 0&&dn(s)?s.fields:[]).flatMap(e=>Cn(e).toReversed()).forEach(([t,r])=>{if(typeof t!=`string`||!dn(r))throw new n(`corrupted fingerprint file`);e.set(t,r.fields.map((e,t)=>c(e,t)?e:0))})},Tn=(e,t)=>{let n=bn(t,0),r=bn(n,0),i=bn(bn(n,1),0);if(r===void 0||r===1)return;let a=xn(bn(e===`isabelle`?bn(i,0):i,0)),o=e===`isabelle`?bn(i,1):void 0,s=bn(bn(r,0),0);return{kind:`stored`,method:{prover:e,timeLimitMs:a*1e3,...typeof o==`string`&&{tactic:o}},isProved:r===0,...s!==void 0&&{reason:typeof s==`number`?_n[s]:String(bn(s,0))}}},En=(e,t)=>{let n=/* @__PURE__ */ new Date,r=t.method,i={float:pt(r)},a=e===`zenon`?L(0,i,5):e===`isabelle`?L(0,L(0,i),r.tactic??`auto`):L(0,i),o=at(t),s=_n.indexOf(o??``),c=o===void 0?0:L(0,s===-1?L(0,o):s);return L(0,L(0,L(0,Qe(t)?0:L(0,c),gn[e].isConstant?gn[e].tag:L(gn[e].tag,a)),L(0,n.getFullYear(),n.getMonth(),n.getDate(),n.getHours(),n.getMinutes(),n.getSeconds()),vn,vn,vn))},Dn=e=>{let t=2**Math.max(9,Math.ceil(Math.log2(e.size/2))),n=Array.from({length:t},()=>0);return e.forEach((e,r)=>{let i=Sn(r)&t-1;n[i]=L(0,r,L(0,...e),n[i])}),L(0,L(0,e.size,L(0,...n),0,512))},On=e=>String(e).padStart(2,`0`),kn=(e,t)=>{let n=/* @__PURE__ */ new Date,r=`${e}.history`,i=xt(r,`${n.getFullYear()}-${On(n.getMonth()+1)}-${On(n.getDate())}_${On(n.getHours())}_${On(n.getMinutes())}_${On(n.getSeconds())}`);Dt(i,{recursive:!0}),[e,...t].filter(e=>I(e)).forEach(e=>Tt(e,xt(i,_t(e)),{preserveTimestamps:!0})),jt(r).map(e=>xt(r,e)).sort((e,t)=>Ft(t).mtimeMs-Ft(e).mtimeMs).slice(10).forEach(e=>Pt(e,{recursive:!0,force:!0}))},An=e=>{let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=new Map([...e].map(([e,r])=>{let i=new Map(hn.flatMap(e=>{let n=r[gn[e].field],i=Tn(e,bn(n,0));return i?(t.set(i,n),[[e,i]]):[]}));return n.set(i,r),[e,i]}));return{results:r,save:i=>{e.clear(),r.forEach((r,i)=>{let a=[...n.get(r)??Array(23).fill(0)];hn.forEach(e=>{let n=r.get(e);n&&(a[gn[e].field]=t.get(n)??En(e,n))}),e.set(i,a)}),It(`${i}.tmp`,Buffer.concat([pn(mn),pn(Dn(e))])),Nt(`${i}.tmp`,i)}}},jn=((e,t)=>{let n=new Map(t.map(e=>{let[t,...n]=e.flag.split(` `);return[t,n.length]}));return{usage:e.replace(`{options}`,t.map(e=>`[${e.flag}]${e.isRepeatable?`...`:``}`).join(` `)),parse:e=>{let t=[],r=[],i=[];for(let a=0;a<e.length;a++){let o=n.get(e[a]);o===void 0?(e[a].startsWith(`-`)?i:r).push(e[a]):(t.push({name:e[a],values:e.slice(a+1,a+1+o)}),a+=o)}return{options:t,positionals:r,unknown:i,incomplete:t.find(e=>e.values.length<(n.get(e.name)??0)),has:e=>t.some(t=>t.name===e),get:e=>t.findLast(t=>t.name===e)?.values}}}})(`tla-ts tlapm {options} <Module.tla|glob>...`,[{flag:`-N`},{flag:`--summary`},{flag:`--strict`},{flag:`--toolbox <start> <end>`},{flag:`--line <num>`},{flag:`--printallobs`},{flag:`--threads <num>`},{flag:`--version`},{flag:`-I <directory>`,isRepeatable:!0},{flag:`-k`},{flag:`--noproving`},{flag:`--nofp`},{flag:`--nofpl <start> <end>`},{flag:`--safefp`},{flag:`--cleanfp`},{flag:`--usefp <file>`},{flag:`--cache-dir <directory>`},{flag:`--debug <flags>`,isRepeatable:!0},{flag:`--method <methods>`},{flag:`--solver <command>`},{flag:`--smt-logic <logic>`},{flag:`--stretch <factor>`},{flag:`--noflatten`}]),Mn=[`Usage: tla-ts <Spec.tla|Spec.cfg|spec.ts|glob>... [-config <Spec.cfg>] [-continue] [-deadlock] [-dump [<format>] <file>] [-fp <num>] [-lncheck <final|default|off>] [-maxSetSize <num>] [-metadir <directory>] [-nowarning] [-seed <num>] [-terse] [-tool] [-view] [-workers <count|auto>]`,` ${jn.usage}`,` tla-ts [<JVM option>]... tlc2.TLC <TLC option>... <Spec>`,` (-cp tla2tools.jar or -Dtla-ts.tlc=1.7.4 picks the TLC to reproduce)`,` tla-ts [<JVM option>]... tla2sany.xml.XMLExporter [-I <directory>]... [-o] [-t] [-r] [-u] <Module.tla>`].join(`
10
- `),Nn={name:``,values:[],doc:` `},Pn=[Nn,{name:`(basic options)`,values:[],doc:` `},Nn,{name:`--help`,values:[],doc:` show this help message and exit`},{name:`-help`,values:[],doc:` (same as --help)`},{name:`--version`,values:[],doc:` show version number and exit`},{name:`--verbose`,values:[],doc:` produce verbose messages`},{name:`-v`,values:[],doc:` (same as --verbose)`},Nn,{name:`--where`,values:[],doc:` show location of standard library and exit`},{name:`--config`,values:[],doc:` show configuration and exit`},{name:`--summary`,values:[],doc:` show summary of theorems (implies -N and not -C)`},{name:`--strict`,values:[],doc:` report incomplete proofs, empty proof targets and failed obligations as errors and exit with a non-zero status`},{name:`--timing`,values:[],doc:` show runtime statistics`},Nn,{name:`-I`,values:[`string`],doc:`<dir> add <dir> to search path`},{name:`-d`,values:[`string`],doc:``},Nn,{name:`-k`,values:[],doc:` keep going on backend failures`},{name:`-N`,values:[],doc:` do not run any backend verifiers`},{name:`-C`,values:[],doc:` check proofs in Isabelle/TLA+`},Nn,{name:`--threads`,values:[`int`],doc:`<int> set number of worker threads to <int>`},{name:`--method`,values:[`string`],doc:`<meth> set default method to <meth> (try --method help)`},{name:`--solver`,values:[`string`],doc:`<solver> set SMT solver to <solver>`},{name:`--smt-logic`,values:[`string`],doc:`<logic> set SMT logic to <logic>`},{name:`--stretch`,values:[`float`],doc:`<f> multiply all timeouts by <f>`},{name:`--fast-isabelle`,values:[],doc:``},Nn,{name:`(advanced options)`,values:[],doc:` `},Nn,{name:`--noflatten`,values:[],doc:` do not flatten obligations`},{name:`--nonormal`,values:[],doc:` do not normalize obligations before printing`},{name:`--debug`,values:[`string`],doc:`{[-]<flag>} enable/disable debugging flags`},{name:`--paranoid`,values:[],doc:``},{name:`--isaprove`,values:[],doc:``},Nn,{name:`--toolbox`,values:[`int`,`int`],doc:`<int><int> toolbox mode`},{name:`--toolbox-vsn`,values:[`int`],doc:`<int> Toolbox protocol version, 1|2, 1 by default.`},{name:`--line`,values:[`int`],doc:`<int> line to prove`},{name:`--wait`,values:[`int`],doc:`<time> wait for <time> before printing obligations in progress`},{name:`--stdin`,values:[],doc:` read the tla file from stdin instead of file system. Only applies if single tla file is provided as input.`},{name:`--prefer-stdlib`,values:[],doc:` prefer built-in standard modules if the module search path contains files with the same names as modules in stdlib.`},{name:`--parser`,values:[`string`],doc:` Set parser backend to use: TLAPM (default) or SANY.`},{name:`--module-jar`,values:[`string`],doc:` Add a path to a .jar file containing additional TLA+ modules, such
9
+ import{t as e}from"./tlapm.js";import{$ as t,A as n,E as r,F as i,G as a,H as o,I as s,K as c,L as l,M as u,N as d,O as f,Q as p,R as m,S as h,V as g,_,at as v,b as y,c as b,it as x,j as S,k as C,nt as w,o as T,ot as E,s as D,st as ee,tt as O,v as k,w as A,x as j}from"./worker.js";import{$ as te,$t as M,At as ne,Bn as re,Bt as ie,Cn as ae,Ct as oe,D as se,Dt as ce,Et as le,Fn as ue,Ft as de,G as fe,Gn as pe,Gt as me,Hn as he,Ht as N,Jn as ge,Jt as _e,Kn as ve,Kt as ye,Ln as be,Lt as P,Mt as xe,Nn as Se,Nt as Ce,Ot as we,Pt as Te,Qn as Ee,Qt as De,Rn as F,Rt as Oe,St as I,T as ke,Tt as Ae,Un as je,Ut as Me,Vn as Ne,Vt as Pe,W as Fe,Wn as Ie,Wt as Le,Xn as Re,Xt as ze,Yn as Be,Yt as L,Zn as Ve,Zt as He,_ as Ue,_n as We,at as Ge,b as Ke,bt as qe,c as Je,ct as Ye,dn as Xe,dt as Ze,en as Qe,er as $e,et,ft as tt,g as nt,gn as rt,h as it,ht as at,i as ot,j as st,jt as ct,kn as lt,kt as ut,l as dt,lt as ft,mt as pt,nt as mt,o as ht,ot as gt,pn as _t,pt as vt,qt as R,r as yt,rr as bt,s as xt,st as St,tn as Ct,tr as wt,un as Tt,ut as Et,vt as Dt,w as Ot,wt as kt,xt as At,yt as jt,zn as z,zt as Mt}from"./transfer.js";import{S as Nt,_ as Pt,a as Ft,b as It,c as Lt,d as Rt,f as zt,g as Bt,h as Vt,i as Ht,l as Ut,m as Wt,n as Gt,p as Kt,r as qt,s as Jt,t as Yt,u as Xt,v as Zt,x as Qt,y as $t}from"./prove.js";import{basename as en,delimiter as tn,dirname as nn,isAbsolute as rn,join as an,resolve as on}from"node:path";import{appendFileSync as sn,closeSync as cn,cpSync as ln,existsSync as B,globSync as un,mkdirSync as dn,openSync as fn,readFileSync as pn,readSync as mn,readdirSync as hn,realpathSync as gn,renameSync as _n,rmSync as vn,statSync as yn,writeFileSync as bn}from"node:fs";import{pathToFileURL as xn}from"node:url";import{spawnSync as Sn}from"node:child_process";import{arch as Cn,availableParallelism as wn,release as Tn,tmpdir as En,type as Dn}from"node:os";import{getHeapStatistics as On}from"node:v8";const kn=`META-INF/MANIFEST.MF`,An=async e=>{if(e===void 0||!B(e))return`master`;let t=await import(`fflate`),n=t.unzipSync(pn(e),{filter:e=>e.name===kn})[kn];return(n&&/^X-Git-Tag: *(\S*)/m.exec(t.strFromU8(n))?.[1])===`v1.7.4`?`1.7.4`:`master`},jn=/[*?[{]/,Mn=e=>e.flatMap(e=>jn.test(e)?un(e).sort().map(e=>({path:e,isGlobbed:!0})):[{path:e,isGlobbed:!1}]),Nn=(e,t)=>e.map(e=>an(e,`${t}.tla`)).find(B),Pn=e=>t=>{let n=Nn(e,t);return n===void 0?void 0:pn(n,`utf8`)},Fn=(e,t,n)=>console.error(`File does not exist: ${e}/${t} while looking in these directories: ${e}, ${n.join(`, `)}, classpath:/tla2sany/StandardModules, classpath:/`),In=e=>`jar:file:${xn(on(e)).pathname}!/tla2sany/StandardModules/`,Ln=e=>e instanceof o?x(e.code):p(e),Rn=(e,t)=>{if(e instanceof k||e instanceof j){let n=pe(e.message),r=e instanceof o?e.code:n&&!n.isEvalException?n.code:F.general;return t.print(r,z.error,Ne(r,e.message,t.isTool))}console.error(`${e.name}: ${e.message}`)},zn=async(e,t=re({isTool:!1}))=>{try{return await e()}catch(e){if(!(e instanceof y))throw e;return Rn(e,t),Ln(e)}},Bn=(e,t,n)=>console.error(`File does not exist: ${rn(e)?e:`${process.cwd()}/${e}`} while looking in these directories: ${[...t,...n===void 0?[]:[In(n)]].join(`, `)}`),Vn=e=>e.endsWith(`/`)?e:`${e}/`,Hn=(e,t)=>n=>{let r=e(n);return r===void 0&&!Ye.has(n)&&t(`${n}.tla`),r},Un=e=>e.classPath?.split(tn).find(e=>e.endsWith(`.jar`));var Wn=`0.0.10-dev.e3e5dd576`;const Gn=2224400062,Kn={int8:0,int16:1,int32:2,shared8:4,shared16:5,shared32:6,block32:8,string8:9,string32:10,doubleLittle:12},qn={smallInt:64,smallString:32,smallBlock:128},V=(e,...t)=>({tag:e,fields:t}),Jn=e=>typeof e==`object`&&`tag`in e,Yn=(e,t)=>{let n=new DataView(e.buffer,e.byteOffset,e.byteLength);if(e.length<t+20||n.getUint32(t)!==Gn)throw new S(`corrupted fingerprint file`);let r=t+20+n.getUint32(t+4),i=[],a=t+20,o=e=>{let t=a;if(a+=e,a>r)throw new S(`corrupted fingerprint file`);return t},s=new TextDecoder,c=t=>{let n=o(t),r=s.decode(e.subarray(n,n+t));return i.push(r),r},l=(e,t)=>{let n=V(e);t>0&&i.push(n);for(let e=0;e<t;e++)n.fields.push(d());return n},u=e=>i[i.length-e],d=()=>{let t=e[o(1)];if(t>=qn.smallBlock)return l(t&15,t>>4&7);if(t>=qn.smallInt)return t&63;if(t>=qn.smallString)return c(t&31);switch(t){case Kn.int8:return n.getInt8(o(1));case Kn.int16:return n.getInt16(o(2));case Kn.int32:return n.getInt32(o(4));case Kn.shared8:return u(n.getUint8(o(1)));case Kn.shared16:return u(n.getUint16(o(2)));case Kn.shared32:return u(n.getUint32(o(4)));case Kn.block32:{let e=n.getUint32(o(4));return l(e&255,e>>>10)}case Kn.string8:return c(n.getUint8(o(1)));case Kn.string32:return c(n.getUint32(o(4)));case Kn.doubleLittle:{let e={float:n.getFloat64(o(8),!0)};return i.push(e),e}}throw new S(`corrupted fingerprint file`)};return{value:d(),next:r}},Xn=e=>{let t=[],n=0,r=0,i=0,a=(e,n)=>{for(let r=(n-1)*8;r>=0;r-=8)t.push(e>>>r&255)},o=new TextEncoder,s=e=>{if(typeof e==`number`)return e>=0&&e<64?t.push(qn.smallInt+e):e>=-128&&e<128?t.push(Kn.int8,e&255):e>=-32768&&e<32768?(t.push(Kn.int16),a(e,2)):(t.push(Kn.int32),a(e,4));if(n++,typeof e==`string`){let n=o.encode(e);n.length<32?t.push(qn.smallString+n.length):n.length<256?t.push(Kn.string8,n.length):(t.push(Kn.string32),a(n.length,4)),t.push(...n),r+=1+Math.floor((n.length+4)/4),i+=1+Math.floor((n.length+8)/8);return}if(!Jn(e)){let n=/* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8));n.setFloat64(0,e.float,!0),t.push(Kn.doubleLittle,...new Uint8Array(n.buffer)),r+=3,i+=2;return}let c=e.fields.length;c===0?n--:(r+=1+c,i+=1+c),e.tag<16&&c<8?t.push(qn.smallBlock+e.tag+(c<<4)):(t.push(Kn.block32),a(c*1024+e.tag,4)),e.fields.forEach(s)};s(e);let c=/* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(20));return[Gn,t.length,n,r,i].forEach((e,t)=>c.setUint32(t*4,e)),new Uint8Array([...new Uint8Array(c.buffer),...t])},Zn=20210223,Qn=[...Lt,`cooper`,`expandenabled`,`expandcdot`,`lambdify`,`enabledaxioms`,`levelcomparison`],$n={zenon:{field:1,tag:1},isabelle:{field:2,tag:0},cooper:{field:4,tag:3,isConstant:!0},smt:{field:10,tag:8},z3:{field:11,tag:9},ls4:{field:17,tag:16},expandenabled:{field:18,tag:6,isConstant:!0},expandcdot:{field:19,tag:8,isConstant:!0},lambdify:{field:20,tag:9,isConstant:!0},enabledaxioms:{field:21,tag:10,isConstant:!0},levelcomparison:{field:22,tag:11,isConstant:!0}},er=[`false`,`timeout`],tr=`tla-ts ${Wn}`,nr=/* @__PURE__ */ new Map([[$n.zenon.field,3],[$n.isabelle.field,4]]),rr=(e,t)=>e!==void 0&&Jn(e)?e.fields[t]:void 0,ir=e=>e!==void 0&&typeof e==`object`&&`float`in e?e.float:1/0,ar=e=>{let t=new TextEncoder().encode(e),n=(e,t)=>e<<t|e>>>32-t,r=Array.from({length:Math.ceil(t.length/4)},(e,n)=>t[n*4]|t[n*4+1]<<8|t[n*4+2]<<16|t[n*4+3]<<24).reduce((e,t)=>{let r=Math.imul(n(Math.imul(t,3432918353),15),461845907);return Math.imul(n(e^r,13),5)+3864292196|0},0),i=Math.imul(r^t.length^(r^t.length)>>>16,2246822507),a=Math.imul(i^i>>>13,3266489909);return(a^a>>>16)&1073741823},or=e=>e!==void 0&&Jn(e)?[[e.fields[0],e.fields[1]],...or(e.fields[2])]:[],sr=(e,t,n)=>{let r=pn(t),i=Yn(r,0),a=Yn(r,i.next).value;if(i.value!==Zn||!Jn(a)||a.tag!==0)throw new S(`corrupted fingerprint file`);let o=rr(rr(a,0),1),s=(e,t)=>{let r=nr.get(t);return!n||r===void 0||rr(rr(e,0),r)===tr};e.clear(),(o!==void 0&&Jn(o)?o.fields:[]).flatMap(e=>or(e).toReversed()).forEach(t=>{if(typeof t[0]!=`string`||!Jn(t[1]))throw new S(`corrupted fingerprint file`);e.set(t[0],t[1].fields.map((e,t)=>s(e,t)?e:0))})},cr=(e,t)=>{let n=rr(t,0),r=rr(n,0),i=rr(rr(n,1),0);if(r===void 0||r===1)return;let a=ir(rr(e===`isabelle`?rr(i,0):i,0)),o=e===`isabelle`?rr(i,1):void 0,s=rr(rr(r,0),0);return{kind:`stored`,method:{prover:e,timeLimitMs:a*1e3,...typeof o==`string`&&{tactic:o}},isProved:r===0,...s!==void 0&&{reason:typeof s==`number`?er[s]:String(rr(s,0))}}},lr=(e,t)=>{let n=/* @__PURE__ */ new Date,r=t.method,i={float:Xt(r)},a=e===`zenon`?V(0,i,5):e===`isabelle`?V(0,V(0,i),r.tactic??`auto`):V(0,i),o=Ht(t),s=er.indexOf(o??``),c=o===void 0?0:V(0,s===-1?V(0,o):s);return V(0,V(0,V(0,Ft(t)?0:V(0,c),$n[e].isConstant?$n[e].tag:V($n[e].tag,a)),V(0,n.getFullYear(),n.getMonth(),n.getDate(),n.getHours(),n.getMinutes(),n.getSeconds()),tr,tr,tr))},ur=e=>{let t=2**Math.max(9,Math.ceil(Math.log2(e.size/2))),n=Array.from({length:t},()=>0);return e.forEach((e,r)=>{let i=ar(r)&t-1;n[i]=V(0,r,V(0,...e),n[i])}),V(0,V(0,e.size,V(0,...n),0,512))},dr=e=>String(e).padStart(2,`0`),fr=(e,t)=>{let n=/* @__PURE__ */ new Date,r=`${e}.history`,i=an(r,`${n.getFullYear()}-${dr(n.getMonth()+1)}-${dr(n.getDate())}_${dr(n.getHours())}_${dr(n.getMinutes())}_${dr(n.getSeconds())}`);dn(i,{recursive:!0}),[e,...t].filter(e=>B(e)).forEach(e=>ln(e,an(i,en(e)),{preserveTimestamps:!0})),hn(r).map(e=>an(r,e)).sort((e,t)=>yn(t).mtimeMs-yn(e).mtimeMs).slice(10).forEach(e=>vn(e,{recursive:!0,force:!0}))},pr=e=>{let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=new Map([...e].map(e=>{let r=new Map(Qn.flatMap(n=>{let r=e[1][$n[n].field],i=cr(n,rr(r,0));return i?(t.set(i,r),[[n,i]]):[]}));return n.set(r,e[1]),[e[0],r]}));return{results:r,save:i=>{e.clear(),r.forEach((r,i)=>{let a=[...n.get(r)??Array(23).fill(0)];Qn.forEach(e=>{let n=r.get(e);n&&(a[$n[e].field]=t.get(n)??lr(e,n))}),e.set(i,a)}),bn(`${i}.tmp`,Buffer.concat([Xn(Zn),Xn(ur(e))])),_n(`${i}.tmp`,i)}}},mr=((e,t)=>{let n=new Map(t.map(e=>{let[t,...n]=e.flag.split(` `);return[t,n.length]}));return{usage:e.replace(`{options}`,t.map(e=>`[${e.flag}]${e.isRepeatable?`...`:``}`).join(` `)),parse:e=>{let t=[],r=[],i=[];for(let a=0;a<e.length;a++){let o=n.get(e[a]);o===void 0?(e[a].startsWith(`-`)?i:r).push(e[a]):(t.push({name:e[a],values:e.slice(a+1,a+1+o)}),a+=o)}return{options:t,positionals:r,unknown:i,incomplete:t.find(e=>e.values.length<(n.get(e.name)??0)),has:e=>t.some(t=>t.name===e),get:e=>t.findLast(t=>t.name===e)?.values}}}})(`tla-ts tlapm {options} <Module.tla|glob>...`,[{flag:`-N`},{flag:`--summary`},{flag:`--strict`},{flag:`--toolbox <start> <end>`},{flag:`--line <num>`},{flag:`--printallobs`},{flag:`--threads <num>`},{flag:`--version`},{flag:`-I <directory>`,isRepeatable:!0},{flag:`-k`},{flag:`--noproving`},{flag:`--nofp`},{flag:`--nofpl <start> <end>`},{flag:`--safefp`},{flag:`--cleanfp`},{flag:`--usefp <file>`},{flag:`--cache-dir <directory>`},{flag:`--debug <flags>`,isRepeatable:!0},{flag:`--method <methods>`},{flag:`--solver <command>`},{flag:`--smt-logic <logic>`},{flag:`--stretch <factor>`},{flag:`--noflatten`}]),hr=[`Usage: tla-ts <Spec.tla|Spec.cfg|spec.ts|glob>... [-config <Spec.cfg>] [-continue] [-deadlock] [-dump [<format>] <file>] [-fp <num>] [-lncheck <final|default|off>] [-maxSetSize <num>] [-metadir <directory>] [-nowarning] [-seed <num>] [-terse] [-tool] [-view] [-workers <count|auto>]`,` ${mr.usage}`,` tla-ts [<JVM option>]... tlc2.TLC <TLC option>... <Spec>`,` (-cp tla2tools.jar or -Dtla-ts.tlc=1.7.4 picks the TLC to reproduce)`,` tla-ts [<JVM option>]... tla2sany.xml.XMLExporter [-I <directory>]... [-o] [-t] [-r] [-u] <Module.tla>`].join(`
10
+ `),gr={name:``,values:[],doc:` `},_r=[gr,{name:`(basic options)`,values:[],doc:` `},gr,{name:`--help`,values:[],doc:` show this help message and exit`},{name:`-help`,values:[],doc:` (same as --help)`},{name:`--version`,values:[],doc:` show version number and exit`},{name:`--verbose`,values:[],doc:` produce verbose messages`},{name:`-v`,values:[],doc:` (same as --verbose)`},gr,{name:`--where`,values:[],doc:` show location of standard library and exit`},{name:`--config`,values:[],doc:` show configuration and exit`},{name:`--summary`,values:[],doc:` show summary of theorems (implies -N and not -C)`},{name:`--strict`,values:[],doc:` report incomplete proofs, empty proof targets and failed obligations as errors and exit with a non-zero status`},{name:`--timing`,values:[],doc:` show runtime statistics`},gr,{name:`-I`,values:[`string`],doc:`<dir> add <dir> to search path`},{name:`-d`,values:[`string`],doc:``},gr,{name:`-k`,values:[],doc:` keep going on backend failures`},{name:`-N`,values:[],doc:` do not run any backend verifiers`},{name:`-C`,values:[],doc:` check proofs in Isabelle/TLA+`},gr,{name:`--threads`,values:[`int`],doc:`<int> set number of worker threads to <int>`},{name:`--method`,values:[`string`],doc:`<meth> set default method to <meth> (try --method help)`},{name:`--solver`,values:[`string`],doc:`<solver> set SMT solver to <solver>`},{name:`--smt-logic`,values:[`string`],doc:`<logic> set SMT logic to <logic>`},{name:`--stretch`,values:[`float`],doc:`<f> multiply all timeouts by <f>`},{name:`--fast-isabelle`,values:[],doc:``},gr,{name:`(advanced options)`,values:[],doc:` `},gr,{name:`--noflatten`,values:[],doc:` do not flatten obligations`},{name:`--nonormal`,values:[],doc:` do not normalize obligations before printing`},{name:`--debug`,values:[`string`],doc:`{[-]<flag>} enable/disable debugging flags`},{name:`--paranoid`,values:[],doc:``},{name:`--isaprove`,values:[],doc:``},gr,{name:`--toolbox`,values:[`int`,`int`],doc:`<int><int> toolbox mode`},{name:`--toolbox-vsn`,values:[`int`],doc:`<int> Toolbox protocol version, 1|2, 1 by default.`},{name:`--line`,values:[`int`],doc:`<int> line to prove`},{name:`--wait`,values:[`int`],doc:`<time> wait for <time> before printing obligations in progress`},{name:`--stdin`,values:[],doc:` read the tla file from stdin instead of file system. Only applies if single tla file is provided as input.`},{name:`--prefer-stdlib`,values:[],doc:` prefer built-in standard modules if the module search path contains files with the same names as modules in stdlib.`},{name:`--parser`,values:[`string`],doc:` Set parser backend to use: TLAPM (default) or SANY.`},{name:`--module-jar`,values:[`string`],doc:` Add a path to a .jar file containing additional TLA+ modules, such
11
11
  as the community modules. Multiple .jar files can be added by using
12
- this option multiple times.`},{name:`--noproving`,values:[],doc:` do not prove, report fingerprinted results only`},Nn,{name:`--printallobs`,values:[],doc:` print obligations in all toolbox messages`},Nn,{name:`--fpdir`,values:[`string`],doc:``},{name:`--safefp`,values:[],doc:` check tlapm, zenon, Isabelle versions for fingerprints`},{name:`--nofp`,values:[],doc:` do not use existing fingerprints, but overwrite any preexisting fingerprints associated with the current proof obligations, using the newly computed fingerprints and results`},{name:`--nofpl`,values:[`int`,`int`],doc:`<int><int> disable fingerprint use between given lines`},{name:`--cleanfp`,values:[],doc:` erase fingerprint file before starting`},Nn,{name:`--erasefp`,values:[`string`,`string`],doc:`<f><back> erase from file <f> all results of backend <back>`},{name:`--printfp`,values:[`string`],doc:`<f> print the fingerprints stored in file <f> and quit`},{name:`--usefp`,values:[`string`],doc:`<f> load fingerprints from file <f> (save as usual)`},{name:`--fpp`,values:[],doc:` print the fingerprints of obligations in toolbox messages`},{name:`--cache-dir`,values:[`string`],doc:'<directory> save auxiliary and temporary files under <directory>. Alternatively, this directory can be defined via the variable `TLAPM_CACHE_DIR` of the runtime environment. The command-line parameter takes precedence over the environment variable. If neither is specified, the default value is ".tlacache".'}],Fn=e=>/^[^ ]* */.exec(e)?.[0].length??0,In=()=>{let e=Math.max(...Pn.map(e=>e.name.length+Fn(e.doc)));return`Usage: tla-ts tlapm <options> FILE ...\noptions are:\n${Pn.filter(e=>e.doc!==``).map(t=>{let n=Fn(t.doc);return` ${t.name} ${t.doc.slice(0,n)}${` `.repeat(e-t.name.length-n)}${t.doc.slice(n)}\n`}).join(``)}`},Ln=e=>{for(let t=0;t<e.length;t++){let n=e[t];if(n===`--version`)return;if(!n.startsWith(`-`))continue;let r=Pn.find(e=>e.name===n);if(!r)return`unknown option '${n}'`;for(let i of r.values){if(t++,t===e.length)return`option '${n}' needs an argument`;let r=e[t];if(i===`int`&&lt(r)===void 0)return`wrong argument '${r}'; option '${n}' expects an integer`;if(i===`float`&&nt(r)===void 0)return`wrong argument '${r}'; option '${n}' expects a float`}let i=e[t];if(n===`--threads`&&(lt(i)??0)<0)return`--threads requires a positive argument`;if(n===`--debug`&&i.split(`,`).includes(`oldsmt`))return`--debug oldsmt: the old SMT encoding has been removed`;if(n===`--method`)try{tt(i)}catch(e){if(!(e instanceof C))throw e;return e.message}}},Rn=t=>[`.`,...e().map(e=>xt(yt(yt(Mt(e))),`lib/tlapm/stdlib`)).filter(I).slice(0,1),...t.options.flatMap(e=>e.name===`-I`?e.values:[]).toReversed()],zn=e=>console.error(`@!!BEGIN\n${e.map(e=>`@!!${e}\n`).join(``)}@!!END\n`),Bn=(e,t,n)=>zn([`type:obligation`,`id:${e.id}`,`loc:${e.location}`,`status:${t}`,...n]),Vn=e=>/^[+,\-./0-9:=@A-Z_a-z]+$/.test(e)?e:`'${e.replaceAll(`'`,`'\\''`)}'`,Hn={failed:10,incomplete:11,emptyTarget:12},Un=(e,t,n)=>{let r=e.summary;n||(r.absent.forEach(e=>console.error(`Missing proof at ${ht(e)}`)),r.omitted.forEach(e=>console.error(`Omitted proof at ${ht(e)}`)));let i=r.absent.length+r.omitted.length>0;i&&console.error(`${$e(e.location)}[ERROR]: Proof incomplete in module ${JSON.stringify(e.name)}: ${r.absent.length} missing, ${r.omitted.length} omitted proof step(s).`);let a=t&&e.obligations.length===0;return a&&console.error(`${$e(e.location)}[ERROR]: No proof obligation found for the selected target.`),[...i?[Hn.incomplete]:[],...a?[Hn.emptyTarget]:[]]},Wn=(e,t,n)=>{console.error(` tlapm ending abnormally with ${e.exception}\n`),n&&zn(t.message===``?[`type:error`,`url:http://tla.msr-inria.inria.fr/bugs`,`msg:Oops, this seems to be a bug in TLAPM.\nPlease give feedback to developers.\n\n\n ${e.exception}\n`]:[`type:warning`,`msg:${t.location===void 0?``:`${t.location}\n\n`}${t.message}`])},Gn=e=>{if(!(e instanceof n))throw e;return{kind:`aborted`,error:e}},Kn=e=>{try{return{kind:`done`,value:e()}}catch(e){return Gn(e)}},qn=(e,t,n)=>{let r=t.method.timeLimitMs,i=t.kind===`decided`?`; time-used: ${(t.timeUsedMs/1e3).toFixed(1)} (${Math.round(100*t.timeUsedMs/r)}%)`:``,a=r===0?``:`time-limit: ${r===1/0?`inf`:Number((r/1e3).toPrecision(6))}${i}`,o=[t.method.tactic,a].filter(Boolean).join(`; `),s=at(t),c=Qe(t),l=t.kind===`reused`,u=t.kind===`decided`?t.note:t.kind===`refused`?`${t.reason}\nObligation:\n\n`:t.kind===`unavailable`?`\n\\* ${t.warning}\n`:void 0,d=t.kind===`unavailable`||l?t.shipped:void 0;Bn(e,c?`proved`:`failed`,[`prover:${t.method.prover}`,...o===``?[]:[`meth:${o}`],...s===void 0?[]:[`reason:${s}`],`already:${l}`,...c?[]:[`obl:${l?``:u??`
13
- `}${d??ut(e,t,{...n,isTemporal:t.method.prover===`ls4`})}`]])},Jn=(e,t)=>{if(e.channel===`stdout`)return console.log(e.text);let n=e.channel===`toolbox`||e.channel===`toolboxOnly`;if(t&&n)return zn([`type:warning`,`msg:${e.text}`]);e.channel!==`toolboxOnly`&&console.error(e.text)},Yn=(e,t)=>Bn(e,`failed`,[`prover:fail`,`meth:time-limit: inf`,`reason:${t}`,`already:false`,`obl:${e.text}`]),Xn=[/^unsat/m,/SPASS beiseite: Proof found/,/SZS status Theorem/],Zn=(e,t,n,r,i)=>{let a=`${t}.out`;It(t,n);let o=performance.now();Rt(`sh`,[`-c`,`file=${Vn(t)}; ${e} >${Vn(a)}`],{stdio:[`ignore`,`inherit`,`inherit`],timeout:Number.isFinite(r)?r:void 0});let s=performance.now()-o,c=I(a)?kt(a,`utf8`):``;return i||[t,a].forEach(e=>Pt(e,{force:!0})),{verdict:Xn.some(e=>e.test(c))?`unsat`:c.startsWith(`sat`)?`sat`:`unknown`,output:c,timeUsedMs:s}},Qn=async(e,t,n,r)=>{let i=An(r.fingerprints),a=r.solver,o=await dt(e.obligations,{...r.backends,workers:r.workers,results:i.results,isFingerprinted:r.isFingerprinted,isProving:r.isProving,...r.isKeepingFiles&&{onInput:(e,n)=>It(`${t}/${e}`,n)},...a!==void 0&&{solveSmt:async(e,n,i)=>Zn(a,`${t}/${e}`,n,i,r.isKeepingFiles)},onReport:(e,t)=>{if(e.attempts.forEach(e=>{e.kind===`decided`&&e.errorOutput!==void 0&&process.stdout.write(e.errorOutput),e.kind===`unavailable`&&process.stderr.write(`${e.warning}\n`)}),e.warnings.forEach(e=>Jn(e,r.isToolbox)),r.isToolbox){if(t.kind.kind===`Error`)return Yn(t,`user error`);e.attempts.forEach(e=>qn(t,e,r.printing)),e.obligation.status===`trivial`&&Bn(t,`trivial`,[`prover:tlapm`,`already:false`])}}}),s=`${t}/${e.name}.thy`;if(It(s,ct(e.name,o,e.obligations,r.backends.isFlattened)),console.log(`(* created new ${JSON.stringify(s)} *)`),i.save(n),console.log(`(* fingerprints written in ${JSON.stringify(n)} *)`),!r.isProving)return!1;let c=o.flatMap((t,n)=>`reason`in t.obligation?[{report:t,obligation:e.obligations[n]}]:[]);r.isToolbox&&c.filter(e=>e.report.attempts.length===0&&e.obligation.kind.kind!==`Error`).forEach(e=>Yn(e.obligation,`unexpected error`)),c.toReversed().forEach(e=>console.error(`${$e(e.obligation.locus)}${gt(mt(`[ERROR]: @[<v2>Could not prove or check:@,%a@]`,Ze(e.obligation.sequent,r.printing)),35)}`));let l=`${e.obligations.length} obligation${e.obligations.length>1?`s`:``}`;return console.error(c.length===0?`${$e(e.location)}[INFO]: All ${l} proved.`:`${$e(e.location)}[ERROR]: ${c.length}/${l} failed.\nThere were backend errors processing module \`${JSON.stringify(e.name)}\`.`),c.length>0},$n=[`rwsetext`,`rw`,`rw+`],er=/* @__PURE__ */ new Set([`tempfiles`,`hidden`,`alldefs`,`rw+`,`rw`,`rwsetext`,`disable_arithmetic`,`no_smt_set_extensionality`,`smarter_types`]),tr=async e=>{let t=jn.parse(e),r=!t.has(`-N`)&&!t.has(`--summary`),i=t.options.flatMap(e=>e.name===`--debug`?e.values.flatMap(e=>e.split(`,`)):[]).reduce((e,t)=>t.startsWith(`-`)?new Set([...e].filter(e=>e!==t.slice(1))):/* @__PURE__ */ new Set([...e,t]),/* @__PURE__ */ new Set),a={isShowingHidden:i.has(`hidden`),isShowingAllDefinitions:i.has(`alldefs`)},o=$n.filter(e=>i.has(e)),s=i.has(`smarter_types`)&&!i.has(`disable_arithmetic`),c=s&&o.length>0?`smarter_types with --debug ${o.at(-1)}`:[...i].find(e=>!er.has(e)),l=Ln(e);if(l!==void 0)return console.error(`tla-ts tlapm: ${l}.\n${In()}`),2;if(t.has(`--version`))return console.log(ft),T.success;let u=t.unknown[0]??(r&&t.has(`--printallobs`)?`--printallobs`:void 0)??(c===void 0?void 0:`--debug ${c}`);if(u!==void 0)return console.error(`Error: tla-ts tlapm does not support the tlapm option ${u}.`),1;let d=Jt(t.positionals).map(e=>e.path),f=d.map(e=>e.endsWith(`.tla`)?e:`${e}.tla`);if(f.length===0)return console.error(Mn),1;let p=t.has(`--toolbox`)||t.has(`--line`);p&&console.log(`\n\\* TLAPM version ${ft}\n\\* launched at ${me(/* @__PURE__ */ new Date)} with command line:\n\\* ${[`tla-ts`,`tlapm`,...e].map(Vn).join(` `)}\n`);let m=t.options.reduce((e,t)=>{let[n,r]=t.values.map(e=>lt(e)??0);return t.name===`--toolbox`?{start:n,end:r===0?1/0:r}:t.name===`--line`?n===0?st:{start:n,end:n}:e},st),h=f.reduce((e,t)=>e.includes(yt(t))?e:[yt(t),...e],Rn(t)),g=/* @__PURE__ */ new Set,_=[],v=Kn(()=>{let e=f.findIndex(e=>!I(e));if(e!==-1){let t=d[e];throw console.error(`File "<unknown>":\nError: File ${JSON.stringify(t)} not found`),new n(`File ${t} not found`,{failure:`Module.Parser.parse_file`})}return rt(f.map(e=>({file:`./${e}`,source:kt(e,`utf8`)})),e=>{g.add(e);let t=h.map(t=>`${t}/${e}.tla`).find(I);if(t!==void 0)return{file:t,source:kt(t,`utf8`)};let n=ot.get(e);return n===void 0?void 0:{file:`${e}.tla`,source:n}},{lines:m,printing:a,onWarning:e=>{e.channel===`error`?_.push(e):Jn(e,p)}})});if(v.kind===`aborted`){let e=_.at(-1)?.locus;return Wn(v.error,{location:e&&ht(e),message:_.toReversed().map(e=>`${e.text}\n\n`).join(``)},p),3}let y=v.value,b=t.get(`--cache-dir`)?.[0]??process.env.TLAPM_CACHE_DIR??`.tlacache`,x=t.get(`--nofpl`)?.map(e=>lt(e)??0)??[0,0],S=t.get(`--method`)?.[0],C={isToolbox:p,isProving:!t.has(`--noproving`),workers:Math.max(1,lt(t.get(`--threads`)?.[0]??``)??Bt()),isFingerprinted:e=>!t.has(`--nofp`)&&!(e.locus&&e.locus.startLine>=x[0]&&e.locus.endLine<=x[1]),fingerprints:/* @__PURE__ */ new Map,backends:{defaultMethods:S===void 0?void 0:tt(S),stretch:nt(t.get(`--stretch`)?.[0]??`1`)??1,isFlattened:!t.has(`--noflatten`)&&[`yes`,`true`,void 0].includes(process.env.TLAPM_FLATTEN),smtLogic:i.has(`disable_arithmetic`)?`UF`:t.get(`--smt-logic`)?.[0]??`UFNIA`,smtEncoding:{isArithmetic:!i.has(`disable_arithmetic`),rewriteLevel:$n.findLastIndex(e=>i.has(e))+1,isSetExtensional:!i.has(`no_smt_set_extensionality`),isTyped:s}},printing:a,isKeepingFiles:i.has(`tempfiles`),solver:t.get(`--solver`)?.[0]??process.env.TLAPM_SMT_SOLVER},w=[];for(let[e,n]of y.entries()){let i=`${b}/${n.name}.tlaps`,a=`${i}/fingerprints`,o=t.get(`--usefp`)?.[0]??a;if(Dt(i,{recursive:!0}),t.has(`--cleanfp`)&&I(a)&&(Pt(a),console.log(`(* fingerprints file ${JSON.stringify(a)} removed *)`)),!t.has(`--cleanfp`)&&I(o)&&n.summary.total!==0&&(console.log(t.has(`--nofp`)?`(* will not use fingerprints (because of option \`--nofp\`), but will now load fingerprints from the file \`${o}\`, in order to overwrite with the new fingerprints, and then save the results at the end. *)`:`(* loading fingerprints in ${JSON.stringify(o)} *)`),wn(C.fingerprints,o,t.has(`--safefp`))),t.has(`--summary`)&&console.log(it(n)),p&&(n.obligations.forEach(e=>Bn(e,`to be proved`,t.has(`--printallobs`)?[`obl:${e.text}`]:[])),zn([`type:obligationsnumber`,`count:${n.obligations.length}`])),t.has(`--strict`)&&w.push(...Un(n,m.start>0||m.end<1/0,t.has(`--summary`))),!r)continue;kn(a,[...g,...y.slice(0,e+1).map(e=>e.name)].map(e=>`${e}.tla`));let s=await Qn(n,i,a,C).then(e=>({kind:`done`,value:e}),Gn);if(s.kind===`aborted`){let e=s.error;return console.error(`${$e(e.locus)}Error: ${e.message}`),Wn(e,{location:e.locus&&ht(e.locus),message:e.message},p),3}if(s.value&&t.has(`--strict`)&&w.push(Hn.failed),s.value&&!t.has(`--strict`)&&!p)return console.error(` tlapm ending abnormally with Failure("backend errors: there are unproved obligations")
12
+ this option multiple times.`},{name:`--noproving`,values:[],doc:` do not prove, report fingerprinted results only`},gr,{name:`--printallobs`,values:[],doc:` print obligations in all toolbox messages`},gr,{name:`--fpdir`,values:[`string`],doc:``},{name:`--safefp`,values:[],doc:` check tlapm, zenon, Isabelle versions for fingerprints`},{name:`--nofp`,values:[],doc:` do not use existing fingerprints, but overwrite any preexisting fingerprints associated with the current proof obligations, using the newly computed fingerprints and results`},{name:`--nofpl`,values:[`int`,`int`],doc:`<int><int> disable fingerprint use between given lines`},{name:`--cleanfp`,values:[],doc:` erase fingerprint file before starting`},gr,{name:`--erasefp`,values:[`string`,`string`],doc:`<f><back> erase from file <f> all results of backend <back>`},{name:`--printfp`,values:[`string`],doc:`<f> print the fingerprints stored in file <f> and quit`},{name:`--usefp`,values:[`string`],doc:`<f> load fingerprints from file <f> (save as usual)`},{name:`--fpp`,values:[],doc:` print the fingerprints of obligations in toolbox messages`},{name:`--cache-dir`,values:[`string`],doc:'<directory> save auxiliary and temporary files under <directory>. Alternatively, this directory can be defined via the variable `TLAPM_CACHE_DIR` of the runtime environment. The command-line parameter takes precedence over the environment variable. If neither is specified, the default value is ".tlacache".'}],vr=e=>/^[^ ]* */.exec(e)?.[0].length??0,yr=()=>{let e=Math.max(..._r.map(e=>e.name.length+vr(e.doc)));return`Usage: tla-ts tlapm <options> FILE ...\noptions are:\n${_r.filter(e=>e.doc!==``).map(t=>{let n=vr(t.doc);return` ${t.name} ${t.doc.slice(0,n)}${` `.repeat(e-t.name.length-n)}${t.doc.slice(n)}\n`}).join(``)}`},br=e=>{for(let t=0;t<e.length;t++){let n=e[t];if(n===`--version`)return;if(!n.startsWith(`-`))continue;let r=_r.find(e=>e.name===n);if(!r)return`unknown option '${n}'`;for(let i of r.values){if(t++,t===e.length)return`option '${n}' needs an argument`;let r=e[t];if(i===`int`&&Kt(r)===void 0)return`wrong argument '${r}'; option '${n}' expects an integer`;if(i===`float`&&zt(r)===void 0)return`wrong argument '${r}'; option '${n}' expects a float`}let i=e[t];if(n===`--threads`&&(Kt(i)??0)<0)return`--threads requires a positive argument`;if(n===`--debug`&&i.split(`,`).includes(`oldsmt`))return`--debug oldsmt: the old SMT encoding has been removed`;if(n===`--method`)try{Rt(i)}catch(e){if(!(e instanceof u))throw e;return e.message}}},xr=t=>[`.`,...e().map(e=>an(nn(nn(gn(e))),`lib/tlapm/stdlib`)).filter(B).slice(0,1),...t.options.flatMap(e=>e.name===`-I`?e.values:[]).toReversed()],Sr=e=>console.error(`@!!BEGIN\n${e.map(e=>`@!!${e}\n`).join(``)}@!!END\n`),Cr=(e,t,n)=>Sr([`type:obligation`,`id:${e.id}`,`loc:${e.location}`,`status:${t}`,...n]),wr=e=>/^[+,\-./0-9:=@A-Z_a-z]+$/.test(e)?e:`'${e.replaceAll(`'`,`'\\''`)}'`,Tr={failed:10,incomplete:11,emptyTarget:12},Er=(e,t,n)=>{let r=e.summary;n||(r.absent.forEach(e=>console.error(`Missing proof at ${Qt(e)}`)),r.omitted.forEach(e=>console.error(`Omitted proof at ${Qt(e)}`)));let i=r.absent.length+r.omitted.length>0;i&&console.error(`${It(e.location)}[ERROR]: Proof incomplete in module ${JSON.stringify(e.name)}: ${r.absent.length} missing, ${r.omitted.length} omitted proof step(s).`);let a=t&&e.obligations.length===0;return a&&console.error(`${It(e.location)}[ERROR]: No proof obligation found for the selected target.`),[...i?[Tr.incomplete]:[],...a?[Tr.emptyTarget]:[]]},Dr=(e,t,n)=>{console.error(` tlapm ending abnormally with ${e.exception}\n`),n&&Sr(t.message===``?[`type:error`,`url:http://tla.msr-inria.inria.fr/bugs`,`msg:Oops, this seems to be a bug in TLAPM.\nPlease give feedback to developers.\n\n\n ${e.exception}\n`]:[`type:warning`,`msg:${t.location===void 0?``:`${t.location}\n\n`}${t.message}`])},Or=e=>{if(!(e instanceof S))throw e;return{kind:`aborted`,error:e}},kr=e=>{try{return{kind:`done`,value:e()}}catch(e){return Or(e)}},Ar=(e,t,n)=>{let r=t.method.timeLimitMs,i=t.kind===`decided`?`; time-used: ${(t.timeUsedMs/1e3).toFixed(1)} (${Math.round(100*t.timeUsedMs/r)}%)`:``,a=r===0?``:`time-limit: ${r===1/0?`inf`:Number((r/1e3).toPrecision(6))}${i}`,o=[t.method.tactic,a].filter(Boolean).join(`; `),s=Ht(t),c=Ft(t),l=t.kind===`reused`,u=t.kind===`decided`?t.note:t.kind===`refused`?`${t.reason}\nObligation:\n\n`:t.kind===`unavailable`?`\n\\* ${t.warning}\n`:void 0,d=t.kind===`unavailable`||l?t.shipped:void 0;Cr(e,c?`proved`:`failed`,[`prover:${t.method.prover}`,...o===``?[]:[`meth:${o}`],...s===void 0?[]:[`reason:${s}`],`already:${l}`,...c?[]:[`obl:${l?``:u??`
13
+ `}${d??qt(e,t,{...n,isTemporal:t.method.prover===`ls4`})}`]])},jr=(e,t)=>{if(e.channel===`stdout`)return console.log(e.text);let n=e.channel===`toolbox`||e.channel===`toolboxOnly`;if(t&&n)return Sr([`type:warning`,`msg:${e.text}`]);e.channel!==`toolboxOnly`&&console.error(e.text)},Mr=(e,t)=>Cr(e,`failed`,[`prover:fail`,`meth:time-limit: inf`,`reason:${t}`,`already:false`,`obl:${e.text}`]),Nr=[/^unsat/m,/SPASS beiseite: Proof found/,/SZS status Theorem/],Pr=(e,t,n,r,i)=>{let a=`${t}.out`;bn(t,n);let o=performance.now();Sn(`sh`,[`-c`,`file=${wr(t)}; ${e} >${wr(a)}`],{stdio:[`ignore`,`inherit`,`inherit`],timeout:Number.isFinite(r)?r:void 0});let s=performance.now()-o,c=B(a)?pn(a,`utf8`):``;return i||[t,a].forEach(e=>vn(e,{force:!0})),{verdict:Nr.some(e=>e.test(c))?`unsat`:c.startsWith(`sat`)?`sat`:`unknown`,output:c,timeUsedMs:s}},Fr=async(e,t,n,r)=>{let i=pr(r.fingerprints),a=r.solver,o=await Jt(e.obligations,{...r.backends,workers:r.workers,results:i.results,isFingerprinted:r.isFingerprinted,isProving:r.isProving,...r.isKeepingFiles&&{onInput:(e,n)=>bn(`${t}/${e}`,n)},...a!==void 0&&{solveSmt:async(e,n,i)=>Pr(a,`${t}/${e}`,n,i,r.isKeepingFiles)},onReport:(e,t)=>{if(e.attempts.forEach(e=>{e.kind===`decided`&&e.errorOutput!==void 0&&process.stdout.write(e.errorOutput),e.kind===`unavailable`&&process.stderr.write(`${e.warning}\n`)}),e.warnings.forEach(e=>jr(e,r.isToolbox)),r.isToolbox){if(t.kind.kind===`Error`)return Mr(t,`user error`);e.attempts.forEach(e=>Ar(t,e,r.printing)),e.obligation.status===`trivial`&&Cr(t,`trivial`,[`prover:tlapm`,`already:false`])}}}),s=`${t}/${e.name}.thy`;if(bn(s,Gt(e.name,o,e.obligations,r.backends.isFlattened)),console.log(`(* created new ${JSON.stringify(s)} *)`),i.save(n),console.log(`(* fingerprints written in ${JSON.stringify(n)} *)`),!r.isProving)return!1;let c=o.flatMap((t,n)=>`reason`in t.obligation?[{report:t,obligation:e.obligations[n]}]:[]);r.isToolbox&&c.filter(e=>e.report.attempts.length===0&&e.obligation.kind.kind!==`Error`).forEach(e=>Mr(e.obligation,`unexpected error`)),c.toReversed().forEach(e=>console.error(`${It(e.obligation.locus)}${$t(Zt(`[ERROR]: @[<v2>Could not prove or check:@,%a@]`,Pt(e.obligation.sequent,r.printing)),35)}`));let l=`${e.obligations.length} obligation${e.obligations.length>1?`s`:``}`;return console.error(c.length===0?`${It(e.location)}[INFO]: All ${l} proved.`:`${It(e.location)}[ERROR]: ${c.length}/${l} failed.\nThere were backend errors processing module \`${JSON.stringify(e.name)}\`.`),c.length>0},Ir=[`rwsetext`,`rw`,`rw+`],Lr=/* @__PURE__ */ new Set([`tempfiles`,`hidden`,`alldefs`,`rw+`,`rw`,`rwsetext`,`disable_arithmetic`,`no_smt_set_extensionality`,`smarter_types`]),Rr=async e=>{let t=mr.parse(e),n=!t.has(`-N`)&&!t.has(`--summary`),r=t.options.flatMap(e=>e.name===`--debug`?e.values.flatMap(e=>e.split(`,`)):[]).reduce((e,t)=>t.startsWith(`-`)?new Set([...e].filter(e=>e!==t.slice(1))):/* @__PURE__ */ new Set([...e,t]),/* @__PURE__ */ new Set),i={isShowingHidden:r.has(`hidden`),isShowingAllDefinitions:r.has(`alldefs`)},a=Ir.filter(e=>r.has(e)),o=r.has(`smarter_types`)&&!r.has(`disable_arithmetic`),s=o&&a.length>0?`smarter_types with --debug ${a.at(-1)}`:[...r].find(e=>!Lr.has(e)),c=br(e);if(c!==void 0)return console.error(`tla-ts tlapm: ${c}.\n${yr()}`),2;if(t.has(`--version`))return console.log(Yt),w.success;let l=t.unknown[0]??(n&&t.has(`--printallobs`)?`--printallobs`:void 0)??(s===void 0?void 0:`--debug ${s}`);if(l!==void 0)return console.error(`Error: tla-ts tlapm does not support the tlapm option ${l}.`),1;let u=Mn(t.positionals).map(e=>e.path),d=u.map(e=>e.endsWith(`.tla`)?e:`${e}.tla`);if(d.length===0)return console.error(hr),1;let f=t.has(`--toolbox`)||t.has(`--line`);f&&console.log(`\n\\* TLAPM version ${Yt}\n\\* launched at ${je(/* @__PURE__ */ new Date)} with command line:\n\\* ${[`tla-ts`,`tlapm`,...e].map(wr).join(` `)}\n`);let p=t.options.reduce((e,t)=>{let[n,r]=t.values.map(e=>Kt(e)??0);return t.name===`--toolbox`?{start:n,end:r===0?1/0:r}:t.name===`--line`?n===0?Wt:{start:n,end:n}:e},Wt),m=d.reduce((e,t)=>e.includes(nn(t))?e:[nn(t),...e],xr(t)),h=/* @__PURE__ */ new Set,g=[],_=kr(()=>{let e=d.findIndex(e=>!B(e));if(e!==-1){let t=u[e];throw console.error(`File "<unknown>":\nError: File ${JSON.stringify(t)} not found`),new S(`File ${t} not found`,{failure:`Module.Parser.parse_file`})}return Bt(d.map(e=>({file:`./${e}`,source:pn(e,`utf8`)})),e=>{h.add(e);let t=m.map(t=>`${t}/${e}.tla`).find(B);if(t!==void 0)return{file:t,source:pn(t,`utf8`)};let n=Ut.get(e);return n===void 0?void 0:{file:`${e}.tla`,source:n}},{lines:p,printing:i,onWarning:e=>{e.channel===`error`?g.push(e):jr(e,f)}})});if(_.kind===`aborted`){let e=g.at(-1)?.locus;return Dr(_.error,{location:e&&Qt(e),message:g.toReversed().map(e=>`${e.text}\n\n`).join(``)},f),3}let v=_.value,y=t.get(`--cache-dir`)?.[0]??process.env.TLAPM_CACHE_DIR??`.tlacache`,b=t.get(`--nofpl`)?.map(e=>Kt(e)??0)??[0,0],x=t.get(`--method`)?.[0],C={isToolbox:f,isProving:!t.has(`--noproving`),workers:Math.max(1,Kt(t.get(`--threads`)?.[0]??``)??wn()),isFingerprinted:e=>!t.has(`--nofp`)&&!(e.locus&&e.locus.startLine>=b[0]&&e.locus.endLine<=b[1]),fingerprints:/* @__PURE__ */ new Map,backends:{defaultMethods:x===void 0?void 0:Rt(x),stretch:zt(t.get(`--stretch`)?.[0]??`1`)??1,isFlattened:!t.has(`--noflatten`)&&[`yes`,`true`,void 0].includes(process.env.TLAPM_FLATTEN),smtLogic:r.has(`disable_arithmetic`)?`UF`:t.get(`--smt-logic`)?.[0]??`UFNIA`,smtEncoding:{isArithmetic:!r.has(`disable_arithmetic`),rewriteLevel:Ir.findLastIndex(e=>r.has(e))+1,isSetExtensional:!r.has(`no_smt_set_extensionality`),isTyped:o}},printing:i,isKeepingFiles:r.has(`tempfiles`),solver:t.get(`--solver`)?.[0]??process.env.TLAPM_SMT_SOLVER},T=[];for(let[e,r]of v.entries()){let i=`${y}/${r.name}.tlaps`,a=`${i}/fingerprints`,o=t.get(`--usefp`)?.[0]??a;if(dn(i,{recursive:!0}),t.has(`--cleanfp`)&&B(a)&&(vn(a),console.log(`(* fingerprints file ${JSON.stringify(a)} removed *)`)),!t.has(`--cleanfp`)&&B(o)&&r.summary.total!==0&&(console.log(t.has(`--nofp`)?`(* will not use fingerprints (because of option \`--nofp\`), but will now load fingerprints from the file \`${o}\`, in order to overwrite with the new fingerprints, and then save the results at the end. *)`:`(* loading fingerprints in ${JSON.stringify(o)} *)`),sr(C.fingerprints,o,t.has(`--safefp`))),t.has(`--summary`)&&console.log(Vt(r)),f&&(r.obligations.forEach(e=>Cr(e,`to be proved`,t.has(`--printallobs`)?[`obl:${e.text}`]:[])),Sr([`type:obligationsnumber`,`count:${r.obligations.length}`])),t.has(`--strict`)&&T.push(...Er(r,p.start>0||p.end<1/0,t.has(`--summary`))),!n)continue;fr(a,[...h,...v.slice(0,e+1).map(e=>e.name)].map(e=>`${e}.tla`));let s=await Fr(r,i,a,C).then(e=>({kind:`done`,value:e}),Or);if(s.kind===`aborted`){let e=s.error;return console.error(`${It(e.locus)}Error: ${e.message}`),Dr(e,{location:e.locus&&Qt(e.locus),message:e.message},f),3}if(s.value&&t.has(`--strict`)&&T.push(Tr.failed),s.value&&!t.has(`--strict`)&&!f)return console.error(` tlapm ending abnormally with Failure("backend errors: there are unproved obligations")
14
14
  Raised at Stdlib.failwith in file "stdlib.ml", line 29, characters 17-33
15
15
  Called from Tlapm_lib.process_module in file "src/tlapm_lib.ml", lines 492-493, characters 12-37
16
16
  Called from Tlapm_lib.main.f in file "src/tlapm_lib.ml", line 640, characters 23-43
17
17
  Called from Stdlib__List.fold_left in file "list.ml", line 125, characters 24-34
18
18
  Called from Tlapm_lib.main in file "src/tlapm_lib.ml", line 643, characters 13-40
19
19
  Called from Tlapm_lib.init in file "src/tlapm_lib.ml", line 659, characters 8-59
20
- `),3}return Object.values(Hn).find(e=>w.includes(e))??T.success},nr=(1n<<63n)-1n,rr=1n<<16n,ir=(e,t)=>{let n=e.map(e=>{let t=BigInt.asIntN(32,e);return t<0n?t:BigInt.asIntN(64,e)}),r=n.toSorted((e,t)=>e<t?-1:+(e>t)),i=r.slice(1).map((e,t)=>e-r[t]).filter(e=>e<=nr),a=/* @__PURE__ */ new Map;e.forEach((e,r)=>{let i=e&t-1n,o=a.get(i),s=n[r];o?(o.min=s<o.min?s:o.min,o.max=s>o.max?s:o.max):a.set(i,{min:s,max:s})});let o=[...a.values()].map(e=>e.max-e.min).filter(e=>e>nr).map(e=>e===nr+1n?-e:(1n<<64n)-e);return[...i,...o].reduce((e,t)=>t<e?t:e,nr)},ar=(e,n)=>{let r=Ue(n)?`tlc2.tool.EvalException`:`java.lang.RuntimeException`;return e===``?t(r):`TLC threw an unexpected exception.\nThis was probably caused by an error in the spec or model.\nThe error occurred when TLC was ${e}.\nThe exception was a ${r}\n: `},or=e=>{let t=e.onOutput,n=e.isTool??!1,a=e.isContinued??!1,o=Ae(e),s=o.config,l=o.environment,u=l.runtime,d=o.search;if(!d)throw new r(`tla-ts can't search a specification without variables`);let m=(e,n,r=n,i=!0)=>t({kind:`message`,code:e,isError:i,message:n,toolMessage:r}),h=d.properties.liveness;if(h.length>0){e.onProgress?.({kind:`liveness-initializing`,isSymmetric:d.isSymmetric,isConstrained:d.isConstrained});let t=ee(()=>xe(()=>re(h,d.spec.temporals,l,{getFingerprint:()=>0,getSuccessors:()=>[]})))?.branches;t&&e.onProgress?.({kind:`liveness-prepared`,branches:t})}if((e.workers??1)!==1)return m(M.general,`Depth-First Iterative Deepening mode does not support multiple workers (https://github.com/tlaplus/tlaplus/issues/548). Please run TLC with a single worker.`),T.error;if(h.length>0)return m(M.general,`Depth-First Iterative Deepening mode does not support checking liveness properties (https://github.com/tlaplus/tlaplus/issues/548). Please check liveness properties in Breadth-First-Search mode.`),T.error;u.generatedStates=-1,u.distinctStates=-1,u.initialStates=-1,u.queueSize=-1,u.diameter=-1,u.isStarted=!0;let g=Ce(o.specification.assumptions,l,m);if(g!==void 0)return g;let _=o.getDescription().actions,v=/* @__PURE__ */ new Map,b={level:1,leveled:0,buckets:rr},x=(e,t)=>{let n=v.get(e);return n===void 0?(BigInt(v.size)>=b.buckets*20n&&(b.buckets*=2n),v.set(e,b.level<<2|b.leveled|t),0):(v.set(e,n|t),n)},C=e=>v.get(e)??0,w=e=>(e&2)===b.leveled||(e&1)==1,E=e=>e===0||e>>>2===b.level,D=0,k={isDone:!1,errorCode:0,continuedCode:0,isKeepingCallStack:!1,errorEntry:void 0,stopCode:`searching`,isMoreLevel:!1},A=(e,t,n)=>!a&&k.isDone?!1:(k.errorEntry=e,k.errorCode=n,k.isDone=!0,k.isKeepingCallStack=t,k.stopCode=`error`,!0),ne=e=>d.toRecord(e.map(e=>e??le(`null`))),ie=()=>{let e=`${D} states generated, ${v.size} distinct states found`;n&&m(M.depthFirstProgress,`Progress: ${e}.`,`Progress(-1) at ${me(/* @__PURE__ */ new Date)}: ${e}, -1 states left on queue.`,!1),m(M.depthFirstStats,`${e}.`,void 0,!1)},oe=()=>t({kind:`success`,optimistic:Ne(v.size,D),actual:v.size===0&&D===0?0:Ee(ir([...v.keys()],b.buckets))}),se=/* @__PURE__ */ new WeakMap,ce;u.getLevel=e=>se.get(e)??0,u.getCurrentState=()=>ce;let de=[],fe,pe=()=>{let e=[],t=t=>(e.push(t),!1),r=d.spec.init;r&&ue(r,l,t,d.spec.scope,t),D=e.length;for(let t of e){if(!t.every(e=>e!==void 0))return m(M.initialStateIncomplete,`State is not completely specified by the initial predicate:\n${j(ne(t))}`),M.initialStateIncomplete;fe=t,se.set(t,1);let e=d.satisfiesConstraints(t),r=e?u.getFingerprint(t):0n,i=e?x(r,0):0;if(e&&i===0&&de.push({state:t,fingerprint:r}),i!==0)continue;let o=()=>s.alias===void 0?d.toRecord(t):d.evaluateAlias(s.alias,t,t,n),c=a?d.getViolatedInvariants(t):[d.findViolatedInvariant(t)].filter(e=>e!==void 0);for(let e of c){if(m(M.invariantViolatedInitial,`Invariant ${e.name} is violated by the initial state:\n${j(o())}`),!a)return M.invariantViolatedInitial;k.continuedCode=M.invariantViolatedInitial}let l=d.findFailedInitialPredicate(t);if(l)return m(M.propertyViolatedInitial,`Property ${l.name} is violated by the initial state:\n${j(o())}`),M.propertyViolatedInitial}return 0},he=(e,t)=>{let n=[];try{return te(e.expression,t,l,e=>{if(n.length===Re())throw new c;return n.push(e.state),!1},e.scope),{successors:n,incomplete:void 0}}catch(e){if(!(e instanceof i))throw e;return{successors:n,incomplete:e}}},ge=(e,t,n)=>{try{let r=n?d.findViolatedInvariant(t,e):void 0;if(r)return{code:M.invariantViolatedBehavior,text:`Invariant ${r.name} is violated.`,isViolated:!0};let i=d.findViolatedActionProperty(e,t);return i&&{code:M.actionPropertyViolatedBehavior,text:`Action property ${i.name} is violated.`,isViolated:!0}}catch(e){if(!(e instanceof y)||!ye(e))throw e;return{code:_e(e,!0).code,text:e.message.slice(0,e.message.indexOf(`
21
- `)),isViolated:!1}}},ve=[],be=[],Se=(e,n,r,i,a)=>{m(e,n,r),m(M.behaviorUpToThisPoint,`The behavior up to this point is:`);let o=[...ve.slice(0,i+1).map(e=>e.state),...a?[a]:[]];t({kind:`behavior`,states:o.map(ne),isInvariant:e===M.invariantViolatedBehavior})},we=(t,n,r)=>{let i=ve[t],o=i.state,l=!0,p=!0,m=!0,h,g=(e,n,r)=>(A(i,r,e)&&Se(e,n,n,t,h),m);ce=o;try{for(let n of _){let i=he(n,o),s=i.incomplete,f=i.successors.length+ +!!s;D+=f,l&&=f===0;for(let e of i.successors){h=e,se.set(e,t+2);let n=d.satisfiesConstraints(e,o)&&d.satisfiesActionConstraints(o,e),i=n?u.getFingerprint(e):0n,s=n?x(i,0):0;if(n&&(p&&=(s&1)==1,m&&=!E(s),!w(s))){if(r.length===Re())throw new c;r.push({state:e,fingerprint:i})}let l=ge(o,e,s===0);if(l?.isViolated&&a)Se(l.code,l.text,l.text,t,e),k.continuedCode=l.code;else if(l)return g(l.code,l.text,!l.isViolated)}if(s)return h=s.state,g(M.incompleteSuccessor,Fe(s.variables,n.name,_.length,e.version),!1);h=void 0}return l&&s.checkDeadlock?g(M.deadlockReached,`Deadlock reached.`,!1):((p||n&&m)&&x(i.fingerprint,1),m)}catch(e){let n=O(e)?new f:e;if(!(n instanceof y))throw e;let r=n instanceof f;if(A(i,!r,r?M.stackOverflow:M.general)){let e=ar(`computing the set of next states`,n);Se(r?M.stackOverflow:M.general,r?n.message:`${e}${n.message}`,r?n.message:`${e}${De(n.message,!0)}`,t,h)}throw n}},Te=(e,t)=>{for(;e.length>0;){let n=C(e[0].fingerprint);if(!w(n)&&t<n>>>2)return!0;e[0]=e[e.length-1],e.pop()}return!1},ke=e=>{let t=[...de];k.stopCode=`searching`,k.isMoreLevel=!1;let n=0;try{for(;k.stopCode===`searching`;){for(;t.length>0&&w(C(t[0].fingerprint));)t[0]=t[t.length-1],t.pop();if(t.length===0){k.stopCode=`done`;return}ve[0]=t[0],be[0]=[],n=0;let r=e<2,i=we(0,r,be[0]);for(k.isMoreLevel||=!i,n=1;!r;){if(!Te(be[n-1],n)){let e=ve[n-1];if(v.set(e.fingerprint,C(e.fingerprint)&-3|b.leveled),n===1)break;n--;continue}ve[n]=be[n-1][0],be[n]=[];let t=n>=e-1,r=we(n,t,be[n]);if(k.isMoreLevel||=!r,n++,t)break}}}catch(e){if(!(e instanceof y))throw e;if(k.stopCode=`error`,A(ve[n],!0,M.general)){let t=ar(``,e);m(M.general,`${t}${e.message}`,`${t}${De(e.message,!0)}`)}}},je=e=>{let n=ae(l);try{if(_.every(t=>{let r=[];return Pe([t],e.state,n,e=>r.push(e)),D+=r.length,r.every(t=>t.every(e=>e!==void 0)&&d.checkReplayedSuccessor(e.state,t,n,()=>x(u.getFingerprint(t),0)===0))}))return}catch(e){if(!(e instanceof y)&&!O(e))throw e}t({kind:`nested-expressions`,callStack:n.callStack?.expressions??[]})},Me=e=>{ie();let t=[e,k.errorCode,k.continuedCode].find(e=>e!==0);return t===void 0?T.success:S(t)},N=()=>{try{return{code:pe(),error:void 0}}catch(e){let t=O(e)?new f:e;if(!(t instanceof y))throw e;return{code:0,error:t}}},P=N();if(P.error){let t=P.error,n=ye(t)&&t.cause instanceof y?t.cause:t,r=fe,i=r?``:ar(`computing initial states`,n),a=r?`\nWhile working on the initial state:\n${j(ne(r))}`:``;m(r?M.initialState:M.general,`${i}${n.message}${a}`,`${i}${De(n.message,!0)}${a}`),D=0,de.length=0;let o=N().error!==void 0;return o&&m(M.nestedExpression,`The error occurred when TLC was evaluating the nested\nexpressions at the following positions:\ntlc2.tool.impl.FastTool@${(Number(BigInt.asUintN(28,Oe([e.source])))|268435456).toString(16)}`),ie(),o?T.specEvaluationFailure:p(n)}if(P.code!==0)return S(P.code);if(m(M.depthFirstInitGenerated,`Finished computing initial states: ${D} states generated, with ${de.length} of them distinct.`,void 0,!1),_.length===0)return oe(),Me(0);let Ie=!1,Le=M.general;for(let t=2;t<=e.maxDepth;t++){if(Ie){let e=k.errorEntry;!e&&k.continuedCode===0&&(Le=0,oe()),e&&k.isKeepingCallStack&&je(e);break}if(m(M.depthFirstLevel,`Starting level ${t}: ${D} states generated, ${v.size} distinct states found.`,void 0,!1),b.level++,b.leveled=2-b.leveled,ke(t),k.isDone=!1,Le=k.isKeepingCallStack?0:k.errorCode,Le!==0)return Me(Le);Ie=k.stopCode===`error`||!k.isMoreLevel}return Me(Le)},sr=/* @__PURE__ */ new Set([M.invariantEvaluationFailed,M.actionPropertyEvaluationFailed,M.incompleteSuccessor]),cr=2147483647,lr=(e,t)=>e.every((e,n)=>fe(e,t[n])),ur=e=>{let t=[];for(let n=e;n;n=n.predecessor){let e=n.predecessor;e&&lr(n.state,e.state)||t.unshift(n)}return t.forEach((e,n)=>{e.predecessor=t[n-1],e.level=n+1}),t},dr=(e,t,n)=>{let r=e.map(e=>t(e.state)),i=/* @__PURE__ */ new Map,a=[],o=[];r.forEach((t,n)=>{if(i.has(t)||(i.set(t,a.length),a.push(e[n].state),o.push([])),n===0)return;let s=i.get(r[n-1])??0,c=i.get(t)??0;s!==c&&!o[s].includes(c)&&o[s].push(c)});let s=n(o,a);if(!s)return;s.addInitialState(0,a[0]),a.forEach((e,t)=>s.addState(t,e,o[t].map(e=>({index:e,state:a[e]}))));let c=s.findViolation();if(!c)return;let l=e=>e.filter((t,n)=>n===0||t!==e[n-1]).length,u=[...c.prefix,...c.cycle],d=l(u),f=l(u.slice(0,c.prefix.length+1));return{length:d,loopStart:r[d-1]===t(a[u[c.prefix.length]])?d-1:f-1,properties:s.getViolatedProperties(e.slice(0,d).map(e=>e.state),f-1)}},fr=(e,t,n,r,i)=>{let a=t.map(()=>/* @__PURE__ */ new Map),o=t=>e===`rlaction`?t.action:r(t.state),s=e=>i(e.predecessor?.state,e.state,-10);return{getNextActionIndex:r=>{if(e===`random`)return Math.floor(n.nextDouble()*t.length);let i=o(r);a.forEach(e=>{e.has(i)||e.set(i,0)});let s=a.map(e=>Math.exp(e.get(i)??0)),c=s.reduce((e,t)=>e+t,0),l=s.map((e,t)=>({index:t,weight:e/c})).sort((e,t)=>t.weight-e.weight),u=n.nextDouble(),d=0;return(l.find((e,t)=>(d=t===0?e.weight:d+e.weight,d>=u))??l[l.length-1]).index},markDisabled:(t,n)=>{e!==`random`&&(e===`rlaction`&&s(n),a[t].set(o(n),-Number.MAX_VALUE))},learnTrace:e=>{for(let n=e;n.predecessor;n=n.predecessor){let e=o(n),r=a.reduce((t,n)=>Math.max(t,n.get(e)??-Number.MAX_VALUE),-Number.MAX_VALUE),i=a[t.indexOf(n.action)],c=o(n.predecessor);i.set(c,.7*(i.get(c)??0)+.3*(s(n)+.7*r))}}}},pr=e=>{let t=e.onSimulation,n=Ae(e),a=n.config,o=n.specification,l=n.environment,u=l.runtime,d=n.search,f=e.seed??0n,p=e.traceDepth===-1?cr:e.traceDepth,m=e.traceCount??(1n<<63n)-1n,h=Me(f);for(let t=0n;t<e.aril;t++)h.nextDouble();let g=Me(h.nextLong()),_={generatedStates:0,traces:0,levelMean:0,levelM2:0,seed:f,aril:e.aril},v=(e,n,r=n,i=!0)=>t({kind:`message`,code:e,isError:i,message:n,toolMessage:r}),b=()=>t({kind:`summary`,statistics:{..._}}),x=/* @__PURE__ */ new WeakMap,C=n.getDescription(),E=C.inits,D=C.actions,O=0,k=0,A;if(u.getSuccessorAction=()=>A,u.getLevel=e=>x.get(e)?.level??0,u.getBehavior=e=>{let t=x.get(e);return t?ur(t).map(e=>e.state):[e]},u.getSimulationValue=(t,n)=>{let r=n&&x.get(n);switch(t){case`diameter`:return k===0?0:O+1;case`generated`:case`distinct`:case`queue`:throw new w(`TLCGet(${t}) was undefined.`);case`action`:return r&&se(r.action);case`config`:return ie([[`mode`,e.isGenerating?`generate`:`simulate`],[`depth`,p===cr?-1:p],[`traces`,Number(BigInt.asIntN(32,m))],[`deadlock`,a.checkDeadlock],[`seed`,String(f)],[`aril`,String(e.aril)],[`worker`,1],[`install`,`unknown`],[`sched`,e.scheduler]]);case`stats`:{let e=/* @__PURE__ */ new Map;for(let t=r;t&&t.level>1;t=t.predecessor)e.set(t.action.name,(e.get(t.action.name)??0)+1);return ie([[`traces`,_.traces],[`duration`,Math.floor((Date.now()-u.startedAt)/1e3)],[`generated`,_.generatedStates],[`behavior`,ie([[`actions`,ie([...e])],[`id`,k]])],[`worker`,0],[`distinct`,-1],[`distinctvalues`,-1],[`retries`,-1],[`actions`,ie([])],[`levelmean`,_.levelMean],[`levelvariance`,Math.round(_.levelM2/(_.traces+1))]])}}},u.isStarted=!0,!d)throw new r(`tla-ts can't simulate a specification without variables`);let ne=t=>{let n=d.findPostconditionViolation(t);if(n)return n.counts!==void 0&&(e.onPrint??console.log)(n.counts),v(n.code,n.message,Be(n.code,n.message,!0)),n},ae=d.properties.liveness,oe=(e,t)=>ee(()=>xe(()=>re(ae,d.spec.temporals,l,{getFingerprint:e=>Number(BigInt.asIntN(32,u.getFingerprint(e.state))),getSuccessors:n=>e[n].map(e=>({index:e,state:t[e]}))}))),de=oe([],[])?.branches;de&&e.onProgress?.({kind:`liveness-prepared`,branches:de});let fe=Ce(o.assumptions,l,v);if(fe!==void 0)return fe;let pe=E[E.length-1],he=(e,t,n)=>{let r={state:e,action:t,predecessor:n,level:(n?.level??0)+1};return x.set(e,r),r},ge=e=>d.toRecord(e.map(e=>e??le(`null`))),ve=t=>t.map((n,r)=>({action:n.action.name,label:ce(n.action,e.version,n.level===1),state:a.alias===void 0||!n.state.every(e=>e!==void 0)?ge(n.state):d.evaluateAlias(a.alias,n.state,(t[r+1]??n).state,e.isTool??!1)})),be=e=>Le(e.map(e=>d.toRecord(e.state)),e.slice(1).map(e=>se(e.action)),void 0),Se=[],we=e=>e.every(e=>e!==void 0),Ee=[],Oe=(e,t)=>{let n=mr(e);if(!t)return v(M.general,`${hr(n)}${n.message}`,`${hr(n)}${De(n.message,!0)}`),b(),T.error;let r=_e(n,!1),i=`While working on the initial state:\n${j(ge(t))}`;return v(M.initialState,`${r.message}\n${i}`,`${r.toolMessage}\n${i}`),b(),S(M.initialState)},ke=d.spec.init,je=e=>{if(Ee.length===Re())throw new c;return Ee.push(e),!1};try{ke&&ue(ke,l,je,d.spec.scope,je)}catch(e){return Oe(e,void 0)}_.generatedStates=Ee.length,v(M.computingInitProgress,`Computed ${Ee.length} initial states...`,void 0,!1);for(let e of Ee){if(!we(e))return v(M.initialStateIncomplete,`State is not completely specified by the initial predicate:\n${j(ge(e))}`),T.error;try{let t=he(e,pe,void 0),n=d.findViolatedInvariant(e);if(n){let e=ve([t])[0].state;return v(M.invariantViolatedInitial,`Invariant ${n.name} is violated by the initial state:\n${j(e)}`),u.counterExample=be([t]),ne(!0),T.safetyViolation}let r=d.findFailedInitialPredicate(e);if(r){let e=ve([t])[0].state;return v(M.propertyViolatedInitial,`Property ${r.name} is violated by the initial state:\n${j(e)}`),u.counterExample=be([t]),ne(!0),T.livenessViolation}d.satisfiesConstraints(e)&&(d.trackStatePossible(e),Se.push(t))}catch(t){return Oe(t,e)}}if(Ee.length===0)return v(M.noInitialStates,`There is no state satisfying the initial state predicate.`),T.error;if(Se.length===0)return v(M.noInitialStatesInModel,`There is no state satisfying the initial state predicate and the state-constraint(s).`),T.error;v(M.initGenerated1,`Finished computing initial states: ${Se.length} distinct state generated at ${me(/* @__PURE__ */ new Date)}.`,void 0,!1);let N=(e,t,n)=>({code:e,message:t,toolMessage:t,node:n,isException:!1,isSummarized:!0}),Ne=(t,n)=>{let r=[],a;u.deferred=void 0,A=n;try{te(n.expression,t.state,l,e=>{let i=he(e.state,n,t);i.deferred=u.deferred,u.deferred=void 0,_.generatedStates++;try{let e=d.findViolatedInvariant(i.state,t.state);if(e)return a=N(M.invariantViolatedBehavior,`Invariant ${e.name} is violated.`,i),!0;let n=d.findViolatedActionProperty(t.state,i.state);if(n)return a=N(M.actionPropertyViolatedBehavior,`Action property ${n.name} is violated.`,i),!0}catch(e){if(!(e instanceof y)||!ye(e))throw e;let t=_e(e,!0);return a={...N(t.code,t.message,i),toolMessage:t.toolMessage},!0}if(!d.satisfiesConstraints(i.state,t.state)||(d.trackStatePossible(i.state),!d.satisfiesActionConstraints(t.state,i.state)))return!1;if(d.trackActionPossible(t.state,i.state),r.length===Re())throw new c;return r.push(i),!1},n.scope,e.isGenerating?g:void 0)}catch(a){if(!(a instanceof i))throw a;let o=he(a.state.map(e=>e??le(`null`)),n,t),s=Fe(a.variables,n.name,D.length,e.version);return{successors:r,error:N(M.incompleteSuccessor,s,o)}}return{successors:r,error:a}},P=Se[0],Pe=fr(e.scheduler,D,g,u.getFingerprint,d.getReward),Ie=t=>{if(ae.length===0)return;let n=ur(t),r=dr(n,u.getFingerprint,oe);if(!r)return;let i=n[r.length];return{name:r.properties[0],properties:r.properties,trace:ve(n.slice(0,r.length)),loopStart:r.loopStart,loopLabel:i&&ce(i.action,e.version,i.level===1)}},ze=()=>{P=Se[Math.floor(g.nextDouble()*Se.length)];for(let e=0;e<p;e++){if(u.isStopped)return`stopped`;let e=Pe.getNextActionIndex(P),t=Te(g),n=[];for(let r=0;r<D.length;r++){let r=Ne(P,D[e]);if(r.error)return r.error;if(n=r.successors,n.length>0)break;Pe.markDisabled(e,P),e=(e+t)%D.length}if(n.length===0){if(a.checkDeadlock)return N(M.deadlockReached,`Deadlock reached.`,P);break}P=n[Math.floor(g.nextDouble()*n.length)],P.deferred?.(P.state)}if(u.isStopped)return`stopped`;let t=Ie(P);if(t)return{...N(M.temporalPropertyViolated,``,P),isException:!0,violation:t};let n=Math.min(p,P.level),r=n-_.levelMean;_.levelMean+=Math.trunc(r/Math.max(_.traces,1)),_.levelM2+=r*(n-_.levelMean),e.scheduler===`rl`&&Pe.learnTrace(P)},Ve=(e,t)=>{let n=mr(e),r=Ue(n)?void 0:He(n.message);if(r)return{code:r.code,message:n.message,toolMessage:Be(r.code,n.message,!0),node:t,isException:!0,isSummarized:!1};let i=hr(n);return{code:M.general,message:`${i}${n.message}`,toolMessage:`${i}${De(n.message,!0)}`,node:t,isException:!0,isSummarized:i!==s}},F=Me(f);u.getRandom=()=>F;let We=[],Ge=e.isContinued??!1;for(;;){_.traces++,k=_.traces;let t=(()=>{try{return ze()}catch(e){return Ve(e,P)}})();if(t===`stopped`||(O++,t&&We.push(t),t?.isException)||BigInt(O)>=m)break;if(t!==void 0&&(!Ge||sr.has(t.code))&&e.traceCount===void 0){_.traces++;break}}let Ke=We.findIndex(e=>e.isException||!Ge||sr.has(e.code)),qe=Ke===-1?We:We.slice(0,Ke+1);qe.forEach(n=>{n.violation?(e.onProgress?.({kind:`violation`,status:`liveness-violation`,violation:n.violation}),b()):(v(n.code,n.message,n.toolMessage),t({kind:`behavior`,trace:ve(ur(n.node)),isLastStateOnly:p===cr}),n.isSummarized&&b())});let Je=qe[qe.length-1],Ye=Je?S(Je.code):T.success;Je&&(u.counterExample=be(ur(Je.node)));let Xe=ne(Je!==void 0),Ze=Xe?S(Xe.code):T.success,Qe=Math.max(Ye,Ze);return t({kind:`progress`,statistics:{..._}}),Qe===T.success&&b(),Qe},mr=e=>{if(O(e))return new f;if(!(e instanceof y))throw e;return e},hr=e=>Ue(e)?g:s,gr={builtin:1,number:2,string:3,ident:4,added:5},_r=()=>({labelFlag:!1,labelRoot:`Lbl_`,fairnessOption:``,checkTermination:!1,specOption:!1,myspecOption:!1,inputVersionNumber:1903}),vr=e=>{let t=0,n=0,r=!1;for(let i of e)if(i===`.`)r=!0;else if(i<`0`||i>`9`||(t=10*t+Number(i),r&&(n+=1),n>3))return-1;return t*10**Math.max(0,3-n)},yr=[`unfair`,`wf`,`sf`],R=()=>({col:0,line:0,macroCol:0,macroLine:-1,lbl:``}),br=e=>e.macroLine<0?`line ${e.line}, column ${e.col}`:`line ${e.line}, column ${e.col} of macro called at line ${e.macroLine}, column ${e.macroCol}`,xr=e=>{if(e.kind!==`LabeledStmt`)throw new b(`ClassCastException: ${e.kind}`);return e},Sr=(e,t)=>{if(t<0||t>=e.length)throw new b(`ArrayIndexOutOfBoundsException: ${t}`);return e[t]},Cr=(e,t,n)=>({string:e,column:t,type:n}),wr=e=>e.type===gr.string?e.string.length+2:e.string.length,Tr=(e=[])=>({tokens:e,anchorTokens:void 0,anchorTokCol:void 0}),Er=e=>{for(;e.tokens.length>0&&e.tokens[0].length===0;)e.tokens.shift();for(;e.tokens.length>0&&e.tokens[e.tokens.length-1].length===0;)e.tokens.pop();let t=Math.min(999999,...e.tokens.filter(e=>e.length>0).map(e=>e[0].column));e.tokens.forEach(e=>e.forEach(e=>{e.column-=t}));let n=[],r=[];e.tokens.forEach((t,i)=>{if(r.push(0),n.push(void 0),t.length===0)return;let a=t[0].column,o=e.tokens.slice(0,i).findLast(e=>e.length>0&&e[0].column<=a);if(o===void 0)return;let s=o.findIndex((e,t)=>t>0&&e.column>a),c=o[(s===-1?o.length:s)-1];n[i]=c,r[i]=c.column}),e.anchorTokens=n,e.anchorTokCol=r},Dr=e=>{let t=Tr(e);return Er(t),t},Or=e=>{let t=e.anchorTokens,n=e.anchorTokCol;if(t===void 0||n===void 0)throw new b(`NullPointerException: TLAExpr.renormalize`);e.tokens.forEach((e,r)=>{let i=t[r];if(i===void 0)return;let a=i.column-n[r];if(n[r]=i.column,a<0)throw new D(`TLAExpr.renormalize() found anchor has moved to left.`);e.forEach(e=>{e.column+=a})})},kr=e=>Dr(e.tokens.map(e=>e.map(e=>({...e})))),Ar=(e,t,n)=>{let r=t.tokens.length;e.tokens.splice(0,0,...t.tokens.slice(0,r-1));let i=t.tokens[r-1],a=e.tokens[r-1],o=i[i.length-1],s=o.column+wr(o)+n;a.forEach(e=>{e.column+=s}),a.splice(0,0,...i);let c=[...t.anchorTokens??[]],l=[...t.anchorTokCol??[]];for(let t=r;t<e.tokens.length;t++)c.push(e.anchorTokens?.[t-r+1]),l.push(e.anchorTokCol?.[t-r+1]??0);e.anchorTokens=c,e.anchorTokCol=l,Or(e)},jr=e=>e.tokens.length===1&&e.tokens[0].length===1,Mr=(e,t)=>Sr(Sr(e.tokens,t.line),t.item),Nr=(e,t,n)=>{if(e.tokens.length<=t.line)throw new E(`TLAExpr.StepCoord called with line too big`);if(e.tokens[t.line].length<=t.item)throw new E(`TLAExpr.StepCoord called with col too big`);let r={line:t.line,item:t.item};for(let t=0;t<n;t++)if(r.item+=1,e.tokens[r.line].length===r.item){for(r.item=0,r.line+=1;r.line<e.tokens.length&&e.tokens[r.line].length===0;)r.line+=1;if(r.line===e.tokens.length)return}return r},Pr=(e,t,n)=>{for(let r=e.tokens.length===0?void 0:{...n};r!==void 0;){let n=Mr(e,r),i=n.type===gr.string;if(!i&&n.string===t)return r;let a=!i&&(n.string===`[`||n.string===`,`)?Nr(e,r,2):void 0,o=a===void 0?void 0:Mr(e,a),s=o!==void 0&&o.type!==gr.string&&[`:`,`|->`,`↦`].includes(o.string),c=i?1:n.string===`.`?2:s?3:1;r=Nr(e,r,c)}},Fr=(e,t,n,r)=>{let i=Mr(e,n);if(jr(e)){let n=kr(t);e.tokens=n.tokens,e.anchorTokens=n.anchorTokens,e.anchorTokCol=n.anchorTokCol;return}let a=e.tokens[n.line],o=n.item+1<a.length?a[n.item+1].column-(i.column+wr(i)):0,s=a.splice(n.item+1),c=n.line,l=+!!r+i.column,u=!r,d=()=>e.tokens[c];if(jr(t)){let e=t.tokens[0][0];i.string=e.string,i.type=e.type}else{r&&(i.string=`(`,i.type=gr.builtin);let n=kr(t);if(n.tokens.forEach((t,r)=>{if(t.forEach(e=>{e.column+=l,u?(i.string=e.string,i.type=e.type,u=!1):d().push(e)}),r+1>=n.tokens.length)return;l=0,c+=1;let a=c;e.tokens.splice(a,0,[]);let o=e.anchorTokens??[],s=e.anchorTokCol??[];e.anchorTokens=e.tokens.map((e,t)=>t<a?o[t]:t===a?n.anchorTokens?.[r+1]:o[t-1]),e.anchorTokCol=e.tokens.map((e,t)=>t<a?s[t]:t===a?n.anchorTokCol?.[r+1]??0:s[t-1])}),r){let e=d()[d().length-1];d().push(Cr(`)`,e.column+wr(e),gr.builtin))}}let f=d(),p={line:c,item:f.length-1};if(s.length>0){let e=f[f.length-1],t=e.column+wr(e)+o-s[0].column;s.forEach(e=>{e.column+=t,f.push(e)})}return Or(e),Nr(e,p,1)},Ir=(e,t,n,r=!0)=>{let i=n.map(t=>Pr(e,t,{line:0,item:0}));for(;;){let a=i.reduce((e,t,n)=>t!==void 0&&(e===void 0||t.line<e.position.line||t.line===e.position.line&&t.item<e.position.item)?{index:n,position:t}:e,void 0);if(a===void 0)return;let o=Nr(e,a.position,1),s=Fr(e,t[a.index],a.position,r);i[a.index]=s===void 0?void 0:Pr(e,n[a.index],s),i.forEach((e,t)=>{if(t!==a.index&&e!==void 0&&s!==void 0){if(o===void 0)throw new b(`NullPointerException: TLAExpr.substituteForAll`);e.line===a.position.line&&(e.item+=s.item-o.item),e.line+=s.line-o.line}})}},Lr=(e,t,n)=>{let r=kr(e);return Ir(r,t,n),r},Rr=(e,t,n)=>e.map(e=>Lr(e,t,n)),zr=(e,t)=>{let n=e=>t===`1.7.4`?``:`(col${e.column}) `,r=e.tokens.map(e=>e.map(e=>e.type===gr.string?`"\\"", "${e.string}", "\\""`:e.string===`\\/`?`"${n(e)}\\\\/"`:e.string.startsWith(`\\`)?`"\\${e.string}"`:e.string===`/\\`?`"${n(e)}/\\\\"`:`"${e.string}"`)),i=r.findIndex(e=>e.length>0);return`<< ${r.map((e,t)=>{let n=i!==-1&&t>i;return e.map((e,t)=>n||t>0?`, ${e}`:e).join(``)}).join(`
22
- `)} >>`},Br=(e,t,n)=>{let r=e=>zr(e,n),i=[0],a=0,o=e=>(i[a+1]=i[a]+e.length,a+=1,e),s=()=>(--a,``),c=()=>`\n${` `.repeat(i[a])}`,l=t<1500,u=e=>`${o(`<<`)}${e.map((e,t)=>`${t>0?`, ${c()}`:``}${`kind`in e?m(e):r(e)}`).join(``)}>>${s()}`,d=e=>`${o(`<<`)}${e.map(e=>`"${e}"`).join(`, `)}>>${s()}`,f=e=>`${o(`<< `)}${e.map((e,t)=>`${t>0?`, ${c()}`:``}${u(e)}`).join(``)} >>${s()}`,p=e=>e?`"="`:`"\\\\in"`,m=e=>{switch(e.kind){case`Uniprocess`:return`${o(``)}[type |-> "uniprocess", ${c()} name |-> "${e.name}", ${c()}${o(` decls |-> `)}${u(e.decls)},${s()}${c()}${o(` defs |-> `)}${r(e.defs)},${s()}${c()}${o(` prcds |-> `)}${u(e.prcds)},${s()}${c()}${o(` body |-> `)}${u(e.body)}]${s()}${s()}`;case`Multiprocess`:return`${o(``)}[type |-> "multiprocess", ${c()} name |-> "${e.name}", ${c()}${o(` decls |-> `)}${u(e.decls)},${s()}${c()}${o(` defs |-> `)}${r(e.defs)},${s()}${c()}${o(` prcds |-> `)}${u(e.prcds)},${s()}${c()}${o(` procs |-> `)}${u(e.procs)}]${s()}${s()}`;case`Procedure`:return l?`${o(``)}[name |-> "${e.name}", ${c()}${o(` params |-> `)}${u(e.params)},${s()}${c()}${o(` decls |-> `)}${u(e.decls)},${s()}${c()}${o(` body |-> `)}${u(e.body)}]${s()}${s()}`:`${o(``)}[name |-> "${e.name}", ${c()}minusLabels |-> ${d(e.minusLabels)}, plusLabels |->${d(e.plusLabels)}, proceduresCalled |->${d(e.proceduresCalled)},${c()}${o(` params |-> `)}${u(e.params)},${s()}${c()}${o(` decls |-> `)}${u(e.decls)},${s()}${c()}${o(` body |-> `)}${u(e.body)}]${s()}${s()}`;case`Process`:return l?`${o(``)}[name |-> "${e.name}", ${c()} eqOrIn |-> ${p(e.isEq)},${c()} id |-> ${r(e.id)},${c()}${o(` decls |-> `)}${u(e.decls)},${s()}${c()}${o(` body |-> `)}${u(e.body)}]${s()}${s()}`:`${o(``)}[name |-> "${e.name}",${c()} fairness |-> "${yr[e.fairness]}", minusLabels |-> ${d(e.minusLabels)}, plusLabels |->${d(e.plusLabels)}, proceduresCalled |->${d(e.proceduresCalled)},${c()} eqOrIn |-> ${p(e.isEq)},${c()} id |-> ${r(e.id)},${c()}${o(` decls |-> `)}${u(e.decls)},${s()}${c()}${o(` body |-> `)}${u(e.body)}]${s()}${s()}`;case`VarDecl`:return`${o(``)}[var |-> "${e.var}", eqOrIn |-> ${p(e.isEq)}, val |-> ${r(e.val)}]${s()}`;case`PVarDecl`:return`${o(``)}[var |-> "${e.var}", eqOrIn |-> "=", val |-> ${r(e.val)}]${s()}`;case`LabeledStmt`:return`${o(``)}[label |-> "${e.label}",${c()}${o(` stmts |-> `)}${u(e.stmts)}]${s()}${s()}`;case`While`:return`${o(``)}[type |-> "while", ${c()} test |-> ${r(e.test)},${c()}${o(` labDo |-> `)}${u(e.labDo)},${s()}${c()}${o(` unlabDo |-> `)}${u(e.unlabDo)}]${s()}${s()}`;case`Assign`:return`${o(``)}[type |-> "assignment",${c()}${o(` ass |-> `)}${u(e.ass)}]${s()}${s()}`;case`SingleAssign`:return`${o(``)}[lhs |-> ${m(e.lhs)},${c()} rhs |-> ${r(e.rhs)}]${s()}`;case`Lhs`:return`[var |-> "${e.var}", sub |-> ${r(e.sub)}]`;case`If`:return`${o(``)}[type |-> "if", ${c()} test |-> ${r(e.test)},${c()}${o(` then |-> `)}${u(e.Then)},${s()}${c()}${o(` else |-> `)}${u(e.Else)}]${s()}${s()}`;case`Either`:return`${o(``)}[type |-> "either", ${c()}${o(` ors |-> `)}${f(e.ors)}]${s()}${s()}`;case`With`:return`${o(``)}[type |-> "with", ${c()} var |-> "${e.var}",${c()} eqOrIn |-> ${p(e.isEq)},${c()} exp |-> ${r(e.exp)},${c()}${o(` do |-> `)}${u(e.Do)}]${s()}${s()}`;case`When`:return`${o(``)}[type |-> "when", ${c()} exp |-> ${r(e.exp)}]${s()}`;case`PrintS`:return`${o(``)}[type |-> "print", ${c()} exp |-> ${r(e.exp)}]${s()}`;case`Assert`:return`${o(``)}[type |-> "assert", ${c()} exp |-> ${r(e.exp)}]${s()}`;case`Skip`:return`[type |-> "skip"]`;case`LabelIf`:return`${o(``)}[type |-> "labelIf",${c()} test |-> ${r(e.test)},${c()}${o(` unlabThen |-> `)}${u(e.unlabThen)},${s()}${c()}${o(` labThen |-> `)}${u(e.labThen)},${s()}${c()}${o(` unlabElse |-> `)}${u(e.unlabElse)},${s()}${c()}${o(` labElse |-> `)}${u(e.labElse)}]${s()}${c()}${s()}`;case`LabelEither`:return`${o(``)}[type |-> "labelEither",${c()}${o(` clauses |-> `)}${u(e.clauses)}]${s()}${c()}${s()}`;case`Clause`:return`${o(``)}${o(`[unlabOr |-> `)}${u(e.unlabOr)},${s()}${c()}${o(` labOr |-> `)}${u(e.labOr)}]${s()}${c()}${s()}`;case`Call`:return`${o(``)}[type |-> "call",${c()} returnTo |-> "${e.returnTo}",${c()} to |-> "${e.to}",${c()}${o(` args |-> `)}${u(e.args)}]${s()}${s()}`;case`Return`:return`[type |-> "return", from |-> "${e.from??`null`}"]`;case`CallReturn`:return`${o(``)}[type |-> "callReturn",${c()} from |-> "${e.from??`null`}",${c()} to |-> "${e.to}",${c()}${o(`args |-> `)}${u(e.args)}]${c()}${s()}${s()}`;case`CallGoto`:return`${o(``)}[type |-> "callGoto",${c()} after |-> "${e.after}",${c()} to |-> "${e.to}",${c()}${o(`args |-> `)}${u(e.args)}]${c()}${s()}${s()}`;case`Goto`:return`[type |-> "goto", to |-> "${e.to}"]`;case`Macro`:return`${o(``)}[name |-> "${e.name}", ${c()}${o(` params |-> `)}${o(`<<`)}${e.params.join(`, ${c()}`)}>>${s()},${s()}${c()}${o(` body |-> `)}${u(e.body)}]${s()}${s()}`;case`MacroCall`:return`${o(``)}[type |-> "macrocall",${c()} name |-> "${e.name}",${c()}${o(` args |-> `)}${u(e.args)}]${s()}${s()}`}};return m(e)},Vr=(e,t,n)=>({lines:e,currentLine:t<e.length?Array.from(e[t]):void 0,line:t,column:n,vcolumn:t<e.length?Array.from(e[t].slice(0,n)).length:0}),Hr=e=>{if(e.currentLine===void 0)return` `;if(e.currentLine.length===e.column)return e.line+=1,e.column=0,e.vcolumn=0,e.currentLine=e.line>=e.lines.length?void 0:Array.from(e.lines[e.line]),`
23
- `;let t=e.currentLine[e.column];return e.column+=1,e.vcolumn+=1,t},Ur=e=>{if(e.column>0)--e.column,--e.vcolumn;else{if(e.line===0)throw new E(`PcalCharReader.backspace trying to move past beginning of reader`);--e.line,e.currentLine=Array.from(e.lines[e.line]),e.column=Math.max(e.currentLine.length-1,0),e.vcolumn=e.column}},Wr=e=>{for(;;){let t=Hr(e);if(t===` `)return` `;if(t!==` `&&t!==`
24
- `)break}return Ur(e),`${(e.currentLine??[]).slice(e.column).join(``)}\n`},Gr=/* @__PURE__ */ new Set([`(`,`[`,`{`,`<<`,`⟨`]),Kr=/* @__PURE__ */ new Set([`>>_`,`⟩_`,`]_`,`)`,`}`,`]`,`>>`,`⟩`]),qr=/* @__PURE__ */ new Set([...Gr,...Kr,...`_ ASSUME ASSUMPTION AXIOM BOOLEAN CASE CONSTANT CONSTANTS EXCEPT EXTENDS FALSE IF INSTANCE LOCAL MODULE OTHER STRING THEOREM TRUE VARIABLE VARIABLES WITH WF_ SF_`.split(` `),...`\\A ∀ \\forall \\E ∃ \\exists \\AA \\EE ~ ¬ \\lnot \\neg <> ◇ CHOOSE ENABLED UNCHANGED SUBSET UNION DOMAIN ' ^+ ⁺ ^* ^#`.split(` `),...`=> ⇒ \\cdot ⋅ <=> ⇔ \\equiv ≡ ~> ↝ -+-> ⇸ \\subseteq ⊆ \\subset ⊂ \\supset ⊃ \\supseteq ⊇ \\ll ≪ \\gg ≫ \\ \\cap \\intersect ∩ \\cup \\union ∪ /\\ ∧ \\/ ∨ \\land \\lor \\X × - + * / ^ | || ‖ & && ++ -- ** // ^^ |- ⊢ |= ⊨ -| ⊣ =| ⫤ <: :> := ≔ ::= ⩴`.split(` `),...`(+) ⊕ (-) ⊖ \\oplus \\ominus (.) ⊙ \\odot (/) ⊘ \\oslash (\\X) ⊗ \\otimes \\uplus ⊎ \\sqcap ⊓ \\sqcup ⊔ \\div ÷ \\star ⋆ \\o ∘ \\circ \\bigcirc ◯ \\bullet ●`.split(` `),...`\\in ∈ \\notin ∉ = # /= ≠ < > =< <= ≤ >= ≥ \\prec ≺ \\succ ≻ \\preceq ⪯ \\succeq ⪰ \\sim ∼ \\simeq ≃ \\approx ≈ \\doteq ≐ \\asymp ≍ \\sqsubset ⊏ \\sqsupset ⊐ \\sqsubseteq ⊑ \\sqsupseteq ⊒ \\propto ∝`.split(` `),...`: -> → |-> ↦ <- ← == ≜ ELSE THEN LET IN [] □ .. ‥ ... … $ $$ ? ?? ⁇ % %% ## @@ !! ‼ \\times \\leq \\geq \\mod \\wr ≀ ≅ ! ; , . -. @`.split(` `)]),Jr=e=>/^[A-Za-z_]$/.test(e),Yr=e=>/^[0-9]$/.test(e),Xr=e=>e===` `||e===`\f`||e===`\r`,Zr=new Set([...qr].filter(e=>!Jr(e[0])&&!(e[0]===`\\`&&Jr(e[1]??``))).flatMap(e=>Array.from(e,(t,n)=>e.slice(0,e.length-n)))),Qr=/* @__PURE__ */ new Set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ~!@#$%^&*()_-+={}[]|:;<,>.?/`'0123456789"),$r=new Set(`; do then := ≔ begin variable variables || ‖ end else elsif if either or while with call return goto print assert skip procedure define process fair`.split(` `)),z={...gr,dashes:6,endModule:7},ei=()=>({delimiter:``,delimiterLine:0,delimiterCol:0,commentDepth:0}),ti=(e,t,n,r)=>{let i=[],a=[],o=``,s=`start`,c=t.vcolumn,l=t.vcolumn,u=Hr(t),d=0,f=!1,p=!1,m=` `,h=()=>{l=t.vcolumn,u=Hr(t)},g=()=>{o+=u,h()},_=()=>{s=`start`,c=l},v=()=>{i.push(a),a=[],c=0},y=e=>{throw new D(`${e} \`${o}' found at\n line ${t.line+1}, column ${c+1}`)},b=()=>{p=!0,e.delimiter=o,e.delimiterCol=c,e.delimiterLine=t.line-+(u===`
25
- `)},x=e=>{n?(e>z.ident&&y(`Illegal token in an expression`),e!==z.string&&($r.has(o)&&!(e===z.ident&&[`.`,`[`,`,`].includes(m))||(o===`,`&&!f&&!r||o===`)`||o===`}`)&&d===0)?(d!==0&&y(`Expression with an unmatched (, [, {, or << followed by`),f&&y("Expression with \\A or \\E but no following `:` followed by"),b(),a.length>0&&v()):(e===z.builtin&&Gr.has(o)&&(d+=1),e===z.builtin&&Kr.has(o)&&(--d,d<0&&y(`Extra (unmatching)`)),m=e===z.string?` `:o,[`\\A`,`∀`,`\\E`,`∃`].includes(o)&&d===0&&(f=!0),f&&o===`:`&&d===0&&(f=!1),(o!==``||e===z.string)&&a.push(Cr(o,c,e)),o=``)):(b(),o=``)},S=e=>{x(e),_()},C=e=>{g(),s=e},w=e=>{h(),s=e},T=n=>{switch(s){case`start`:if(Xr(n))return h(),_();if(Jr(n))return C(`id`);if(n===`ℕ`||n===`ℤ`||n===`ℝ`)return g(),S(z.ident);if(Yr(n))return C(`numOrId`);if(n===`\\`)return C(`bs`);if(n===`-`)return C(`dash1`);if(n===`=`)return C(`eq1`);if(n===`(`)return w(`leftParen`);if(n===`"`)return w(`string`);if(n===`
26
- `)return h(),v(),_();if(Zr.has(n))return C(`builtIn`);if(n===` `){s=`done`;return}return g(),y(`Illegal lexeme`);case`id`:return o===`WF_`||o===`SF_`?S(z.builtin):Jr(n)||Yr(n)?g():S(qr.has(o)?z.builtin:z.ident);case`numOrId`:return Yr(n)?g():Jr(n)?C(`id`):S(z.number);case`bs`:if([`b`,`B`,`o`,`O`,`h`,`H`].includes(n))return C(`numOrBi`);if(Jr(n)){s=`bsBuiltIn`;return}if(n===`*`){h(),o=``,s=`lineComment`;return}s=`builtIn`;return;case`numOrBi`:s=Yr(n)?`num`:`bsBuiltIn`;return;case`num`:if(Yr(n))return g();if(!Jr(n))return S(z.number);g(),o.startsWith(`\\`)&&y(`Illegal lexeme`),s=`id`;return;case`bsBuiltIn`:return Jr(n)&&n!==`_`?g():qr.has(o)?S(z.builtin):y(`Illegal lexeme `);case`builtIn`:if(Zr.has(o+n))return g();if(!qr.has(o)){for(Ur(t);!qr.has(o);)Ur(t),o.length===0&&y(`Illegal lexeme`),o=Array.from(o).slice(0,-1).join(``);h()}return S(z.builtin);case`dash1`:case`dash2`:if(n===`-`)return C(s===`dash1`?`dash2`:`dash3`);s=`builtIn`;return;case`dash3`:return n!==`-`&&y(`Illegal lexeme`),C(`dashes`);case`dashes`:return n===`-`?g():S(z.dashes);case`eq1`:case`eq2`:if(n===`=`)return C(s===`eq1`?`eq2`:`eq3`);s=`builtIn`;return;case`eq3`:return n!==`=`&&y(`Illegal lexeme`),C(`eqs`);case`eqs`:return n===`=`?g():S(z.endModule);case`leftParen`:if(n===`*`)return e.commentDepth=1,w(`comment`);o=`(`,s=`builtIn`;return;case`string`:if(n===`\\`)return C(`escString`);if(n===`"`)return h(),S(z.string);g(),Qr.has(n)||y(`Illegal character in string`);return;case`escString`:g(),[`"`,`\\`,`t`,`n`,`f`,`r`].includes(n)||y(`Illegal character following \\ in string`),s=`string`;return;case`lineComment`:return n===`(`?w(`lineComParen`):n===`*`&&e.commentDepth>0?w(`lineComStar`):n===`
27
- `||n===` `?(o=``,e.commentDepth=0,_()):e.commentDepth===0?g():h();case`lineComParen`:if(n===`*`)return e.commentDepth+=1,w(`lineComment`);e.commentDepth===0&&(o+=`(`),s=`lineComment`;return;case`lineComStar`:if(n===`)`){if(--e.commentDepth,e.commentDepth<0)throw new E(`Failure of assertion: case LINE_COM_STAR`);return w(`lineComment`)}e.commentDepth===0&&(o+=`*`),s=`lineComment`;return;case`comment`:case`orComment`:{let t=s===`comment`;if(n===`*`)return w(t?`commentStar`:`orCommentStar`);if(n===`(`)return w(t?`commentParen`:`orCommentParen`);if(n===`
28
- `){o=``,h(),v(),s=`orComment`;return}if(n===` `)throw new D(t?`Input ended in the middle of a comment`:`Input ended in the middle of a multi-line comment`);return e.commentDepth===1?g():h()}case`commentStar`:case`orCommentStar`:{let t=s===`commentStar`?`comment`:`orComment`;if(n!==`)`){e.commentDepth===1&&(o+=`*`),s=t;return}if(h(),--e.commentDepth,t===`orComment`&&e.commentDepth<0)throw new E(`Assertion failure`);if(e.commentDepth!==0){s=t;return}return o=``,_()}case`commentParen`:case`orCommentParen`:{let t=s===`commentParen`?`comment`:`orComment`;if(n===`*`)return e.commentDepth+=1,w(t);e.commentDepth===1&&(o+=`(`),s=t;return}}};for(;s!==`done`&&!p;)T(u);return u!==`
29
- `&&Ur(t),Dr(i)},ni=(e,t,n)=>ti(e,t,!0,n),ri=(e,t)=>(ti(e,t,!1,!1),e.delimiter),ii=(e,t)=>({params:e,tokenizer:ei(),lookahead:{tokens:Array.from({length:10},()=>``),columns:Array.from({length:10},()=>0),lines:Array.from({length:10},()=>0)},lastToken:{column:0,line:0,text:``},isInMacro:!1,log:t}),ai=()=>Dr([[Cr(`defaultInitValue`,0,0)]]),oi=(e,t)=>[...e,...t.filter((n,r)=>!e.includes(n)&&t.indexOf(n)===r)],si=(e,t)=>!t.some(t=>e.includes(t)),ci=(e,t)=>{t.splice(0,t.length,...e)},li=(e,t,n)=>{let r=e.params,i=e.lookahead,a=e.lastToken,o=0,s=[],c=[],l=1,u=/* @__PURE__ */ new Set,d=!1,f=!1,p,m=[],h=!1,g=[],_=[],v=[],y=!1,x=!1,S=r.inputVersionNumber>=1500,C=e=>{throw new D(`${e}\n line ${a.line}, column ${a.column}`)},w=()=>{if(o===0)return Wr(t),a.column=t.vcolumn+1,a.line=t.line+1,a.text=ri(e.tokenizer,t),a.text;a.column=i.columns[0]+1,a.line=i.lines[0]+1;let n=i.tokens[0];for(let e=1;e<o;e++)i.tokens[e-1]=i.tokens[e],i.columns[e-1]=i.columns[e],i.lines[e-1]=i.lines[e];return--o,a.text=n,n},T=n=>{for(;o<n;){let n=o;if(Wr(t)===` `)throw new D(`Premature end of file, perhaps because of unclosed comment, near\n line ${i.lines[n]+1}, column ${i.columns[n]+1}`);i.columns[n]=t.vcolumn,i.lines[n]=t.line,i.tokens[n]=ri(e.tokenizer,t),o+=1}return i.tokens[n-1]},ee=n=>{if(n<o)throw new E(`ParseAlgorithm.PeekPastAlgToken called to peek after a token
30
- it has already peeked at`);for(;n>o;)i.tokens[o]=ri(e.tokenizer,t),o+=1;return Wr(t)},O=(n=!1)=>{if(o!==0)throw new E(`ParseAlgorithm: GetExpr called after lookahead`);let r=ni(e.tokenizer,t,n);return i.tokens[0]=e.tokenizer.delimiter,i.columns[0]=e.tokenizer.delimiterCol,i.lines[0]=e.tokenizer.delimiterLine,o=1,r},k=(e,t)=>{let n=w();n!==e&&n!==t&&C(`Expected "${e}" but found "${n}"`)},A=(e,t)=>{if(e===`;`){let e=T(1);if(`end begin else elsif or do macro procedure process fair define } {`.split(` `).includes(e))return;if(`if either while with call return goto print assert skip`.split(` `).includes(e))throw new D(`Missing \`;' before line ${i.lines[0]+1}, column ${i.columns[0]+1}`)}k(e,t)},te=()=>{let e=w();return e===`=`?!0:e===`\\in`||e===`∈`?!1:C(`Expected "=" or "\\in" but found "${e}"`)},ne=()=>A(T(1)===`,`?`,`:`;`),re=()=>A(h?`{`:`begin`),ie=e=>{h?A(`}`):(A(`end`),A(e))},ae=()=>{T(1)===`variables`?k(`variables`):A(`variable`)},oe=()=>{let e={...R(),kind:`VarDecl`,var:w(),col:a.column,line:a.line,isEq:!0,val:ai()};if(![`=`,`\\in`,`∈`].includes(T(1)))return f=!0,e;if(e.isEq=te(),e.val=O(),e.val.tokens.length===0)throw new b(`NullPointerException`);return e},se=()=>{ae();let e=[],t=[`begin`,`{`,`procedure`,`process`,`fair`,`define`,`macro`];for(;!t.includes(T(1));)e.push(oe()),ne();return e},ce=()=>{let e={...R(),kind:`PVarDecl`,var:w(),col:a.column,line:a.line,val:ai()};if(T(1)!==`=`)return f=!0,e;if(A(`=`),e.val=O(),e.val.tokens.length===0)throw new b(`NullPointerException`);return e},le=()=>{ae();let e=[];for(;T(1)!==`begin`&&T(1)!==`{`;)e.push(ce()),ne();return e},ue=()=>{if(`while if assert print else elsif either or end with when await skip call return goto`.split(` `).includes(T(1)))return!1;let e=Wr(t);return e.length>0&&e[0]===`:`&&!(e.length>1&&e[1]===`=`)},de=()=>{if(!ue())return``;let t=w();e.isInMacro&&C(`A label may not appear in a macro.`),t===`Done`&&C("Cannot use `Done' as a label."),t===`Error`&&C("Cannot use `Error' as a label."),A(`:`),d=!0,u.add(t);let n=T(1);return n!==`+`&&n!==`-`||(A(n),(n===`+`?g:_).push(t),S=!1),t},j=()=>{let e=[],t=e=>!h&&[`end`,`else`,`elsif`,`or`].includes(e)||h&&e===`}`;for(;!t(T(1));)e.push(...pe());return h&&e.length===0&&C(`Empty statement list`),e},fe=e=>{k(`{`);let t=j();if(A(`}`),A(`;`),e!==``){if(t[0].lbl!==``)throw new D(`Duplicate labeling of statement`,t[0]);t[0].lbl=e}return t},pe=()=>{let e=de();if(h&&T(1)===`{`)return fe(e);let t=me();return t.lbl=e,[t]},me=()=>{let e=T(1);if(e===`if`)return ge(0);if(e===`either`)return _e();if(e===`with`)return ve(0);if(e===`when`||e===`await`){k(e);let t=a.column,n=a.line,r=O();if(r.tokens.length===0)throw new b(`NullPointerException`);return A(`;`),{...R(),kind:`When`,col:t,line:n,exp:r}}if(e===`print`||e===`assert`){k(e);let t=a.column,n=a.line,r=O();return r.tokens.length===0&&C(`Empty expression in ${e} statement at `),A(`;`),{...R(),kind:e===`print`?`PrintS`:`Assert`,col:t,line:n,exp:r}}if(e===`skip`){k(`skip`);let e={...R(),kind:`Skip`,col:a.column,line:a.line};return A(`;`),e}if(e===`call`)return Se();if(e===`return`){k(`return`);let e={...R(),kind:`Return`,col:a.column,line:a.line,from:p};return A(`;`),e}if(e===`goto`){k(`goto`);let e=a.column,t=a.line,n=w();return y=!0,(n===`Done`||n===`"Done"`)&&(x=!0),A(`;`),{...R(),kind:`Goto`,col:e,line:t,to:n}}return e===`while`?he():ee(1)[0]===`(`?Ce():be()},he=()=>{k(`while`);let e=a.column,t=a.line;h&&A(`(`);let n=O();h&&A(`)`),n.tokens.length===0&&C(`Empty while test at `),h||A(`do`);let r=h?pe():j();return h||(A(`end`),A(`while`),A(`;`)),r.length===0&&C(`Missing body of while statement at`),{...R(),kind:`While`,col:e,line:t,test:n,unlabDo:r,labDo:[]}},ge=e=>{k(e===0?`if`:`elsif`);let t={...R(),kind:`LabelIf`,col:a.column,line:a.line,test:Tr(),unlabThen:[],labThen:[],unlabElse:[],labElse:[]};h&&A(`(`),t.test=O(),h&&A(`)`),t.test.tokens.length===0&&C(`Empty if test at `),h||A(`then`),t.unlabThen=h?pe():j();let n=T(1);return n===`else`&&(k(`else`),t.unlabElse=h?pe():j()),!h&&n===`elsif`&&(t.unlabElse=[ge(e+1)]),!h&&![`else`,`elsif`,`end`].includes(n)&&C(`Expecting "else", "elsif", or "end"`),!h&&e===0&&(A(`end`),A(`if`),A(`;`)),t.unlabElse.length===0&&Sr(t.unlabThen,t.unlabThen.length-1),t},_e=()=>{k(`either`);let e={...R(),kind:`LabelEither`,col:a.column,line:a.line,clauses:[]};for(;;){let t={...R(),kind:`Clause`,unlabOr:h?pe():j(),labOr:[]};if(t.unlabOr.length===0)throw new D("`either' statement with empty `or' clause",e);if(e.clauses.push(t),T(1)!==`or`)break;k(`or`)}if(h||(k(`end`),A(`either`),A(`;`)),e.clauses.length===1)throw new D("`either' statement has no `or'",e);return e},ve=e=>{e===0&&(A(`with`),h&&A(`(`));let t={...R(),kind:`With`,col:a.column,line:a.line,var:w(),isEq:!0,exp:Tr(),Do:[]};t.isEq=te(),t.exp=O(),h&&T(1)===`)`||ne(),t.exp.tokens.length===0&&C(`Empty with expression at `);let n=!h&&T(1)===`do`,r=h&&T(1)===`)`;if(n&&A(`do`),r&&k(`)`),t.Do=n?j():r?pe():[ve(e+1)],n&&(A(`end`),A(`with`),A(`;`)),t.Do.length===0)throw new D(`Missing body of with statement`,t);return t},ye=()=>{let e=i.columns[0]+1,t=i.lines[0]+1,n={...R(),kind:`Lhs`,col:e,line:t,var:w(),sub:O()};A(`:=`,`≔`);let r=O();return r.tokens.length===0&&C(`Empty right-hand side of assignment at `),{...R(),kind:`SingleAssign`,col:e,line:t,lhs:n,rhs:r}},be=()=>{let e={...R(),kind:`Assign`,col:i.columns[0]+1,line:i.lines[0]+1,ass:[ye()]};for(;T(1)===`||`||T(1)===`‖`;){w();try{e.ass.push(ye())}catch(e){if(!(e instanceof D))throw e;C(`Bad assignment statement at `)}}return A(`;`),e},M=()=>{let e=[];if(ee(0)[0]!==`)`)for(;;){let t=O();if(e.push(t),t.tokens.length===0&&C(`Empty argument in call statement at `),T(1)===`)`)break;A(`,`)}return A(`)`),A(`;`),e},xe=()=>{k(`call`);let e={...R(),kind:`Call`,col:a.column,line:a.line,returnTo:``,to:w(),args:[]};return A(`(`),e.args=M(),v.includes(e.to)||v.push(e.to),e},Se=()=>{let e=xe();if(T(1)===`return`)return k(`return`),A(`;`),{...R(),kind:`CallReturn`,col:e.col,line:e.line,to:e.to,from:p,args:e.args};if(T(1)!==`goto`)return e;k(`goto`);let t={...R(),kind:`CallGoto`,col:e.col,line:e.line,to:e.to,after:w(),args:e.args};return y=!0,(t.to===`Done`||t.to===`"Done"`)&&(x=!0),A(`;`),t},Ce=()=>{let e={...R(),kind:`MacroCall`,name:w(),col:a.column,line:a.line,args:[]};return k(`(`),e.args=M(),e},we=t=>{e.isInMacro=!0,k(`macro`);let n={...R(),kind:`Macro`,col:a.column,line:a.line,name:w(),params:[],body:[]};for(A(`(`);T(1)!==`)`;)n.params.length>0&&A(`,`),n.params.push(w());return k(`)`),re(),n.body=j(),ie(`macro`),T(1)===`;`&&w(),Fe(n.body,t),e.isInMacro=!1,n},Te=()=>{A(`procedure`);let e={...R(),kind:`Procedure`,col:a.column,line:a.line,name:w(),minusLabels:[],plusLabels:[],proceduresCalled:[],params:[],decls:[],body:[]};for(p=e.name,g=[],_=[],v=[],A(`(`);T(1)!==`)`;)e.params.length>0&&A(`,`),e.params.push(ce());return k(`)`),T(1)!==`begin`&&T(1)!==`{`&&(e.decls=le()),re(),e.body=j(),ie(`procedure`),T(1)===`;`&&w(),p=void 0,e.plusLabels=g,e.minusLabels=_,e.proceduresCalled=v,e},Ee=()=>{A(`process`);let e=a.column,t=a.line;h&&A(`(`);let n=w(),r=te(),i=O();g=[],_=[],v=[],h&&A(`)`),i.tokens.length===0&&C(`Empty process id at `);let o=T(1)===`begin`||T(1)===`{`?[]:se();re();let s=j();return ie(`process`),T(1)===`;`&&w(),{...R(),kind:`Process`,col:e,line:t,name:n,fairness:0,minusLabels:_,plusLabels:g,proceduresCalled:v,isEq:r,id:i,decls:o,body:s}},De=()=>{let e=`${r.labelRoot}${l}`;return l+=1,u.has(e)?De():e},Oe=e=>{e.lbl===``&&(e.lbl=De(),s.push(e.lbl),c.push(br(e)))},ke=(e,t,n,r,i)=>{ci(r,i);let a=t,o=!1,s=e=>{Oe(e),o=!0,i.length=0};return e.forEach(e=>{if(e.lbl!==``&&(o=!0,i.length=0,n))throw new D("Label in `with' statement",e);if(a){if(n)throw new D("Statement follows `call' or `return' inside a `with' statement.",e);s(e),a=!1}switch(e.kind){case`LabelIf`:{let t=[],r=[],o=ke(e.unlabThen,!1,n,i,t);a=ke(e.unlabElse,!1,n,i,r)||o,ci(oi(t,r),i);return}case`LabelEither`:{let t=[];e.clauses.forEach(e=>{let r=[];a=ke(e.unlabOr,!1,n,i,r)||a,ci(oi(r,t),t)}),ci(t,i);return}case`While`:if(n)throw new D("`while' inside a `with' statement",e);s(e),ke(e.unlabDo,!1,!1,i,[]),a=!1;return;case`With`:{let t=[];a=ke(e.Do,!1,!0,n?[...r]:[],t),ci(t,i),!n&&!si(r,i)&&s(e);return}}let t=e.kind===`Call`||e.kind===`CallGoto`,c=e.kind===`Return`||e.kind===`CallReturn`,l=e.kind===`Assign`?oi([],e.ass.map(e=>e.lhs.var)):t||c?[`stack`,...c||e.to===p?m.flatMap(e=>[...e.params,...e.decls].map(e=>e.var)):[]]:[];if(a=t||c||e.kind===`Goto`,si(i,l))ci(oi(i,l),i);else{if(n)throw new D(e.kind===`Assign`?"Second assignment to same variable inside a `with' statement":"Call or return makes second assignment to a variable inside a `with' statement",e);s(e),ci(l,i)}}),o||a},Ae=e=>{let t=e=>{let t=e.findIndex(e=>e.lbl!==``),n=t===-1?e:e.slice(0,t);return Ae(n),{unlabeled:n,labeled:je(t===-1?[]:e.slice(t))}};e.forEach(e=>{switch(e.kind){case`LabelIf`:{let n=t(e.unlabThen);e.unlabThen=n.unlabeled,e.labThen=n.labeled;let r=t(e.unlabElse);e.unlabElse=r.unlabeled,e.labElse=r.labeled;return}case`LabelEither`:e.clauses.forEach(e=>{let n=t(e.unlabOr);e.unlabOr=n.unlabeled,e.labOr=n.labeled});return;case`While`:{let n=t(e.unlabDo);e.unlabDo=n.unlabeled,e.labDo=n.labeled}}})},je=e=>{let t=[];return e.forEach(e=>{if(e.lbl===``&&t.length>0)t[t.length-1].stmts.push(e);else{if(e.lbl===``)throw new E(`Failure of assertion: Missing Label in MakeLabeledStmtSeq`);t.push({...R(),kind:`LabeledStmt`,col:e.col,line:e.line,macroCol:e.macroCol,macroLine:e.macroLine,label:e.lbl,stmts:[e]})}}),t.forEach(e=>Ae(e.stmts)),t},Me=(e,t)=>{let n=e[t];switch(n.kind){case`LabelIf`:{let r=N(n.unlabThen);n.labThen.forEach(e=>N(e.stmts));let i=N(n.unlabElse);return n.labElse.forEach(e=>N(e.stmts)),n.labThen.length>0||n.labElse.length>0||r===2||i===2?2:(e[t]={...R(),kind:`If`,test:n.test,Then:n.unlabThen,Else:n.unlabElse},+(r+i>0))}case`LabelEither`:{let r=n.clauses.reduce((e,t)=>{let n=Math.max(e,N(t.unlabOr));return t.labOr.forEach(e=>N(e.stmts)),t.labOr.length>0?2:n},0);return r===2?2:(e[t]={...R(),kind:`Either`,ors:n.clauses.map(e=>e.unlabOr)},r)}case`With`:{let e=N(n.Do);if(e===2)throw new D(`with statement at ${br(n)} contains a labeled statement`);return e}case`While`:if(t!==0)throw new E("ParseAlgorithm.ClassifyStmtSeq encountered `while' not at beginning of StmtSeq.");return N(n.unlabDo),n.labDo.forEach(e=>N(e.stmts)),0;case`Call`:return e[t+1]?.kind===`Return`?0:1;case`Return`:case`CallReturn`:if(p===void 0)throw new D(`return statement not in a procedure at ${br(n)}`);return 1;case`Goto`:case`CallGoto`:return 1;case`Assign`:case`When`:case`PrintS`:case`Assert`:case`Skip`:case`MacroCall`:return 0;default:throw new E(`ParseAlgorithm.ClassifyStmtSeq encountered the unexpected statement type ${n.kind}`)}},N=e=>{for(let t=0;t<e.length;t++){let n=Me(e,t);if(n!==0){if(t===e.length-1)return n;throw new E(`Translator discovered later than it should have that\n Statement at ${br(e[t+1])} must have a label`)}}return 0},Ne=e=>{ke(e,!0,!1,[],[]);let t=je(e);return t.forEach(e=>N(e.stmts)),t},P=(e,t,n,r,i)=>{let a=e=>Lr(e,t,n),o=e=>e.map(e=>P(e,t,n,r,i)),s=e=>e.map(e=>({...R(),kind:`LabeledStmt`,label:e.label,stmts:e.stmts.map(e=>P(e,t,n,-1,0))})),c={...R(),col:e.col,line:e.line,macroCol:r>0?i:e.macroCol,macroLine:r>0?r:e.macroLine};switch(e.kind){case`Assign`:return{...c,kind:`Assign`,ass:e.ass.map(e=>Pe(e,t,n,r,i))};case`If`:return{...c,kind:`If`,test:a(e.test),Then:o(e.Then),Else:o(e.Else)};case`Either`:return{...c,kind:`Either`,ors:e.ors.map(o)};case`With`:return{...c,kind:`With`,var:e.var,isEq:e.isEq,exp:a(e.exp),Do:o(e.Do)};case`When`:case`Assert`:case`PrintS`:return{...c,kind:e.kind,exp:a(e.exp)};case`Skip`:return{...c,kind:`Skip`,macroCol:r>0?i:0,macroLine:r>0?r:-1};case`While`:return{...c,kind:`While`,test:a(e.test),unlabDo:o(e.unlabDo),labDo:s(e.labDo)};case`LabelIf`:return{...c,kind:`LabelIf`,test:a(e.test),unlabThen:o(e.unlabThen),labThen:s(e.labThen),unlabElse:o(e.unlabElse),labElse:s(e.labElse)};case`LabelEither`:return{...c,kind:`LabelEither`,clauses:e.clauses.map(e=>({...R(),kind:`Clause`,labOr:s(e.labOr),unlabOr:o(e.unlabOr)}))};case`Call`:return{...c,kind:`Call`,to:e.to,returnTo:e.returnTo,args:Rr(e.args,t,n)};case`Return`:return{...c,kind:`Return`,from:e.from};case`CallReturn`:return{...c,kind:`CallReturn`,to:e.to,from:e.from,args:Rr(e.args,t,n)};case`CallGoto`:return{...c,kind:`CallGoto`,to:e.to,after:e.after,args:Rr(e.args,t,n)};case`Goto`:return{...c,kind:`Goto`,to:e.to};default:throw new E(`Found unexpected statement type in macro at${br(e)}`)}},Pe=(e,t,n,r,i)=>{let a=Lr(e.rhs,t,n),o={...R(),kind:`Lhs`,var:e.lhs.var,sub:e.lhs.sub.tokens.length===0?e.lhs.sub:Lr(e.lhs.sub,t,n)},s={...R(),kind:`SingleAssign`,col:e.col,line:e.line,macroCol:r>0?i:e.macroCol,macroLine:r>0?r:e.macroLine,lhs:o,rhs:a},c=n.indexOf(o.var);if(c===-1)return s;let l=t[c],u=Mr(l,{line:0,item:0});if(u.type!==gr.ident)throw new D(`Macro expansion substitutes \`${u.string}' for assignment variable\n at ${br(s)}`);if(o.var=u.string,Nr(l,{line:0,item:0},1)===void 0)return s;let d=kr(l);return d.tokens[0].splice(0,1),Er(d),o.sub.tokens.length===0?o.sub=d:Ar(o.sub,d,0),s},Fe=(e,t)=>{let n=e.flatMap(e=>{switch(e.kind){case`LabelIf`:return Fe(e.unlabThen,t),Fe(e.unlabElse,t),[e];case`LabelEither`:return e.clauses.forEach(e=>Fe(e.unlabOr,t)),[e];case`With`:return Fe(e.Do,t),[e];case`While`:return Fe(e.unlabDo,t),[e];case`MacroCall`:return Ie(e,t);default:return[e]}});e.splice(0,e.length,...n)},Ie=(e,t)=>{let n=t.findLast(t=>t.name===e.name);if(n===void 0)throw new D(`Macro ${e.name} undefined,\n at ${br(e)}`);if(n.params.length!==e.args.length)throw new D(`Macro ${e.name} called with wrong number of arguments at \n ${br(e)}`);let r=n.body.map(t=>P(t,e.args,n.params,e.line,e.col));return r.length>0&&(r[0].lbl=e.lbl),r},Le=e=>{e.forEach((t,n)=>{if(e.slice(n+1).some(e=>e.name===t.name))throw new D(`Multiple definitions of macro name \`${t.name}'`)})},Re=e=>{if(e.length===0)return;let t=()=>{S=!1},n=e[0];if(e.length>1||n.kind!==`LabeledStmt`)return t();if(n.stmts.length===0)return;let r=n.stmts[0];if(n.stmts.length>1||r.kind!==`While`||!jr(r.test)||r.test.tokens[0][0].string!==`TRUE`)return t();r.labDo.length>0&&(S=!1),r.unlabDo.some(e=>[`LabelIf`,`LabelEither`,`LabeledStmt`].includes(e.kind))&&(S=!1)},ze=()=>{let e=s.length>1?`Missing labels at the following locations:`:`Missing label at the following location:`;throw new D([e,...c].join(`
31
- `))},Be=e=>m.forEach(t=>{p=t.name,Fe(t.body,e),t.body=Ne(t.body)}),Ve=()=>{n&&w()!==`algorithm`&&C("`--fair' not followed by `algorithm'");let t=w();h=T(1)===`{`,h&&k(`{`);let i=T(1)===`variable`||T(1)===`variables`?se():[],a=Tr();T(1)===`define`&&(k(`define`),h&&A(`{`),a=O(!0),ie(`define`),A(`;`));let o=[];for(;T(1)===`macro`;)o.push(we(o));for(;T(1)===`procedure`;)m.push(Te()),S=!1;if(T(1)===`fair`&&(T(2)===`process`||T(2)===`+`&&T(3)===`process`)||T(1)===`process`){let n=[];for(;T(1)===`fair`||T(1)===`process`;){let e=T(1)===`fair`;e&&k(`fair`);let t=e&&T(1)===`+`;t&&k(`+`);let i=t||!e&&r.fairnessOption===`sf`?2:e||r.fairnessOption===`wf`?1:0;n.push({...Ee(),fairness:i})}return ie(`algorithm`),Le(o),n.forEach(e=>{Fe(e.body,o),e.body=Ne(e.body),Re(e.body)}),Be(o),s.length>0&&(r.labelFlag||ze(),e.log(`Labels added.`)),(x||y)&&(S=!1),{...R(),kind:`Multiprocess`,name:t,decls:i,defs:a,macros:o,prcds:m,procs:n}}r.inputVersionNumber===1500&&T(1)===`fair`&&(A(`fair`),T(1)===`+`&&A(`+`),r.fairnessOption=`wf`),n&&([``,`wf`,`wfNext`].includes(r.fairnessOption)||e.log(`Warning: Option \`${r.fairnessOption}' specified for --fair algorithm.`),r.fairnessOption=`wf`),re();let c=j();Le(o),Fe(c,o),Be(o),h&&A(`}`),ie(`algorithm`);let l=Ne(c);return s.length>0&&(d&&!r.labelFlag&&ze(),e.log(`Labels added.`)),(y||x)&&(S=!1),Re(l),{...R(),kind:`Uniprocess`,name:t,decls:i,defs:a,macros:o,prcds:m,body:l}};try{return{ast:Ve(),shouldOmitPC:S,hasDefaultInitialization:f}}catch(e){if(!(e instanceof b))throw e;return C(`Unknown error at or before`)}},B={global:0,label:1,procedure:2,process:3,processVar:4,procedureVar:5,parameter:6},ui=[`Global variable`,`Label`,`Procedure`,`Process`,`Process variable`,`Procedure variable`,`Parameter`],di=/* @__PURE__ */ new Set([B.global,B.processVar,B.procedureVar,B.parameter]),fi=(e,t,n,r)=>e.symbols.find(e=>e.id===n&&e.context===r&&e.type===t),pi=(e,t,n)=>e.symbols.find(e=>e.id===t&&e.context===n),mi=(e,t)=>{let n=e.procedures.findIndex(e=>e.name===t);return n===-1?e.procedures.length:n},hi=(e,t,n,r)=>!(t===B.procedureVar||t===B.processVar||t===B.parameter?fi(e,B.global,n,``)!==void 0||pi(e,n,r)!==void 0:fi(e,t,n,r)!==void 0)&&(e.symbols.push({type:t,id:n,context:r,useThis:n}),!0),gi=(e,t,n,r)=>fi(e,t,n,r)?.useThis??n,_i=(e,t,n)=>{let r=pi(e,t,n);return r===void 0?t:di.has(r.type)?r.useThis:t},vi=e=>{let t={symbols:[],procedures:[],processNames:[],errorReport:``},n=(e,n)=>{hi(t,B.label,e.label,n)||(t.errorReport+=`\nLabel ${e.label} redefined at line ${e.line}, column ${e.col}`),e.stmts.forEach(e=>r(e,n))},r=(e,t)=>{let i=e=>e.forEach(e=>r(e,t)),a=e=>e.forEach(e=>n(e,t));switch(e.kind){case`While`:i(e.unlabDo),a(e.labDo);return;case`If`:i(e.Then),i(e.Else);return;case`With`:i(e.Do);return;case`LabelIf`:i(e.unlabThen),a(e.labThen),i(e.unlabElse),a(e.labElse);return;case`Either`:e.ors.forEach(i);return;case`LabelEither`:e.clauses.forEach(e=>{i(e.unlabOr),a(e.labOr)});return;case`Assign`:case`When`:case`PrintS`:case`Assert`:case`Skip`:case`Call`:case`Return`:case`CallReturn`:case`CallGoto`:case`Goto`:return;default:throw new E(`Unexpected AST type ${e.kind}`)}},i=(e,n,r=n===``?B.global:B.processVar)=>{hi(t,r,e.var,n)||(t.errorReport+=`\n${ui[r]} ${e.var} redefined at line ${e.line}, column ${e.col}`)};if(hi(t,B.global,`pc`,``),e.prcds.length>0&&hi(t,B.global,`stack`,``),e.decls.forEach(e=>i(e,``)),e.prcds.forEach(e=>{let r=mi(t,e.name)<t.procedures.length;r&&(t.errorReport+=`\nProcedure ${e.name} redefined at line ${e.line}, column ${e.col}`),r||t.procedures.push({name:e.name,params:e.params,decls:e.decls,initialPC:e.body.length===0?void 0:xr(e.body[0]).label}),hi(t,B.procedure,e.name,``),e.decls.forEach(t=>i(t,e.name,B.procedureVar)),e.params.forEach(t=>i(t,e.name,B.parameter)),e.body.forEach(t=>n(xr(t),e.name))}),e.kind===`Multiprocess`&&e.procs.forEach(e=>{let r=t.processNames.includes(e.name);r&&(t.errorReport+=`\nProcess ${e.name} redefined at line ${e.line}, column ${e.col}`),r||t.processNames.push(e.name),hi(t,B.process,e.name,``),e.decls.forEach(t=>i(t,e.name)),e.body.forEach(t=>n(xr(t),e.name))}),e.kind===`Uniprocess`&&e.body.forEach(e=>n(xr(e),``)),t.errorReport.length>0)throw new D(t.errorReport);return t},yi=e=>{let t=t=>e.symbols.filter(e=>e.useThis===t).length>1,n=!1;for(let r=0;r<=7;r+=1)e.symbols.forEach(e=>{if(e.type===r){e.useThis=e.id;for(let n=1;r>0&&t(e.useThis);n+=1)e.useThis+=n===1?`_`:e.context[n-2]??String(r);e.id!==e.useThis&&(n=!0)}});return n},bi=e=>{let t=e.symbols.filter(e=>e.id===`defaultInitValue`).map(e=>`${ui[e.type]} name`);if(t.length>0)throw new D(`Cannot use \`defaultInitValue' as ${t.join(` or `)}`)},xi=(e,t,n)=>{let r=(e,n)=>{let r=[],i=[];e.tokens.forEach(e=>e.forEach(e=>{if(e.type!==gr.ident)return;let a=_i(t,e.string,n);r.includes(e.string)||a===e.string||(r.push(e.string),i.push(Dr([[Ti(a)]])))})),i.length>0&&Ir(e,i,r,!1)},i=(e,n)=>{e.var=_i(t,e.var,n),r(e.val,n)},a=(e,n)=>e.forEach((r,i)=>{e[i]=gi(t,B.label,r,n)}),o=(e,n)=>e===void 0?void 0:gi(t,B.procedure,e,n),s=(e,n)=>{e.label=gi(t,B.label,e.label,n),e.stmts.forEach(e=>c(e,n))},c=(e,n)=>{let i=e=>e.forEach(e=>c(e,n)),a=e=>e.forEach(e=>s(e,n)),l=e=>e.forEach(e=>r(e,n));switch(e.kind){case`LabeledStmt`:s(e,n);return;case`While`:i(e.unlabDo),a(e.labDo),r(e.test,n);return;case`Assign`:e.ass.forEach(e=>{e.lhs.var=_i(t,e.lhs.var,n),r(e.lhs.sub,n),r(e.rhs,n)});return;case`If`:i(e.Then),i(e.Else),r(e.test,n);return;case`With`:r(e.exp,n),i(e.Do);return;case`When`:case`PrintS`:case`Assert`:r(e.exp,n);return;case`Skip`:return;case`LabelIf`:r(e.test,n),i(e.unlabThen),a(e.labThen),i(e.unlabElse),a(e.labElse);return;case`Call`:e.returnTo=gi(t,B.procedure,e.returnTo,n),e.to=gi(t,B.procedure,e.to,n),l(e.args);return;case`Return`:e.from=o(e.from,n);return;case`CallReturn`:e.from=o(e.from,n),e.to=gi(t,B.procedure,e.to,n),l(e.args);return;case`CallGoto`:e.after=gi(t,B.procedure,e.after,n),e.to=gi(t,B.procedure,e.to,n),l(e.args);return;case`Goto`:if(fi(t,B.label,e.to,n)===void 0&&e.to!==`Done`)throw new D(`goto to non-existent label \`${e.to}' at line ${e.line}, column ${e.col}`);e.to=gi(t,B.label,e.to,n);return;case`Either`:e.ors.forEach(i);return;case`LabelEither`:e.clauses.forEach(e=>{i(e.unlabOr),a(e.labOr)});return;default:throw new E(`Unexpected AST type${e.kind}`)}},l=e=>{e.decls.forEach(t=>i(t,e.name)),e.params.forEach(t=>i(t,e.name)),e.body.forEach(t=>s(xr(t),e.name));let n=Sr(t.procedures,mi(t,e.name));a(e.plusLabels,e.name),a(e.minusLabels,e.name),n.initialPC!==void 0&&(n.initialPC=gi(t,B.label,n.initialPC,e.name)),e.name=gi(t,B.procedure,e.name,``),n.name=e.name},u=e=>{e.decls.forEach(t=>i(t,e.name)),e.body.forEach(t=>s(xr(t),e.name)),a(e.plusLabels,e.name),a(e.minusLabels,e.name),e.name=gi(t,B.process,e.name,``)};e.decls.forEach(e=>i(e,``)),e.kind===`Multiprocess`&&((e,t)=>{e.forEach(l);let r=e.map(e=>e.name),i=e.map(e=>r.map(t=>e.proceduresCalled.includes(t)));r.forEach((e,t)=>i.forEach(e=>e.forEach((n,r)=>{e[r]=n||e[t]&&i[t][r]}))),e.forEach((e,t)=>{e.proceduresCalled=r.filter((e,n)=>i[t][n])});for(let e of t){u(e);let t=e.proceduresCalled;for(let e=0;e<t.length;e+=1){let a=r.indexOf(t[e]);if(a===-1){n(`\nUnrecoverable error:\n -- Could not find procedure name \`${t[e]}'.\n`);return}r.forEach((e,n)=>{i[a][n]&&!t.includes(e)&&t.push(e)})}}})(e.prcds,e.procs),e.kind===`Uniprocess`&&(e.prcds.forEach(l),e.body.forEach(e=>s(xr(e),``)))},Si=e=>Cr(e,0,gr.string),Ci=e=>Cr(e,0,gr.added),wi=e=>Cr(e,0,gr.builtin),Ti=e=>Cr(e,0,gr.ident),Ei=(e,t)=>{let n=[];return e.forEach(e=>{let r=n.at(-1),i=r===void 0?0:r.column+wr(r)+t;n.push(Cr(e.string,i,e.type))}),Dr([n])},Di=e=>e.tokens.forEach((t,n)=>{let r=n===0||n===e.tokens.length-1?1:6;t.forEach(e=>{if(e.column=r,r+=wr(e),e.type===gr.builtin)switch(e.string){case`|->`:case`↦`:e.column=Math.max(16,e.column+1),r=e.column+5;return;case`[`:case`<<`:r+=1;return;case`]`:case`>>`:e.column+=1,r+=1;return;case`\\o`:e.column+=1,r+=2}})}),Oi=(e,t,n,r=0,i=0)=>({...R(),kind:`SingleAssign`,line:r,col:i,lhs:{...R(),kind:`Lhs`,var:e,sub:t},rhs:n}),ki=(e,t=0,n=0)=>({...R(),kind:`Assign`,line:t,col:n,ass:e}),Ai=(e,t,n=0,r=0)=>ki([Oi(e,Dr([]),t,n,r)],n,r),ji=e=>{if(e.tokens.length>1)return!1;let t=Sr(e.tokens,0);return t.length===1?t[0].string===`TRUE`:t.length===3&&t[0].string===`(`&&t[1].string===`TRUE`&&t[2].string===`)`},Mi=e=>({...R(),kind:`When`,exp:Ei([Ci(`pc`),wi(`=`),Si(e)],1)}),Ni=e=>Ai(`pc`,Dr([[Si(e??`null`)]])),Pi=e=>[Ti(`Head`),wi(`(`),Ci(`stack`),wi(`)`),wi(`.`),Ti(e)],Fi=()=>[Ti(`Tail`),wi(`(`),Ci(`stack`),wi(`)`)],Ii=e=>Dr([Pi(e)]),Li=(e,t,n,r)=>{let i=[[wi(`<<`),wi(`[`),Ti(`procedure`),wi(`|->`),Si(e),wi(`,`)],[Ti(`pc`),wi(`|->`),...t]];n.forEach(e=>{i[i.length-1].push(wi(`,`)),i.push([Ti(e.var),wi(`|->`),Ti(e.var)])}),i[i.length-1].push(wi(`]`),wi(`>>`)),i.push(r);let a=Tr(i);return Di(a),Er(a),a},Ri=(e,t,n)=>{if(t.params.length!==n.args.length)throw new D(`Procedure ${n.to} called with wrong number of arguments`,n);return t.params.forEach((t,r)=>e.ass.push(Oi(t.var,Dr([]),n.args[r],n.line,n.col))),[e,...t.decls.map(e=>Ai(e.var,e.val,n.line,n.col)),Ni(t.initialPC)]},zi=(e,t,n)=>{let r,i=(e,n)=>{let r=mi(t,e.to);if(r===t.procedures.length)throw new D(`Call of non-existent procedure ${e.to}`,e);let i=t.procedures[r],a=Li(e.to,[Si(n)],[...i.decls,...i.params],[wi(`\\o`),Ci(`stack`)]);return Ri(Ai(`stack`,a,e.line,e.col),i,e)},a=e=>{e.from??=r;let n=e.from;if(n===void 0)throw new D("`return' statement not in procedure",e);let i=mi(t,n);if(i>=t.procedures.length)throw new D(`Error in procedure (perhaps name used elsewhere)`,e);let a=t.procedures[i],o=(t,n)=>ki([Oi(t,Tr(),n,e.line,e.col)],e.line,e.col);return[o(`pc`,Ii(`pc`)),...a.decls.map(e=>o(e.var,Ii(e.var))),...a.params.map(e=>o(e.var,Ii(e.var))),o(`stack`,Dr([Fi()]))]},o=e=>{let n=e.from;if(n===void 0)throw new D(`\`return' statement following \`call' at ${br(e)} not in a procedure`);let r=Sr(t.procedures,mi(t,n)),i=mi(t,e.to);if(i===t.procedures.length)throw new D(`Call of non-existent procedure ${e.to}`,e);let a=t.procedures[i],o=ki([],e.line,e.col);if(n!==e.to){r.decls.forEach(t=>o.ass.push(Oi(t.var,Tr(),Ii(t.var),e.line,e.col)));let t=Li(e.to,Pi(`pc`),[...a.decls,...a.params],[wi(`\\o`),...Fi()]);o.ass.push(Oi(`stack`,Dr([]),t,e.line,e.col))}return Ri(o,a,e)},s=(e,t)=>{if(e.length===0)return{stmts:[],labeledStmts:[],needsGoto:!n};let r={stmts:e,labeledStmts:[],needsGoto:!1},c=e[e.length-1];switch(c.kind){case`LabelIf`:case`LabelEither`:{let n=c.kind===`LabelIf`?f(c,t):p(c,t);e.pop(),e.push(n.stmt),r.labeledStmts=n.labeledStmts;break}case`Goto`:e.pop(),e.push(Ni(c.to));break;case`Call`:e.pop(),e.push(...i(c,t));break;case`Return`:e.pop(),e.push(...a(c));break;case`CallReturn`:e.pop(),e.push(...o(c));break;case`CallGoto`:e.pop(),e.push(...i({...R(),kind:`Call`,returnTo:``,to:c.to,args:c.args,line:c.line,col:c.col},c.after));break;case`If`:{let e=s(c.Then,t),i=s(c.Else,t);r.labeledStmts.push(...e.labeledStmts,...i.labeledStmts),c.Then=e.stmts,c.Else=i.stmts,n||(r.needsGoto=e.needsGoto&&i.needsGoto,r.needsGoto||(e.needsGoto&&c.Then.push(Ni(t)),i.needsGoto&&c.Else.push(Ni(t))));break}case`Either`:{let e=c.ors.map((e,n)=>{let i=s(e,t);return c.ors[n]=i.stmts,r.labeledStmts.push(...i.labeledStmts),i});r.needsGoto=e.every(e=>e.needsGoto),!n&&!r.needsGoto&&e.forEach((e,n)=>{e.needsGoto&&c.ors[n].push(Ni(t))});break}case`With`:{let e=s(c.Do,t);c.Do=e.stmts,r.labeledStmts.push(...e.labeledStmts),r.needsGoto=e.needsGoto;break}default:r.needsGoto=!0}return n&&(r.needsGoto=!1),r},c=(e,t)=>{let n=s(e,t);return n.needsGoto&&n.stmts.push(Ni(t)),n},l=(e,t)=>{let r=e.stmts.at(0);if(r?.kind===`While`)return d(e,r,t);let i=c([...e.stmts],t),a=[];return n||(i.stmts.unshift(Mi(e.label)),a.push({...R(),kind:`LabeledStmt`,col:e.col,line:e.line,label:e.label,stmts:i.stmts})),a.push(...i.labeledStmts),a},u=(e,t)=>e.flatMap((n,r)=>l(n,r<e.length-1?e[r+1].label:t)),d=(e,t,r)=>{let i=t.labDo.length===0?e.label:t.labDo[0].label,a=c([...t.unlabDo],i),o=c(e.stmts.slice(1),r),s=ji(t.test),l=s?a.stmts:[{...R(),kind:`If`,test:t.test,Then:a.stmts,Else:o.stmts}];return[{...R(),kind:`LabeledStmt`,col:e.col,line:e.line,label:e.label,stmts:[...n?[]:[Mi(e.label)],...l]},...u(t.labDo,e.label),...a.labeledStmts,...s?[]:o.labeledStmts]},f=(e,t)=>{let n=c(e.unlabThen,e.labThen.length===0?t:e.labThen[0].label),r=c(e.unlabElse,e.labElse.length===0?t:e.labElse[0].label),i=u(e.labThen,t);return i.push(...u(e.labElse,t)),i.push(...n.labeledStmts,...r.labeledStmts),{stmt:{...R(),kind:`If`,col:e.col,line:e.line,test:e.test,Then:n.stmts,Else:r.stmts},labeledStmts:i}},p=(e,t)=>{let n=[],r=[];return e.clauses.forEach(e=>{let i=c(e.unlabOr,e.labOr.length>0?e.labOr[0].label:t);n.push(i.stmts),r.push(...i.labeledStmts),r.push(...u(e.labOr,t))}),{stmt:{...R(),kind:`Either`,col:e.col,line:e.line,ors:n},labeledStmts:r}},m=(e,t)=>u(e.map(xr),t),h=e=>{r=e.name;let n=m(e.body,gi(t,B.label,`Error`,``));return r=void 0,{...R(),kind:`Procedure`,col:e.col,line:e.line,name:e.name,minusLabels:[],plusLabels:[],proceduresCalled:[],params:e.params,decls:e.decls,body:n}},g=e=>({...R(),kind:`Process`,col:e.col,line:e.line,name:e.name,fairness:0,minusLabels:[],plusLabels:[],proceduresCalled:[],isEq:e.isEq,id:e.id,decls:e.decls,body:m(e.body,`Done`)}),_=e.prcds.map(h);return e.kind===`Uniprocess`?{...R(),kind:`Uniprocess`,col:e.col,line:e.line,name:e.name,decls:e.decls,defs:e.defs,macros:[],prcds:_,body:m(e.body,`Done`)}:{...R(),kind:`Multiprocess`,col:e.col,line:e.line,name:e.name,decls:e.decls,defs:e.defs,macros:[],prcds:_,procs:e.procs.map(g)}},Bi=(e,t)=>{let n=t?[]:[`pc`];if(n.push(...e.decls.map(e=>e.var)),e.prcds.length>0&&n.push(`stack`),e.prcds.forEach(e=>{n.push(...e.params.map(e=>e.var)),n.push(...e.decls.map(e=>e.var))}),e.kind===`Multiprocess`&&e.procs.forEach(e=>n.push(...e.decls.map(e=>e.var))),n.length===0)throw new D(`The algorithm has no variables.`);let r=(e,t)=>{let r=n.indexOf(t);return r===-1?0:(e[r]+=1,e[r])},i=(e,t)=>t.forEach((t,n)=>{e[n]=Math.max(e[n],t)}),a=e=>[...e].sort((e,t)=>e.lhs.var<t.lhs.var?-1:+(e.lhs.var>t.lhs.var)),o=(e,t)=>{let o=[...t];e.ass=a(e.ass),new Set(e.ass.map(e=>e.lhs.var)).forEach(t=>{let i=e.ass.filter(e=>e.lhs.var===t);if(!n.includes(t))throw new D(`Assignment to undeclared variable ${t}`,i[0]);let a=i.some(e=>e.lhs.sub.tokens.length===0);if(r(o,t)>1||i.length>1&&a)throw new D(`Multiple assignment to ${t}`,e)}),i(t,o)},s=(e,t)=>{switch(e.kind){case`Assign`:o(e,t);return;case`If`:{let n=[...t],r=[...t];e.Then.forEach(e=>s(e,n)),e.Else.forEach(e=>s(e,r)),i(t,n),i(t,r);return}case`Either`:{let n=[...t];e.ors.forEach(e=>{let r=[...t];e.forEach(e=>s(e,r)),i(n,r)}),i(t,n);return}case`With`:e.Do.forEach(e=>s(e,t));return;case`When`:case`PrintS`:case`Assert`:case`Skip`:return;default:throw new E(`Unexpected AST type ${e.kind}`)}},c=e=>e.forEach(e=>{let t=n.map(()=>0);xr(e).stmts.forEach(e=>s(e,t))});e.prcds.forEach(e=>c(e.body)),(e.kind===`Uniprocess`?[e.body]:e.procs.map(e=>e.body)).forEach(c)},Vi=(e,t,n,r)=>{let i=vi(e);yi(i)&&r(`Warning: symbols were renamed.`),xi(e,i,r),Bi(zi(e,i,t),t),n&&bi(i)},Hi=`[ \\t\\n\\x0B\\f\\r]`,Ui=RegExp(`\\\\\\* BEGIN TRANSLATION${Hi}+\\(${Hi}*([cC][hH]([eE][cC])?[kK][sS][uU][mM]\\([pP]([lL][uU][sS])?[cC][aA][lL]\\))${Hi}*(=${Hi}*"(?<pcal>[0-9A-Fa-f]*)"|\\\\in${Hi}*STRING)${Hi}*\\/\\\\${Hi}*([cC][hH]([eE][cC])?[kK][sS][uU][mM]\\([tT][lL][aA]\\+?\\))${Hi}*(=${Hi}*"(?<tla>[0-9A-Fa-f]*)"|\\\\in${Hi}*STRING)${Hi}*\\)`),Wi=e=>process.getBuiltinModule(`node:zlib`).crc32(Buffer.from(e,`utf8`)).toString(16),Gi=(e,t)=>e.log(`\nUnrecoverable error:\n -- ${t}.\n`),Ki=(e,t)=>Gi(e,t.node===void 0||t.node.line===0?t.message:`${t.message}\n at ${br(t.node)}`),qi=e=>e.map(e=>`${Array.from(e).reduce((e,t)=>t===` `?e+` `.repeat(8-e.length%8):e+t,``)} `),Ji=(e,t,n,r)=>{for(let i=Math.max(t,0);i<e.length;i++){let t=e[i],a=t.indexOf(n);if(a===-1)continue;let o=a+n.length,s=t.slice(o).search(/[^ ]/);if(s!==-1&&o+s===t.indexOf(r))return i}return-1},Yi=(e,t)=>{for(;t.line<e.length;){let n=e[t.line];for(;t.column<n.length&&n[t.column]===` `;)t.column+=1;if(t.column<n.length)return n;t.line+=1,t.column=0}return``},Xi=(e,t,n)=>{let r=Array.from(e.slice(t)).findIndex(e=>n.includes(e));return r===-1?e.length:t+e.slice(t,t+r).length},Zi=e=>/^[\p{L}\p{Nd}_]$/u.test(e),Qi=(e,t,n)=>{for(;t.line<e.length;){let r=Yi(e,t);if(r.slice(t.column).startsWith(n)){let e=t.column+n.length;if(e>=r.length||!/^[\p{L}_]$/u.test(r[e]))return t.column=Xi(r,e,` `),!0}t.column=Xi(r,t.column,` `)}return!1},$i=(e,t)=>Gi(e,`Command-line error: ${t}`),ea=(e,t)=>{let n=e.params,r=!0,i=!1,a=t=>(r&&=(n.fairnessOption=``,!1),n.fairnessOption===``?(n.fairnessOption=t,!0):($i(e,`Can only have one of -wf, -sf, -wfNext, and -nof options`),!1));for(let r=0;r<t.length;r++){let o=t[r],s=t[r+1];switch(o){case`-spec`:case`spec`:case`-myspec`:case`myspec`:{let t=o.endsWith(`myspec`);if(n[t?`myspecOption`:`specOption`]=!0,n.specOption&&n.myspecOption){$i(e,`
32
- Can have at most one of the options -spec, -myspec, -spec2, -myspec2, writeAST`);return}if(s===void 0){$i(e,`Specification name must follow \`-${t?`myspec`:`spec`}' option`);return}r+=1;continue}case`-termination`:case`termination`:n.checkTermination=!0;continue;case`-noold`:case`-nocfg`:case`-noDoneDisjunct`:case`noDoneDisjunct`:continue;case`-wf`:case`wf`:case`-sf`:case`sf`:case`-wfNext`:case`wfNext`:case`-nof`:case`nof`:if(!a(o.replace(/^-/,``)))return;o.endsWith(`nof`)&&(i=!0);continue;case`-label`:case`label`:n.labelFlag=!0;continue;case`-labelRoot`:case`labelRoot`:if(s===void 0){$i(e,"Label root must follow `-labelRoot' option");return}if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(s)){$i(e,`Label root must be a valid PlusCal identifier (must start with a letter and contain only letters, numbers, and underscores)`);return}n.labelRoot=s,r+=1;continue;case`-version`:case`version`:{if(s===void 0){$i(e,"Version number must follow `-version' option");return}let t=vr(s);if(t<0||t>1903){Gi(e,t<0?`Illegal version ${s} specified.`:`Specified version ${s} later than current version 1.12`),$i(e,`Bad version number`);return}n.inputVersionNumber=t,r+=1;continue}case`-lineWidth`:if(!/^[+-]?\d+$/.test(s??``)||Number(s)<60){$i(e,"Integer value at least 60 must follow `-lineWidth' option");return}r+=1;continue;default:$i(e,`Unknown or illegal option in options statement: ${o}`);return}}n.checkTermination&&n.fairnessOption===``&&!i&&(n.fairnessOption=`wf`)},ta=(e,t,n)=>{if(Yi(t,n),n.column+=7,!Yi(t,n).slice(n.column).startsWith(`(`)){Gi(e,"`PlusCal options' not followed by '('");return}n.column+=1;let r=[];for(;;){let e=Yi(t,n);if(n.line>=t.length||e[n.column]===`)`)break;if(e[n.column]===`,`){n.column+=1;continue}let i=Xi(e,n.column,` ,)`);r.push(e.slice(n.column,i)),n.column=i}n.line>=t.length?Gi(e,`No closing ')' found in options statement`):ea(e,r)},na=(e,t,n)=>{let r=0,i=!1,a=!1;for(let o=t;!i&&o<e.length;o++){let s=e[o],c=o===t?n:0,l=[s.slice(0,c)];a=!1;for(let e=c;!i&&e<s.length;e++){let t=s[e],n=s.slice(e,e+2);if(n===`(*`&&!a)r+=1,l.push(` `),e+=1;else if(n===`*)`&&!a&&r===0)l.push(n),i=!0;else if(n===`*)`&&!a)--r,l.push(` `),e+=1;else if(r>0)l.push(` `);else if(a&&t===`\\`&&n.length===2)l.push(n),e+=1;else{if(!a&&n===`\\*`){l.push(` `);break}t===`"`&&(a=!a),l.push(t)}}if(a)return new D(`Unterminated string in line ${o+1}`);e[o]=l.join(``)}},ra=(e,t)=>{let n=10*2**Math.max(0,Math.ceil(Math.log2(t/10)));throw new b(`java.lang.ArrayIndexOutOfBoundsException: Index ${e} out of bounds for length ${n}`)},ia=(e,t,n)=>{if(!t.some(e=>e.indexOf(`algorithm`)>0))return/* @__PURE__ */ new Set([`NO_PLUSCAL_EXISTS`]);let r=qi(t),i={line:0,column:0};for(;Qi(r,i,`PlusCal`);){let t=Yi(r,i).slice(i.column),n=Array.from(t).findIndex(e=>!Zi(e));if(t.startsWith(`options`)&&(n===-1?t.length:n)===7){ta(e,r,i);break}}let a=0,o=-1,s=!1;for(;a<r.length;a++){let e=r[a];if(/^=+$/.test(e))break;let t=e.indexOf(`--algorithm`),n=e.indexOf(`--fair`);if(t!==-1){o=t+11;break}if(n!==-1){o=n+6,s=!0;break}}let c=/* @__PURE__ */ new Set,l=Ji(r,0,`BEGIN`,`TRANSLATION`);l===-1&&c.add(`NO_TRANSLATION_EXISTS`);let u=Ji(r,l+1,`END`,`TRANSLATION`);if(u===-1&&c.add(`NO_TRANSLATION_EXISTS`),l===-1&&u===-1)return c;if(o===-1)return c.add(`NO_PLUSCAL_EXISTS`),c;let d=na(r,a,o);if(d!==void 0)return Ki(e,d),/* @__PURE__ */ new Set([`ERROR_ENCOUNTERED`]);let f;try{let t=li(e,Vr(r,a,o),s);f=t.ast,Vi(t.ast,t.shouldOmitPC,t.hasDefaultInitialization,e.log)}catch(t){if(!(t instanceof D))throw t;Ki(e,t)}l===-1&&ra(-1,r.length);let p=Ui.exec(r[l]);if(p===null)return c.add(`NO_PCAL_CHECKSUMS_EXIST`),c;let m=p.groups?.pcal,h=s&&n!==`1.7.4`?`fair`:f===void 0?void 0:Br(f,e.params.inputVersionNumber,n);m!==void 0&&(h===void 0||m!==Wi(h))&&c.add(`PCAL_DIVERGENCE_EXISTS`);let g=p.groups?.tla;if(g!==void 0){if(u===-1)throw new b(`java.lang.IllegalArgumentException: fromIndex(${l+1}) > toIndex(-1)`);let e=t.slice(l+1,u).join(``);g!==Wi(e)&&c.add(`TLA_DIVERGENCE_EXISTS`)}return c.size===0?/* @__PURE__ */ new Set([`NO_DIVERGENCE`]):c},aa=[[`STRING`,0,0,[],[]],[`FALSE`,0,0,[],[]],[`TRUE`,0,0,[],[]],[`BOOLEAN`,0,0,[],[]],[`=`,2,0,[2,2],[1,1]],[`/=`,2,0,[2,2],[1,1]],[`.`,2,0,void 0,void 0],[`'`,1,2,[1],[0]],[`\\lnot`,1,0,[3],[1]],[`\\neg`,1,0,void 0,void 0],[`\\land`,2,0,[3,3],[1,1]],[`\\lor`,2,0,[3,3],[1,1]],[`\\equiv`,2,0,[3,3],[1,1]],[`=>`,2,0,[3,3],[1,1]],[`SUBSET`,1,0,[2],[1]],[`UNION`,1,0,[2],[1]],[`DOMAIN`,1,0,[2],[1]],[`\\subseteq`,2,0,[2,2],[1,1]],[`\\in`,2,0,[2,2],[1,1]],[`\\notin`,2,0,[2,2],[1,1]],[`\\`,2,0,[2,2],[1,1]],[`\\intersect`,2,0,[2,2],[1,1]],[`\\union`,2,0,[2,2],[1,1]],[`\\times`,2,0,[2,2],[1,1]],[`~>`,2,3,[3,3],[0,0]],[`[]`,1,3,[3],[0]],[`<>`,1,3,[3],[0]],[`ENABLED`,1,1,[2],[0]],[`UNCHANGED`,1,2,[1],[0]],[`\\cdot`,2,2,[2,2],[0,0]],[`-+->`,2,3,[3,3],[0,0]],[`$AngleAct`,2,2,[2,1],[0,0]],[`$BoundedChoose`,-1,0,[2],[1]],[`$BoundedExists`,-1,0,[3],[1]],[`$BoundedForall`,-1,0,[3],[1]],[`$CartesianProd`,-1,0,[2],[1]],[`$Case`,-1,0,[3],[1]],[`$ConjList`,-1,0,[3],[1]],[`$DisjList`,-1,0,[3],[1]],[`$Except`,-1,0,[2],[1]],[`$FcnApply`,2,0,[2,2],[1,1]],[`$FcnConstructor`,-1,0,[3],[1]],[`$IfThenElse`,3,0,[3,3,3],[1,1,1]],[`$NonRecursiveFcnSpec`,1,0,[3],[1]],[`$Pair`,2,0,[3,3],[1,1]],[`$RcdConstructor`,-1,0,[3],[1]],[`$RcdSelect`,2,0,[2,0],[1,1]],[`$RecursiveFcnSpec`,1,0,[3],[1]],[`$Seq`,-1,0,[2],[1]],[`$SetEnumerate`,-1,0,[2],[1]],[`$SetOfAll`,-1,0,[2],[1]],[`$SetOfFcns`,-1,0,[2],[1]],[`$SetOfRcds`,-1,0,[2],[1]],[`$SF`,2,3,[1,2],[0,0]],[`$SquareAct`,2,2,[2,1],[0,0]],[`$SubsetOf`,1,0,[2],[1]],[`$TemporalExists`,1,3,[3],[0]],[`$TemporalForall`,1,3,[3],[0]],[`$TemporalWhile`,2,3,[3,3],[0,0]],[`$Tuple`,-1,0,[2],[1]],[`$UnboundedChoose`,1,0,[2],[1]],[`$UnboundedExists`,1,0,[3],[1]],[`$UnboundedForall`,1,0,[3],[1]],[`$WF`,2,3,[1,2],[0,0]],[`$Nop`,1,0,[3],[1]],[`$Qed`,0,0,[],[]],[`$Pfcase`,1,0,[3],[1]],[`$Have`,1,0,[3],[1]],[`$Take`,1,0,[3],[1]],[`$Pick`,1,0,[3],[1]],[`$Witness`,-1,0,[2],[1]],[`$Suffices`,1,0,[3],[1]]],oa={file:`--TLA+ BUILTINS--`,beginLine:0,beginColumn:0,endLine:0,endColumn:0},V=e=>({id:e,levelChecked:0,level:0,levelParams:/* @__PURE__ */ new Set,allParams:/* @__PURE__ */ new Set,nonLeibnizParams:/* @__PURE__ */ new Set,argLevelParams:/* @__PURE__ */ new Map,levelCorrect:!0,levelConstraints:/* @__PURE__ */ new Map,argLevelConstraints:/* @__PURE__ */ new Map}),sa=e=>aa.map(([t,n,r,i,a])=>{let o=e(),s=n<0?void 0:Array.from({length:n},(t,n)=>({...V(e()),kind:`FormalParam`,name:`Formal_${n}`,arity:0,location:void 0})),c=i!==void 0&&a!==void 0,l=a?.map(e=>e>0);return{...V(o),levelChecked:c?99:0,level:r,kind:`OpDef`,defKind:`BuiltIn`,name:t,arity:n,params:s,body:void 0,isLocal:!1,location:oa,module:void 0,source:void 0,preComments:[],isDefined:!0,inRecursive:!1,inRecursiveSection:!1,recursiveSection:-1,letInLevel:0,weights:n<0?(a??[]).slice(0,1):a??[],isLeibnizArg:c?l:void 0,isLeibniz:l?.every(Boolean)??!0,opLevelCond:void 0,maxLevels:n<0?(i??[]).slice(0,1):i??[],minMaxLevel:void 0,labels:/* @__PURE__ */ new Map,step:void 0}}),ca=(e,t)=>{let n=JSON.stringify(t);e.some(e=>JSON.stringify(e)===n)||e.push(t)},la=e=>e===void 0?`Unknown location`:typeof e==`string`?`In module ${e}`:e.beginLine===0&&e.beginColumn===0&&e.endLine===0&&e.endColumn===0?`In module ${e.file}`:`line ${e.beginLine}, col ${e.beginColumn} to line ${e.endLine}, col ${e.endColumn} of module ${e.file}`,ua=e=>e?.kind===`OpAppl`&&e.nullKind===`absent`,da=()=>({buckets:Array.from({length:11},()=>[]),count:0,threshold:8}),fa=(e,t)=>(e&2147483647)%t,pa=e=>{let t=e.buckets.length*2+1,n=Array.from({length:t},()=>[]);for(let r=e.buckets.length-1;r>=0;r--)e.buckets[r].forEach(e=>n[fa(e.hash,t)].unshift(e));e.buckets=n,e.threshold=Math.floor(t*.75)},ma=(e,t,n=t)=>e.buckets[fa(je(n),e.buckets.length)].find(e=>e.key===t)?.value,ha=(e,t,n,r=t)=>{let i=je(r),a=e.buckets[fa(i,e.buckets.length)].find(e=>e.key===t);a?a.value=n:(e.count>=e.threshold&&pa(e),e.buckets[fa(i,e.buckets.length)].unshift({hash:i,key:t,value:n}),e.count++)},ga=e=>e.buckets.toReversed().flatMap(e=>e.map(e=>e.value)),_a=`\0module `,va=()=>({table:da(),symbols:[]}),ya=e=>e.kind===`Module`?_a+e.name:e.name,ba=(e,t)=>{ha(e.table,ya(t),t,t.name),e.symbols.push(t)},xa=e=>e.kind===`ThmOrAssumpDef`?e.params.length:e.kind===`Module`?0:e.arity,Sa=(e,t)=>ma(e.table,t),Ca=(e,t)=>ma(e.table,_a+t,t),wa=e=>e.context.symbols.filter(e=>e.kind===`OpDef`&&e.defKind===`UserDefined`),Ta=(e,t)=>ga(e.context.table).filter(e=>e.kind===`OpDecl`&&e.declKind===t).toReversed(),Ea=e=>e.context.symbols.filter(e=>e.kind===`ThmOrAssumpDef`),Da=/* @__PURE__ */ new Map([[`$Qed`,`QED step`],[`$Pfcase`,`CASE`],[`$Have`,`HAVE`],[`$Take`,`TAKE`],[`$Pick`,`PICK`],[`$Witness`,`WITNESS`],[`$Suffices`,`SUFFICES`]]),Oa=e=>{if(e.length>3&&e.endsWith(`!!!`))return[...Oa(e.slice(0,-3)),`!!`];let t=e.split(`!`);return t.some(e=>e.length===0)?[e]:t},ka=e=>{switch(e.kind){case`Identifier`:return Oa(e.name).map(e=>({op:`Name`,name:e,args:void 0}));case`Apply`:{let t=Oa(e.operator),n=e.argumentCounts??t.map((n,r)=>r===t.length-1?e.args.length:0),r=0;return t.map((t,i)=>{let a=e.args.slice(r,r+n[i]);return r+=n[i],{op:`Name`,name:t,args:a.length>0?a:void 0}})}case`Subexpression`:return e.selectors.map(e=>{switch(e.kind){case`Name`:return{op:`Name`,name:e.name,args:e.args.length>0?e.args:void 0};case`Operand`:return{op:e.operand,name:String(e.operand),args:void 0};case`Bound`:return{op:`Null`,name:`!(...)`,args:e.args};case`At`:return{op:`@`,name:`@`,args:void 0};case`Colon`:return{op:`:`,name:`:`,args:void 0}}})}},Aa=e=>{let t=e[e.length-1];return t.op!==`Name`||t.args===void 0},ja=e=>typeof e.op==`number`?`argument selector ${e.name}`:e.name,Ma=(e,t)=>typeof e==`number`?e>0&&e<=t?e:-1:e===`<<`?t>0?1:-1:e===`>>`&&t===2?2:-1,Na=e=>e.kind===`OpDecl`||e.kind===`FormalParam`||e.kind===`OpDef`&&(e.defKind===`BuiltIn`||e.defKind===`NumberedProofStep`),Pa=e=>e.kind===`FormalParam`||e.kind===`OpDecl`||e.kind===`OpDef`||e.kind===`ThmOrAssumpDef`||e.kind===`Module`,Fa=e=>(e.bounded?.length??0)>0?(e.bounded??[]).flat():e.unbounded??[],Ia=(e,t)=>e===void 0?t:{...e,endLine:t.endLine,endColumn:t.endColumn},La=e=>(t,n,r,i,a)=>{let o=[],s=[],c=[],l={name:void 0,nameLocation:void 0,node:void 0,index:0,mode:`FindingOpName`,previousMode:void 0,letInContext:void 0,definitionArityFound:0,definitionArgs:[],isInSuffices:!1},u=()=>t[l.index].location??a,d=e=>e.args??[];for(;l.index<t.length;){let f=t[l.index];if((f.op!==`Name`&&f.op!==`Null`||n!==0)&&f.args!==void 0)return e.addError(u(),`Selector \`${f.name}' should not have argument(s).`);switch(l.mode){case`FindingOpName`:{let f,p,m=[];for(;f===void 0&&l.index<t.length;){let n=t[l.index];if(p=n.op===`Name`?l.name===void 0?e.resolveSynonym(n.name):`${l.name}!${e.resolveSynonym(n.name)}`:void 0,l.name===void 0&&n.op!==`Name`)return e.addError(u(),`Need name or step number here, not \`${n.name}'.`);p!==void 0&&(f=l.letInContext===void 0?e.resolveSymbol(p):Sa(l.letInContext,p)),f===void 0&&(p!==void 0&&(l.name=p,l.nameLocation=Ia(l.nameLocation,u())),m.push(...d(n)),l.index++)}if(f===void 0&&e.version===`1.7.4`){let n=t.length-1;return e.addError(t[n].location??a,`Unknown operator: \`${ja(t[n])}'.`)}if(f===void 0)return e.addError(l.nameLocation??a,`Unknown operator: \`${l.name}'.`);if(f.kind===`Module`)return e.addError(u(),`Module name (${t[l.index].name}) not allowed here.`);if(l.node=f,l.nameLocation=Ia(l.nameLocation,u()),l.name=p,Na(f)&&t.length!==1)return e.addError(u(),`Cannot take subexpression of \`${l.name}'.`);let h=xa(f);if(n===0){if(m.push(...d(t[l.index])),l.definitionArityFound+m.length!==h)return e.addError(t[l.index].argsLocation??a,`The operator ${l.name} requires ${h-l.definitionArityFound} arguments.`);m.forEach((t,n)=>l.definitionArgs.push(e.generateArgument(f,n+l.definitionArityFound,t,u())))}if(l.definitionArityFound=h,f.kind===`OpDef`&&f.defKind===`ModuleInstance`){if(l.index===t.length-1&&!(i||r))return e.addError(u(),`Operator name ${l.name} is incomplete.`)}else{let n=f.kind===`OpDef`&&f.defKind===`UserDefined`||f.kind===`ThmOrAssumpDef`?f:void 0;if(f.kind===`OpDef`&&f.defKind===`UserDefined`&&!f.isDefined&&t.length!==1)return e.addError(u(),`Subexpression of \`${l.name}' used inside the operator's definition.`);if(l.index!==t.length-1&&n!==void 0){s.push(...n.params??[]),l.name=void 0,l.nameLocation=void 0,l.mode=t[l.index+1].op===`Name`?`FollowingLabels`:`FindingSubExpr`,c.push(...l.definitionArgs),l.definitionArityFound=0,l.definitionArgs=[];let e=n.body;for(;e?.kind===`SubstIn`;)o.push(e),e=e.body;for(;e?.kind===`APSubstIn`;)o.push(e),e=e.body;l.mode===`FindingSubExpr`&&(l.node=e)}}l.previousMode=`FindingOpName`;break}case`FollowingLabels`:{let r=l.node,i=r?.kind===`OpDef`||r?.kind===`ThmOrAssumpDef`||r?.kind===`Label`?r.labels.get(f.name):void 0;if(i===void 0)return e.addError(u(),`Cannot find label \`${f.name}'.`);if(l.node=i,e.isOutOfLabelScope(i))return e.addError(u(),`Accessing subexpression labeled \`${f.name}' of ASSUME/PROVE clause within the scope of a declaration\n from outside that declaration's scope.`);if(n===0){if(i.params.length!==d(f).length)return e.addError(u(),`Label \`${f.name}' used with wrong number of arguments.`);c.push(...d(f).map(e.generateExpression))}s.push(...i.params),l.index<t.length-1&&t[l.index+1].op!==`Name`&&(l.mode=`FindingSubExpr`),l.mode===`FindingSubExpr`&&(l.node=i.body),l.previousMode=`FollowingLabels`;break}case`FindingSubExpr`:{let n=l.node,r=()=>e.addError(u(),`Nonexistent operand specified by \`${ja(f)}'.`);if(f.op===`:`){if(!(l.previousMode!==`FindingSubExpr`&&(l.index===t.length-1&&l.previousMode===`FindingOpName`||l.index<t.length-1&&t[l.index+1].op===`Name`)))return e.addError(u(),`\`!:' can be used only after a name and either at the end after an
33
- operator name or before an operator name.`)}else if(n===void 0)return e.addError(u(),`Subexpression selection failed, probably due to an error in the selected expression.`);else if(n.kind===`LetIn`){if(Ma(f.op,1)!==1)return e.addError(u(),`A LET/IN expression has only one operand.`);l.node=n.body}else if(n.kind===`OpAppl`){let i=n.operator,a=n.operands,o=i.kind===`FormalParam`||i.kind===`OpDecl`&&i.declKind===2||i.kind===`OpDef`&&i.defKind===`UserDefined`,p=()=>e.addError(u(),`Internal error: Expecting $Pair and didn't find it.`),m=e=>e?.kind===`OpAppl`&&e.operator.name===`$Pair`,h=Ma(f.op,a.length);if(o){let e=Ma(f.op,i.arity);if(e===-1)return r();l.node=a[e-1]}else if(i.kind===`OpDef`&&i.defKind===`BuiltIn`){if(i.name===`$RcdConstructor`||i.name===`$SetOfRcds`){if(h===-1)return r();let e=a[h-1];if(!m(e))return p();l.node=e.operands[1]}else if(i.name===`$Case`){if(l.index===t.length-1)return e.addError(u(),`Subexpression of CASE must have form !i!j.`);if(h===-1)return r();let n=a[h-1];if(!m(n))return p();l.index++;let i=Ma(t[l.index].op,2);if(i===-1)return e.addError(u(),`Second selector for CASE subexpression must specify one of two operands.`);if(l.node=n.operands[i-1],l.node===void 0)return e.addError(u(),`Selecting OTHER in a CASE statement.`)}else if(i.name===`$Except`){if(h>1)return e.addError(u(),`Selecting subexpression of an EXCEPT not yet implemented.`);if(h===-1)return r();l.node=a[h-1]}else if((n.bounded?.length??0)===0&&(n.unbounded?.length??0)===0){if(h===-1)return r();l.node=a[h-1]}else if(f.op===`Null`||f.op===`@`){let t=Fa(n);if(s.push(...t),f.op===`Null`){if(d(f).length!==t.length)return e.addError(u(),`Selector with ${d(f).length} argument(s) used for quantifier with ${t.length} bound identifier(s).`);c.push(...d(f).map(e.generateExpression))}l.node=a[0]}else{let e=Ma(f.op,n.ranges.length);if(e===-1)return r();l.node=n.ranges[e-1]}}else return e.addError(u(),`Choosing operand \`${f.name}' of subexpression with no operands.`)}else if(n.kind===`AssumeProve`){if(n.isSuffices&&!l.isInSuffices){if(Ma(f.op,1)!==1)return e.addError(u(),`Accessing non-existent subexpression of a SUFFICES`);l.isInSuffices=!0}else{l.isInSuffices=!1;let i=Ma(f.op,1+n.assumptions.length);if(i===-1)return r();if(e.isOutOfClauseScope(n,i))return e.addError(u(),`Accessing ASSUME/PROVE clause within the scope of a declaration
34
- from outside that declaration's scope.`);if(i<=n.assumptions.length){if(l.node=n.assumptions[i-1],l.node.kind===`NewSymb`&&l.index!==t.length-1)return e.addError(u(),`Selected a subexpression of a NEW clause of an ASSUME.`)}else l.node=n.goal}}else if(n.kind===`OpArg`){let t=n.op;if(t.kind!==`OpDef`||t.name!==`LAMBDA`)return e.addError(u(),`Trying to select subexpression of an operator argument.`);if(f.op!==`Null`&&f.op!==`@`)return e.addError(u(),`Cannot use !${f.name} to select subexpression of a LAMBDA.`);if(f.op===`Null`){if(t.arity!==d(f).length)return e.addError(u(),`Selector with ${d(f).length} arguments used for LAMBDA expression taking ${t.arity} arguments.`);c.push(...d(f).map(e.generateExpression))}s.push(...t.params??[]),l.node=t.body}else if(n.kind===`Label`)l.node=n.body,l.index--;else return e.addError(u(),`Selecting subexpression of expression that has none.`);if(l.node===void 0)return e.addError(u(),`An unexpected null node specified by '${f.name}'.\nThis is probably due to a previous error.`);if(l.index!==t.length-1){let n=t[l.index+1];if(n.op===`Name`){for(;l.node?.kind===`Label`;)l.node=l.node.body;if(l.node?.kind!==`LetIn`)return e.addError(u(),`A name selector here must be from a LET clause.`);l.letInContext=l.node.context,l.mode=`FindingOpName`}else if(n.op===`:`)return e.addError(u(),`!: should not follow an operand selector.`)}l.previousMode=`FindingSubExpr`;break}}l.index++}let f=l.node;if(f===void 0)return e.addError(a,`Subexpression selection failed, probably due to an error in the selected expression.`);if(f.kind===`AssumeProve`||f.kind===`NewSymb`)return r?f:e.addError(a,f.kind===`AssumeProve`?`Selected ASSUME/PROVE instead of expression.`:`Selected a NEW declaration as an expression or operator.`);if(n<0){let t=f.kind===`OpDef`&&(f.defKind===`UserDefined`||f.defKind===`NumberedProofStep`||f.defKind===`ModuleInstance`&&i)||f.kind===`ThmOrAssumpDef`;return l.previousMode!==`FindingOpName`||!t?e.addError(a,`DEF clause entry should describe a defined operator.`):f.kind===`OpDef`&&f.step!==void 0&&f.step.kind!==`DefStep`?e.addError(a,`DEF clause entry refers to a non-definition step.`):f}if(f.kind===`OpDef`&&f.defKind===`NumberedProofStep`)return e.addError(a,r?`Step number of non-fact used as a fact`:`Step number of non-expression step used as an expression.`);if(n>0){let t=s.length+(f.kind===`OpArg`?xa(f.op):l.previousMode===`FindingOpName`&&Pa(f)?xa(f):0);if(n!==t)return e.addError(a,`Expected arity ${n} but found operator of arity ${t}.`)}let p=f;if(l.previousMode===`FindingOpName`&&s.length+o.length>0){if(p.kind!==`OpDef`&&p.kind!==`ThmOrAssumpDef`)return e.addError(t[t.length-1].location??a,`Internal Error: Found unexpected node kind after FindingOpName`);c.push(...l.definitionArgs);let n=(p.params??[]).map(t=>{let n=e.createFormalParam(t.name,t.arity,t.location);return s.push(n),t.arity===0?e.createOpAppl(n,[],a):e.createOpArg(n,a)});p=e.createOpAppl(p,n,a)}if(p.kind===`OpArg`){if(n===0)return e.addError(a,`Selected operator argument when expression expected.`);if(s.length+o.length>0){let t=p.op;s.push(...Array.from({length:xa(t)},(t,n)=>e.createFormalParam(`NewParam${n}`,0,void 0))),p=e.createOpAppl(t,l.definitionArgs,a)}}if(!r){if(p.kind===`ThmOrAssumpDef`&&p.body.kind===`AssumeProve`)return e.addError(a,`ASSUME/PROVE used where an expression is required.`);if(p.kind===`ThmOrAssumpDef`&&p.body.kind===`OpAppl`){let t=Da.get(p.body.operator.name);if(t!==void 0)return e.addError(a,`${t} proof step selected instead of expression.`)}}if(p.kind===`FormalParam`||p.kind===`OpDecl`||p.kind===`ThmOrAssumpDef`||p.kind===`OpDef`&&(p.defKind===`UserDefined`||p.defKind===`BuiltIn`))return n>0?e.createOpArg(p,a):e.createOpAppl(p,l.definitionArgs,a);if(p.kind===`OpArg`)return p;if(p.kind===`OpDef`||p.kind===`Module`)return(r||i)&&p.kind===`OpDef`?p:e.addError(a,`Module instantiation selected instead of expression.`);let m=o.reduceRight((t,n)=>e.copySubstIn(n,t),p),h=s.length>0?e.createLambda(s,m,a):void 0;return n>0?h===void 0||s.length!==n?e.addError(a,`Expected operator argument with arity ${n} but found one of arity ${s.length}.`):e.createOpArg(h,a):s.length===c.length?h===void 0?e.createOpAppl(e.getBuiltin(`$Nop`),[m],a):e.createOpAppl(h,c,a):e.addError(a,`Expected ${s.length} arguments but found ${c.length}.`)},Ra=/* @__PURE__ */ new Map([[`(`,`)`],[`[`,`]`],[`{`,`}`],[`<<`,`>>`]]),za=(e,t)=>`${e}:${t}`,Ba=(e,t)=>{let n=ge(t).filter(e=>e.kind!==`End`).map(Ye),r=[0,0];for(let e=0;e<t.length;e++)t[e]===`
35
- `&&r.push(e+1);return{name:e,source:t,tokens:n,lineOffsets:r,tokenIndexes:new Map(n.map((e,t)=>[za(e.line,e.column),t]))}},H=(e,t,n)=>e.tokens[t]!==void 0&&e.tokens[t].text===n&&e.tokens[t].kind!==`String`,Va=(e,t,n)=>{let r=0,i=e.tokens.length;for(;r<i;){let a=r+i>>>1,o=e.tokens[a];o.line<t.line||o.line===t.line&&(n?o.column<=t.column:o.column<t.column)?r=a+1:i=a}return r},Ha=(e,t)=>e.tokenIndexes.get(za(t.line,t.column))??Math.min(Va(e,t,!1),e.tokens.length-1),Ua=(e,t)=>Math.max(Va(e,t,!0)-1,0),Wa=(e,t)=>{let n=e.tokens[t].text,r=Ra.get(n);if(r===void 0)return t;let i=0;for(let a=t;a<e.tokens.length;a++)if(H(e,a,n))i++;else if(H(e,a,r)&&(i--,i===0))return a;return t},Ga=(e,t)=>({start:Ha(e,t.start),end:Ua(e,t.end)}),U=(e,t)=>{let n=t.location.range;if(n)return Ga(e,n);let r=Ha(e,t.location);return{start:r,end:Wa(e,r)}},Ka=(e,t)=>{let n=t.start-1,r=t.end+1;return H(e,n,`(`)&&H(e,r,`)`)&&Wa(e,n)===r?Ka(e,{start:n,end:r}):t},qa=(e,t)=>{let n=t.start-1,r=t.end+1;return H(e,n,`(`)&&Wa(e,n)===r&&(H(e,n-1,`(`)||H(e,n-1,`,`))?qa(e,{start:n,end:r}):t},W=(e,t)=>({file:e.name,beginLine:e.tokens[t.start].line,beginColumn:e.tokens[t.start].column,endLine:e.tokens[t.end].line,endColumn:e.tokens[t.end].endColumn}),G=(e,t)=>W(e,{start:t,end:t}),Ja=(e,t,n)=>{let r=0,i=e.lineOffsets[t];for(;i<e.source.length;){if(r=e.source[i]===` `?Ge(r):r+1,r>=n)return i;i++}return i},Ya=(e,t)=>{let n=e.tokens[t],r=Ja(e,n.line,n.column);return e.source.slice(r,Ja(e,n.line,n.endColumn)+1)},Xa=(e,t)=>{let n=e.tokens[t],r=e.tokens[t+1];return n?.kind===`Operator`&&n.text===`[]`&&r?.kind===`Keyword`&&(r.text===`ASSUME`||r.text===`PROVE`)&&r.line===n.line&&r.column===n.endColumn+1},Za=e=>{let t=Ba(``,e),n=t.tokens.reduce((e,n,r)=>{if(!Xa(t,r))return e;let i=Ja(t,n.line,n.column);return`${e.slice(0,i)} ${e.slice(i+2)}`},e);if(n!==e&&qe(e)!==void 0)throw new o(`SANY rejects a []ASSUME or []PROVE outside an ASSUME/PROVE`);return n},Qa=(e,t)=>{let n=e.tokens[t-1],r=e.tokens[t],i=n===void 0?0:Ja(e,n.line,n.endColumn)+1,a=e.source.slice(i,Ja(e,r.line,r.column)),o=[],s=0;for(;s<a.length;)if(a.startsWith(`\\*`,s)){let e=a.indexOf(`
36
- `,s),t=e===-1?a.length:e+1;o.push(a.slice(s,t)),s=t}else if(a.startsWith(`(*`,s)){let e=1,t=s,n=s+2;for(;e>0&&n<a.length;){let r=a.startsWith(`(*`,n),i=a.startsWith(`*)`,n);r||i?(e+=r?1:-1,n+=2,o.push(a.slice(t,n)),t=n):n++}t<n&&o.push(a.slice(t,n)),s=n}else s++;return o},$a=(e,t,n,r)=>{let i=[];for(let a=t;a<n&&i.length<r.length;a++){let t=e.tokens[a];t.kind===`Identifier`&&t.text===r[i.length]&&i.push(a)}return i},eo=(e,t,n,r)=>{for(let i=t;i<=n;i++)if(H(e,i,r))return i;return-1},to=new Map(be.flatMap(([e,...t])=>t.map(t=>[t,e]))),no=e=>e.split(`!`).map(e=>to.get(e)??(e===`~`?`\\lnot`:e)).join(`!`),ro=e=>e[e.length-1],io=(e,t)=>{for(let n=e.length-1;n>=0;n--){let r=Sa(e[n],t);if(r)return r}},ao=e=>e.kind===`OpDecl`?`${e.kind}${e.declKind}`:e.kind===`OpDef`?e.defKind:e.kind,oo=(e,t)=>{if(e.kind===`OpDef`&&t.kind===`OpDef`){let n=e.source??e;return n===(t.source??t)?n.module===void 0||so(n.module):!1}if(e.kind===`ThmOrAssumpDef`&&t.kind===`ThmOrAssumpDef`){let n=e.source??e;return n===(t.source??t)&&so(n.module)}return!1},so=e=>Ta(e,2).length===0&&Ta(e,3).length===0,co=(e,t)=>{let n=io(e.contexts,t.name);if(n===t)return;if(n===void 0){ba(ro(e.contexts),t);return}let r=t.kind===`FormalParam`||ao(n)!==ao(t)||xa(n)!==xa(t);n.kind===`OpDef`&&n.defKind===`BuiltIn`&&!(r&&e.version===`1.7.4`)?e.addError(t.location,`Symbol ${t.name} is a built-in operator, and cannot be redefined.`):r?e.addError(t.location,`Multiply-defined symbol '${t.name}': this definition or declaration conflicts \nwith the one at ${la(n.location)}.`):oo(t,n)||e.addWarning(t.location,`Multiple declarations or definitions for symbol ${t.name}. \nThis duplicates the one at ${la(n.location)}.`)},lo=e=>e.labelScopes.push({labels:/* @__PURE__ */ new Map,params:[]}),uo=e=>e.labelScopes.pop()?.labels??/* @__PURE__ */ new Map,fo=(e,t)=>{let n=t.kind===`AssumeProve`?e.assumeProveScopes.get(t):void 0;n&&(n.isInProof=!1)},po=(e,t)=>W(e,U(e,t)),mo=(e,t)=>t.range?Ga(e,t.range):{start:Ha(e,t),end:Ha(e,t)},ho=(e,t)=>W(e,mo(e,t)),go=(e,t)=>{for(let n=e.contexts.length-1;n>=0;n--){let r=Ca(e.contexts[n],t);if(r?.kind===`Module`)return r}return e.externalModules.get(t)},_o=(e,t)=>{let n=go(e,t);if(n===void 0)throw new o(`Could not find module ${t}`);return n},vo=(e,t,n)=>{e.contexts.push(t);let r=n();return e.contexts.pop(),r},yo=(e,t,n,r,i)=>{let a={...V(e.getId()),kind:`FormalParam`,name:t,arity:n,location:r};return i&&co(e,a),a},bo=(e,t)=>({...V(e.getId()),kind:`OpDef`,defKind:`UserDefined`,arity:t.params?.length??0,params:[],body:void 0,isLocal:!1,module:e.currentModule,source:void 0,preComments:[],isDefined:!0,inRecursive:!1,inRecursiveSection:!1,recursiveSection:-1,letInLevel:0,weights:(t.params??[]).map(()=>0),isLeibnizArg:(t.params??[]).map(()=>!0),isLeibniz:!0,opLevelCond:void 0,maxLevels:(t.params??[]).map(()=>3),minMaxLevel:void 0,labels:/* @__PURE__ */ new Map,step:void 0,...t}),xo=(e,t)=>{t.letInLevel=e.curLevel,e.unresolvedSum>0&&(t.recursiveSection=e.recursiveSectionCount,t.inRecursiveSection=e.unresolvedCount[e.curLevel]>0,e.currentModule.opDefsInRecursiveSection.push(t))},So=(e,t,n,r,i={},a=e.getId())=>({...V(a),kind:`OpAppl`,operator:t,operands:n,unbounded:i.unbounded,bounded:i.bounded,tupleOrs:i.tupleOrs,ranges:i.ranges??[],location:r}),Co=e=>({...So(e,wo(e,`$Nop`),[],oa,{},e.nullApplicationId),nullKind:`null`}),wo=(e,t)=>{let n=e.builtinsByName.get(t);if(!n)throw new r(`SANY has no builtin operator ${t}`);return n},K=(e,t,n,r,i={})=>So(e,wo(e,t),n,r,i),To=(e,t,n)=>({...V(e.getId()),kind:`String`,value:t,location:n}),Eo=(e,t,n)=>({...V(e.getId()),kind:`OpArg`,op:t,location:n}),Do=(e,t,n)=>{let r=io(e.contexts,no(t));if(r===void 0||r.kind===`Module`)throw new o(`Unknown operator: \`${t}' at line ${n.beginLine}, column ${n.beginColumn} of module ${n.file}`);return r},Oo=(e,t,n,r)=>{if(t.kind!==`OpDef`||t.defKind!==`UserDefined`)return;let i=t.params??[];i.length===n.length?i.forEach((i,a)=>{let o=n[a];i.arity===0&&o.kind===`OpArg`&&e.addError(r,`Operator used in argument number ${a+1} has incorrect number of arguments.`);let s=o.kind===`OpArg`&&xa(o.op)===i.arity&&!(o.op.kind===`OpDef`&&(o.op.params??[]).some(e=>e.arity>0));i.arity>0&&!s&&e.addError(r,`Argument number ${a+1} to operator '${t.name}' \nshould be a ${i.arity}-parameter operator.`)}):e.addError(r,`Wrong number of arguments (${n.length}) given to operator '${t.name}', \nwhich requires ${i.length} arguments.`)},ko=/* @__PURE__ */ new Map([[`Identifier`,`N_GeneralId`],[`Subexpression`,`N_GeneralId`],[`Number`,`N_Number`],[`Decimal`,`N_Real`],[`SetEnumeration`,`N_SetEnumerate`],[`SetFilter`,`N_SubsetOf`],[`SetMap`,`N_SetOfAll`],[`Tuple`,`N_Tuple`],[`FunctionApplication`,`N_FcnAppl`],[`FunctionConstruction`,`N_FcnConst`],[`FunctionSet`,`N_SetOfFcns`],[`Record`,`N_RcdConstructor`],[`RecordSet`,`N_SetOfRcds`],[`FieldAccess`,`N_RecordComponent`],[`Except`,`N_Except`],[`Prime`,`N_PostfixExpr`],[`Always`,`N_PrefixExpr`],[`Eventually`,`N_PrefixExpr`],[`Enabled`,`N_PrefixExpr`],[`Unchanged`,`N_PrefixExpr`],[`Forall`,`N_BoundedQuant`],[`Exists`,`N_BoundedQuant`],[`UnboundedQuantifier`,`N_UnboundedQuant`],[`Choose`,`N_UnBoundedOrBoundedChoose`],[`If`,`N_IfThenElse`],[`Case`,`N_Case`],[`Let`,`N_LetIn`],[`BoxAction`,`N_ActionExpr`],[`AngleAction`,`N_ActionExpr`],[`WeakFairness`,`N_FairnessExpr`],[`StrongFairness`,`N_FairnessExpr`]]),Ao=/* @__PURE__ */ new Set([`N_GeneralId`,`N_OpApplication`,`N_PrefixExpr`,`N_InfixExpr`,`N_PostfixExpr`,`N_FcnAppl`,`N_RecordComponent`]),jo=(e,t)=>H(e,t.start,`(`)&&Wa(e,t.start)===t.end,Mo=(e,t)=>Ka(e,U(e,t)),No=(e,t,n)=>Mo(e,t.args[0]).start===n.start?t.args.length===2?`N_InfixExpr`:`N_PostfixExpr`:e.tokens[n.start].kind===`Identifier`?`N_OpApplication`:`N_PrefixExpr`,Po=(e,t,n)=>jo(e,n)?`N_ParenExpr`:t.kind===`String`?Ya(e,n.start):t.kind===`Apply`?No(e,t,n):ko.get(t.kind),Fo=(e,t,n)=>{if(t.kind===`String`&&!jo(e,n))return!1;if(t.kind===`Identifier`&&!t.name.includes(`!`))return!0;let r=Po(e,t,n);return r===void 0||Ao.has(r)?void 0:!0},Io=(e,t,n)=>{let r=(t,n=Mo(e,t))=>({last:n,lastKind:Po(e,t,n)});if(jo(e,n))return{hasChildlessFirstChild:!1,...r(t,{start:n.start+1,end:n.end-1})};switch(t.kind){case`If`:case`BoxAction`:case`AngleAction`:return{hasChildlessFirstChild:!1,...r(t.kind===`If`?t.condition:t.action)};case`Tuple`:case`SetEnumeration`:{let i=t.elements[0];return i===void 0?{hasChildlessFirstChild:!1,last:{start:n.end,end:n.end},lastKind:e.tokens[n.end].text}:{hasChildlessFirstChild:!1,...r(i)}}case`Always`:case`Eventually`:case`Enabled`:case`Unchanged`:return{hasChildlessFirstChild:!0,...r(t.expression,{start:n.start+1,end:n.end})};case`Prime`:return{hasChildlessFirstChild:Fo(e,t.expression,Mo(e,t.expression)),last:{start:n.end,end:n.end},lastKind:`N_GenPostfixOp`};case`FunctionApplication`:case`FieldAccess`:{let n=t.kind===`FunctionApplication`?t.function:t.record,r=Mo(e,n),i=r.end+1;return{hasChildlessFirstChild:Fo(e,n,r),last:{start:i,end:i},lastKind:e.tokens[i].text}}case`Apply`:{let i=No(e,t,n);if(i===`N_OpApplication`)return t.operator.includes(`!`)?void 0:{hasChildlessFirstChild:!0,last:{start:n.start+1,end:n.end},lastKind:`N_OpArgs`};if(i===`N_PrefixExpr`)return{hasChildlessFirstChild:!0,...r(t.args[0],{start:n.start+1,end:n.end})};let a=Mo(e,t.args[0]),o=a.end+1;return{hasChildlessFirstChild:Fo(e,t.args[0],a),last:{start:o,end:o},lastKind:i===`N_InfixExpr`?`N_GenInfixOp`:`N_GenPostfixOp`}}}},Lo=(e,t)=>{let n=Mo(e.file,t);if((t.kind===`Identifier`||t.kind===`Subexpression`||t.kind===`OperatorReference`)&&!jo(e.file,n))return!1;let r=Io(e.file,t,n);if(r?.hasChildlessFirstChild===void 0||r.lastKind===void 0)return!1;let i=W(e.file,r.last);return r.hasChildlessFirstChild&&e.addError(W(e.file,n),`Was expecting a GeneralId.`),r.lastKind===`N_OpArgs`?e.addError(i,"Selector `!(...)' should not have argument(s)."):(e.addError(i,`Unexpected token found.`),e.addError(i,`Need name or step number here, not \`${r.lastKind}'.`)),e.addError(W(e.file,n),`DEF clause entry should describe a defined operator.`),!0},Ro=e=>/^[A-Za-z0-9_]+$/.test(e),zo=e=>e!==`!!`&&e.includes(`!`),Bo=e=>BigInt(e.startsWith(`\\`)?`0${e.slice(1).replace(/^h/i,`x`)}`:e).toString(),Vo=/* @__PURE__ */ new Set([`Identifier`,`Subexpression`,`OperatorReference`,`Lambda`]),Ho=e=>{let t=e.kind===`Apply`?ka(e):void 0;return Vo.has(e.kind)||t!==void 0&&Aa(t)},Uo=/* @__PURE__ */ new Set([`'`,`^+`,`^*`,`^#`]),Wo=(e,t)=>Uo.has(t)?`N_GenPostfixOp`:e.kind===`Lambda`||t===`~`||t===`-.`?`N_GenNonExpPrefixOp`:`N_GenInfixOp`,Go=(e,t,n)=>{let r=n.start;return t.map(t=>{let i=t.op===`Name`?t.name:t.op===`Null`?`(`:String(t.op),a=eo(e,r,n.end,i);if(a===-1)return t;if(t.op===`Null`){let n=Wa(e,a);return r=n+1,{...t,location:W(e,{start:a,end:n})}}r=a+1;let o=G(e,a);if(t.args===void 0||!H(e,a+1,`(`))return{...t,location:o};let s=Wa(e,a+1);return r=s+1,{...t,location:o,argsLocation:W(e,{start:a+1,end:s})}})},Ko=(e,t,n,r,i)=>{let a=ka(t);if(a===void 0)throw new o(`Expected a name, found ${t.kind}`);return e.selectorToNode(Go(e.file,a,U(e.file,t)),n,r,i,po(e.file,t))},qo=(e,t)=>{let n=Ko(e,t,0,!1,!1);if(n.kind!==`OpAppl`)throw new o(`Expected an expression`);return n},Jo=(e,t)=>{if(t.kind!==`OpAppl`)return;let n=e.functions.find(e=>e.name===t.operator.name);n&&(n.node.operator=wo(e,`$RecursiveFcnSpec`))},Yo=e=>e.reduce((e,t)=>{let n=e[e.length-1];return n!==void 0&&n[0].set===t.set&&t.pattern.kind===`Name`&&n[0].pattern.kind===`Name`?n.push(t):e.push([t]),e},[]),Xo=(e,t,n)=>hs(e,t,n,Yo(t).map(t=>q(e,t[0].set))),Zo=(e,t,n)=>{let r=e.labelScopes.at(-1);r?.params.push(t);let i=q(e,n);return r?.params.pop(),i},Qo=(e,t,n,r,i,a)=>vo(e,va(),()=>{let o=Xo(e,n,r),s=Zo(e,o.bounded.flat(),i);return K(e,t,[s],a,o)}),$o=(e,t)=>{let n=U(e.file,t),r=$a(e.file,n.start,n.end,t.params);return vo(e,va(),()=>{let i=t.params.map((t,n)=>yo(e,t,0,G(e.file,r[n]),!0)),a=Zo(e,i,t.body);return bo(e,{name:`LAMBDA`,params:i,body:a,location:W(e.file,n),preComments:Qa(e.file,n.start)})})},es=(e,t)=>t.kind===`OperatorReference`?t.operator:t.kind===`Lambda`&&t.body.kind===`Apply`?t.body.operator:e.tokens[Ha(e,t.location)].text,ts=(e,t,n)=>{let r=po(e.file,t);if(t.kind===`Lambda`)return t.location.range!==void 0&&t.operator===void 0?Eo(e,$o(e,t),r):Eo(e,Do(e,es(e.file,t),r),r);if(!Ho(t))return e.addError(r,`Arity ${n.arity} operator (not an expression) is expected \nto substitute for CONSTANT '${n.name}'.`),Co(e);if(t.kind===`OperatorReference`)return Eo(e,Do(e,t.operator,r),r);let i=Ko(e,t,n.arity,!1,!1);if(i.kind===`OpArg`||i.kind===`OpAppl`&&i.nullKind!==void 0)return i;throw new o(`Expected an operator argument at line ${r.beginLine}, column ${r.beginColumn}`)},ns=(e,t,n,r,i)=>{let a=t.kind===`OpDef`&&(t.defKind===`UserDefined`||t.defKind===`ModuleInstance`)?t.params?.[n]?.arity??0:0;if(a===0)return q(e,r);let s=U(e.file,r),c=W(e.file,s),l=`${n+1} (counting from 1)`,u=qa(e.file,s);if(u!==s||!Ho(r))return e.addError(W(e.file,u),`An expression appears as argument number ${l} to operator '${t.name}', in a position an operator is required.`),Co(e);if(r.kind===`Identifier`||r.kind===`Subexpression`||r.kind===`Apply`){let t=Ko(e,r,a,!1,!1);if(t.kind===`OpArg`||t.kind===`OpAppl`)return t;throw new o(`Expected an operator argument at ${la(c)}`)}if(r.kind===`Lambda`&&r.location.range!==void 0&&r.operator===void 0){let o=$o(e,r),s=xa(o);return s===a?Eo(e,o,c):(e.addError(i,`Lambda expression with arity ${s} used as argument ${n+1} of operator \`${t.name}', \nbut an operator of arity ${a} is required.`),Co(e))}let d=es(e.file,r),f=io(e.contexts,no(d));if(f===void 0)return e.addError(c,`Could not find declaration or definition of symbol '${d}'.`),Co(e);let p=xa(f);return p===a?Eo(e,f,c):(e.addError(i,`Operator with incorrect arity passed as argument. \nOperator '${f.name}' of arity ${p} is argument number ${l} to operator \`${la(t.location)}', \nbut an operator of arity ${a} was expected.`),Co(e))},rs=(e,t)=>{let n=po(e.file,t);if(t.isBulleted)return K(e,t.kind===`And`?`$ConjList`:`$DisjList`,t.operands.map(t=>q(e,t)),n);let r=U(e.file,t),i=t.kind===`And`?`\\land`:`\\lor`,[a,...o]=t.operands;return o.reduce((t,n,a)=>{let s=Mo(e.file,n),c=a===o.length-1?r.end:s.end;return K(e,i,[t,q(e,n)],W(e.file,{start:r.start,end:c}))},q(e,a))},is=(e,t)=>{let n=U(e.file,t),r=t.arms.map((r,i)=>{let a=Mo(e.file,r.condition),o=i===t.arms.length-1&&t.other===void 0,s=Mo(e.file,r.body),c=[q(e,r.condition),q(e,r.body)];return K(e,`$Pair`,c,W(e.file,{start:a.start,end:o?n.end:s.end}))}),i=t.other;if(i){let t=Mo(e.file,i),a=as(e.file,t.start,`OTHER`);r.push(K(e,`$Pair`,[void 0,q(e,i)],W(e.file,{start:a,end:n.end})))}return K(e,`$Case`,r,W(e.file,n))},as=(e,t,n)=>{for(let r=t;r>=0;r--)if(H(e,r,n))return r;return t},os=(e,t)=>{let n=U(e.file,t),r=W(e.file,n),i=[q(e,t.function)],a=K(e,`$Except`,i,r),o=U(e.file,t.function),s=eo(e.file,o.end+1,n.end,`EXCEPT`)+1;return t.updates.forEach(t=>{let r=eo(e.file,s,n.end,`!`),o=Mo(e.file,t.value),c=W(e.file,{start:r,end:o.end}),l=r+1,u=t.path.map(t=>{if(t.kind===`Field`){let n=ss(e.file,l,t.name);return l=n+1,To(e,t.name,G(e.file,n))}let r=eo(e.file,l,n.end,`[`),i=Wa(e.file,r);return l=i+1,t.args.length===1?q(e,t.args[0]):K(e,`$Tuple`,t.args.map(t=>q(e,t)),W(e.file,{start:r,end:i}))}),d=K(e,`$Seq`,u,c),f=K(e,`$Pair`,[d],c);e.exceptSpecStack.push(f),e.exceptStack.push(a),f.operands.push(q(e,t.value)),e.exceptSpecStack.pop(),e.exceptStack.pop(),i.push(f),s=o.end+1}),a},ss=(e,t,n)=>{for(let r=t;r<e.tokens.length;r++)if(e.tokens[r].text===n&&e.tokens[r].kind!==`String`)return r;return t},cs=(e,t,n)=>{let r=U(e.file,n),i=r.start+1,a=n.fields.map((t,r)=>{let a=ss(e.file,i,t.name),o=Mo(e.file,t.value);return i=o.end+1,n.fields.slice(0,r).some(e=>e.name===t.name)&&e.addError(G(e.file,a),`Non-unique fields in constructor.`),K(e,`$Pair`,[To(e,t.name,G(e.file,a)),q(e,t.value)],W(e.file,{start:a,end:o.end}))}),o=K(e,t,a,W(e.file,r));return e.currentModule.records.push(o),o},ls=(e,t)=>({line:e.tokens[t].line,column:e.tokens[t].column}),us=(e,t)=>{let n=[],r=t;for(;e.tokens[r]?.kind===`Identifier`;){let t=H(e,r+1,`(`)?Wa(e,r+1):r,i=e.tokens.slice(r+1,t).filter(e=>e.text===`_`).length;if(n.push({name:e.tokens[r].text,arity:i,location:{...ls(e,r),range:{module:e.name,start:ls(e,r),end:ls(e,t)}}}),!H(e,t+1,`,`))break;r=t+2}return n},ds=(e,t)=>{let n=[...t.definitions.map(t=>({unit:{kind:`Definition`,definition:t},span:vs(e,t)})),...(t.instances??[]).map(t=>({unit:{kind:`Instance`,instance:t},span:vs(e,t)}))],r=U(e,t).start,i=Mo(e,t.body).start,a=[];for(let t=r+1;t<i;t++){let r=n.some(e=>e.span.start<=t&&t<=e.span.end);H(e,t,`RECURSIVE`)&&!r&&a.push({unit:{kind:`Recursive`,declarations:us(e,t+1)},span:{start:t,end:t}})}return[...n,...a].toSorted((e,t)=>e.span.start-t.span.start).map(e=>e.unit)},fs=(e,t)=>{let n=va();return vo(e,n,()=>{e.curLevel++,e.unresolvedCount[e.curLevel]=0;let r=[],i=[];ds(e.file,t).forEach(t=>{t.kind===`Recursive`?Ss(e,t.declarations):t.kind===`Instance`?Es(e,t.instance,r,i):t.definition.kind===`Function`?xs(e,t.definition,r):ys(e,t.definition,r)}),Cs(e),e.curLevel=Math.max(e.curLevel-1,0);let a=q(e,t.body);return{...V(e.getId()),kind:`LetIn`,opDefs:r,instances:i,body:a,context:n,location:po(e.file,t)}})},ps=(e,t)=>{let n=U(e.file,t),r=W(e.file,n);return vo(e,va(),()=>{let i=t.pattern,a=i.kind===`Name`?[i.name]:i.names;if(t.set===void 0){let o=$a(e.file,n.start,n.end,a),s=a.map((t,r)=>yo(e,t,0,G(e.file,i.kind===`Name`?n.start:o[r]),!0)),c=Zo(e,s,t.body);return K(e,`$UnboundedChoose`,[c],r,{unbounded:s})}let o=q(e,t.set),s=U(e.file,t.set),c=$a(e.file,n.start,s.start,a),l=a.map((t,n)=>yo(e,t,0,G(e.file,c[n]),!0)),u=Zo(e,l,t.body);return K(e,`$BoundedChoose`,[u],r,{bounded:[l],tupleOrs:[i.kind===`Tuple`],ranges:[o]})})},ms=(e,t)=>{if(Ro(t.operator)||zo(t.operator)||t.args.length>2||io(e.contexts,no(t.operator))!==void 0)return;let n=U(e.file,t);if(e.file.tokens[n.start].text===t.operator&&H(e.file,n.start+1,`(`))return;let r=Mo(e.file,t.args[0]),i=t.args.length===1&&r.start!==n.start,a=i?n.start:r.end+1,o=Ya(e.file,a);return{index:a,name:i&&o===`-`?`-.`:o,fixity:i?`prefix`:t.args.length===2?`infix`:`postfix`}},q=(e,t)=>{let n=po(e.file,t);switch(t.kind){case`Number`:return{...V(e.getId()),kind:`Numeral`,value:Bo(t.text??String(t.value)),location:n};case`Decimal`:{let[r,i]=t.text.split(`.`),a=BigInt(r+i),o=a<=9223372036854775807n;return{...V(e.getId()),kind:`Decimal`,mantissa:a.toString(),exponent:String(o?-i.length:i.length),integralPart:r,fractionalPart:i,location:n}}case`String`:return To(e,t.value,n);case`Identifier`:{let n=qo(e,t);return Jo(e,n),n}case`Apply`:{let r=ms(e,t);if(r!==void 0)return e.addError(G(e.file,r.index),`Could not find declaration or definition of symbol '${r.name}'.`),e.addError(n,`Couldn't resolve ${r.fixity} operator symbol \`${r.name}'.`),{...Co(e),nullKind:`absent`};let i=qo(e,t);return(zo(t.operator)||Ro(t.operator))&&Jo(e,i),i}case`Bracket`:return e.addError(G(e.file,U(e.file,t).start),"Unsupported expression type `['."),{...Co(e),nullKind:`absent`};case`OperatorReference`:case`Lambda`:{let r=e.file.tokens[U(e.file,t).start].text;return e.addError(n,r===`LAMBDA`?`LAMBDA expression used where an expression is required.`:`Unsupported expression type \`${Wo(t,r)}'.`),{...Co(e),nullKind:`absent`}}case`And`:case`Or`:return rs(e,t);case`Prime`:return K(e,`'`,[q(e,t.expression)],n);case`Unchanged`:return K(e,`UNCHANGED`,[q(e,t.expression)],n);case`Enabled`:return K(e,`ENABLED`,[q(e,t.expression)],n);case`Always`:return K(e,`[]`,[q(e,t.expression)],n);case`Eventually`:return K(e,`<>`,[q(e,t.expression)],n);case`If`:return K(e,`$IfThenElse`,[q(e,t.condition),q(e,t.consequent),q(e,t.alternative)],n);case`Case`:return is(e,t);case`Let`:return fs(e,t);case`Forall`:case`Exists`:return Qo(e,t.kind===`Forall`?`$BoundedForall`:`$BoundedExists`,t.bounds,U(e.file,t).start,t.body,n);case`UnboundedQuantifier`:{let r=U(e.file,t),i=U(e.file,t.body),a=$a(e.file,r.start,i.start,t.names),o=t.isTemporal?t.quantifier===`Forall`?`$TemporalForall`:`$TemporalExists`:t.quantifier===`Forall`?`$UnboundedForall`:`$UnboundedExists`;return vo(e,va(),()=>{let r=t.names.map((t,n)=>yo(e,t,0,G(e.file,a[n]),!0)),i=Zo(e,r,t.body);return K(e,o,[i],n,{unbounded:r})})}case`Choose`:return ps(e,t);case`SetEnumeration`:return K(e,`$SetEnumerate`,t.elements.map(t=>q(e,t)),n);case`Tuple`:return K(e,`$Tuple`,t.elements.map(t=>q(e,t)),n);case`SetFilter`:{let r=q(e,t.bound.set),i=U(e.file,t);return vo(e,va(),()=>{let a=hs(e,[t.bound],i.start,[r]),o=Zo(e,a.bounded.flat(),t.predicate);return K(e,`$SubsetOf`,[o],n,a)})}case`SetMap`:return Qo(e,`$SetOfAll`,t.bounds,U(e.file,t.expression).end+1,t.expression,n);case`FunctionConstruction`:return Qo(e,`$FcnConstructor`,t.bounds,U(e.file,t).start,t.body,n);case`FunctionSet`:return K(e,`$SetOfFcns`,[q(e,t.domain),q(e,t.range)],n);case`Record`:return cs(e,`$RcdConstructor`,t);case`RecordSet`:return cs(e,`$SetOfRcds`,t);case`Except`:return os(e,t);case`ExceptAt`:{let t=e.exceptStack[e.exceptStack.length-1],r=e.exceptSpecStack[e.exceptSpecStack.length-1];return t===void 0||r===void 0?(e.addError(n,`@ used where its meaning is not defined.`),Co(e)):{...V(e.getId()),kind:`At`,except:t,component:r,location:r.location}}case`FunctionApplication`:{let r=q(e,t.function);if(ua(r))return r;Jo(e,r);let i=r.kind===`OpAppl`?r.operator:void 0,a=i?.kind===`OpDef`&&i.defKind===`UserDefined`?i.body:void 0;if(a?.kind===`OpAppl`&&(a.operator.name===`$NonRecursiveFcnSpec`||a.operator.name===`$RecursiveFcnSpec`)){let r=(a.bounded??[]).reduce((e,t,n)=>e+(a.tupleOrs?.[n]?1:t.length),0);if(t.args.length>=2&&r!==t.args.length)return e.addError(n,`Function '${i?.name}' is defined with ${r} parameters, but is applied to ${t.args.length} arguments.`),Co(e)}let o=t.args.length===1?q(e,t.args[0]):K(e,`$Tuple`,t.args.map(t=>q(e,t)),n);return K(e,`$FcnApply`,[r,o],n)}case`FieldAccess`:{let r=q(e,t.record),i=U(e.file,t);return K(e,`$RcdSelect`,[r,To(e,t.field,G(e.file,i.end))],n)}case`Product`:return K(e,`$CartesianProd`,t.factors.map(t=>q(e,t)),n);case`BoxAction`:case`AngleAction`:return K(e,t.kind===`BoxAction`?`$SquareAct`:`$AngleAct`,[q(e,t.action),q(e,t.subscript)],n);case`WeakFairness`:case`StrongFairness`:return K(e,t.kind===`WeakFairness`?`$WF`:`$SF`,[q(e,t.subscript),q(e,t.action)],n);case`Label`:return gs(e,t);case`Subexpression`:return qo(e,t)}},hs=(e,t,n,r)=>{let i=Yo(t),a=n;return{bounded:i.map(t=>{let n=U(e.file,t[0].set),r=t.flatMap(e=>e.pattern.kind===`Name`?[e.pattern.name]:e.pattern.names),i=$a(e.file,a,n.start,r);return a=n.end+1,r.map((t,n)=>yo(e,t,0,G(e.file,i[n]),!0))}),tupleOrs:i.map(e=>e[0].pattern.kind===`Tuple`),ranges:r}},gs=(e,t)=>{let n=po(e.file,t),r=e.labelScopes.at(-1);if(r===void 0)return e.addError(n,`Label not in definition or proof step.`),Co(e);if(e.assumeProveState.isDeclared.slice(2,e.assumeProveState.depth+1).some(Boolean))return e.addError(n,`Label not allowed within scope of declaration in nested ASSUME/PROVE.`),Co(e);if(e.exceptStack.length>0&&e.exceptSpecStack.length>0)return e.addError(n,`Labels inside EXCEPT clauses are not yet implemented.`),Co(e);lo(e);let i=q(e,t.body),a=uo(e),o=$a(e.file,U(e.file,t).start,U(e.file,t.body).start,t.params),s=t.params.map((n,r)=>{let i=io(e.contexts,n);if(i?.kind===`FormalParam`)return i;let a=G(e.file,o[r]);return e.addError(a,`Illegal parameter ${n} of label \`${t.name}'.`),yo(e,n,0,a,!1)}),c={...V(e.getId()),kind:`Label`,name:t.name,params:s,body:i,labels:a,isAssumeProve:!1,location:n},l=/* @__PURE__ */ new Set;if(s.forEach(t=>{l.has(t)&&e.addError(n,`Repeated formal parameter ${t.name} \nin label \`${c.name}'.`),l.add(t)}),r.params.flat().forEach(t=>{l.delete(t)||e.addError(n,`Label ${c.name} must contain formal parameter \`${t.name}'.`)}),l.size>0){let t=[...l].map(e=>`${e.name} `).join(``);e.addError(n,`Label ${c.name} declares extra parameter(s) ${t}`)}r.labels.has(c.name)?e.addError(n,`Duplicate label \`${c.name}'.`):r.labels.set(c.name,c);let u=e.assumeProveState.goal;return u&&e.labelGoals.set(c,{scope:u,clause:e.assumeProveState.goalClause}),c},_s=(e,t,n,r)=>{let i=n.start;return t.params.map(t=>{let n=t.location?Ha(e.file,t.location):ss(e.file,i,t.name),a=ks(e.file,n,t.arity);i=a.end+1;let o=t.arity===1&&H(e.file,n+1,`_`);return yo(e,o?e.file.tokens[n].spelling??t.name:no(t.name),t.arity,W(e.file,a),r)})},vs=(e,t)=>{let n=mo(e,t.location);return t.isLocal&&!H(e,n.start,`LOCAL`)&&H(e,n.start-1,`LOCAL`)?{start:n.start-1,end:n.end}:n},ys=(e,t,n)=>{let r=vs(e.file,t),i=W(e.file,r),a=no(t.name),o={start:t.isLocal?r.start+1:r.start,end:r.end},s=vo(e,va(),()=>{let n=_s(e,t,o,!0),r=io(e.contexts,a);if(r?.kind===`OpDef`&&r.inRecursive&&!r.isDefined){let t=r.params?.length===n.length&&n.every(e=>e.arity===0);r.letInLevel===e.curLevel?(t||e.addError(i,`Definition of ${r.name} has different arity than its RECURSIVE declaration.`),r.params=n):e.addError(i,`Recursive operator ${a} defined at wrong LET/IN level.`)}else r!==void 0&&e.addError(i,`Operator ${a} already defined or declared.`);return lo(e),{params:n,body:q(e,t.body),existing:r}}),c=uo(e),l=s.existing,u=s.params,d=Qa(e.file,r.start);if(l?.kind===`OpDef`&&l.inRecursive&&!l.isDefined&&l.letInLevel===e.curLevel){l.weights=u.map(()=>0),l.maxLevels=u.map(()=>3),l.isLeibnizArg=u.map(()=>!0),l.labels=c,bs(e,l,s.body,i,d),e.currentModule.definitions.push(l),n?.push(l);return}let f=bo(e,{name:a,params:u,body:s.body,isLocal:t.isLocal,location:i,preComments:d,labels:c});co(e,f),xo(e,f),e.currentModule.definitions.push(f),n?.push(f)},bs=(e,t,n,r,i)=>{t.isDefined=!0,t.body=n,t.location=r,t.preComments=i,t.inRecursive&&(e.unresolvedCount[e.curLevel]--,e.unresolvedSum--)},xs=(e,t,n)=>{let r=vs(e.file,t),i=W(e.file,r),a=va(),o=t.isLocal?r.start+1:r.start,s=vo(e,a,()=>Xo(e,t.bounds,o+1)),c=vo(e,a,()=>io(e.contexts,t.name)),l=vo(e,a,()=>yo(e,t.name,0,i,c===void 0)),u=K(e,`$NonRecursiveFcnSpec`,[],i,{unbounded:[l],...s}),d=c?.kind===`OpDef`&&c.inRecursive&&!c.isDefined,f=d&&c.letInLevel===e.curLevel;f?c.arity!==0&&e.addError(i,`Function ${c.name} has operator arguments in its RECURSIVE declaration.`):d?e.addError(i,`Recursive function ${t.name} defined at wrong LET/IN level.`):c!==void 0&&e.addError(i,`Function name \`${t.name}' already defined or declared.`);let p=Qa(e.file,r.start),m=c===void 0?bo(e,{name:t.name,params:[],body:u,isLocal:t.isLocal,location:i,preComments:p}):c.kind===`OpDef`&&(f||!d)?c:void 0;f?c.arity===0&&bs(e,c,u,i,p):c===void 0&&m!==void 0&&(co(e,m),xo(e,m)),m!==void 0&&(e.currentModule.definitions.push(m),n?.push(m)),e.functions.unshift({name:t.name,node:u}),lo(e);let h=()=>Zo(e,s.bounded.flat(),t.body),g=m===void 0?h():vo(e,a,h),_=uo(e);m!==void 0&&(m.labels=_),e.functions.shift(),u.operands=[g],u.operator.name===`$NonRecursiveFcnSpec`&&(u.unbounded=void 0)},Ss=(e,t)=>{e.unresolvedSum===0&&e.recursiveSectionCount++,e.unresolvedCount[e.curLevel]+=t.length,e.unresolvedSum+=t.length,t.forEach(t=>{let n=As(e.file,t);e.getId();let r=Array.from({length:t.arity},()=>yo(e,``,0,void 0,!1)),i=bo(e,{name:no(t.name),params:r,location:W(e.file,n),isDefined:!1,inRecursive:!0,inRecursiveSection:!0,recursiveSection:e.recursiveSectionCount,letInLevel:e.curLevel});co(e,i),e.recursiveDeclarations.push(i),e.currentModule.opDefsInRecursiveSection.push(i)})},Cs=e=>{e.unresolvedCount[e.curLevel]!==0&&(e.recursiveDeclarations.filter(t=>t.letInLevel===e.curLevel&&!t.isDefined).forEach(t=>e.addError(t.location,`Symbol ${t.name} declared in RECURSIVE statement but not defined.`)),e.unresolvedSum-=e.unresolvedCount[e.curLevel])},ws=(e,t,n,r)=>{e.getId();let i=ga(n.table).filter(e=>e.kind===`OpDecl`),a=i.flatMap(t=>{let n=io(e.contexts,t.name);if(n===void 0)return[];let i=t.declKind===3||t.declKind===2&&t.arity===0;return i&&Oo(e,n,[],r),[{op:t,expr:i?So(e,n,[],r):Eo(e,n,r),isImplicit:!0}]}),o=(t,n)=>{(n.kind===`OpArg`?xa(n.op):0)!==t.arity&&e.addError(n.location,`An operator must be substituted for symbol '${t.name}', and it must have arity ${t.arity}.`)},s=vs(e.file,t),c=eo(e.file,s.start,s.end,`WITH`)+1;return t.substitutions.forEach(t=>{let i=eo(e.file,c,s.end,t.name);i!==-1&&(c=U(e.file,t.expression).end+1);let l=Sa(n,no(t.name));if(l?.kind!==`OpDecl`){e.addError(i===-1?r:G(e.file,i),`Identifier '${i===-1?t.name:Ya(e.file,i)}' is not a legal target of a substitution. \nA legal target must be a declared CONSTANT or VARIABLE in the module being instantiated. \n(Also, check for warnings about multiple declarations of this same identifier.)`);return}let u=l.arity===0?q(e,t.expression):ts(e,t.expression,l);o(l,u);let d=a.find(e=>e.op.name===l.name);d&&!d.isImplicit?e.addError(po(e.file,t.expression),`Multiple substitutions for symbol '${l.name}' in substitution.`):d?(d.expr=u,d.isImplicit=!1):a.push({op:l,expr:u,isImplicit:!1})}),a.filter(t=>t.isImplicit&&e.version!==`1.7.4`).forEach(e=>o(e.op,e.expr)),i.filter(e=>!a.some(t=>t.op.name===e.name)).forEach(t=>e.addError(r,`Substitution missing for symbol ${t.name} declared at ${la(t.location)} \nand instantiated in module ${e.currentModule.name}.`)),a},Ts=(e,t,n,r,i,a,o=e.currentModule)=>(ua(r)&&e.addError(a,t===`SubstIn`?`Substitution error, probably due to error
37
- in module being instantiated.`:`Substitution error, probably due to error in module being instantiated.`),{...V(e.getId()),kind:t,substs:n,body:r,instantiatingModule:o,instantiatedModule:i,location:a}),Es=(e,t,n,r)=>{let i=vs(e.file,t),a=W(e.file,i),o=Qa(e.file,i.start),s=t.name??``,c=va(),l=t.isLocal?i.start+1:i.start;t.params.length>0&&e.contexts.push(c);let u=_s(e,t,{start:l,end:i.end},t.params.length>0),d=_o(e,t.module),f=d.context,p=ws(e,t,f,a);t.params.length>0&&e.contexts.pop(),ga(f.table).forEach(r=>{if(r.kind!==`OpDef`||r.isLocal||r.defKind!==`UserDefined`&&r.defKind!==`ModuleInstance`)return;let i=[...u,...r.params??[]],c=`${s}!${r.name}`,l=r.defKind===`UserDefined`?bo(e,{name:c,params:i,body:p.length>0&&r.body?Ts(e,`SubstIn`,p,r.body,d,a):r.body,isLocal:t.isLocal,location:a,source:r.source??r,preComments:o,labels:r.labels}):bo(e,{defKind:`ModuleInstance`,name:c,params:i,isLocal:t.isLocal,location:a,module:r.module,source:r.source??r,preComments:o});co(e,l),r.defKind===`UserDefined`&&xo(e,l),(n??e.currentModule.definitions).push(l)}),ga(f.table).forEach(r=>{if(r.kind!==`ThmOrAssumpDef`||r.isLocal)return;let i=p.length>0?Ts(e,`APSubstIn`,p,r.body,d,a):r.body,o={...V(e.getId()),kind:`ThmOrAssumpDef`,name:`${s}!${r.name}`,isTheorem:r.isTheorem,body:i,params:[...u,...r.params],isLocal:t.isLocal,location:a,module:e.currentModule,source:r.source??r,labels:r.labels,isLeibnizArg:[],isLeibniz:!1,opLevelCond:[],maxLevels:[],minMaxLevel:[]};co(e,o),(n??e.currentModule.definitions).push(o)});let m={...V(e.getId()),kind:`Instance`,name:s,isLocal:t.isLocal,params:u,module:d,substs:p,location:a};(r??e.currentModule.topLevel).push(m);let h=bo(e,{defKind:`ModuleInstance`,name:s,params:u,isLocal:t.isLocal,location:a,preComments:o});co(e,h),e.version!==`1.7.4`&&n?.push(h)},Ds=(e,t)=>(co(e,t),t),Os=(e,t,n=!0,r)=>{let i=vs(e.file,t),a=r??W(e.file,i),o=Qa(e.file,i.start),s=_o(e,t.module),c=s.context,l=ws(e,t,c,a),u=t.isLocal,d=so(s);ga(c.table).forEach(t=>{if(t.kind!==`OpDef`||t.defKind!==`UserDefined`||t.isLocal)return;let n=(n,r)=>{let i=bo(e,{name:t.name,params:t.params,body:r,isLocal:u,location:a,module:n,source:t.source??t,preComments:o,labels:t.labels});return co(e,i),i},r=t.module===void 0||so(t.module),i=d||r?u?n(t.module,t.body):Ds(e,t):n(e.currentModule,t.body&&Ts(e,`SubstIn`,l,t.body,s,a));e.currentModule.definitions.push(i),xo(e,i)}),ga(c.table).forEach(t=>{if(t.kind!==`ThmOrAssumpDef`||t.isLocal)return;let r=(n,r)=>{let i={...t,...V(e.getId()),body:r,isLocal:u,location:a,module:n,source:t.source??t};return co(e,i),i},i=d?u?r(t.module,t.body):Ds(e,t):so(t.module)?u?r(e.currentModule,t.body):t:r(e.currentModule,Ts(e,`APSubstIn`,l,t.body,s,a));n&&e.currentModule.definitions.push(i)});let f={...V(e.getId()),kind:`Instance`,name:void 0,isLocal:u,params:[],module:s,substs:l,location:a};return n&&e.currentModule.topLevel.push(f),f},ks=(e,t,n)=>n===0?{start:t,end:t}:H(e,t,`_`)?{start:t,end:H(e,t+2,`_`)?t+2:t+1}:H(e,t+1,`(`)?{start:t,end:Wa(e,t+1)}:{start:t,end:H(e,t+1,`_`)?t+1:t},As=(e,t)=>ks(e,mo(e,t.location).start,t.arity),js=(e,t,n)=>{let r=As(e.file,t);t.name===`@`&&n===3&&e.addError(W(e.file,r),`Attempted to declare '@' as a variable.`);let i={...V(e.getId()),levelChecked:1,level:+(n===3),kind:`OpDecl`,name:no(t.name),arity:t.arity,declKind:n,location:W(e.file,r),module:e.currentModule};return n===2&&(i.levelParams.add(i),i.allParams.add(i)),co(e,i),i},Ms=(e,t,n)=>{e.unresolvedSum!==0&&e.addError(ho(e.file,t),`${n} may not appear within a recursive definition section.`)},Ns={Constant:{declKind:24,level:0},Variable:{declKind:25,level:1},State:{declKind:26,level:1},Action:{declKind:27,level:2},Temporal:{declKind:28,level:3}},Ps=(e,t)=>{let n=go(e,t.name)??(t.name===e.currentModule.name?e.currentModule:void 0);return n===void 0?(e.addError(G(e.file,Ha(e.file,t.location)+1),`Module \`${t.name}' used without being extended or instantiated.`),[]):[n]},Fs=(e,t)=>t.flatMap(t=>{if(t.kind===`ModuleFact`)return Ps(e,t);let n=ka(t);if(n===void 0||!Aa(n))return[q(e,t)];let r=Ko(e,t,0,!0,!1);if(r.kind===`ThmOrAssumpDef`)throw new o(`Expected a fact`);return[r]}),Is=(e,t)=>t.flatMap(t=>{if(t.kind===`ModuleFact`)return Ps(e,t);if(Lo(e,t))return[];let n=Ko(e,t.kind===`OperatorReference`?{kind:`Identifier`,name:t.operator,location:t.location}:t,-1,!1,!0);return n.kind===`OpDef`||n.kind===`ThmOrAssumpDef`&&!n.name.startsWith(`<`)?[n]:(e.addError(po(e.file,t),`DEF clause entry should describe a defined operator.`),[])}),Ls=(e,t,n)=>{t.isOnly||t.facts.length+t.defs.length>0||e.addError(n,`Empty BY, USE, or HIDE`)},Rs=(e,t)=>{let n=ho(e.file,t.location);Ls(e,t,n);let r=Fs(e,t.facts),i=Is(e,t.defs);return r.length+i.length===0&&e.addError(n,`Empty USE or HIDE statement.`),t.kind===`Hide`&&r.filter(e=>e.kind===`OpAppl`&&e.operator.kind!==`ThmOrAssumpDef`).forEach(t=>e.addError(t.location,`The only expression allowed as a fact in a HIDE is
38
- the name of a theorem, assumption, or step.`)),{...V(e.getId()),kind:`UseOrHide`,facts:r,defs:i,isOnly:t.isOnly,isHide:t.kind===`Hide`,location:n}},zs=(e,t)=>{let n=mo(e.file,t.location),r=t.set&&q(e,t.set),i=ss(e.file,n.start,t.name),a=Ns[t.level],o={...V(e.getId()),levelChecked:1,level:a.level,kind:`OpDecl`,name:no(t.name),arity:t.arity,declKind:a.declKind,location:W(e.file,ks(e.file,i,t.arity)),module:e.currentModule};return co(e,o),{...V(e.getId()),kind:`NewSymb`,declaration:o,set:r,location:W(e.file,n)}},Bs=(e,t,n,r)=>{let i=mo(e.file,t.location),a=Xa(e.file,i.start-1),o=U(e.file,t.conclusion).start,s=e.file.tokens.findLastIndex((e,t)=>t<o&&e.kind===`Keyword`&&e.text===`PROVE`),c=W(e.file,{start:a?i.start-1:i.start,end:i.start});a!==Xa(e.file,s-1)&&e.addError(c,a?`[]ASSUME matched by PROVE instead of []PROVE`:`ASSUME matched by []PROVE instead of PROVE`);let l=e.getId();n>1&&e.contexts.push(va()),a&&e.contexts.some(t=>e.assumeContexts.has(t))&&e.addError(c,`[]ASSUME used within the scope of an ordinary ASSUME's assumptions`),a||e.assumeContexts.add(ro(e.contexts));let u={isDeclaredBefore:[!1],hasGoal:r!==void 0,isSuffices:r?.isSuffices??!1,isInProof:!0};e.assumeProveState.depth=n,e.assumeProveState.isDeclared[n]=!1,n===1&&(e.assumeProveState.goal=r&&u,e.assumeProveState.goalClause=0);let d=t.assumptions.map((t,r)=>{let i=t.kind===`NewSymbol`,a=t.kind===`AssumeProve`?Bs(e,t,n+1):i?zs(e,t):q(e,t);return e.assumeProveState.depth=n,i&&(e.assumeProveState.isDeclared[n]=!0),u.isDeclaredBefore.push(u.isDeclaredBefore[r]||i),n===1&&e.assumeProveState.goalClause++,a}),f=q(e,t.conclusion);n>1&&e.contexts.pop(),e.assumeProveState.depth=n-1,n===1&&(e.assumeProveState.goal=void 0);let p={...V(l),kind:`AssumeProve`,assumptions:d,goal:f,isSuffices:u.isSuffices,isBoxed:a,location:W(e.file,{start:a?i.start-1:i.start,end:i.end})};return e.assumeProveScopes.set(p,u),p},Vs=(e,t,n,r,i,a,o=!0)=>({...V(t),kind:`ThmOrAssumpDef`,name:n,isTheorem:o,body:r,params:[],isLocal:!1,location:i,module:e.currentModule,source:void 0,labels:a,isLeibnizArg:[],isLeibniz:!1,opLevelCond:[],maxLevels:[],minMaxLevel:[]}),Hs=(e,t)=>{let n=ho(e.file,t.location);t.kind===`By`&&Ls(e,t,n);let r=t.kind===`By`?Fs(e,t.facts):[],i=t.kind===`By`?Is(e,t.defs):[];return t.kind===`By`&&e.getId(),t.kind===`By`&&r.length+i.length===0&&e.addError(n,`Empty BY`),{...V(e.getId()),kind:`LeafProof`,facts:r,defs:i,isOmitted:t.kind===`Omitted`,isOnly:t.kind===`By`&&t.isOnly,location:n}},Us=(e,t,n)=>{let r=W(e.file,n);switch(t.kind){case`Have`:return K(e,`$Have`,[q(e,t.expression)],r);case`Case`:return K(e,`$Pfcase`,[q(e,t.expression)],r);case`Witness`:return K(e,`$Witness`,t.expressions.map(t=>q(e,t)),r);case`Qed`:return K(e,`$Qed`,[],r);case`Take`:case`Pick`:{let i=t.kind===`Pick`,a=i?`$Pick`:`$Take`;i&&e.contexts.push(va());let o=n=>t.kind===`Pick`?[Zo(e,n,t.body)]:[];if(t.bounds.length>0){let i=Xo(e,t.bounds,n.start),s=o(i.bounded.flat());return K(e,a,s,r,i)}let s=$a(e.file,n.start,n.end+1,t.names),c=t.names.map((t,n)=>yo(e,t,0,G(e.file,s[n]),!0)),l=o(c);return K(e,a,l,r,{unbounded:c})}}},Ws=(e,t)=>{if((t.kind===`And`||t.kind===`Or`)&&!t.isBulleted)return!0;if(t.kind!==`Apply`||t.args.length!==2)return!1;let n=Mo(e,t.args[0]),r=U(e,t).start;return n.start===r&&!H(e,n.end+1,`(`)},Gs=(e,t)=>{if(t.kind!==`Steps`)return Hs(e,t);let n=va();e.contexts.push(n);let r=[],i=[],a,s=(t,n,i)=>{if(t.kind===`Define`){let n=t.definitions.map(t=>{let n=[];t.kind===`Instance`?Es(e,t,n,r):t.kind===`Function`?xs(e,t,n):ys(e,t,n);let i=n[t.kind===`Instance`?n.length-1:0];if(i?.kind!==`OpDef`)throw new o(`A DEFINE step defines no operator`);return i});return{...V(e.getId()),kind:`DefStep`,defs:n,location:W(e.file,i)}}if(t.kind===`Use`||t.kind===`Hide`)return{...Rs(e,t),location:W(e.file,n)};if(t.kind===`Instance`)return Os(e,t,!1,W(e.file,i))},c=t.steps.map(t=>{let n=mo(e.file,t.location),r=Ga(e.file,t.head),c={start:r.start+1,end:r.end},l=t.body;t.name!==void 0&&/^<[*+]>/.test(t.token)&&e.addError(G(e.file,n.start),`<*> and <+> cannot be used for a named step.`),t.name!==void 0&&lo(e);let u=t.name===void 0?void 0:e.getId();l.kind!==`Assert`&&(a=void 0);let d=s(l,n,c);if(d!==void 0)return t.name!==void 0&&co(e,bo(e,{defKind:`NumberedProofStep`,name:t.name,location:W(e.file,n),labels:uo(e),step:d})),d;let f=l.kind===`Assert`&&l.statement.kind===`AssumeProve`;f&&(a=void 0);let p=l.kind===`Assert`&&l.isSuffices,m=va(),h=l.kind===`Assert`?(n=>{if(n.kind===`AssumeProve`){let r=vo(e,m,()=>Bs(e,n,1,t.name===void 0?void 0:{isSuffices:p}));return r.isSuffices=p,r}if(p){let t=q(e,n);return K(e,`$Suffices`,[t],W(e.file,c))}let r=a!==void 0&&n.kind===`Apply`&&Ws(e.file,n)&&n.args[0].kind===`ExceptAt`,i=r?q(e,n.args[1]):void 0,o=r?So(e,Do(e,n.operator,po(e.file,n)),[K(e,`$Nop`,[a],po(e.file,n.args[0])),i],po(e.file,n)):q(e,n),s=o.kind===`OpAppl`?o.operands[1]:void 0;return a=Ws(e.file,n)?s:void 0,o})(l.statement):Us(e,l,c);if(h===void 0)throw new o(`Unexpected proof step ${l.kind}`);let g=l.kind===`Pick`?e.contexts.pop():void 0,_=t.name===void 0||u===void 0?void 0:Vs(e,u,t.name,h,G(e.file,Ha(e.file,t.location)),uo(e));_&&co(e,_);let v=f&&!p;v&&e.contexts.push(m);let y=t.proof&&Gs(e,t.proof);return v&&e.contexts.pop(),fo(e,h),f&&p&&(i.push(m),e.contexts.push(m)),g?.symbols.forEach(t=>co(e,t)),{...V(e.getId()),kind:`Theorem`,definition:_,body:h,proof:y,isSuffices:p,location:W(e.file,n)}});return i.forEach(()=>{e.contexts.pop()?.symbols.forEach(e=>ba(n,e))}),e.contexts.pop(),{...V(e.getId()),kind:`NonLeafProof`,steps:c,instances:r,proofLevel:t.level,location:ho(e.file,t.location)}},Ks=(e,t)=>{let n=ho(e.file,t.location),r=t.statement,i=va();t.name!==void 0&&lo(e);let a=t.name===void 0?void 0:e.getId();r.kind===`AssumeProve`&&e.contexts.push(i);let o=r.kind===`AssumeProve`?Bs(e,r,1,t.name===void 0?void 0:{isSuffices:!1}):q(e,r),s=t.name===void 0||a===void 0?void 0:Vs(e,a,t.name,o,n,uo(e));s&&(r.kind===`AssumeProve`&&e.contexts.pop(),co(e,s),e.currentModule.definitions.push(s),r.kind===`AssumeProve`&&e.contexts.push(i));let c=t.proof&&Gs(e,t.proof);r.kind===`AssumeProve`&&e.contexts.pop(),fo(e,o);let l={...V(e.getId()),kind:`Theorem`,definition:s,body:o,proof:c,isSuffices:!1,location:n};e.currentModule.topLevel.push(l)},qs=(e,t)=>{let n=ho(e.file,t.location);t.name!==void 0&&lo(e);let r=q(e,t.expression),i=t.name===void 0?void 0:Vs(e,e.getId(),t.name,r,n,uo(e),!1);i&&(co(e,i),e.currentModule.definitions.push(i));let a={...V(e.getId()),kind:`Assume`,definition:i,body:r,location:n};e.currentModule.topLevel.push(a)},Js=e=>e.kind===`OpDef`||e.kind===`FormalParam`?`definition`:`declaration`,Ys=e=>[...e.kind===`Let`?e.instances??[]:[],...we(e).flatMap(Ys)],Xs=e=>e.kind===`AssumeProve`?[...e.assumptions,e.conclusion].flatMap(e=>e.kind===`NewSymbol`?[]:Xs(e)):Ys(e),Zs=e=>e?.kind===`Steps`?e.steps.flatMap(e=>[...e.body.kind===`Instance`?[e.body]:[],...e.body.kind===`Define`?e.body.definitions.flatMap(e=>e.kind===`Instance`?[e]:[]):[],...Zs(e.proof)]):[],Qs=(e,t)=>{let n=/* @__PURE__ */ new Set;for(let r of e.units)if(r.kind===`Module`&&n.add(r.module.name),r.kind===`Instance`&&r.instance.module===t.module)return n.has(t.module);return e.modules.some(e=>e.name===t.module&&Ke(e.location,t.location))},$s=e=>{let t=[],n=[],r=/* @__PURE__ */ new Map,i=(a,o)=>{let s=a===e,c=(e,t)=>e.forEach(e=>{t.push(e),r.has(e)||r.set(e,a.name)}),l=e=>!o.has(e);c(a.extends.filter(l),t),c(a.units.flatMap(e=>e.kind===`Instance`?[e.instance]:e.kind===`Definition`?Ys(e.definition.body):e.kind===`Theorem`&&s?[...Xs(e.theorem.statement),...Zs(e.theorem.proof)]:e.kind===`Assumption`&&s?Ys(e.assumption.expression):[]).filter(e=>l(e.module)&&!Qs(a,e)).map(e=>e.module),n);let u=new Map(o);a.modules.forEach(e=>{let t=new Map(u),n=/* @__PURE__ */ new Set,r=e=>{n.has(e)||(n.add(e),e.extends.forEach(e=>{let n=t.get(e);n!==void 0&&(n.modules.forEach(e=>{t.has(e.name)||t.set(e.name,e)}),r(n))}))};r(e),i(e,t),u.set(e.name,e)})};return i(e,/* @__PURE__ */ new Map),{extendees:t,instancees:n,importers:r}},ec=(e,t,n={})=>{let r=[],i=(e,t)=>ca(r,{location:e,text:t,isWarning:!1}),a=(e,t)=>ca(r,{location:e,text:t,isWarning:!0}),s=n.version===`1.7.4`?-1:0,c=()=>++s,l=0;n.version!==`1.7.4`&&sa(c);let f=sa(c);c();let p=new Map(f.map(e=>[e.name,e])),m=/* @__PURE__ */ new Map,h=/* @__PURE__ */ new Map,g=(e,t)=>{let r=e===n.rootFileName&&n.rootFilePath||`${e}.tla`,i=t=>new u(`Could not parse module ${e} from file ${r}`,e,t),a=n.version===`1.7.4`?pe(t):void 0;if(a!==void 0)throw i(a);try{return de(Za(t))}catch(e){throw e instanceof o?i(qe(t)??`***Parse Error***\n${e.message}`):e}},_=(e,t,r)=>{let i=h.get(e);if(i)return i;if(t===void 0)throw new d(e,r,n.version!==`1.7.4`);n.onParse?.(e);let a=g(e,t);if(a.name!==e)throw new u(`File name '${e}' does not match the name '${a.name}' of the top level module it contains.`,void 0);let o={file:Ba(a.name,t),module:a};return h.set(e,o),o},v=[],y=/* @__PURE__ */ new Set,b=[],x=(e,n,r)=>{let i=b.indexOf(e);if(i!==-1)throw new u(`Circular dependency among .tla files; dependency cycle is:\n\n ${[...b.slice(i),e].map(e=>`${e}.tla`).join(` --> `)}`,void 0);if(y.has(e))return;y.add(e),b.push(e);let a=ee(e,_(e,n,r).module);[...a.extendees,...a.instancees].forEach(n=>x(n,t(n),e)),b.pop(),v.push(e)},S=/* @__PURE__ */ new Set,C=(e,t)=>S.has(`${e} ${t}`),w=(e,t,n)=>{let r=h.get(e);if(!r||n.has(e))return;n.add(e);let i=ee(e,r.module),a=i[t].find(t=>!C(e,t));if(a!==void 0)return{name:a,importer:e,namingModule:i.importers.get(a)??e};for(let r of[...i.extendees,...i.instancees]){let i=C(e,r)?w(r,t,n):void 0;if(i)return i}},T=n=>{_(n,e);let r=()=>w(n,`extendees`,/* @__PURE__ */ new Set)??w(n,`instancees`,/* @__PURE__ */ new Set);for(let e=r();e!==void 0;e=r())h.has(e.name)||_(e.name,t(e.name),e.namingModule),S.add(`${e.importer} ${e.name}`)},E=n.rootFileName??g(``,e).name,ee=(e,t)=>{let r=$s(t);return e!==E||n.rootExtendees===void 0||(r.extendees.splice(t.extends.length,0,...n.rootExtendees),n.rootExtendees.forEach(t=>{r.importers.has(t)||r.importers.set(t,e)})),r};T(E),x(E,e);let D=(e,t,r,o)=>{let s={kind:`Module`,id:c(),name:e.name,location:ho(t,e.location),extendees:[],context:ro(o),topLevel:[],definitions:[],opDefsInRecursiveSection:[],isLevelChecked:!1,levelCorrect:!0,argLevelParams:/* @__PURE__ */ new Map,levelConstraints:/* @__PURE__ */ new Map,argLevelConstraints:/* @__PURE__ */ new Map,records:[]};r&&r.definitions.push(s);let u={version:n.version,addError:i,addWarning:a,getId:c,builtinsByName:p,externalModules:m,nullApplicationId:l,file:t,contexts:o,currentModule:s,curLevel:0,unresolvedCount:[0],unresolvedSum:0,recursiveSectionCount:0,functions:[],exceptStack:[],exceptSpecStack:[],labelScopes:[],assumeContexts:/* @__PURE__ */ new WeakSet,assumeProveState:{depth:0,isDeclared:[],goal:void 0,goalClause:0},assumeProveScopes:/* @__PURE__ */ new WeakMap,labelGoals:/* @__PURE__ */ new WeakMap,recursiveDeclarations:[],selectorToNode:La({version:n.version,resolveSymbol:e=>io(o,e),resolveSynonym:no,generateExpression:e=>q(u,e),generateArgument:(e,t,n,r)=>ns(u,e,t,n,r),createOpAppl:(e,t,n)=>{let r=So(u,e,t,n);return Oo(u,e,t,n),r},createOpArg:(e,t)=>Eo(u,e,t),createFormalParam:(e,t,n)=>yo(u,e,t,n,!1),createLambda:(e,n,r)=>bo(u,{name:`LAMBDA`,params:e,body:n,location:r,preComments:Qa(t,Ha(t,{line:r.beginLine,column:r.beginColumn}))}),copySubstIn:(e,t)=>Ts(u,`SubstIn`,e.substs,t,e.instantiatedModule,e.location,e.instantiatingModule),getBuiltin:e=>wo(u,e),addError:(e,t)=>(i(e,t),Co(u)),isOutOfLabelScope:e=>{let t=u.labelGoals.get(e);return t!==void 0&&t.scope.isDeclaredBefore[t.clause]&&t.scope.isSuffices===t.scope.isInProof},isOutOfClauseScope:(e,t)=>{let n=u.assumeProveScopes.get(e);return n!==void 0&&n.isDeclaredBefore[t-1]&&(!n.hasGoal||n.isSuffices===n.isInProof)}})};return e.extends.forEach(e=>{let t=_o(u,e);s.extendees.push(t);let n=ro(o);t.context.symbols.forEach(e=>{if(e.kind!==`Module`&&e.kind!==`FormalParam`&&e.kind!==`OpDecl`&&e.isLocal)return;let t=e.kind===`Module`?Ca(n,e.name):Sa(n,e.name);t===void 0?ba(n,e):t!==e&&t.kind!==e.kind?i(e.location,`The ${Js(e)} of '${e.name}' conflicts with \nits ${Js(t)} at ${la(t.location)}.`):t!==e&&!oo(t,e)&&a(e.location,`Warning: the ${Js(t)} of '${e.name}' conflicts with \nits ${Js(t)} at ${la(t.location)}.`)}),s.topLevel.push(...t.topLevel)}),e.units.forEach(e=>{switch(e.kind){case`Variables`:Ms(u,e.location,`A VARIABLE declaration`),e.declarations.forEach(e=>js(u,e,3));break;case`Constants`:Ms(u,e.location,`A declaration`),e.declarations.forEach(e=>js(u,e,2));break;case`Recursive`:Ss(u,e.declarations);break;case`Definition`:e.definition.kind===`Function`?xs(u,e.definition,void 0):ys(u,e.definition,void 0);break;case`Instance`:e.instance.name===void 0?Os(u,e.instance):Es(u,e.instance,void 0,void 0);break;case`Assumption`:Ms(u,e.assumption.location,`An ASSUME`),qs(u,e.assumption);break;case`Theorem`:Ms(u,e.theorem.location,`A THEOREM`),Ks(u,e.theorem);break;case`Use`:Ms(u,e.use.location,`A USE or HIDE`),s.topLevel.push(Rs(u,e.use));break;case`Module`:{Ms(u,e.module.location,`A MODULE `);let n=D(e.module,t,s,[...o,va()]),r=go(u,n.name);r===void 0?ba(ro(o),n):r!==n&&i(n.location,`Multiply-defined module '${n.name}': this definition or declaration conflicts \nwith the one at ${la(r.location)}.`);break}}}),Cs(u),s},O=v.map(e=>{n.onAnalyze?.(e),l=Array.from({length:4},c)[1];let t=_(e,void 0),i=va();f.toReversed().forEach(e=>ba(i,e));let a=D(t.module,t.file,void 0,[i]);return m.set(e,a),n.onModule?.(a,r),a});return{root:O[O.length-1],modules:O,messages:r}},tc=(e,t,n,r)=>ca(e.messages,{location:t,text:n,isWarning:!1,...r!==void 0&&!e.isTlc174&&{code:r}}),J=(e,t)=>{for(let n of t)e.add(n)},nc=(e,t,n)=>`${e.id}:${t}:${n.id}`,rc=(e,t,n,r)=>{e.set(nc(t,n,r),{op:t,index:n,param:r})},ic=(e,t,n=()=>!0)=>{t.forEach((t,r)=>{n(t)&&e.set(r,t)})},ac=(e,t,n)=>{e.set(t,Math.min(n,e.get(t)??3))},oc=(e,t,n=()=>!0)=>{t.forEach((t,r)=>{n(r)&&ac(e,r,t)})},sc=(e,t)=>`${e.id}:${t}`,cc=(e,t,n,r)=>{let i=sc(t,n),a=e.get(i)?.level??0;e.set(i,{param:t,position:n,level:Math.max(r,a)})},lc=(e,t,n=()=>!0)=>{t.forEach(t=>{n(t)&&cc(e,t.param,t.position,t.level)})},uc=(e,t)=>{e.levelParams=t.levelParams,e.allParams=t.allParams,e.levelConstraints=t.levelConstraints,e.argLevelConstraints=t.argLevelConstraints,e.argLevelParams=t.argLevelParams},dc=(e,t)=>{J(e.levelParams,t.levelParams),J(e.allParams,t.allParams),oc(e.levelConstraints,t.levelConstraints),lc(e.argLevelConstraints,t.argLevelConstraints),ic(e.argLevelParams,t.argLevelParams)},fc=(e,t)=>t.includes(e.op)||t.includes(e.param),pc=e=>e.kind===`OpDecl`||e.kind===`FormalParam`,mc=e=>e.kind!==`Module`,hc=e=>e.kind===`OpDef`||e.kind===`ThmOrAssumpDef`,gc=(e,t)=>e.kind===`OpDef`&&e.arity<0?0:t,_c=(e,t)=>e.kind===`OpDef`?e.weights[gc(e,t)]??0:0,vc=(e,t)=>e.maxLevels[gc(e,t)]??3,yc=(e,t,n)=>e.minMaxLevel?.[t]?.[n]??0,bc=(e,t)=>e.kind===`OpDef`?e.isLeibnizArg?.[gc(e,t)]??!0:e.isLeibnizArg[t]??!0,xc=(e,t,n,r)=>e.opLevelCond?.[t]?.[n]?.[r]??!1,Sc=e=>[...e.unbounded??[],...(e.bounded??[]).flat()],Cc=(e,t)=>t.find(t=>t.op===e)?.expr,wc=(e,t,n)=>{let r=Cc(e,t);return r===void 0?/* @__PURE__ */ new Set([e]):n?r.allParams:r.levelParams},Tc=(e,t)=>{let n=/* @__PURE__ */ new Map;return e.forEach((e,r)=>{let i=Cc(e.op,t);if(i===void 0){n.set(r,e);return}if(i.kind!==`OpArg`||!pc(i.op))return;let a=i.op;wc(e.param,t,!1).forEach(t=>rc(n,a,e.index,t))}),n},Ec=(e,t,n,r,i)=>{let a=/* @__PURE__ */ new Map;return e.levelConstraints.forEach((e,r)=>{let i=n||r.kind!==`OpDecl`?e:r.declKind===2?0:r.declKind===3?1:e;wc(r,t,!1).forEach(e=>ac(a,e,i))}),e.argLevelParams.forEach(e=>{let n=Cc(e.op,t);if(n?.kind!==`OpArg`||n.op.kind!==`OpDef`)return;Y(n.op,r,i);let o=vc(n.op,e.index);wc(e.param,t,!1).forEach(e=>ac(a,e,o))}),a},Dc=(e,t,n,r)=>{let i=/* @__PURE__ */ new Map;return e.argLevelConstraints.forEach(e=>{let n=Cc(e.param,t);n===void 0?cc(i,e.param,e.position,e.level):n.kind===`OpArg`&&pc(n.op)&&cc(i,n.op,e.position,e.level)}),e.argLevelParams.forEach(e=>{let a=Cc(e.param,t);if(a===void 0)return;let o=Cc(e.op,t),s=o===void 0?e.op:o.kind===`OpArg`?o.op:void 0;s!==void 0&&pc(s)&&(Y(a,n,r),cc(i,s,e.index,a.level))}),i},Oc=(e,t)=>Ta(e,3).length>0||(Lc(e,t),wa(e).some(e=>(e.body?.level??0)!==0))?!1:e.topLevel.every(e=>e.kind!==`Theorem`||e.level===0),kc=(e,t,n)=>{e.minMaxLevel=t.map(e=>Array.from({length:e.arity},(t,r)=>n.argLevelConstraints.get(sc(e,r))?.level??0)),e.opLevelCond=t.map(e=>t.map(t=>Array.from({length:e.arity},(r,i)=>n.argLevelParams.has(nc(e,i,t))))),J(e.levelParams,n.levelParams),J(e.allParams,n.allParams),J(e.nonLeibnizParams,n.nonLeibnizParams),t.forEach((t,n)=>{e.levelParams.delete(t),e.allParams.delete(t),e.nonLeibnizParams.has(t)&&(e.nonLeibnizParams.delete(t),e.isLeibnizArg&&(e.isLeibnizArg[n]=!1),e.isLeibniz=!1)}),e.levelConstraints=new Map(n.levelConstraints),t.forEach(t=>e.levelConstraints.delete(t)),e.argLevelConstraints=new Map(n.argLevelConstraints),t.forEach(t=>{for(let n=0;n<t.arity;n++)e.argLevelConstraints.delete(sc(t,n))}),ic(e.argLevelParams,n.argLevelParams,e=>!t.some(t=>t===e.op)||!t.some(t=>t===e.param))},Ac=(e,t,n,r,i)=>{e.operands.forEach((a,o)=>{if(a===void 0||(a.level>vc(t,o)&&(n&&Y(a,r,i)&&tc(i,e.location,`Level error in applying operator ${t.name}:\nThe level of argument ${o+1} exceeds the maximum level allowed by the operator.`),e.levelCorrect=!1),a.kind!==`OpArg`||!hc(a.op)))return;let s=a.op;Y(s,r,i);let c=xa(s);for(let l=0;l<c;l++){let c=yc(t,o,l);vc(s,l)>=c||(n&&Y(a,r,i)&&tc(i,e.location,`Level error in applying operator ${t.name}:\nThe permitted level of argument ${l+1} of the operator argument ${o+1} \nmust be at least ${c}.`),e.levelCorrect=!1)}e.operands.forEach((n,l)=>{for(let u=0;u<c;u++)n===void 0||!xc(t,o,l,u)||n.level<=vc(s,u)||(Y(a,r,i)&&Y(n,r,i)&&tc(i,e.location,`Level error in applying operator ${t.name}:\nThe level of argument ${l+1} exceeds the maximum level allowed by the operator.`,`HIGHER_ORDER_OPERATOR_COPARAMETER_LEVEL_CONSTRAINTS_EXCEEDED`),e.levelCorrect=!1)})}),e.ranges.forEach((n,a)=>{let o=Y(n,r,i);n.level<=2||(o&&tc(i,e.location,`Level error in applying operator ${t.name}:\nThe level of the range for the bounded variable ${la(e.bounded?.[a]?.[0]?.location)} \nexceeds the maximum level allowed by the operator.`),e.levelCorrect=!1)})},jc=(e,t,n,r,i)=>{let a=t.params??[],o=t=>e.operands.find((e,n)=>a[n]===t);oc(e.levelConstraints,t.levelConstraints),e.operands.forEach(t=>{t!==void 0&&oc(e.levelConstraints,t.levelConstraints,e=>!n.has(e))}),e.ranges.forEach(t=>oc(e.levelConstraints,t.levelConstraints)),e.operands.forEach((n,r)=>{let i=vc(t,r);n?.levelParams.forEach(t=>ac(e.levelConstraints,t,i))}),e.operands.forEach((n,a)=>{if(n?.kind!==`OpArg`||!hc(n.op))return;let o=n.op;Y(o,r,i);let s=xa(o);e.operands.forEach((n,r)=>{for(let i=0;i<s;i++){if(!xc(t,a,r,i))continue;let s=vc(o,i);n?.levelParams.forEach(t=>ac(e.levelConstraints,t,s)),!o.isLeibniz&&!bc(o,i)&&n&&J(e.nonLeibnizParams,n.allParams)}})}),t.argLevelParams.forEach(t=>{let n=o(t.op);n?.kind===`OpArg`&&hc(n.op)&&(Y(n.op,r,i),ac(e.levelConstraints,t.param,vc(n.op,t.index)))}),lc(e.argLevelConstraints,t.argLevelConstraints),e.operands.forEach(t=>{t&&lc(e.argLevelConstraints,t.argLevelConstraints)}),e.ranges.forEach(t=>lc(e.argLevelConstraints,t.argLevelConstraints)),e.operands.forEach((n,r)=>{if(n?.kind!==`OpArg`||!pc(n.op))return;let i=n.op;for(let n=0;n<i.arity;n++)cc(e.argLevelConstraints,i,n,yc(t,r,n));e.operands.forEach((n,a)=>{for(let o=0;o<i.arity;o++)n!==void 0&&xc(t,r,a,o)&&cc(e.argLevelConstraints,i,o,n.level)})}),t.argLevelParams.forEach(t=>{let n=o(t.op);n!==void 0&&(Y(n,r,i),cc(e.argLevelConstraints,t.op,t.index,n.level))}),e.operands.forEach(t=>{t!==void 0&&ic(e.argLevelParams,t.argLevelParams,e=>!n.has(e.param))}),e.ranges.forEach(t=>ic(e.argLevelParams,t.argLevelParams)),t.argLevelParams.forEach((t,n)=>{let a=o(t.op);if(a===void 0){let a=o(t.param);a===void 0?e.argLevelParams.set(n,t):(Y(a,r,i),a.levelParams.forEach(n=>rc(e.argLevelParams,t.op,t.index,n)))}else a.kind===`OpArg`&&pc(a.op)&&rc(e.argLevelParams,a.op,t.index,t.param)}),e.operands.forEach((n,r)=>{if(n?.kind!==`OpArg`||!pc(n.op))return;let i=n.op;e.operands.forEach((n,a)=>{for(let o=0;o<i.arity;o++)n!==void 0&&xc(t,r,a,o)&&n.levelParams.forEach(t=>rc(e.argLevelParams,i,o,t))})})},Mc=/* @__PURE__ */ new Map([[`\\land`,`\\land`],[`\\lor`,`\\lor`],[`=>`,`=>`],[`\\equiv`,`\\equiv`],[`$ConjList`,`Conjunction list`],[`$DisjList`,`Disjunction list`]]),Nc=(e,t)=>{let n=(n,r)=>{tc(t,n,r),t.isTlc174||(e.levelCorrect=!1)},r=e.operator.name,i=e.operands[0];if((r===`[]`||r===`<>`)&&i?.level===2&&i.kind===`OpAppl`){let t=r===`[]`;i.operator.name!==(t?`$SquareAct`:`$AngleAct`)&&n(e.location,t?`[] followed by action not of form [A]_v.`:`<> followed by action not of form <<A>>_v.`)}r!==`~>`&&r!==`-+->`||i?.level!==2&&e.operands[1]?.level!==2||n(e.location,`Action used where only temporal formula or state predicate allowed.`);let a=Mc.get(r);a!==void 0&&e.operands.some(e=>e?.level===3)&&e.operands.some(e=>e?.level===2)&&n(e.location,`${a} has both temporal formula and action as arguments.`),e.level===3&&(r===`$BoundedExists`||r===`$BoundedForall`)&&e.ranges.forEach(e=>{e.level===2&&n(e.location,`Action-level bound of quantified temporal formula.`)})},Pc=(e,t,n)=>{if(e.levelChecked>=t)return e.levelCorrect;e.levelChecked=t,e.levelCorrect=!0;let r=e.operands.filter(e=>e!==void 0);r.forEach(r=>{Y(r,t,n)||(e.levelCorrect=!1)}),e.ranges.forEach(r=>{Y(r,t,n)||(e.levelCorrect=!1)});let i=e.operator;if(hc(i)){let r=Y(i,t,n);Ac(e,i,r,t,n),e.level=e.operands.reduce((e,t,n)=>t!==void 0&&_c(i,n)===1?Math.max(e,t.level):e,i.level),e.ranges.forEach(t=>{e.level=Math.max(e.level,t.level)}),J(e.levelParams,i.levelParams),J(e.allParams,i.allParams),J(e.nonLeibnizParams,i.nonLeibnizParams),e.operands.forEach((t,n)=>{t!==void 0&&(_c(i,n)===1&&J(e.levelParams,t.levelParams),J(e.allParams,t.allParams),J(e.nonLeibnizParams,t.nonLeibnizParams),bc(i,n)||J(e.nonLeibnizParams,t.allParams))}),e.ranges.forEach(t=>{J(e.levelParams,t.levelParams),J(e.allParams,t.allParams),J(e.nonLeibnizParams,t.nonLeibnizParams)});let a=new Set(Sc(e));a.forEach(t=>{e.levelParams.delete(t),e.allParams.delete(t),e.nonLeibnizParams.delete(t)}),jc(e,i,a,t,n)}else Y(i,t,n),e.level=r.reduce((e,t)=>Math.max(e,t.level),i.kind===`Module`?0:i.level),e.levelParams=/* @__PURE__ */ new Set([i]),e.allParams.add(i),r.forEach((t,n)=>{J(e.levelParams,t.levelParams),J(e.allParams,t.allParams),J(e.nonLeibnizParams,t.nonLeibnizParams),oc(e.levelConstraints,t.levelConstraints),cc(e.argLevelConstraints,i,n,t.level),lc(e.argLevelConstraints,t.argLevelConstraints),t.levelParams.forEach(t=>rc(e.argLevelParams,i,n,t)),ic(e.argLevelParams,t.argLevelParams)});return Nc(e,n),e.levelCorrect},Fc=(e,t,n)=>{if(e.levelChecked>=t||!e.inRecursiveSection&&e.levelChecked>0)return e.levelCorrect;e.levelChecked=t;let r=e.body;if(r===void 0)return e.levelCorrect=e.step===void 0||Y(e.step,t,n),e.levelCorrect;e.levelCorrect=Y(r,t,n),e.level=Math.max(e.level,r.level);let i=e.params??[];return i.forEach((t,n)=>{let i=r.levelConstraints.get(t);i!==void 0&&(e.maxLevels[n]=Math.min(e.maxLevels[n],i)),r.levelParams.has(t)&&(e.weights[n]=Math.max(e.weights[n],1))}),kc(e,i,r),e.levelCorrect},Ic=(e,t,n)=>(e.levelChecked>=t||(e.levelChecked=t,e.maxLevels=e.params.map(()=>3),e.isLeibnizArg=e.params.map((t,n)=>n===e.params.length-1),e.params.length>0&&(e.isLeibniz=!0),e.levelCorrect=Y(e.body,t,n),e.level=e.body.level,e.params.forEach((t,n)=>{let r=e.body.levelConstraints.get(t);r!==void 0&&(e.maxLevels[n]=r)}),kc(e,e.params,e.body)),e.levelCorrect),Lc=(e,t)=>{if(e.isLevelChecked)return e.levelCorrect;e.isLevelChecked=!0;let n=e.opDefsInRecursiveSection,r=0;for(;r<n.length;){let e=n[r].recursiveSection,i=r;for(;i<n.length&&n[i].recursiveSection===e;){let e=n[i];e.inRecursive?(e.levelChecked=1,e.maxLevels=e.maxLevels.map(()=>2),e.weights=e.weights.map(()=>1)):e.levelChecked=0,i++}let a=n.slice(r,i),o=/* @__PURE__ */ new Set,s=/* @__PURE__ */ new Set,c=0;a.forEach(e=>{e.inRecursive&&(e.levelChecked=0),Fc(e,1,t),e.inRecursive&&(e.maxLevels.forEach((n,r)=>{n>=2||tc(t,e.location,`Argument ${r+1} of recursive operator ${e.name} is primed`)}),c=Math.max(c,e.level),J(o,e.levelParams),J(s,e.allParams))}),a.forEach(e=>{e.inRecursive&&(e.levelChecked=2),e.level=Math.max(e.level,c),J(e.levelParams,o),J(e.allParams,s)}),a.forEach(e=>{e.inRecursive&&(e.levelChecked=1),Fc(e,2,t)}),r=i}e.levelCorrect=!0;let i=t=>{t||(e.levelCorrect=!1)};e.definitions.filter(e=>e.kind===`Module`).forEach(e=>i(Lc(e,t)));let a=wa(e);return a.forEach(e=>i(Fc(e,1,t))),Ea(e).forEach(e=>i(Ic(e,1,t))),e.topLevel.forEach(e=>i(Y(e,1,t))),Oc(e,t)||Ta(e,2).forEach(t=>ac(e.levelConstraints,t,0)),a.forEach(t=>{oc(e.levelConstraints,t.levelConstraints),lc(e.argLevelConstraints,t.argLevelConstraints),ic(e.argLevelParams,t.argLevelParams,e=>!fc(e,t.params??[]))}),e.topLevel.forEach(t=>{oc(e.levelConstraints,t.levelConstraints),lc(e.argLevelConstraints,t.argLevelConstraints),ic(e.argLevelParams,t.argLevelParams)}),e.levelCorrect},Rc=(e,t,n,r)=>(e.levelChecked>=n||(e.levelChecked=n,t.forEach(t=>{mc(t)&&(t.kind!==`OpDef`||t.defKind!==`ModuleInstance`)&&(e.levelCorrect=Y(t,n,r)&&e.levelCorrect,e.level=Math.max(e.level,t.level),dc(e,t),J(e.nonLeibnizParams,t.nonLeibnizParams))})),e.levelCorrect),zc=(e,t)=>{e?.kind===`NonLeafProof`&&e.steps.forEach(e=>{if(e.kind!==`Theorem`||e.body.kind!==`OpAppl`)return;let n=e.body.operator.name;n===`$Take`||n===`$Witness`||n===`$Have`?e.body.level!==0&&tc(t,e.body.location,`Non-constant TAKE, WITNESS, or HAVE for temporal goal.`):n===`$Pfcase`?(e.body.level!==0&&tc(t,e.body.location,`Non-constant CASE for temporal goal.`),zc(e.proof,t)):n===`$Qed`&&zc(e.proof,t)})},Bc=(e,t,n)=>{if(e.levelChecked>=t)return e.levelCorrect;e.levelChecked=t,e.levelParams=/* @__PURE__ */ new Set,e.levelCorrect=!0;let r=e.module;Lc(r,n)||(e.levelCorrect=!1),e.substs.forEach(r=>{Y(r.expr,t,n)||(e.levelCorrect=!1)});let i=Oc(r,n);e.substs.forEach(a=>{!i&&a.expr.level>a.op.level&&(Y(a.expr,t,n)&&tc(n,e.location,`Level error in instantiating module '${r.name}':\nThe level of the expression or operator substituted for '${a.op.name}' \nmust be at most ${a.op.level}.`),e.levelCorrect=!1),a.expr.kind!==`OpArg`||a.expr.op.kind!==`OpDef`||a.expr.op.defKind!==`UserDefined`&&a.expr.op.defKind!==`BuiltIn`||a.expr.op.isLeibniz||tc(n,e.location,`Error in instantiating module '${r.name}':\n A non-Leibniz operator substituted for '${a.op.name}'.`)}),e.substs.forEach(i=>{let a=r.levelConstraints.get(i.op);if(a!==void 0&&i.expr.level>a&&(Y(i.expr,t,n)&&tc(n,e.location,`Level error in instantiating module '${r.name}':\nThe level of the expression or operator substituted for '${i.op.name}' \nmust be at most ${a}.`),e.levelCorrect=!1),i.op.arity<=0||i.expr.kind!==`OpArg`||i.expr.op.kind!==`OpDef`)return;let o=i.expr.op,s=Y(o,t,n);for(let t=0;t<i.op.arity;t++){let a=r.argLevelConstraints.get(sc(i.op,t))?.level;a===void 0||vc(o,t)>=a||(s&&tc(n,e.location,`Level error in instantiating module '${r.name}':\nThe level of the argument ${t+1} of the operator ${o.name} \nmust be at least ${a}.`),e.levelCorrect=!1)}}),r.argLevelParams.forEach(i=>{e.substs.forEach(a=>{e.substs.forEach(o=>{if(i.op!==a.op||i.param!==o.op||a.expr.kind!==`OpArg`)return;let s=a.expr.op,c=Y(s,t,n);if(s.kind!==`OpDef`)return;let l=vc(s,i.index);o.expr.level<=l||(c&&Y(o.expr,t,n)&&tc(n,e.location,`Level error when instantiating module '${r.name}':\nThe level of the argument ${i.index} of the operator ${a.op.name}' \nmust be at most ${l}.`),e.levelCorrect=!1)})})});let a=t=>!e.params.some(e=>e===t);return oc(e.levelConstraints,Ec(r,e.substs,i,t,n),a),e.substs.forEach(t=>oc(e.levelConstraints,t.expr.levelConstraints,a)),lc(e.argLevelConstraints,Dc(r,e.substs,t,n),e=>a(e.param)),e.substs.forEach(t=>lc(e.argLevelConstraints,t.expr.argLevelConstraints,e=>a(e.param))),ic(e.argLevelParams,Tc(r.argLevelParams,e.substs),t=>!fc(t,e.params)),e.substs.forEach(t=>ic(e.argLevelParams,t.expr.argLevelParams,t=>!fc(t,e.params))),e.levelCorrect},Y=(e,t,n)=>{if(!mc(e))return Lc(e,n);switch(e.kind){case`OpAppl`:return Pc(e,t,n);case`OpDef`:return Fc(e,t,n);case`ThmOrAssumpDef`:return Ic(e,t,n);case`FormalParam`:return e.levelChecked===0&&(e.levelChecked=t,e.levelParams.add(e),e.allParams.add(e)),!0;case`OpDecl`:return!0;case`Numeral`:case`String`:case`Decimal`:return e.levelChecked<t&&(e.levelChecked=t),!0;case`OpArg`:{if(e.levelChecked>=t)return e.levelCorrect;e.levelChecked=t;let r=e.op;return e.levelCorrect=Y(r,t,n),r.kind===`Module`||(e.level=r.level,uc(e,r)),e.levelCorrect}case`LetIn`:{if(e.levelChecked>=t)return e.levelCorrect;e.levelChecked=t,e.levelCorrect=!0;let r=e.opDefs.filter(e=>e.kind!==`OpDef`||e.defKind!==`ModuleInstance`);return r.forEach(r=>{Y(r,t,n)||(e.levelCorrect=!1)}),Y(e.body,t,n)||(e.levelCorrect=!1),e.instances.forEach(r=>{Y(r,t,n)||(e.levelCorrect=!1)}),e.level=e.body.level,e.levelParams=new Set(e.body.levelParams),e.allParams=new Set(e.body.allParams),oc(e.levelConstraints,e.body.levelConstraints),r.forEach(t=>oc(e.levelConstraints,t.levelConstraints)),lc(e.argLevelConstraints,e.body.argLevelConstraints),r.forEach(t=>lc(e.argLevelConstraints,t.argLevelConstraints)),ic(e.argLevelParams,e.body.argLevelParams),r.forEach(t=>{let n=t.kind===`OpDef`?t.params??[]:[];ic(e.argLevelParams,t.argLevelParams,e=>!fc(e,n))}),e.instances.forEach(t=>ic(e.argLevelParams,t.argLevelParams)),e.levelCorrect}case`Label`:{if(e.levelChecked>=t)return!0;e.levelChecked=t,e.params.forEach(e=>Y(e,t,n));let r=Y(e.body,t,n);return e.level=e.body.level,uc(e,e.body),r}case`At`:{if(e.levelChecked>=t)return!0;e.levelChecked=t;let r=e.except.operands,i=r[0];if(i===void 0)return!0;Y(i,t,n),e.level=i.level;let a=[i];for(let i of r.slice(1))if(i!==void 0){if(Y(i,t,n),i===e.component)break;e.level=Math.max(e.level,i.level),a.push(i)}return a.forEach(t=>dc(e,t)),!0}case`SubstIn`:case`APSubstIn`:{if(e.levelChecked>=t)return e.levelCorrect;e.levelChecked=t,e.levelCorrect=!0;let r=e.body;Y(r,t,n)||(e.levelCorrect=!1),e.substs.forEach(r=>{Y(r.expr,t,n)||(e.levelCorrect=!1)}),e.level=e.substs.reduce((e,t)=>r.levelParams.has(t.op)?Math.max(e,t.expr.level):e,r.level),r.levelParams.forEach(t=>J(e.levelParams,wc(t,e.substs,!1))),e.kind===`APSubstIn`?r.allParams.forEach(t=>J(e.allParams,wc(t,e.substs,!0))):(e.allParams=new Set(r.allParams),e.nonLeibnizParams=new Set(r.nonLeibnizParams),e.substs.forEach(t=>{e.allParams.has(t.op)&&(e.allParams.delete(t.op),J(e.allParams,t.expr.allParams),J(e.nonLeibnizParams,t.expr.nonLeibnizParams),e.nonLeibnizParams.has(t.op)&&(e.nonLeibnizParams.delete(t.op),J(e.nonLeibnizParams,t.expr.allParams)))}));let i=Oc(e.instantiatedModule,n);return e.levelConstraints=Ec(r,e.substs,i,t,n),e.argLevelConstraints=Dc(r,e.substs,t,n),e.argLevelParams=Tc(r.argLevelParams,e.substs),e.levelCorrect}case`Instance`:return Bc(e,t,n);case`Assume`:{if(e.levelChecked>=t)return!0;e.levelChecked=t;let r=Y(e.body,t,n),i=!e.definition||Y(e.definition,t,n);return e.level=e.body.level,uc(e,e.body),e.level!==0&&tc(n,e.location,`Level error: assumptions must be level 0 (Constant), \nbut this one has level ${e.level}.`),r&&i}case`Theorem`:{if(e.levelChecked>=t)return!0;let r=Rc(e,[e.definition??e.body,...e.proof?[e.proof]:[]],t,n),i=e.body;return i.kind===`OpAppl`&&i.operator.name===`$Pick`&&i.level===3&&i.ranges.forEach(e=>{e.level!==0&&tc(n,e.location,`Non-constant bound of temporal PICK.`)}),i.level===3&&zc(e.proof,n),r}case`LeafProof`:case`UseOrHide`:return Rc(e,e.facts,t,n);case`NonLeafProof`:return Rc(e,[...e.steps,...e.instances],t,n);case`DefStep`:return Rc(e,e.defs,t,n);case`NewSymb`:return e.levelChecked>=t||(e.levelChecked=t,e.level=e.declaration.level,e.set===void 0)||(e.levelCorrect=Y(e.set,t,n),e.level=Math.max(e.level,e.set.level),e.level===3&&(e.levelCorrect=!1,tc(n,e.location,`Level error:
39
- Temporal formula used as set.`)),uc(e,e.set)),e.levelCorrect;case`AssumeProve`:return e.levelChecked>=t||(e.levelChecked=t,e.levelCorrect=!0,e.assumptions.forEach(r=>{Y(r,t,n)||(e.levelCorrect=!1)}),Y(e.goal,t,n),e.level=e.assumptions.reduce((e,t)=>Math.max(e,t.level),e.goal.level),[e.goal,...e.assumptions].forEach(t=>dc(e,t)),e.levelCorrect&&e.levelParams.forEach(t=>{t.kind===`OpDecl`&&t.declKind===2&&ac(e.levelConstraints,t,2)})),e.levelCorrect}},Vc=e=>{switch(e.kind){case`OpAppl`:return[...e.ranges,...e.operands];case`OpDef`:case`ThmOrAssumpDef`:case`Label`:return[e.body];case`LetIn`:return[...e.opDefs,...e.instances,e.body];case`SubstIn`:case`APSubstIn`:return[e.body,...e.substs.map(e=>e.expr)];case`Instance`:return e.substs.map(e=>e.expr);case`AssumeProve`:return[...e.assumptions,e.goal];case`NewSymb`:return[e.set];default:return[]}},Hc=/* @__PURE__ */ new Map([[`Integers`,`Int`],[`Naturals`,`Nat`],[`Reals`,`Reals`]]),Uc=e=>{let t=/* @__PURE__ */ new Set,n=e=>{if(e===void 0||t.has(e))return!1;if(t.add(e),e.kind===`OpAppl`){let t=e.operator;if(t.kind===`OpDecl`||t.kind===`FormalParam`)return!0;if(t.kind===`OpDef`){if(t.name===`BOOLEAN`)return!0;let e=t.module?.name;if(e!==void 0&&Hc.get(e)===t.name||n(t))return!0}}return Vc(e).some(n)};return n(e)},Wc=e=>e.operands.filter(e=>e?.kind===`OpAppl`),Gc=e=>{let t=e.operands[0];return t?.kind===`String`?t:void 0},Kc=e=>JSON.stringify([e.operands.length,...Wc(e).map(e=>Gc(e)?.value).sort()]),qc=(e,t=/* @__PURE__ */ new Set)=>(e.extendees.forEach(e=>{t.has(e)||(t.add(e),qc(e,t))}),t),Jc=e=>{let t=e.records.map(t=>({domain:Kc(t),warnings:Wc(t).flatMap(t=>{let n=Gc(t),r=n&&Sa(e.context,n.value);return n===void 0||r===void 0?[]:[{location:n.location,text:`The field name "${n.value}" in the record constructor is identical to the existing definition or declaration\nnamed ${n.value}, located at ${la(r.location)}.\nThe field in the record will not take the value of the ${n.value} definition or declaration.\nIn TLA+, field names in records are strings, regardless of any similarly named declarations or definitions.\nTherefore, DOMAIN [${n.value} |-> ...] = {"${n.value}"} holds true.`,isWarning:!0}]})})),n=new Set(t.flatMap(e=>e.warnings.length>0?[e.domain]:[])),r=/* @__PURE__ */ new Set;return[...[...qc(e)].flatMap(e=>e.records),...e.records].forEach(e=>{let t=Kc(e);n.has(t)&&!r.has(t)&&Wc(e).some(Uc)&&r.add(t)}),t.flatMap(e=>r.has(e.domain)?[]:e.warnings)},Yc=e=>`${la(e.location)}\n\n${e.text}`,Xc=e=>{let t=e.filter(e=>!e.isWarning),n=e.filter(e=>e.isWarning);return[t.length>0?`*** Errors: ${t.length}\n\n`:``,...t.map(e=>`${Yc(e)}\n\n\n`),n.length>0?`*** Warnings: ${n.length}\n\n`:``,...n.map(e=>`${Yc(e)}\n\n\n`)].join(``)},Zc=4802,Qc=/* @__PURE__ */ new Set([`FiniteSets`,`Sequences`,`Bags`,`Naturals`,`Integers`,`Reals`,`RealTime`,`Randomization`,`TLC`]),$c=e=>{let t=/* @__PURE__ */ new Set,n=[],r=e=>{t.add(e.name),n.push(...e.extends),e.modules.forEach(r)};return r(e),n.filter(e=>!t.has(e))},el=e=>{try{return de(Za(e))}catch(e){if(e instanceof o)return;throw e}},tl=(e,t)=>t===`1.7.4`&&pe(e)!==void 0?void 0:el(e)?.name,nl=(e,t,n={})=>{let r=_t(e,`.tla`),i=We(n.version),a=n.fileName??r,o=I(e),s=o?kt(e,`utf8`):i.get(r),c=[],l=e=>{c.push(e),n.onPrint?.(e)},d=e=>l(`${e}\n`),f=n.version===`1.7.4`,p=f&&n.isXmlExport,m=e=>{n.isXmlExport||d(e)},h=n.describeFile,g=/* @__PURE__ */ new Map([[r,o?`file`:`standard`]]),_=!1,v=[],y=!1,x=!1,S=ii(_r(),d),C=/* @__PURE__ */ new Map,w=[],T=()=>w.splice(0).forEach(e=>e.isError?n.onPrintError?.(`${e.text}\n`):d(e.text)),E=e=>{let t=C.get(e),r=t?.module.location.range;if(t===void 0||r===void 0)return;let i=t.text.split(/\r\n|\r|\n/),a=ia(S,i.slice(r.start.line-1,r.end.line),n.version),o=a.has(`TLA_DIVERGENCE_EXISTS`),s=a.has(`PCAL_DIVERGENCE_EXISTS`),c=o===s?void 0:`The ${o?`TLA+ translation`:`PlusCal algorithm`} in module ${e} has changed since its last translation.`;if(f){let t=o&&s?`The PlusCal algorithm and its TLA+ translation in module ${e} filename since the last translation.`:c;t===void 0?a.has(`ERROR_ENCOUNTERED`)&&w.push({text:`A unexpected problem was encountered attempting to validate the specification for ${e}`,isError:!0}):w.push({text:`!! WARNING: ${t}`,isError:!1});return}let l=o&&s?`Both the PlusCal algorithm and its TLA+ translation in module ${e} have changed since the last translation.`:c??(a.has(`ERROR_ENCOUNTERED`)?`An unexpected problem was encountered attempting to validate the specification for ${e}`:void 0);if(l===void 0)return;let u=!a.has(`ERROR_ENCOUNTERED`)||o||s;v.some(e=>e.text===l)||v.push({location:e,text:l,isWarning:u})},ee=(e,t)=>{if(n.isXmlExport||C.has(e))return;let r=el(t);if(r===void 0||r.name!==e)return;let i=[...C.values()].filter(t=>$c(t.module).includes(e));C.set(e,{text:t,module:r}),i.forEach(()=>E(e)),$c(r).filter(t=>t!==e&&C.has(t)).forEach(E)},D=()=>{if(T(),y)return;y=!0;let e=v.filter(e=>e.isWarning);e.length>0&&(m(`Warnings (${e.length}) during syntax parsing of ${a}:\n\n`),e.forEach(e=>m(`${Yc(e)}\n\n\n`))),e.length!==v.length&&(d(Xc(v)),_=!0,x=!0)},O=e=>{let n=i.get(e),r=t(e),a=r===void 0&&n===void 0&&s!==void 0&&!f?he(s,e):void 0,o=r??a;return g.set(e,r===void 0?a===void 0?`standard`:`root file`:`file`),o!==void 0&&ee(e,o),o??n},k=(()=>{try{if(s===void 0)throw new u(`Cannot find source file for module ${a}`,void 0);return ee(r,s),ec(s,O,{rootFileName:r,rootFilePath:n.isXmlExport?`${a.replace(/\.tla$/,``)}.tla`:void 0,version:n.version,rootExtendees:n.rootExtendees,onParse:e=>{h&&d(`Parsing file ${h(e,g.get(e)??`file`)}`),e===r&&E(r),T()},onAnalyze:e=>{D(),(h||p)&&!x&&d(`Semantic processing of module ${e}`)},onModule:(e,t)=>{if(x||(t.every(e=>e.isWarning)&&Lc(e,{messages:t,isTlc174:f}),t.length===0))return;if(t.some(e=>!e.isWarning)&&(_=!0),f)return d(`Semantic errors:\n\n${Xc(t)}`);let n=t.filter(e=>e.isWarning);n.length>0&&(m(`*** Warnings: ${n.length}\n`),n.forEach(e=>m(`${Yc(e)}\n\n\n`)));let r=t.filter(e=>!e.isWarning);r.length!==0&&(d(`Semantic errors:\n\n*** Errors: ${r.length}\n`),r.forEach(e=>d(`${Yc(e)}\n\n`)))}})}catch(e){if(_=!0,e instanceof b){d(`\nFatal errors while parsing TLA+ spec in file ${a}\n`),d(e.message),d(Xc(v));return}if(!(e instanceof u))throw e;let t={location:e.location,text:e.message,isWarning:!1},n=f&&e.parseError?.includes(` and token "" `);if(e.parseError!==void 0&&!n&&!p&&d(e.parseError),d(`\nFatal errors while parsing TLA+ spec in file ${a}\n`),n){d(`java.lang.NullPointerException: Cannot invoke "String.length()" because "str" is null`);return}if(f){d(`tla2sany.semantic.AbortException`),l(`*** Abort messages: 1\n\n${Yc(t)}\n\n\n`);return}d(Yc(t)),d(Xc(y?[t]:[...v,t]))}})();if(k!==void 0&&D(),k!==void 0&&!_&&!n.isXmlExport&&!f){let e=k.modules.filter(e=>!Qc.has(e.name));h&&e.forEach(e=>d(`Linting of module ${e.name}`));let t=n.suppressedCodes?.includes(Zc)?[]:e.flatMap(Jc),r=n.errorCodes?.includes(Zc)?`Warning treated as error: `:``;t.forEach(e=>d(`${r}${Yc(e)}\n\n\n`)),r&&t.length>0&&(_=!0)}return{text:c.join(``),isFailed:_,specification:x?void 0:k}},rl=e=>e.kind===`OpDef`&&e.defKind!==`BuiltIn`&&e.defKind!==`ModuleInstance`,il=(e,t)=>e.context.symbols.find(e=>rl(e)&&e.name===t),al=e=>v(new y(`Parsing or semantic analysis failed.Parsing or semantic analysis failed.${e}`),T.specParseError),ol=(e,t,n,r,i)=>{let a=t.replace(`__DebuggerExpr__`,`__DebuggerModule__`),s=`---- MODULE ${a} ----\nEXTENDS ${e}\n\n${t} == ${n}\n====`,c=e=>al(`Unknown location\n\n${e} while parsing breakpoint expression "${n}"`);try{Je(s)}catch(e){throw e instanceof o?al(`Syntax error while parsing breakpoint expression "${n}"`):e}let l=!1,u=!1,d=(()=>{try{return ec(s,r,{version:i,onModule:(e,t)=>{let n=()=>t.every(e=>e.isWarning);if(!n())return;let r=Lc(e,{messages:t,isTlc174:i===`1.7.4`});e.name===a&&(l=!0,u=r&&n())}})}catch(e){throw e instanceof o?c(`Semantic error`):e}})();if(!l)throw c(`Semantic error`);if(!u)throw c(`Level-checking error`);let f=il(d.root,t)?.level??0;if(f===3)throw al(`Unknown location\n\nDebug expressions must be action-level or below; actual level: ${f} (Temporal)`);return f},sl=(e,t,n,r,i)=>{let a=Date.now(),o=n.map((e,n)=>({expression:e.expression,name:il(t,e.expression)?e.expression:`__DebuggerExpr__${a+n}`})),s=o.map(e=>e.name),c=o.filter(e=>e.name!==e.expression);if(c.length===0)return{names:s,source:e};let l=n=>n===t.name?e:r(n),u=t.context.symbols.find(e=>e.kind===`OpDecl`&&e.declKind===3),d=c.map(e=>{let n=`${e.name} == `;return ol(t.name,e.name,e.expression,l,i)===0&&u?`${e.name} ==\nLET ${e.name}State == ${u.name} IN\n${` `.repeat(n.length)}${e.expression}`:`${n}${e.expression}`}),f=e.split(`
40
- `),p=(Je(e).location.range?.end.line??f.length)-1,m=f[p].search(/={4,}/);return{names:s,source:[...f.slice(0,p),f[p].slice(0,m),...d,f[p].slice(m),...f.slice(p+1)].join(`
41
- `)}},cl=(1n<<63n)-1n,ll=[[-123456,-123456],[-1,0],[1e3,1003],[1005,1005],[1101,1102],[2e3,2001],[2100,2149],[2154,2274],[2279,2287],[2300,2301],[2400,2405],[2501,2502],[2772,2780],[3e3,3002],[3100,3114],[4e3,4002],[5001,5007],[7e3,7010],[2e4,2e4]],ul=[[4003,4005],[4200,4206],[4220,4224],[4240,4247],[4260,4262],[4270,4275],[4290,4294],[4310,4315],[4330,4337],[4350,4357]],dl=/* @__PURE__ */ new Map([[4800,`EXTENDED_MODULES_SYMBOL_UNIFICATION_AMBIGUITY`],[4801,`INSTANCED_MODULES_SYMBOL_UNIFICATION_AMBIGUITY`],[4802,`RECORD_CONSTRUCTOR_FIELD_NAME_CLASH`],[4803,`PLUSCAL_ALGORITHM_AND_TRANSLATION_CHANGED_SINCE_LAST_TRANSLATION`],[4804,`PLUSCAL_ALGORITHM_CHANGED_SINCE_LAST_TRANSLATION`],[4805,`PLUSCAL_TRANSLATION_CHANGED_SINCE_LAST_TRANSLATION`]]),fl=(e,t,n)=>({module:e,constant:n,operators:[{kind:`postcondition`,operator:t}]}),pl={json:fl(`_JsonTrace`,`_JsonTrace`,`_JsonTraceFile`),tla:fl(`_TLAPlusCounterExample`,`_TLAPlusCounterExample`,`_TLAPlusCounterExampleFile`),tlc:fl(`_TLCTrace`,`_TLCTrace`,`_TLCTraceFile`),tlcplain:fl(`_TLCTracePlain`,`_TLCTrace`,`_TLCTraceFile`),tlctespec:fl(`_TLCTESpec`,`_TLCTrace`,`_TLCTraceFile`),tlcaction:fl(`_TLCActionTrace`,`_TLCTrace`,`_TLCTraceFile`),dot:fl(`_DotTrace`,`_DotTrace`,`_DotTraceFile`)},ml=(e,t)=>({module:e,constant:`${t}InputFile`,operators:[{kind:`constraint`,operator:`${t}Constraint`},{kind:`view`,operator:`${t}View`}]}),hl={tlc:ml(`_TLCTrace`,`_TLCTrace`),json:ml(`_JsonTrace`,`_JsonTrace`)},gl=(e,t)=>e.some(e=>t>=e[0]&&t<=e[1]),_l=(e,t)=>{if(e===``)return[e];let n=e.split(t);for(;n.at(-1)===``;)n.pop();return n},vl=(e,t)=>[...new Set(e.filter(e=>t.includes(e)))].sort((e,t)=>e-t),yl=(e,t)=>{if(!/^[+-]?\d+$/.test(e))return;let n=BigInt(e);return BigInt.asIntN(t,n)===n?n:void 0},bl=e=>/^[+-]?(NaN|Infinity|(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?[fFdD]?)$/.test(e.trim())?Number.parseFloat(e.trim().replace(/[fFdD]$/,``)):void 0,xl=()=>({specs:[],configPath:void 0,seed:0n,aril:0n,workers:1,coverage:void 0,livenessCheck:`default`,dump:void 0,fingerprintIndex:0,maxSetSize:void 0,isLazyValueExpanded:!0,isViewPrinted:!1,metadir:void 0,recoverDirectory:void 0,mode:`model-check`,dfidDepth:void 0,traceDepth:100,traceCount:void 0,scheduler:`random`,isTool:!1,isContinued:!1,isDeadlockChecked:!0,isWarningEnabled:!0,isTraceSpecForced:!1,isTraceSpecDisabled:!1,isTraceBinaryDisabled:!1,traceSpecPath:void 0,isDiffTrace:!1,suppressedCodes:[],errorCodes:[],userFile:void 0,invariants:[],moduleOperators:[]}),Sl={"-modelcheck":()=>{},"-difftrace":e=>{e.isDiffTrace=!0},"-deadlock":e=>{e.isDeadlockChecked=!1},"-cleanup":()=>{},"-nowarning":e=>{e.isWarningEnabled=!1},"-gzip":()=>{},"-terse":e=>{e.isLazyValueExpanded=!1},"-continue":e=>{e.isContinued=!0},"-view":e=>{e.isViewPrinted=!0},"-debug":()=>{},"-tool":e=>{e.isTool=!0}},Cl=(e,t,n)=>(r,i)=>{let a=yl(i,e);return a===void 0?`${t} But encountered ${i}`:n(r,a,i)},wl=(e,t,n,r)=>({missing:t,apply:Cl(32,n,(t,n)=>{let i=BigInt.asIntN(32,n*60000n);if(i<0n)return`Error: expect a nonnegative integer for -${e} option.`;r(t,Number(i)/6e4)})}),Tl={"-teSpecOutDir":{missing:`Error: expected a path for -teSpecOutDir option.`,apply:(e,t)=>{e.traceSpecPath=t}},"-userFile":{missing:`Error: need to specify the full qualified file.`,apply:(e,t)=>{try{wt(Ot(t,`w`))}catch{return`Error: Failed to create user output log file.`}e.userFile=t}},"-lncheck":{missing:`Error: expect a strategy such as final for -lncheck option.`,apply:(e,t)=>{e.livenessCheck=t.toLowerCase()}},"-config":{missing:`Error: expect a file name for -config option.`,apply:(e,t)=>{let n=t.replace(/\.cfg$/,``);e.configPath=n.endsWith(`.tla`)?n:`${n}.cfg`}},"-coverage":wl(`coverage`,`Error: coverage report interval required.`,`Error: An integer for coverage report interval required.`,(e,t)=>{e.coverage=t}),"-checkpoint":wl(`checkpoint`,`Error: checkpoint interval required.`,`Error: An integer for checkpoint interval is required.`,()=>{}),"-depth":{missing:`Error: trace length required.`,apply:Cl(32,`Error: An integer for trace length required.`,(e,t)=>{e.traceDepth=Number(t)})},"-seed":{missing:`Error: seed required.`,apply:Cl(64,`Error: An integer for seed required.`,(e,t)=>{e.seed=t})},"-aril":{missing:`Error: aril required.`,apply:Cl(64,`Error: An integer for aril required.`,(e,t)=>{e.aril=t})},"-maxSetSize":{missing:`Error: maxSetSize required.`,apply:Cl(32,`Error: An integer for maxSetSize required.`,(e,t,n)=>{if(t<1n)return`Error: Value in interval [0, ${ne}] for maxSetSize required. But encountered ${n}`;e.maxSetSize=Number(t)})},"-recover":{missing:`Error: need to specify the metadata directory for recovery.`,apply:(e,t)=>{e.recoverDirectory=t}},"-metadir":{missing:`Error: need to specify the metadata directory.`,apply:(e,t)=>{e.metadir=t}},"-workers":{missing:`Error: expect an integer or 'auto' for -workers option.`,apply:(e,t)=>{let n=t.trim().toLowerCase()===`auto`?BigInt(Bt()):yl(t,32);if(n===void 0)return`Error: worker number or 'auto' required. But encountered ${t}`;if(n<1n)return`Error: at least one worker required.`;e.workers=Number(n)}},"-dfid":{missing:`Error: expect a nonnegative integer for -dfid option.`,apply:Cl(32,`Error: expect a nonnegative integer for -dfid option.`,(e,t)=>{if(t<0n)return`Error: expect a nonnegative integer for -dfid option.`;e.dfidDepth=Number(t)})},"-fp":{missing:`Error: expect an integer for -fp option.`,apply:Cl(32,`Error: A number for -fp is required.`,(e,t)=>{if(t<0n||t>=131)return`Error: The number for -fp must be between 0 and 130 (inclusive).`;e.fingerprintIndex=Number(t)})},"-fpmem":{missing:`Error: fpset memory size required.`,apply:(e,t)=>{let n=bl(t);if(n===void 0||n<0)return`Error: An positive integer or a fraction for fpset memory size/percentage required. But encountered ${t}`;n>1&&process.stdout.write(`Using -fpmem with an abolute memory value has been deprecated. Please allocate memory for the TLC process via the JVM mechanisms and use -fpmem to set the fraction to be used for fingerprint storage.
42
- `)}},"-fpbits":{missing:`Error: fpbits required.`,apply:Cl(32,`Error: An integer for fpbits required.`,(e,t,n)=>t<0n||t>30n?`Error: Value in interval [0, 30] for fpbits required. But encountered ${n}`:void 0)}},El={"-loadtrace":{name:`-loadTrace`,missing:`Error: A format and a file name for loading traces required.`,formats:hl},"-dumptrace":{name:`-dumpTrace`,missing:`Error: A format and a file name for dumping traces required.`,formats:pl}},Dl=e=>{let t=xl(),n=0,r=e=>({kind:`command-line`,error:e,isTool:t.isTool}),i=()=>({kind:`uncaught`,error:`java.lang.ArrayIndexOutOfBoundsException: Index ${e.length} out of bounds for length ${e.length}`,isTool:t.isTool}),a={tlc:[],sany:[]},o={tlc:[],sany:[]},s=()=>e[n],c=()=>e[n++];for(;n<e.length;){let l=c();if(Object.hasOwn(Sl,l))Sl[l](t);else if(Object.hasOwn(Tl,l)){let e=c();if(e===void 0)return r(Tl[l].missing);let n=Tl[l].apply(t,e);if(n!==void 0)return r(n)}else if(l===`-simulate`||l===`-generate`){t.mode=l===`-generate`?`generate`:`simulate`;let e=s();if(e===void 0||![`stats=`,`file=`,`num=`,`sched`].some(t=>e.includes(t)))continue;n++;let i=e.split(`,`).some(e=>e.startsWith(`file=`));t.scheduler=e.split(`,`).includes(`sched=rl`)?`rl`:e.split(`,`).includes(`sched=rlaction`)?`rlaction`:`random`;for(let n of e.split(`,`).filter(e=>e.startsWith(`num=`))){let e=n.replace(`num=`,``);if(t.traceCount=yl(e,64),t.traceCount===void 0)return{kind:`uncaught`,error:`java.lang.NumberFormatException: For input string: "${e}"`,isTool:t.isTool}}if((t.traceCount??cl)===cl&&i)return r(`Error: You need to specify a 'num' argument when using the 'file' argument, for example: '"num=5,file=test.txt"'.`)}else if(l===`-suppressMessages`||l===`-messagesAsErrors`){let e=c();if(e===void 0)return r(`Error: ${l} requires a comma-separated list of message codes.`);let t=l===`-suppressMessages`?a:o;for(let n of _l(e,`,`)){let e=n.replace(/^[^!-\uffff]+|[^!-\uffff]+$/g,``),i=yl(e,32);if(i===void 0)return r(`Error: For input string: "${e}"`);let o=Number(i);if(gl(ll,o))t.tlc.push(o);else{if(!dl.has(o)&&!gl(ul,o))return r(`Error: unknown message code: ${o}`);if(t===a&&!dl.has(o))return r(`Error: code ${o} is an error and cannot be suppressed.`);t.sany.push(o)}}}else if(l===`-inv`){let e=c();if(e===void 0)return i();t.invariants.push({modules:[...new Set([...e.matchAll(/INSTANCE\s+(\w+)/g)].map(e=>e[1]))],expression:e})}else if(l===`-invlevel`){let e=c();if(e===void 0)return i();if(yl(e,32)===void 0)return r(`Error: An integer for -invlevel required. But encountered ${e}`);t.invariants.push({modules:[`TLC`,`Naturals`],expression:`LET _T == INSTANCE TLC _N == INSTANCE Naturals IN _N!<(_T!TLCGet("level"), ${e})`})}else if(l===`-debugger`){let e=s();e!==void 0&&[`port=`,`nosuspend`,`nohalt`,`suspend`,`halt`].some(t=>e.includes(t))&&n++}else if(l===`-generateSpecTE`)t.isTraceSpecForced=!0,s()===`nomonolith`&&n++;else if(l===`-noGenerateSpecTE`||l.toLowerCase()===`-note`)t.isTraceSpecDisabled=!0;else if(l===`-noGenerateSpecTEBin`||l.toLowerCase()===`-notebin`)t.isTraceBinaryDisabled=!0;else{if(l===`-help`||l===`-h`)return`usage`;if(l===`-dump`){let i=s();if(i?.startsWith(`class,`))return r(`Trying to instantiate a custom IStateWriter implementation ${i.replaceAll(`class,`,``)}.`);let a=i?.startsWith(`dot`)&&n+1<e.length?2:1;if(t.dump=e.slice(n,n+a),n+=a,t.dump.length===0)return r(`Error: A file name for dumping states required.`)}else if(Object.hasOwn(El,l.toLowerCase())){let i=El[l.toLowerCase()];if(n+1>=e.length)return r(i.missing);let a=c(),o=c();if(!Object.hasOwn(i.formats,a.toLowerCase()))return r(`Error: Unknown format ${a} given to ${i.name}.`);let s=i.formats[a.toLowerCase()];t.moduleOperators.push(...s.operators.map(e=>({...e,module:s.module,constants:{[s.constant]:o}})))}else if(l.toLowerCase()===`-postcondition`){let e=c();if(e===void 0)return r(`Error: Module!Operator for postCondition required.`);if(!e.includes(`!`))return r(`Module!Operator for postCondition required. Encountered: ${e}`);let n=_l(e,`!`);if(n.length!==2)return r(`Module!Operator for postCondition must be of the form module!operator. Encountered: ${e}`);if(n[0]===``)return r(`Module name for postCondition required. Encountered: ${e}`);if(n[0].includes(`.`))return r(`Module name for postCondition must not contain a dot. Encountered: ${n[0]}`);if(n[1].includes(`.`))return r(`Operator name for postCondition must not contain a dot. Encountered: ${n[1]}`);t.moduleOperators.push({kind:`postcondition`,module:n[0],operator:n[1]})}else{if(l.startsWith(`-`))return r(`Error: unrecognized option: ${l}`);t.specs.push(l)}}}if(!t.isWarningEnabled&&a.tlc.length+a.sany.length>0)return r(`Error: -nowarning already suppresses all warnings, making -suppressMessages redundant. Remove -nowarning to suppress only the specified messages, or remove -suppressMessages to suppress all warnings.`);let l=vl(a.tlc,o.tlc),u=l.length>0?l.map(String):vl(a.sany,o.sany).map(e=>dl.get(e)??String(e));return u.length>0?r(`Error: The following codes were set to both -suppressMessages and -messagesAsErrors: [${u.join(`, `)}]`):(t.suppressedCodes=[...a.tlc,...a.sany],t.errorCodes=[...o.tlc,...o.sany],t)},Ol=(e,t)=>e.print(M.computingInitProgress,F.none,`Computed ${t} initial states...`),kl=(e,t)=>e===`invariant-violation`?{code:M.invariantViolatedInitial,text:`Invariant ${t} is violated by the initial state:`}:{code:M.propertyViolatedInitial,text:`Property ${t} is violated by the initial state:`},Al=(e,t)=>t?.forEach(t=>{if(typeof t==`string`)return console.log(t);if(t.kind===`initial-states-progress`)return Ol(e,t.count);let n=kl(t.status,t.name);e.print(n.code,F.error,`${n.text}\n${j(t.state)}`)}),jl={code:M.behaviorUpToThisPoint,text:`The behavior up to this point is:`},Ml={code:M.counterExample,text:`The following behavior constitutes a counter-example:
43
- `},Nl={"error-trace":{heading:jl,isLastDiffed:!1},simulation:{heading:jl,isLastDiffed:!0},"counter-example":{heading:Ml,isLastDiffed:!0}},Pl=(e,t,n)=>{let r=Nl[n].heading,i=n===`counter-example`&&e.version===`1.7.4`;t.length>0&&e.print(r.code,F.error,r.text);try{t.forEach((r,a)=>{(a>0||i)&&Al(e,r.output);let o=e.isDiffTrace&&a>0&&(Nl[n].isLastDiffed||a<t.length-1);e.print(M.statePrint2,F.state,`${a+1}: <${r.label??r.action??`Initial predicate`}>\n${j(r.state,o?t[a-1].state:void 0)}`)})}catch(t){if(!(t instanceof x))throw t;e.print(M.general,F.error,t.message)}},Fl=(e,t)=>t===`1.7.4`||e.length===0?`Temporal properties were violated.
44
- `:e.length===1?`Temporal property ${e[0]} was violated.\n`:`Temporal properties ${e.slice(0,-1).join(`, `)}${e.length>2?`,`:``} and ${e[e.length-1]} were violated.\n`,Il=e=>e.filter((t,n)=>t!==e[n-1]).map((e,t)=>`${t}) ${oe(e)}\n`).toReversed().join(``),Ll=e=>{if(e.length===0)return` The error call stack is empty.
45
- `;let t=[];return e.forEach((n,r)=>{let i=n.location.range;n!==e[r-1]&&i&&t.push(`${t.length}. Line ${i.start.line}, column ${i.start.column} to line ${i.end.line}, column ${i.end.column} in ${i.module}\n`)}),`${t.join(``)}\n`},Rl=(e,t)=>{let n=t.generated,r=t.distinct,i=me(/* @__PURE__ */ new Date);n===r?e.print(M.initGenerated1,F.none,`Finished computing initial states: ${r} distinct state${r===1?``:`s`} generated at ${i}.`):e.print(M.initGenerated2,F.none,`Finished computing initial states: ${n} state${n===1?``:`s`} generated, with ${r} of them distinct at ${i}.`)},zl=(e,t,n)=>{let r=Math.max(Date.now()-(n??0),1)/6e4,i=e=>e.toLocaleString(`en-US`),a=(e,t)=>n===void 0?``:` (${i(Math.floor(e/r))} ${t}/min)`;e.print(M.progress,F.none,`Progress(${Math.max(t.depth,1)}) at ${me(/* @__PURE__ */ new Date)}: ${i(t.generatedStates)} states generated${a(t.generatedStates,`s`)}, ${i(t.distinctStates)} distinct states found${a(t.distinctStates,`ds`)}, ${i(t.queuedStates)} states left on queue.`)},Bl={init:M.coverageInit,next:M.coverageNext,invariant:M.coverageProperty,implied:M.coverageProperty,constraint:M.coverageConstraint},Vl=(e,t,n)=>{let r=(t,n)=>e.print(t,F.none,n);r(M.coverageStart,`The coverage statistics at ${me(/* @__PURE__ */ new Date)} (see https://explain.tlapl.us/module-coverage-statistics for how to interpret the following statistics).`),t.variables.forEach(e=>r(M.coverageVariable,`<${e.label}>: ${e.distinct}`)),t.relations.forEach(e=>{let t=Bl[e.kind];r(t,t===M.coverageProperty?`<${e.label}>`:`<${e.label}>: ${e.distinct}:${e.generated}`),e.expressions.forEach(e=>{let t=` ${`|`.repeat(e.depth)}${e.location}`;e.cost>0?r(M.coverageValueCost,`${t}: ${e.count}:${e.cost}`):r(M.coverageValue,`${t}: ${e.count}`)})}),Date.now()-n>3e5?r(M.coverageEndOverhead,`End of statistics (please note that for performance reasons large models
46
- are best checked with coverage and cost statistics disabled).`):r(M.coverageEnd,`End of statistics.`)},Hl=(e,t)=>xt(e,`${t}.class`),Ul=(e,t,n,r)=>{let i=e.print;switch(t.kind){case`parsed`:n.isParsed=!0,e.isTool&&i(M.sanyFinished,F.none,`SANY finished.`),i(M.starting,F.none,`Starting... (${me(/* @__PURE__ */ new Date)})`);return;case`constant-level-invariant`:if(e.version===`1.7.4`)return;i(M.constantLevelInvariant,F.warning,`The invariant ${t.name} is a constant-level formula (i.e., it contains no variables, primes, or temporal operators) and evaluates to TRUE. To assert constant-level formulas in your spec, use ASSUME ConstInv. If you optionally want to give the assumption a name, write ASSUME YourAssumption == ConstInv instead. See https://explain.tlapl.us/assumptions-and-invariants for additional details.`);return;case`state-level-property`:if(e.version===`1.7.4`)return;i(M.stateLevelProperty,F.warning,`The formula ${t.name} is a state-level formula, but it was used as a PROPERTY (or PROPERTIES), where a temporal formula is typically expected. State-level formulas used as PROPERTY or PROPERTIES are only checked in the initial state. To verify that the formula ${t.name} holds in all states of every behavior, use INVARIANT ${t.name} instead. Alternatively, applying the "always" temporal operator ([]) to the state-level formula ${t.name} changes it into a temporal formula, asserting that ${t.name} holds in all states of every behavior. See https://explain.tlapl.us/invariants-and-properties for additional details.`);return;case`liveness-initializing`:t.isSymmetric&&i(M.livenessSymmetry,F.warning,`Declaring symmetry during liveness checking is dangerous. It might cause TLC to miss violations of the stated liveness properties. Please check liveness without symmetry defined.`),t.isConstrained&&e.version===`1.7.4`&&i(M.livenessConstraints,F.warning,`Declaring state or action constraints during liveness checking is dangerous: Please read section 14.3.5 on page 247 of Specifying Systems (https://lamport.azurewebsites.net/tla/book.html) and optionally the discussion at https://discuss.tlapl.us/msg00994.html for more details.`);return;case`liveness-prepared`:i(M.temporalBranches,F.none,`Implied-temporal checking--satisfiability problem has ${t.branches} branches.`);return;case`java-override`:{let e=Lt(St(Hl(r,t.module))).href;i(t.isMatched?M.javaOverrideLoaded:M.javaOverrideMismatch,t.isMatched?F.none:F.warning,`${t.isMatched?`Loading`:`Failed to match`} ${t.operator} operator override from ${e.replace(`file:///`,`file:/`)} with signature: <Java Method: ${t.signature}>.`);return}case`initial-states-started`:i(M.computingInit,F.none,`Computing initial states...`);return;case`initial-states-progress`:Ol(e,t.count);return;case`initial-states-computed`:Rl(e,t.initialStates);return;case`progress`:zl(e,t.statistics,n.startTime),t.statistics.coverage&&Vl(e,t.statistics.coverage,n.startTime);return;case`liveness-started`:{n.livenessStartTime=Date.now(),t.isComplete&&zl(e,t.statistics);let r=t.branches>1?`${t.branches} branches of `:``,a=t.branches*t.states;i(M.checkingTemporal,F.none,`Checking ${r}temporal properties for the ${t.isComplete?`complete`:`current`} state space with ${a} total distinct states at (${me(/* @__PURE__ */ new Date)})`);return}case`liveness-finished`:Wl(e,n);return;case`sequential-fallback`:process.stderr.write(`Warning: the search ordered the string ${JSON.stringify(t.string)} against another string it created, so tla-ts checks the model again with one worker. Workers don't agree on the order of strings the search creates.\n`);return;case`warning`:i(t.code,F.warning,t.text);return;case`violation`:Kl(t.status,t.violation,e)}},Wl=(e,t)=>{t.livenessStartTime!==void 0&&(e.print(M.checkingTemporalEnd,F.none,`Finished checking temporal properties in ${P(Date.now()-t.livenessStartTime)} at ${me(/* @__PURE__ */ new Date)}`),t.livenessStartTime=void 0)},Gl=(e,t)=>{t&&(t.counts&&console.log(t.counts),e.print(t.code,F.error,Be(t.code,t.message,e.isTool)))},Kl=(e,t,n)=>{let r=n.print,i=t.name,a=t.loopStart,o=a===void 0&&t.trace.length===1&&(e===`invariant-violation`||e===`liveness-violation`),s={code:M.temporalPropertyViolated,text:Fl(t.properties??[i],n.version)},c={success:void 0,error:void 0,"assumption-violation":t.message?{code:M.assumptionEvaluationError,text:Be(M.assumptionEvaluationError,`Evaluating assumption ${i} failed.\n${t.message}`,n.isTool)}:{code:M.assumptionFalse,text:`Assumption ${i} is false.`},deadlock:{code:M.deadlockReached,text:`Deadlock reached.`},"invariant-violation":o?kl(`invariant-violation`,i):{code:M.invariantViolatedBehavior,text:`Invariant ${i} is violated.`},"property-violation":s,"liveness-violation":a===void 0?o?kl(`liveness-violation`,i):{code:M.actionPropertyViolatedBehavior,text:`Action property ${i} is violated.`}:s,"postcondition-violation":{code:t.postcondition?.code??M.general,text:Be(t.postcondition?.code??M.general,t.message??`Postcondition ${i} is false.`,n.isTool)}}[e],l=e===`property-violation`,u=a!==void 0&&!l,d=l||u;if(d&&n.version!==`1.7.4`&&Al(n,t.trace[0]?.output),t.counts&&console.log(t.counts),c){let e=o?`${c.text}\n${j(t.trace[0].state)}`:c.text;r(c.code,F.error,e)}if(o||(d||Al(n,t.trace[0]?.output),Pl(n,t.trace,d?`counter-example`:`error-trace`)),Al(n,t.traceOutput),u){let e=t.loopLabel;a===t.trace.length-1?r(M.statePrint3,F.state,`${a+2}: Stuttering`):n.isTool?r(M.backToState,F.state,`${a+1}: Back to state${e?`: <${e}>\n`:``}`):console.log(`Back to state ${a+1}${e?`: <${e}>\n`:``}`)}t.warning&&n.version!==`1.7.4`&&r(t.warning.code,F.warning,t.warning.text);let f=t.unwitnessed??(e===`postcondition-violation`?void 0:t.postcondition);return Al(n,t.postconditionOutput),Gl(n,f),!o&&e!==`assumption-violation`},ql=(e,t)=>e.print(M.nestedExpression,F.error,`The error occurred when TLC was evaluating the nested\nexpressions at the following positions:\n${Ll(t)}`),Jl=(e,t,n)=>e.print(M.success,F.none,[`Model checking completed. No error has been found.`,` Estimates of the probability that TLC did not check all reachable states`,` because two distinct states had the same fingerprint:`,` calculated (optimistic): val = ${ze(t)}`,...n===void 0?[]:[` based on the actual fingerprints: val = ${ze(n)}`]].join(`
47
- `)),Yl=(e,t)=>{switch(t.kind){case`message`:e.print(t.code,t.isError?F.error:F.none,e.isTool?t.toolMessage:t.message);return;case`behavior`:t.states.forEach((n,r)=>t.isInvariant?e.print(M.statePrint2,F.state,`${r+1}: \n${j(n,e.isDiffTrace?t.states[r-1]:void 0)}`):e.print(M.statePrint1,F.state,`${r+1}:\n${j(n)}`));return;case`nested-expressions`:ql(e,t.callStack);return;case`success`:Jl(e,t.optimistic,t.actual)}},Xl=(e,t,n)=>{let r=t.print;if(e.failure){let n=e.failure,i=t.isTool?n.toolMessage:n.message,a=()=>{let e=n.fingerprint;if(e){let i=n.callStack?.length&&t.version!==`1.7.4`?Ll(n.callStack):Il(e.sources);r(M.fingerprintFailed,F.error,`TLC was unable to fingerprint.\n\nFingerprint Stack Trace:\n${i}\nReason:\n${De(e.reason,t.isTool)}`)}else n.callStack&&ql(t,n.callStack)};n.isCallStackFirst&&a();let o=n.initialState&&(()=>{try{return`While working on the initial state:\n${j(n.initialState)}`}catch(e){throw e instanceof y?v(new y(`${s}${e.message}`),T.error):e}})();r(o?M.initialState:n.code,F.error,o?`${i}\n${o}`:i),Al(t,n.trace[0]?.output),Pl(t,n.trace,`error-trace`);let c=n.traceFailure;c&&r(c.code,F.error,t.isTool?c.toolMessage:c.message),Al(t,n.traceOutput),Gl(t,n.postcondition),n.isCallStackFirst||a()}else if(e.violation){if(!Kl(e.status,e.violation,t))return;let n=e.additionalViolation;n&&Kl(`property-violation`,n,t),e.liveCallStack&&ql(t,e.liveCallStack)}else e.status===`success`&&(Wl(t,n),Jl(t,Ne(e.distinctStates,e.generatedStates),e.fingerprintDistance===void 0?void 0:Ee(e.fingerprintDistance)));if(e.failure?.isWithoutStatistics)return;e.status!==`success`&&Wl(t,n),e.coverage&&Vl(t,e.coverage,n.startTime),t.isTool&&zl(t,e,n.startTime),r(M.stats,F.none,`${e.generatedStates} states generated, ${e.distinctStates} distinct states found, ${e.queuedStates} states left on queue.`);let i=t.version===`1.7.4`,a=i?e.outDegrees??e.violationOutDegrees:e.outDegrees;(!i||a)&&r(M.searchDepth,F.none,`The depth of the complete state graph search is ${i?Math.max(e.depth,1):e.depth}.`);let o=a&&Ve(a);o&&r(M.stateGraphOutdegree,F.none,o)},Zl=e=>e.print(M.version,F.none,`TLC2 Version ${sn} (rev: tla-ts)`),Ql=(e,t,n)=>{let r=N({isTool:e,version:t});return Zl(r),r.print(M.commandLineError,F.error,`${n}\nUsage: java tlc2.TLC [-help] [-option] inputfile`),1},$l=(e,t)=>{let n=`${t.workers} worker${t.workers===1?``:`s`} on ${Bt()} cores with ${Math.floor(Wt().heap_size_limit/1024/1024)}MB heap and 64MB offheap memory [pid: ${process.pid}] (${Ut()} ${Vt()} ${zt()}, Node.js ${process.versions.node} ${process.arch.endsWith(`64`)?64:32}bit`;t.mode===`model-check`&&t.dfidDepth!==void 0?e.print(M.depthFirstModelChecking,F.none,`Running depth-first search Model-Checking with fp ${t.fingerprintIndex} and seed ${t.seed} with ${n}).`):t.mode===`model-check`?e.print(M.modelChecking,F.none,`Running breadth-first search Model-Checking with fp ${t.fingerprintIndex} and seed ${t.seed} with ${n}, MSBDiskFPSet, DiskStateQueue).`):e.print(M.simulating,F.none,`Running ${t.scheduler===`rl`?`RL`:`Random`} Simulation with seed ${t.seed} with ${n}).`)},eu=(e,t)=>{let n=e.print;switch(t.kind){case`message`:n(t.code,t.isError?F.error:F.none,e.isTool?t.toolMessage:t.message);return;case`behavior`:{let r=t.trace[t.trace.length-1];if(!t.isLastStateOnly){Pl(e,t.trace,`simulation`);return}n(M.errorState,F.none,`The error state is:
48
- `),n(M.statePrint1,F.state,`:\n${j(r.state)}`);return}case`progress`:{let r=t.statistics;if(e.isTool){tu(e,r);return}let i=r.levelM2/(r.traces+1);n(M.simulationProgress,F.none,`Progress: ${r.generatedStates} states checked, ${r.traces} traces generated (trace length: mean=${r.levelMean}, var(x)=${Math.round(i)}, sd=${Math.round(Math.sqrt(i))})`);return}case`summary`:e.isTool&&tu(e,t.statistics),n(M.simulationStats,F.none,`The number of states generated: ${t.statistics.generatedStates}\nSimulation using seed ${t.statistics.seed} and aril ${t.statistics.aril}`)}},tu=(e,t)=>e.print(M.simulationProgress,F.none,`Progress(${t.traces}) at ${me(/* @__PURE__ */ new Date)}: ${t.generatedStates} states generated, -1 distinct states found, -1 states left on queue.`),nu=[{name:`-checkpoint`,sampleValue:`minutes`,description:`interval between check point; defaults to 30`,isOptional:!0},{name:`-cleanup`,description:`clean up the states directory`,isOptional:!0},{name:`-config`,sampleValue:`file`,description:`provide the configuration file; defaults to SPEC.cfg`,isOptional:!0},{name:`-continue`,description:`continue running even when an invariant is violated; default
20
+ `),3}return Object.values(Tr).find(e=>T.includes(e))??w.success},zr=(1n<<63n)-1n,Br=1n<<16n,Vr=(e,t)=>{let n=e.map(e=>{let t=BigInt.asIntN(32,e);return t<0n?t:BigInt.asIntN(64,e)}),r=n.toSorted((e,t)=>e<t?-1:+(e>t)),i=r.slice(1).map((e,t)=>e-r[t]).filter(e=>e<=zr),a=/* @__PURE__ */ new Map;e.forEach((e,r)=>{let i=e&t-1n,o=a.get(i),s=n[r];o?(o.min=s<o.min?s:o.min,o.max=s>o.max?s:o.max):a.set(i,{min:s,max:s})});let o=[...a.values()].map(e=>e.max-e.min).filter(e=>e>zr).map(e=>e===zr+1n?-e:(1n<<64n)-e);return[...i,...o].reduce((e,t)=>t<e?t:e,zr)},Hr=(e,n)=>{let r=ge(n)?`tlc2.tool.EvalException`:`java.lang.RuntimeException`;return e===``?t(r):`TLC threw an unexpected exception.\nThis was probably caused by an error in the spec or model.\nThe error occurred when TLC was ${e}.\nThe exception was a ${r}\n: `},Ur=e=>{let t=e.onOutput,n=e.isTool??!1,r=e.isContinued??!1,a=nt(e),o=a.config,s=a.environment,c=s.runtime,u=a.search;if(!u)throw new g(`tla-ts can't search a specification without variables`);let d=(e,n,r=n,i=!0)=>t({kind:`message`,code:e,isError:i,message:n,toolMessage:r}),f=u.properties.liveness;if(f.length>0){e.onProgress?.({kind:`liveness-initializing`,isSymmetric:u.isSymmetric,isConstrained:u.isConstrained});let t=ee(()=>Re(()=>Ot(f,u.spec.temporals,s,{getFingerprint:()=>0,forEachActionSuccessors:()=>{}})))?.branches;t&&e.onProgress?.({kind:`liveness-prepared`,branches:t})}if((e.workers??1)!==1)return d(F.general,`Depth-First Iterative Deepening mode does not support multiple workers (https://github.com/tlaplus/tlaplus/issues/548). Please run TLC with a single worker.`),w.error;if(f.length>0)return d(F.general,`Depth-First Iterative Deepening mode does not support checking liveness properties (https://github.com/tlaplus/tlaplus/issues/548). Please check liveness properties in Breadth-First-Search mode.`),w.error;c.generatedStates=-1,c.distinctStates=-1,c.initialStates=-1,c.queueSize=-1,c.diameter=-1,c.isStarted=!0;let m=Ue(a.specification.assumptions,s,d);if(m!==void 0)return m;let h=a.getDescription(),_=h.actions,v=a.coverage,y=v&&dt(v,s,h);c.getSuccessorAction=(e,t)=>_.find(n=>mt(n.expression,e,s,n.scope).some(e=>e.state.every((e,n)=>Se(e,t[n]))));let b=/* @__PURE__ */ new Map,S={level:1,leveled:0,buckets:Br},C=(e,t)=>{let n=b.get(e);return n===void 0?(BigInt(b.size)>=S.buckets*20n&&(S.buckets*=2n),b.set(e,S.level<<2|S.leveled|t),0):(b.set(e,n|t),n)},T=e=>b.get(e)??0,E=e=>(e&2)===S.leveled||(e&1)==1,D=e=>e===0||e>>>2===S.level,k=0,A={isDone:!1,errorCode:0,continuedCode:0,isKeepingCallStack:!1,errorEntry:void 0,stopCode:`searching`,isMoreLevel:!1},M=(e,t,n)=>!r&&A.isDone?!1:(A.errorEntry=e,A.errorCode=n,A.isDone=!0,A.isKeepingCallStack=t,A.stopCode=`error`,!0),ne=e=>u.toRecord(e.map(e=>e??rt(`null`))),re=()=>{let e=_.length>0?a.getCoverage():void 0;e&&t({kind:`coverage`,coverage:e});let r=`${k} states generated, ${b.size} distinct states found`;n&&d(F.depthFirstProgress,`Progress: ${r}.`,`Progress(-1) at ${je(/* @__PURE__ */ new Date)}: ${r}, -1 states left on queue.`,!1),d(F.depthFirstStats,`${r}.`,void 0,!1)},ie=()=>t({kind:`success`,optimistic:ht(b.size,k),actual:b.size===0&&k===0?0:ot(Vr([...b.keys()],S.buckets))}),oe=/* @__PURE__ */ new WeakMap,se;c.getLevel=e=>oe.get(e)??0,c.getCurrentState=()=>se;let ce=[],le,ue=()=>{let e=[],t=t=>(e.push(t),!1),i=u.spec.init;y?Ge(y.inits,s,t,e=>t([...e])):i&&te(i,s,t,u.spec.scope,t),k=e.length;for(let t of e){if(!t.every(e=>e!==void 0))return d(F.initialStateIncomplete,`State is not completely specified by the initial predicate:\n${ae(ne(t))}`),F.initialStateIncomplete;le=t,oe.set(t,1);let e=u.satisfiesConstraints(t),i=e?c.getFingerprint(t):0n,a=e?C(i,0):0;if(e&&a===0&&ce.push({state:t,fingerprint:i}),a!==0)continue;let s=()=>o.alias===void 0?u.toRecord(t):u.evaluateAlias(o.alias,t,t,n),l=e=>d(F.invariantViolatedInitial,`Invariant ${e} is violated by the initial state:\n${ae(s())}`);r&&u.forEachViolatedInvariant(t,e=>{l(e.name),A.continuedCode=F.invariantViolatedInitial});let f=r?void 0:u.findViolatedInvariant(t);if(f)return l(f.name),F.invariantViolatedInitial;let p=u.findFailedInitialPredicate(t);if(p)return d(F.propertyViolatedInitial,`Property ${p.name} is violated by the initial state:\n${ae(s())}`),F.propertyViolatedInitial}return 0},de=[],fe,pe=0,me=e=>{if(pe++,fe)return!1;if(de.length===lt())throw new l;return de.push(e),!1},N=e=>me(e.state),ge=e=>(pe++,fe??=[...e],!0),_e=(e,t)=>{let n=_[e],r=y?.actions[e];return de=[],fe=void 0,pe=0,v&&r?(St(r,r.node,t,s,me,ge),v.primary[r.node]+=pe):et(n.expression,t,s,N,n.scope,void 0,void 0,ge),{successors:de,incomplete:fe,count:pe}},ye=(e,t,n)=>{try{let r=n?u.findViolatedInvariant(t,e):void 0;if(r)return{code:F.invariantViolatedBehavior,text:`Invariant ${r.name} is violated.`,isViolated:!0};let i=u.findViolatedActionProperty(e,t);return i&&{code:F.actionPropertyViolatedBehavior,text:`Action property ${i.name} is violated.`,isViolated:!0}}catch(e){if(!(e instanceof j)||!Be(e))throw e;return{code:ve(e,!0).code,text:e.message.slice(0,e.message.indexOf(`
21
+ `)),isViolated:!1}}},be=[],P=[],xe=(e,n,r,i,a)=>{d(e,n,r),d(F.behaviorUpToThisPoint,`The behavior up to this point is:`);let o=[...be.slice(0,i+1).map(e=>e.state),...a?[a]:[]];t({kind:`behavior`,states:o.map(ne),isInvariant:e===F.invariantViolatedBehavior})},Ce=(t,n,a)=>{let d=be[t],f=d.state,p=!0,m=!0,h=!0,g,v=(e,n,r)=>(M(d,r,e)&&xe(e,n,n,t,g),h);se=f;try{for(let n=0;n<_.length;n++){let i=_[n],o=_e(n,f),d=o.incomplete;k+=o.count,p&&=o.count===0;for(let e of o.successors){g=e,oe.set(e,t+2);let n=u.satisfiesConstraints(e,f)&&u.satisfiesActionConstraints(f,e),i=n?c.getFingerprint(e):0n,o=n?C(i,0):0;if(n&&(m&&=(o&1)==1,h&&=!D(o),!E(o))){if(a.length===lt())throw new l;a.push({state:e,fingerprint:i})}let s=ye(f,e,o===0);if(s?.isViolated&&r)xe(s.code,s.text,s.text,t,e),A.continuedCode=s.code;else if(s)return v(s.code,s.text,!s.isViolated)}if(d)return g=d,v(F.incompleteSuccessor,it(s.variables.filter((e,t)=>d[t]===void 0),i.name,_.length,e.version),!1);g=void 0}return p&&o.checkDeadlock?v(F.deadlockReached,`Deadlock reached.`,!1):((m||n&&h)&&C(d.fingerprint,1),h)}catch(e){let n=O(e)?new i:e;if(!(n instanceof j))throw e;let r=n instanceof i;if(M(d,!r,r?F.stackOverflow:F.general)){let e=Hr(`computing the set of next states`,n);xe(r?F.stackOverflow:F.general,r?n.message:`${e}${n.message}`,r?n.message:`${e}${he(n.message,!0)}`,t,g)}throw n}},we=(e,t)=>{for(;e.length>0;){let n=T(e[0].fingerprint);if(!E(n)&&t<n>>>2)return!0;e[0]=e[e.length-1],e.pop()}return!1},Te=e=>{let t=[...ce];A.stopCode=`searching`,A.isMoreLevel=!1;let n=0;try{for(;A.stopCode===`searching`;){for(;t.length>0&&E(T(t[0].fingerprint));)t[0]=t[t.length-1],t.pop();if(t.length===0){A.stopCode=`done`;return}be[0]=t[0],P[0]=[],n=0;let r=e<2,i=Ce(0,r,P[0]);for(A.isMoreLevel||=!i,n=1;!r;){if(!we(P[n-1],n)){let e=be[n-1];if(b.set(e.fingerprint,T(e.fingerprint)&-3|S.leveled),n===1)break;n--;continue}be[n]=P[n-1][0],P[n]=[];let t=n>=e-1,r=Ce(n,t,P[n]);if(A.isMoreLevel||=!r,n++,t)break}}}catch(e){if(!(e instanceof j))throw e;if(A.stopCode=`error`,M(be[n],!0,F.general)){let t=Hr(``,e);d(F.general,`${t}${e.message}`,`${t}${he(e.message,!0)}`)}}},Ee=e=>{let n=Fe(s);try{if(_.every(t=>{let r=[];return gt([t],e.state,n,e=>r.push(e)),k+=r.length,r.every(t=>t.every(e=>e!==void 0)&&u.checkReplayedSuccessor(e.state,t,n,()=>C(c.getFingerprint(t),0)===0))}))return}catch(e){if(!(e instanceof j)&&!O(e))throw e}t({kind:`nested-expressions`,callStack:n.callStack?.expressions??[]})},De=e=>{re();let t=[e,A.errorCode,A.continuedCode].find(e=>e!==0);return t===void 0?w.success:x(t)},Oe=()=>{try{return{code:ue(),error:void 0}}catch(e){let t=O(e)?new i:e;if(!(t instanceof j))throw e;return{code:0,error:t}}},I=Oe();if(I.error){let t=I.error,n=Be(t)&&t.cause instanceof j?t.cause:t,r=le,i=r?``:Hr(`computing initial states`,n),a=r?`\nWhile working on the initial state:\n${ae(ne(r))}`:``;d(r?F.initialState:F.general,`${i}${n.message}${a}`,`${i}${he(n.message,!0)}${a}`),k=0,ce.length=0;let o=Oe().error!==void 0;return o&&d(F.nestedExpression,`The error occurred when TLC was evaluating the nested\nexpressions at the following positions:\ntlc2.tool.impl.FastTool@${(Number(BigInt.asUintN(28,Tt([e.source])))|268435456).toString(16)}`),re(),o?w.specEvaluationFailure:p(n)}if(I.code!==0)return x(I.code);if(d(F.depthFirstInitGenerated,`Finished computing initial states: ${k} states generated, with ${ce.length} of them distinct.`,void 0,!1),_.length===0)return ie(),De(0);let ke=!1,Ae=F.general;for(let t=2;t<=e.maxDepth;t++){if(ke){let e=A.errorEntry;!e&&A.continuedCode===0&&(Ae=0,ie()),e&&A.isKeepingCallStack&&Ee(e);break}d(F.depthFirstLevel,`Starting level ${t}: ${k} states generated, ${b.size} distinct states found.`,void 0,!1),S.level++,S.leveled=2-S.leveled;let e=pt(c.seed);if(c.getRandom=()=>e,Te(t),A.isDone=!1,Ae=A.isKeepingCallStack?0:A.errorCode,Ae!==0)return De(Ae);ke=A.stopCode===`error`||!A.isMoreLevel}return De(Ae)},Wr=/* @__PURE__ */ new Set([F.invariantEvaluationFailed,F.actionPropertyEvaluationFailed,F.incompleteSuccessor]),Gr=2147483647,Kr=()=>!1,qr=(e,t,n)=>{for(let r=0;r<n.length;r++){let i=n[r];if(!_t(be,Kr,e[i],t[i]))return!1}return!0},Jr=(e,t)=>{let n=[];for(let r=e;r;r=r.predecessor){let e=r.predecessor;e&&qr(r.state,e.state,t)||n.unshift(r)}return n.forEach((e,t)=>{e.predecessor=n[t-1],e.level=t+1}),n},Yr=(e,t,n,r,i)=>{let a=t.map(()=>/* @__PURE__ */ new Map),o=t=>e===`rlaction`?t.action:r(t.state),s=e=>i(e.predecessor?.state,e.state,-10);return{getNextActionIndex:r=>{if(e===`random`)return Math.floor(n.nextDouble()*t.length);let i=o(r);a.forEach(e=>{e.has(i)||e.set(i,0)});let s=a.map(e=>Math.exp(e.get(i)??0)),c=s.reduce((e,t)=>e+t,0),l=s.map((e,t)=>({index:t,weight:e/c})).sort((e,t)=>t.weight-e.weight),u=n.nextDouble(),d=0;return(l.find((e,t)=>(d=t===0?e.weight:d+e.weight,d>=u))??l[l.length-1]).index},markDisabled:(t,n)=>{e!==`random`&&(e===`rlaction`&&s(n),a[t].set(o(n),-Number.MAX_VALUE))},learnTrace:e=>{for(let n=e;n.predecessor;n=n.predecessor){let e=o(n),r=a.reduce((t,n)=>Math.max(t,n.get(e)??-Number.MAX_VALUE),-Number.MAX_VALUE),i=a[t.indexOf(n.action)],c=o(n.predecessor);i.set(c,.7*(i.get(c)??0)+.3*(s(n)+.7*r))}}}},Xr=e=>{let t=e.onSimulation,r=nt(e),i=r.config,a=r.specification,o=r.environment,s=o.runtime,u=r.search,d=e.seed??0n,f=e.traceDepth===-1?Gr:e.traceDepth,p=e.traceCount??(1n<<63n)-1n,m=pt(d);for(let t=0n;t<e.aril;t++)m.nextDouble();let h=pt(m.nextLong()),_={generatedStates:0,traces:0,levelMean:0,levelM2:0,seed:d,aril:e.aril},v=(e,n,r=n,i=!0)=>t({kind:`message`,code:e,isError:i,message:n,toolMessage:r}),y=()=>{let e=r.getCoverage();e&&t({kind:`coverage`,coverage:e})},b=()=>{y(),t({kind:`summary`,statistics:{..._}})},S=/* @__PURE__ */ new WeakMap,C=r.getDescription(),T=C.inits,D=C.actions,ee=r.coverage,O=ee&&dt(ee,o,C),k=0,M=0,ne;if(s.getSuccessorAction=()=>ne,s.getLevel=e=>S.get(e)?.level??0,s.getSimulationValue=(t,r)=>{let a=r&&S.get(r);switch(t){case`diameter`:return M===0?0:k+1;case`generated`:case`distinct`:case`queue`:throw new n(`TLCGet(${t}) was undefined.`);case`action`:return a&&st(a.action);case`config`:return vt([[`mode`,e.isGenerating?`generate`:`simulate`],[`depth`,f===Gr?-1:f],[`traces`,Number(BigInt.asIntN(32,p))],[`deadlock`,i.checkDeadlock],[`seed`,String(d)],[`aril`,String(e.aril)],[`worker`,1],[`install`,`unknown`],[`sched`,e.scheduler]]);case`stats`:{let e=/* @__PURE__ */ new Map;for(let t=a;t&&t.level>1;t=t.predecessor)e.set(t.action.name,(e.get(t.action.name)??0)+1);let t=Ee([...e.keys()]).map(t=>[t,e.get(t)??0]);return vt([[`traces`,_.traces],[`duration`,Math.floor((Date.now()-s.startedAt)/1e3)],[`generated`,_.generatedStates],[`behavior`,vt([[`actions`,vt(t)],[`id`,M]])],[`worker`,0],[`distinct`,-1],[`distinctvalues`,-1],[`retries`,-1],[`actions`,We([])],[`levelmean`,_.levelMean],[`levelvariance`,Math.round(_.levelM2/(_.traces+1))]])}}},s.isStarted=!0,!u)throw new g(`tla-ts can't simulate a specification without variables`);s.getBehavior=e=>{let t=S.get(e);return t?Jr(t,u.getTlcOrder()).map(e=>e.state):[e]};let re=t=>{let n=u.findPostconditionViolation(t);if(n)return n.counts!==void 0&&(e.onPrint??console.log)(n.counts),v(n.code,n.message,Ne(n.code,n.message,!0)),n},ie=E(()=>Re(()=>ke(u.properties.liveness,u.spec.temporals,o))),oe=ie?.solutions.length;oe&&e.onProgress?.({kind:`liveness-prepared`,branches:oe});let ce=Ue(a.assumptions,o,v);if(ce!==void 0)return ce;let le=T[T.length-1],de=(e,t,n)=>{let r={state:e,action:t,predecessor:n,level:(n?.level??0)+1};return S.set(e,r),r},fe=e=>u.toRecord(e.map(e=>e??rt(`null`))),me=t=>t.map((n,r)=>{let a=t[r+1]??n;return{action:n.action.name,label:se(n.action,e.version,n.level===1),state:i.alias===void 0?fe(n.state):u.evaluateAlias(i.alias,n.incomplete??n.state,a.incomplete??a.state,e.isTool??!1)}}),N=(e,t=me(e),n)=>tt(t.map(e=>e.state),e.slice(1).map(e=>st(e.action)),n),_e=e=>tt([fe(e.state)],[],void 0),ye=[],be=e=>e.every(e=>e!==void 0),P=[],xe=(e,t)=>{let n=Zr(e);if(!t)return v(F.general,`${Qr(n)}${n.message}`,`${Qr(n)}${he(n.message,!0)}`),b(),w.error;let r=ve(n,!1),i=`While working on the initial state:\n${ae(fe(t))}`;return v(F.initialState,`${r.message}\n${i}`,`${r.toolMessage}\n${i}`),b(),x(F.initialState)},Se=u.spec.init,Ce=e=>{if(P.length===lt())throw new l;return P.push(e),!1};try{O?Ge(O.inits,o,Ce,e=>Ce([...e])):Se&&te(Se,o,Ce,u.spec.scope,Ce)}catch(e){return xe(e,void 0)}_.generatedStates=P.length,v(F.computingInitProgress,`Computed ${P.length} initial states...`,void 0,!1);let we=[];for(let e of P){if(!be(e))return v(F.initialStateIncomplete,`State is not completely specified by the initial predicate:\n${ae(fe(e))}`),w.error;try{let t=de(e,le,void 0),n=u.findViolatedInvariant(e);if(n){let e=me([t])[0].state;return v(F.invariantViolatedInitial,`Invariant ${n.name} is violated by the initial state:\n${ae(e)}`),s.counterExample=_e(t),re(!0),w.safetyViolation}we.push(t),u.satisfiesConstraints(e)&&(u.trackStatePossible(e),ye.push(t))}catch(t){return xe(t,e)}}if(P.length===0)return v(F.noInitialStates,`There is no state satisfying the initial state predicate.`),w.error;if(ye.length===0)return v(F.noInitialStatesInModel,`There is no state satisfying the initial state predicate and the state-constraint(s).`),w.error;for(let e of we)try{let t=u.findFailedInitialPredicate(e.state);if(t){let n=me([e])[0].state;return v(F.propertyViolatedInitial,`Property ${t.name} is violated by the initial state:\n${ae(n)}`),s.counterExample=_e(e),re(!0),w.livenessViolation}}catch(t){return xe(t,e.state)}v(F.initGenerated1,`Finished computing initial states: ${ye.length} distinct state generated at ${je(/* @__PURE__ */ new Date)}.`,void 0,!1),ye.forEach(e=>e.state.forEach(ue));let Te=(e,t,n)=>({code:e,message:t,toolMessage:t,node:n,isException:!1,isSummarized:!0}),De=(t,n)=>{let r=D[n],i=O?.actions[n],a=[],c;s.deferred=void 0,ne=r;let d=e=>{let n=de(e.state,r,t);n.deferred=s.deferred,s.deferred=void 0,_.generatedStates++;try{let e=u.findViolatedInvariant(n.state,t.state);if(e)return c=Te(F.invariantViolatedBehavior,`Invariant ${e.name} is violated.`,n),!0;let r=u.findViolatedActionProperty(t.state,n.state);if(r)return c=Te(F.actionPropertyViolatedBehavior,`Action property ${r.name} is violated.`,n),!0}catch(e){if(!(e instanceof j)||!Be(e))throw e;let t=ve(e,!0);return c={...Te(t.code,t.message,n),toolMessage:t.toolMessage},!0}if(!u.satisfiesConstraints(n.state,t.state)||(u.trackStatePossible(n.state),!u.satisfiesActionConstraints(t.state,n.state)))return!1;if(u.trackActionPossible(t.state,n.state),a.length===lt())throw new l;return ee&&i&&ee.secondary[i.node]++,a.push(n),!1};try{ee&&i&&!e.isGenerating?Ke(ee,i,t.state,o,e=>{if(d({state:e,action:r.name}))throw Je}):et(r.expression,t.state,o,ee&&i?e=>(ee.primary[i.node]++,d(e)):d,r.scope,e.isGenerating?h:void 0)}catch(n){if(n===Je)return{successors:a,error:c};if(!(n instanceof A))throw n;let i=de(n.state.map(e=>e??rt(`null`)),r,t);i.incomplete=n.state;let o=it(n.variables,r.name,D.length,e.version);return{successors:a,error:Te(F.incompleteSuccessor,o,i)}}return{successors:a,error:c}},Oe=ye[0],I=Yr(e.scheduler,D,h,s.getFingerprint,u.getReward),Ae=t=>{if(!ie)return;let n=Jr(t,u.getTlcOrder());for(let e=0;e<n.length;e++)n[e].state.forEach(ue);let r=ie.findTraceViolation(n.map(e=>e.state),n.map(e=>s.getFingerprint(e.state)));if(!r)return;let i=r.backPosition===void 0?void 0:n[r.backPosition],a=r.positions.map(e=>n[e]),o=i?r.cyclePosition-1:a.length-1,c=me(a),l=i?st(i.action):Ze(void 0);return{...Te(F.temporalPropertyViolated,``,t),isException:!0,violation:{name:r.properties[0],properties:r.properties,trace:c,loopStart:o,loopLabel:i&&se(i.action,e.version,i.level===1)},failures:r.failures.map(e=>Pe(e,t)),counterExample:N(a,c,{start:o,action:l})}},Me=()=>{Oe=ye[Math.floor(h.nextDouble()*ye.length)];for(let e=0;e<f;e++){if(s.isStopped)return`stopped`;let e=I.getNextActionIndex(Oe),t=at(h),n=[];for(let r=0;r<D.length;r++){let r=De(Oe,e);if(r.error)return r.error;if(n=r.successors,n.length>0)break;I.markDisabled(e,Oe),e=(e+t)%D.length}if(n.length===0){if(i.checkDeadlock)return Te(F.deadlockReached,`Deadlock reached.`,Oe);break}Oe=n[Math.floor(h.nextDouble()*n.length)],Oe.deferred?.(Oe.state)}if(s.isStopped)return`stopped`;let t=Ae(Oe);if(t)return t;let n=Math.min(f,Oe.level),r=n-_.levelMean;_.levelMean+=Math.trunc(r/Math.max(_.traces,1)),_.levelM2+=r*(n-_.levelMean),e.scheduler===`rl`&&I.learnTrace(Oe)},Pe=(e,t)=>{let n=Zr(e),r=ge(n)?void 0:pe(n.message);if(r)return{code:r.code,message:n.message,toolMessage:Ne(r.code,n.message,!0),node:t,isException:!0,isSummarized:!1};let i=Qr(n);return{code:F.general,message:`${i}${n.message}`,toolMessage:`${i}${he(n.message,!0)}`,node:t,isException:!0,isSummarized:i!==c}},Fe=pt(d);s.getRandom=()=>Fe;let Ie=[],Le=e.isContinued??!1;for(;;){_.traces++,M=_.traces;let t=(()=>{try{return Me()}catch(e){return Pe(e,Oe)}})();if(t===`stopped`||(k++,t&&Ie.push(t),t?.isException)||BigInt(k)>=p)break;if(t!==void 0&&(!Le||Wr.has(t.code))&&e.traceCount===void 0){_.traces++;break}}let ze=Ie.findIndex(e=>e.isException||!Le||Wr.has(e.code)),L=ze===-1?Ie:Ie.slice(0,ze+1);L.forEach(n=>{n.violation?(n.failures?.forEach(e=>v(e.code,e.message,e.toolMessage)),e.onProgress?.({kind:`violation`,status:`liveness-violation`,violation:n.violation}),b()):(v(n.code,n.message,n.toolMessage),t({kind:`behavior`,trace:me(Jr(n.node,u.getTlcOrder())),isLastStateOnly:f===Gr}),n.isSummarized&&b())});let Ve=L[L.length-1],He=Ve?x(Ve.code):w.success;Ve&&(s.counterExample=Ve.counterExample??N(Jr(Ve.node,u.getTlcOrder())));let qe=re(Ve!==void 0),Ye=qe?x(qe.code):w.success,Xe=Math.max(He,Ye);return t({kind:`progress`,statistics:{..._}}),e.coverage!==void 0&&e.coverage<=1&&y(),Xe===w.success&&b(),Xe},Zr=e=>{if(O(e))return new i;if(!(e instanceof j))throw e;return e},Qr=e=>ge(e)?a:c,$r={builtin:1,number:2,string:3,ident:4,added:5},ei=()=>({labelFlag:!1,labelRoot:`Lbl_`,fairnessOption:``,checkTermination:!1,specOption:!1,myspecOption:!1,inputVersionNumber:1903}),ti=e=>{let t=0,n=0,r=!1;for(let i of e)if(i===`.`)r=!0;else if(i<`0`||i>`9`||(t=10*t+Number(i),r&&(n+=1),n>3))return-1;return t*10**Math.max(0,3-n)},ni=[`unfair`,`wf`,`sf`],H=()=>({col:0,line:0,macroCol:0,macroLine:-1,lbl:``}),ri=e=>e.macroLine<0?`line ${e.line}, column ${e.col}`:`line ${e.line}, column ${e.col} of macro called at line ${e.macroLine}, column ${e.macroCol}`,ii=e=>{if(e.kind!==`LabeledStmt`)throw new b(`ClassCastException: ${e.kind}`);return e},ai=(e,t)=>{if(t<0||t>=e.length)throw new b(`ArrayIndexOutOfBoundsException: ${t}`);return e[t]},oi=(e,t,n)=>({string:e,column:t,type:n}),si=e=>e.type===$r.string?e.string.length+2:e.string.length,ci=(e=[])=>({tokens:e,anchorTokens:void 0,anchorTokCol:void 0}),li=e=>{for(;e.tokens.length>0&&e.tokens[0].length===0;)e.tokens.shift();for(;e.tokens.length>0&&e.tokens[e.tokens.length-1].length===0;)e.tokens.pop();let t=Math.min(999999,...e.tokens.filter(e=>e.length>0).map(e=>e[0].column));e.tokens.forEach(e=>e.forEach(e=>{e.column-=t}));let n=[],r=[];e.tokens.forEach((t,i)=>{if(r.push(0),n.push(void 0),t.length===0)return;let a=t[0].column,o=e.tokens.slice(0,i).findLast(e=>e.length>0&&e[0].column<=a);if(o===void 0)return;let s=o.findIndex((e,t)=>t>0&&e.column>a),c=o[(s===-1?o.length:s)-1];n[i]=c,r[i]=c.column}),e.anchorTokens=n,e.anchorTokCol=r},ui=e=>{let t=ci(e);return li(t),t},di=e=>{let t=e.anchorTokens,n=e.anchorTokCol;if(t===void 0||n===void 0)throw new b(`NullPointerException: TLAExpr.renormalize`);e.tokens.forEach((e,r)=>{let i=t[r];if(i===void 0)return;let a=i.column-n[r];if(n[r]=i.column,a<0)throw new D(`TLAExpr.renormalize() found anchor has moved to left.`);e.forEach(e=>{e.column+=a})})},fi=e=>ui(e.tokens.map(e=>e.map(e=>({...e})))),pi=(e,t,n)=>{let r=t.tokens.length;e.tokens.splice(0,0,...t.tokens.slice(0,r-1));let i=t.tokens[r-1],a=e.tokens[r-1],o=i[i.length-1],s=o.column+si(o)+n;a.forEach(e=>{e.column+=s}),a.splice(0,0,...i);let c=[...t.anchorTokens??[]],l=[...t.anchorTokCol??[]];for(let t=r;t<e.tokens.length;t++)c.push(e.anchorTokens?.[t-r+1]),l.push(e.anchorTokCol?.[t-r+1]??0);e.anchorTokens=c,e.anchorTokCol=l,di(e)},mi=e=>e.tokens.length===1&&e.tokens[0].length===1,hi=(e,t)=>ai(ai(e.tokens,t.line),t.item),gi=(e,t,n)=>{if(e.tokens.length<=t.line)throw new T(`TLAExpr.StepCoord called with line too big`);if(e.tokens[t.line].length<=t.item)throw new T(`TLAExpr.StepCoord called with col too big`);let r={line:t.line,item:t.item};for(let t=0;t<n;t++)if(r.item+=1,e.tokens[r.line].length===r.item){for(r.item=0,r.line+=1;r.line<e.tokens.length&&e.tokens[r.line].length===0;)r.line+=1;if(r.line===e.tokens.length)return}return r},_i=(e,t,n)=>{for(let r=e.tokens.length===0?void 0:{...n};r!==void 0;){let n=hi(e,r),i=n.type===$r.string;if(!i&&n.string===t)return r;let a=!i&&(n.string===`[`||n.string===`,`)?gi(e,r,2):void 0,o=a===void 0?void 0:hi(e,a),s=o!==void 0&&o.type!==$r.string&&[`:`,`|->`,`↦`].includes(o.string),c=i?1:n.string===`.`?2:s?3:1;r=gi(e,r,c)}},vi=(e,t,n,r)=>{let i=hi(e,n);if(mi(e)){let n=fi(t);e.tokens=n.tokens,e.anchorTokens=n.anchorTokens,e.anchorTokCol=n.anchorTokCol;return}let a=e.tokens[n.line],o=n.item+1<a.length?a[n.item+1].column-(i.column+si(i)):0,s=a.splice(n.item+1),c=n.line,l=+!!r+i.column,u=!r,d=()=>e.tokens[c];if(mi(t)){let e=t.tokens[0][0];i.string=e.string,i.type=e.type}else{r&&(i.string=`(`,i.type=$r.builtin);let n=fi(t);if(n.tokens.forEach((t,r)=>{if(t.forEach(e=>{e.column+=l,u?(i.string=e.string,i.type=e.type,u=!1):d().push(e)}),r+1>=n.tokens.length)return;l=0,c+=1;let a=c;e.tokens.splice(a,0,[]);let o=e.anchorTokens??[],s=e.anchorTokCol??[];e.anchorTokens=e.tokens.map((e,t)=>t<a?o[t]:t===a?n.anchorTokens?.[r+1]:o[t-1]),e.anchorTokCol=e.tokens.map((e,t)=>t<a?s[t]:t===a?n.anchorTokCol?.[r+1]??0:s[t-1])}),r){let e=d()[d().length-1];d().push(oi(`)`,e.column+si(e),$r.builtin))}}let f=d(),p={line:c,item:f.length-1};if(s.length>0){let e=f[f.length-1],t=e.column+si(e)+o-s[0].column;s.forEach(e=>{e.column+=t,f.push(e)})}return di(e),gi(e,p,1)},yi=(e,t,n,r=!0)=>{let i=n.map(t=>_i(e,t,{line:0,item:0}));for(;;){let a=i.reduce((e,t,n)=>t!==void 0&&(e===void 0||t.line<e.position.line||t.line===e.position.line&&t.item<e.position.item)?{index:n,position:t}:e,void 0);if(a===void 0)return;let o=gi(e,a.position,1),s=vi(e,t[a.index],a.position,r);i[a.index]=s===void 0?void 0:_i(e,n[a.index],s),i.forEach((e,t)=>{if(t!==a.index&&e!==void 0&&s!==void 0){if(o===void 0)throw new b(`NullPointerException: TLAExpr.substituteForAll`);e.line===a.position.line&&(e.item+=s.item-o.item),e.line+=s.line-o.line}})}},bi=(e,t,n)=>{let r=fi(e);return yi(r,t,n),r},xi=(e,t,n)=>e.map(e=>bi(e,t,n)),Si=(e,t)=>{let n=e=>t===`1.7.4`?``:`(col${e.column}) `,r=e.tokens.map(e=>e.map(e=>e.type===$r.string?`"\\"", "${e.string}", "\\""`:e.string===`\\/`?`"${n(e)}\\\\/"`:e.string.startsWith(`\\`)?`"\\${e.string}"`:e.string===`/\\`?`"${n(e)}/\\\\"`:`"${e.string}"`)),i=r.findIndex(e=>e.length>0);return`<< ${r.map((e,t)=>{let n=i!==-1&&t>i;return e.map((e,t)=>n||t>0?`, ${e}`:e).join(``)}).join(`
22
+ `)} >>`},Ci=(e,t,n)=>{let r=e=>Si(e,n),i=[0],a=0,o=e=>(i[a+1]=i[a]+e.length,a+=1,e),s=()=>(--a,``),c=()=>`\n${` `.repeat(i[a])}`,l=t<1500,u=e=>`${o(`<<`)}${e.map((e,t)=>`${t>0?`, ${c()}`:``}${`kind`in e?m(e):r(e)}`).join(``)}>>${s()}`,d=e=>`${o(`<<`)}${e.map(e=>`"${e}"`).join(`, `)}>>${s()}`,f=e=>`${o(`<< `)}${e.map((e,t)=>`${t>0?`, ${c()}`:``}${u(e)}`).join(``)} >>${s()}`,p=e=>e?`"="`:`"\\\\in"`,m=e=>{switch(e.kind){case`Uniprocess`:return`${o(``)}[type |-> "uniprocess", ${c()} name |-> "${e.name}", ${c()}${o(` decls |-> `)}${u(e.decls)},${s()}${c()}${o(` defs |-> `)}${r(e.defs)},${s()}${c()}${o(` prcds |-> `)}${u(e.prcds)},${s()}${c()}${o(` body |-> `)}${u(e.body)}]${s()}${s()}`;case`Multiprocess`:return`${o(``)}[type |-> "multiprocess", ${c()} name |-> "${e.name}", ${c()}${o(` decls |-> `)}${u(e.decls)},${s()}${c()}${o(` defs |-> `)}${r(e.defs)},${s()}${c()}${o(` prcds |-> `)}${u(e.prcds)},${s()}${c()}${o(` procs |-> `)}${u(e.procs)}]${s()}${s()}`;case`Procedure`:return l?`${o(``)}[name |-> "${e.name}", ${c()}${o(` params |-> `)}${u(e.params)},${s()}${c()}${o(` decls |-> `)}${u(e.decls)},${s()}${c()}${o(` body |-> `)}${u(e.body)}]${s()}${s()}`:`${o(``)}[name |-> "${e.name}", ${c()}minusLabels |-> ${d(e.minusLabels)}, plusLabels |->${d(e.plusLabels)}, proceduresCalled |->${d(e.proceduresCalled)},${c()}${o(` params |-> `)}${u(e.params)},${s()}${c()}${o(` decls |-> `)}${u(e.decls)},${s()}${c()}${o(` body |-> `)}${u(e.body)}]${s()}${s()}`;case`Process`:return l?`${o(``)}[name |-> "${e.name}", ${c()} eqOrIn |-> ${p(e.isEq)},${c()} id |-> ${r(e.id)},${c()}${o(` decls |-> `)}${u(e.decls)},${s()}${c()}${o(` body |-> `)}${u(e.body)}]${s()}${s()}`:`${o(``)}[name |-> "${e.name}",${c()} fairness |-> "${ni[e.fairness]}", minusLabels |-> ${d(e.minusLabels)}, plusLabels |->${d(e.plusLabels)}, proceduresCalled |->${d(e.proceduresCalled)},${c()} eqOrIn |-> ${p(e.isEq)},${c()} id |-> ${r(e.id)},${c()}${o(` decls |-> `)}${u(e.decls)},${s()}${c()}${o(` body |-> `)}${u(e.body)}]${s()}${s()}`;case`VarDecl`:return`${o(``)}[var |-> "${e.var}", eqOrIn |-> ${p(e.isEq)}, val |-> ${r(e.val)}]${s()}`;case`PVarDecl`:return`${o(``)}[var |-> "${e.var}", eqOrIn |-> "=", val |-> ${r(e.val)}]${s()}`;case`LabeledStmt`:return`${o(``)}[label |-> "${e.label}",${c()}${o(` stmts |-> `)}${u(e.stmts)}]${s()}${s()}`;case`While`:return`${o(``)}[type |-> "while", ${c()} test |-> ${r(e.test)},${c()}${o(` labDo |-> `)}${u(e.labDo)},${s()}${c()}${o(` unlabDo |-> `)}${u(e.unlabDo)}]${s()}${s()}`;case`Assign`:return`${o(``)}[type |-> "assignment",${c()}${o(` ass |-> `)}${u(e.ass)}]${s()}${s()}`;case`SingleAssign`:return`${o(``)}[lhs |-> ${m(e.lhs)},${c()} rhs |-> ${r(e.rhs)}]${s()}`;case`Lhs`:return`[var |-> "${e.var}", sub |-> ${r(e.sub)}]`;case`If`:return`${o(``)}[type |-> "if", ${c()} test |-> ${r(e.test)},${c()}${o(` then |-> `)}${u(e.Then)},${s()}${c()}${o(` else |-> `)}${u(e.Else)}]${s()}${s()}`;case`Either`:return`${o(``)}[type |-> "either", ${c()}${o(` ors |-> `)}${f(e.ors)}]${s()}${s()}`;case`With`:return`${o(``)}[type |-> "with", ${c()} var |-> "${e.var}",${c()} eqOrIn |-> ${p(e.isEq)},${c()} exp |-> ${r(e.exp)},${c()}${o(` do |-> `)}${u(e.Do)}]${s()}${s()}`;case`When`:return`${o(``)}[type |-> "when", ${c()} exp |-> ${r(e.exp)}]${s()}`;case`PrintS`:return`${o(``)}[type |-> "print", ${c()} exp |-> ${r(e.exp)}]${s()}`;case`Assert`:return`${o(``)}[type |-> "assert", ${c()} exp |-> ${r(e.exp)}]${s()}`;case`Skip`:return`[type |-> "skip"]`;case`LabelIf`:return`${o(``)}[type |-> "labelIf",${c()} test |-> ${r(e.test)},${c()}${o(` unlabThen |-> `)}${u(e.unlabThen)},${s()}${c()}${o(` labThen |-> `)}${u(e.labThen)},${s()}${c()}${o(` unlabElse |-> `)}${u(e.unlabElse)},${s()}${c()}${o(` labElse |-> `)}${u(e.labElse)}]${s()}${c()}${s()}`;case`LabelEither`:return`${o(``)}[type |-> "labelEither",${c()}${o(` clauses |-> `)}${u(e.clauses)}]${s()}${c()}${s()}`;case`Clause`:return`${o(``)}${o(`[unlabOr |-> `)}${u(e.unlabOr)},${s()}${c()}${o(` labOr |-> `)}${u(e.labOr)}]${s()}${c()}${s()}`;case`Call`:return`${o(``)}[type |-> "call",${c()} returnTo |-> "${e.returnTo}",${c()} to |-> "${e.to}",${c()}${o(` args |-> `)}${u(e.args)}]${s()}${s()}`;case`Return`:return`[type |-> "return", from |-> "${e.from??`null`}"]`;case`CallReturn`:return`${o(``)}[type |-> "callReturn",${c()} from |-> "${e.from??`null`}",${c()} to |-> "${e.to}",${c()}${o(`args |-> `)}${u(e.args)}]${c()}${s()}${s()}`;case`CallGoto`:return`${o(``)}[type |-> "callGoto",${c()} after |-> "${e.after}",${c()} to |-> "${e.to}",${c()}${o(`args |-> `)}${u(e.args)}]${c()}${s()}${s()}`;case`Goto`:return`[type |-> "goto", to |-> "${e.to}"]`;case`Macro`:return`${o(``)}[name |-> "${e.name}", ${c()}${o(` params |-> `)}${o(`<<`)}${e.params.join(`, ${c()}`)}>>${s()},${s()}${c()}${o(` body |-> `)}${u(e.body)}]${s()}${s()}`;case`MacroCall`:return`${o(``)}[type |-> "macrocall",${c()} name |-> "${e.name}",${c()}${o(` args |-> `)}${u(e.args)}]${s()}${s()}`}};return m(e)},wi=(e,t,n)=>({lines:e,currentLine:t<e.length?Array.from(e[t]):void 0,line:t,column:n,vcolumn:t<e.length?Array.from(e[t].slice(0,n)).length:0}),Ti=e=>{if(e.currentLine===void 0)return` `;if(e.currentLine.length===e.column)return e.line+=1,e.column=0,e.vcolumn=0,e.currentLine=e.line>=e.lines.length?void 0:Array.from(e.lines[e.line]),`
23
+ `;let t=e.currentLine[e.column];return e.column+=1,e.vcolumn+=1,t},Ei=e=>{if(e.column>0)--e.column,--e.vcolumn;else{if(e.line===0)throw new T(`PcalCharReader.backspace trying to move past beginning of reader`);--e.line,e.currentLine=Array.from(e.lines[e.line]),e.column=Math.max(e.currentLine.length-1,0),e.vcolumn=e.column}},Di=e=>{for(;;){let t=Ti(e);if(t===` `)return` `;if(t!==` `&&t!==`
24
+ `)break}return Ei(e),`${(e.currentLine??[]).slice(e.column).join(``)}\n`},Oi=/* @__PURE__ */ new Set([`(`,`[`,`{`,`<<`,`⟨`]),ki=/* @__PURE__ */ new Set([`>>_`,`⟩_`,`]_`,`)`,`}`,`]`,`>>`,`⟩`]),Ai=/* @__PURE__ */ new Set([...Oi,...ki,...`_ ASSUME ASSUMPTION AXIOM BOOLEAN CASE CONSTANT CONSTANTS EXCEPT EXTENDS FALSE IF INSTANCE LOCAL MODULE OTHER STRING THEOREM TRUE VARIABLE VARIABLES WITH WF_ SF_`.split(` `),...`\\A ∀ \\forall \\E ∃ \\exists \\AA \\EE ~ ¬ \\lnot \\neg <> ◇ CHOOSE ENABLED UNCHANGED SUBSET UNION DOMAIN ' ^+ ⁺ ^* ^#`.split(` `),...`=> ⇒ \\cdot ⋅ <=> ⇔ \\equiv ≡ ~> ↝ -+-> ⇸ \\subseteq ⊆ \\subset ⊂ \\supset ⊃ \\supseteq ⊇ \\ll ≪ \\gg ≫ \\ \\cap \\intersect ∩ \\cup \\union ∪ /\\ ∧ \\/ ∨ \\land \\lor \\X × - + * / ^ | || ‖ & && ++ -- ** // ^^ |- ⊢ |= ⊨ -| ⊣ =| ⫤ <: :> := ≔ ::= ⩴`.split(` `),...`(+) ⊕ (-) ⊖ \\oplus \\ominus (.) ⊙ \\odot (/) ⊘ \\oslash (\\X) ⊗ \\otimes \\uplus ⊎ \\sqcap ⊓ \\sqcup ⊔ \\div ÷ \\star ⋆ \\o ∘ \\circ \\bigcirc ◯ \\bullet ●`.split(` `),...`\\in ∈ \\notin ∉ = # /= ≠ < > =< <= ≤ >= ≥ \\prec ≺ \\succ ≻ \\preceq ⪯ \\succeq ⪰ \\sim ∼ \\simeq ≃ \\approx ≈ \\doteq ≐ \\asymp ≍ \\sqsubset ⊏ \\sqsupset ⊐ \\sqsubseteq ⊑ \\sqsupseteq ⊒ \\propto ∝`.split(` `),...`: -> → |-> ↦ <- ← == ≜ ELSE THEN LET IN [] □ .. ‥ ... … $ $$ ? ?? ⁇ % %% ## @@ !! ‼ \\times \\leq \\geq \\mod \\wr ≀ ≅ ! ; , . -. @`.split(` `)]),ji=e=>/^[A-Za-z_]$/.test(e),Mi=e=>/^[0-9]$/.test(e),Ni=e=>e===` `||e===`\f`||e===`\r`,Pi=new Set([...Ai].filter(e=>!ji(e[0])&&!(e[0]===`\\`&&ji(e[1]??``))).flatMap(e=>Array.from(e,(t,n)=>e.slice(0,e.length-n)))),Fi=/* @__PURE__ */ new Set("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ~!@#$%^&*()_-+={}[]|:;<,>.?/`'0123456789"),Ii=new Set(`; do then := ≔ begin variable variables || ‖ end else elsif if either or while with call return goto print assert skip procedure define process fair`.split(` `)),U={...$r,dashes:6,endModule:7},Li=()=>({delimiter:``,delimiterLine:0,delimiterCol:0,commentDepth:0}),Ri=(e,t,n,r)=>{let i=[],a=[],o=``,s=`start`,c=t.vcolumn,l=t.vcolumn,u=Ti(t),d=0,f=!1,p=!1,m=` `,h=()=>{l=t.vcolumn,u=Ti(t)},g=()=>{o+=u,h()},_=()=>{s=`start`,c=l},v=()=>{i.push(a),a=[],c=0},y=e=>{throw new D(`${e} \`${o}' found at\n line ${t.line+1}, column ${c+1}`)},b=()=>{p=!0,e.delimiter=o,e.delimiterCol=c,e.delimiterLine=t.line-+(u===`
25
+ `)},x=e=>{n?(e>U.ident&&y(`Illegal token in an expression`),e!==U.string&&(Ii.has(o)&&!(e===U.ident&&[`.`,`[`,`,`].includes(m))||(o===`,`&&!f&&!r||o===`)`||o===`}`)&&d===0)?(d!==0&&y(`Expression with an unmatched (, [, {, or << followed by`),f&&y("Expression with \\A or \\E but no following `:` followed by"),b(),a.length>0&&v()):(e===U.builtin&&Oi.has(o)&&(d+=1),e===U.builtin&&ki.has(o)&&(--d,d<0&&y(`Extra (unmatching)`)),m=e===U.string?` `:o,[`\\A`,`∀`,`\\E`,`∃`].includes(o)&&d===0&&(f=!0),f&&o===`:`&&d===0&&(f=!1),(o!==``||e===U.string)&&a.push(oi(o,c,e)),o=``)):(b(),o=``)},S=e=>{x(e),_()},C=e=>{g(),s=e},w=e=>{h(),s=e},E=n=>{switch(s){case`start`:if(Ni(n))return h(),_();if(ji(n))return C(`id`);if(n===`ℕ`||n===`ℤ`||n===`ℝ`)return g(),S(U.ident);if(Mi(n))return C(`numOrId`);if(n===`\\`)return C(`bs`);if(n===`-`)return C(`dash1`);if(n===`=`)return C(`eq1`);if(n===`(`)return w(`leftParen`);if(n===`"`)return w(`string`);if(n===`
26
+ `)return h(),v(),_();if(Pi.has(n))return C(`builtIn`);if(n===` `){s=`done`;return}return g(),y(`Illegal lexeme`);case`id`:return o===`WF_`||o===`SF_`?S(U.builtin):ji(n)||Mi(n)?g():S(Ai.has(o)?U.builtin:U.ident);case`numOrId`:return Mi(n)?g():ji(n)?C(`id`):S(U.number);case`bs`:if([`b`,`B`,`o`,`O`,`h`,`H`].includes(n))return C(`numOrBi`);if(ji(n)){s=`bsBuiltIn`;return}if(n===`*`){h(),o=``,s=`lineComment`;return}s=`builtIn`;return;case`numOrBi`:s=Mi(n)?`num`:`bsBuiltIn`;return;case`num`:if(Mi(n))return g();if(!ji(n))return S(U.number);g(),o.startsWith(`\\`)&&y(`Illegal lexeme`),s=`id`;return;case`bsBuiltIn`:return ji(n)&&n!==`_`?g():Ai.has(o)?S(U.builtin):y(`Illegal lexeme `);case`builtIn`:if(Pi.has(o+n))return g();if(!Ai.has(o)){for(Ei(t);!Ai.has(o);)Ei(t),o.length===0&&y(`Illegal lexeme`),o=Array.from(o).slice(0,-1).join(``);h()}return S(U.builtin);case`dash1`:case`dash2`:if(n===`-`)return C(s===`dash1`?`dash2`:`dash3`);s=`builtIn`;return;case`dash3`:return n!==`-`&&y(`Illegal lexeme`),C(`dashes`);case`dashes`:return n===`-`?g():S(U.dashes);case`eq1`:case`eq2`:if(n===`=`)return C(s===`eq1`?`eq2`:`eq3`);s=`builtIn`;return;case`eq3`:return n!==`=`&&y(`Illegal lexeme`),C(`eqs`);case`eqs`:return n===`=`?g():S(U.endModule);case`leftParen`:if(n===`*`)return e.commentDepth=1,w(`comment`);o=`(`,s=`builtIn`;return;case`string`:if(n===`\\`)return C(`escString`);if(n===`"`)return h(),S(U.string);g(),Fi.has(n)||y(`Illegal character in string`);return;case`escString`:g(),[`"`,`\\`,`t`,`n`,`f`,`r`].includes(n)||y(`Illegal character following \\ in string`),s=`string`;return;case`lineComment`:return n===`(`?w(`lineComParen`):n===`*`&&e.commentDepth>0?w(`lineComStar`):n===`
27
+ `||n===` `?(o=``,e.commentDepth=0,_()):e.commentDepth===0?g():h();case`lineComParen`:if(n===`*`)return e.commentDepth+=1,w(`lineComment`);e.commentDepth===0&&(o+=`(`),s=`lineComment`;return;case`lineComStar`:if(n===`)`){if(--e.commentDepth,e.commentDepth<0)throw new T(`Failure of assertion: case LINE_COM_STAR`);return w(`lineComment`)}e.commentDepth===0&&(o+=`*`),s=`lineComment`;return;case`comment`:case`orComment`:{let t=s===`comment`;if(n===`*`)return w(t?`commentStar`:`orCommentStar`);if(n===`(`)return w(t?`commentParen`:`orCommentParen`);if(n===`
28
+ `){o=``,h(),v(),s=`orComment`;return}if(n===` `)throw new D(t?`Input ended in the middle of a comment`:`Input ended in the middle of a multi-line comment`);return e.commentDepth===1?g():h()}case`commentStar`:case`orCommentStar`:{let t=s===`commentStar`?`comment`:`orComment`;if(n!==`)`){e.commentDepth===1&&(o+=`*`),s=t;return}if(h(),--e.commentDepth,t===`orComment`&&e.commentDepth<0)throw new T(`Assertion failure`);if(e.commentDepth!==0){s=t;return}return o=``,_()}case`commentParen`:case`orCommentParen`:{let t=s===`commentParen`?`comment`:`orComment`;if(n===`*`)return e.commentDepth+=1,w(t);e.commentDepth===1&&(o+=`(`),s=t;return}}};for(;s!==`done`&&!p;)E(u);return u!==`
29
+ `&&Ei(t),ui(i)},zi=(e,t,n)=>Ri(e,t,!0,n),Bi=(e,t)=>(Ri(e,t,!1,!1),e.delimiter),Vi=(e,t)=>({params:e,tokenizer:Li(),lookahead:{tokens:Array.from({length:10},()=>``),columns:Array.from({length:10},()=>0),lines:Array.from({length:10},()=>0)},lastToken:{column:0,line:0,text:``},isInMacro:!1,log:t}),Hi=()=>ui([[oi(`defaultInitValue`,0,0)]]),Ui=(e,t)=>[...e,...t.filter((n,r)=>!e.includes(n)&&t.indexOf(n)===r)],Wi=(e,t)=>!t.some(t=>e.includes(t)),Gi=(e,t)=>{t.splice(0,t.length,...e)},Ki=(e,t,n)=>{let r=e.params,i=e.lookahead,a=e.lastToken,o=0,s=[],c=[],l=1,u=/* @__PURE__ */ new Set,d=!1,f=!1,p,m=[],h=!1,g=[],_=[],v=[],y=!1,x=!1,S=r.inputVersionNumber>=1500,C=e=>{throw new D(`${e}\n line ${a.line}, column ${a.column}`)},w=()=>{if(o===0)return Di(t),a.column=t.vcolumn+1,a.line=t.line+1,a.text=Bi(e.tokenizer,t),a.text;a.column=i.columns[0]+1,a.line=i.lines[0]+1;let n=i.tokens[0];for(let e=1;e<o;e++)i.tokens[e-1]=i.tokens[e],i.columns[e-1]=i.columns[e],i.lines[e-1]=i.lines[e];return--o,a.text=n,n},E=n=>{for(;o<n;){let n=o;if(Di(t)===` `)throw new D(`Premature end of file, perhaps because of unclosed comment, near\n line ${i.lines[n]+1}, column ${i.columns[n]+1}`);i.columns[n]=t.vcolumn,i.lines[n]=t.line,i.tokens[n]=Bi(e.tokenizer,t),o+=1}return i.tokens[n-1]},ee=n=>{if(n<o)throw new T(`ParseAlgorithm.PeekPastAlgToken called to peek after a token
30
+ it has already peeked at`);for(;n>o;)i.tokens[o]=Bi(e.tokenizer,t),o+=1;return Di(t)},O=(n=!1)=>{if(o!==0)throw new T(`ParseAlgorithm: GetExpr called after lookahead`);let r=zi(e.tokenizer,t,n);return i.tokens[0]=e.tokenizer.delimiter,i.columns[0]=e.tokenizer.delimiterCol,i.lines[0]=e.tokenizer.delimiterLine,o=1,r},k=(e,t)=>{let n=w();n!==e&&n!==t&&C(`Expected "${e}" but found "${n}"`)},A=(e,t)=>{if(e===`;`){let e=E(1);if(`end begin else elsif or do macro procedure process fair define } {`.split(` `).includes(e))return;if(`if either while with call return goto print assert skip`.split(` `).includes(e))throw new D(`Missing \`;' before line ${i.lines[0]+1}, column ${i.columns[0]+1}`)}k(e,t)},j=()=>{let e=w();return e===`=`?!0:e===`\\in`||e===`∈`?!1:C(`Expected "=" or "\\in" but found "${e}"`)},te=()=>A(E(1)===`,`?`,`:`;`),M=()=>A(h?`{`:`begin`),ne=e=>{h?A(`}`):(A(`end`),A(e))},re=()=>{E(1)===`variables`?k(`variables`):A(`variable`)},ie=()=>{let e={...H(),kind:`VarDecl`,var:w(),col:a.column,line:a.line,isEq:!0,val:Hi()};if(![`=`,`\\in`,`∈`].includes(E(1)))return f=!0,e;if(e.isEq=j(),e.val=O(),e.val.tokens.length===0)throw new b(`NullPointerException`);return e},ae=()=>{re();let e=[],t=[`begin`,`{`,`procedure`,`process`,`fair`,`define`,`macro`];for(;!t.includes(E(1));)e.push(ie()),te();return e},oe=()=>{let e={...H(),kind:`PVarDecl`,var:w(),col:a.column,line:a.line,val:Hi()};if(E(1)!==`=`)return f=!0,e;if(A(`=`),e.val=O(),e.val.tokens.length===0)throw new b(`NullPointerException`);return e},se=()=>{re();let e=[];for(;E(1)!==`begin`&&E(1)!==`{`;)e.push(oe()),te();return e},ce=()=>{if(`while if assert print else elsif either or end with when await skip call return goto`.split(` `).includes(E(1)))return!1;let e=Di(t);return e.length>0&&e[0]===`:`&&!(e.length>1&&e[1]===`=`)},le=()=>{if(!ce())return``;let t=w();e.isInMacro&&C(`A label may not appear in a macro.`),t===`Done`&&C("Cannot use `Done' as a label."),t===`Error`&&C("Cannot use `Error' as a label."),A(`:`),d=!0,u.add(t);let n=E(1);return n!==`+`&&n!==`-`||(A(n),(n===`+`?g:_).push(t),S=!1),t},ue=()=>{let e=[],t=e=>!h&&[`end`,`else`,`elsif`,`or`].includes(e)||h&&e===`}`;for(;!t(E(1));)e.push(...fe());return h&&e.length===0&&C(`Empty statement list`),e},de=e=>{k(`{`);let t=ue();if(A(`}`),A(`;`),e!==``){if(t[0].lbl!==``)throw new D(`Duplicate labeling of statement`,t[0]);t[0].lbl=e}return t},fe=()=>{let e=le();if(h&&E(1)===`{`)return de(e);let t=pe();return t.lbl=e,[t]},pe=()=>{let e=E(1);if(e===`if`)return he(0);if(e===`either`)return N();if(e===`with`)return ge(0);if(e===`when`||e===`await`){k(e);let t=a.column,n=a.line,r=O();if(r.tokens.length===0)throw new b(`NullPointerException`);return A(`;`),{...H(),kind:`When`,col:t,line:n,exp:r}}if(e===`print`||e===`assert`){k(e);let t=a.column,n=a.line,r=O();return r.tokens.length===0&&C(`Empty expression in ${e} statement at `),A(`;`),{...H(),kind:e===`print`?`PrintS`:`Assert`,col:t,line:n,exp:r}}if(e===`skip`){k(`skip`);let e={...H(),kind:`Skip`,col:a.column,line:a.line};return A(`;`),e}if(e===`call`)return P();if(e===`return`){k(`return`);let e={...H(),kind:`Return`,col:a.column,line:a.line,from:p};return A(`;`),e}if(e===`goto`){k(`goto`);let e=a.column,t=a.line,n=w();return y=!0,(n===`Done`||n===`"Done"`)&&(x=!0),A(`;`),{...H(),kind:`Goto`,col:e,line:t,to:n}}return e===`while`?me():ee(1)[0]===`(`?xe():ve()},me=()=>{k(`while`);let e=a.column,t=a.line;h&&A(`(`);let n=O();h&&A(`)`),n.tokens.length===0&&C(`Empty while test at `),h||A(`do`);let r=h?fe():ue();return h||(A(`end`),A(`while`),A(`;`)),r.length===0&&C(`Missing body of while statement at`),{...H(),kind:`While`,col:e,line:t,test:n,unlabDo:r,labDo:[]}},he=e=>{k(e===0?`if`:`elsif`);let t={...H(),kind:`LabelIf`,col:a.column,line:a.line,test:ci(),unlabThen:[],labThen:[],unlabElse:[],labElse:[]};h&&A(`(`),t.test=O(),h&&A(`)`),t.test.tokens.length===0&&C(`Empty if test at `),h||A(`then`),t.unlabThen=h?fe():ue();let n=E(1);return n===`else`&&(k(`else`),t.unlabElse=h?fe():ue()),!h&&n===`elsif`&&(t.unlabElse=[he(e+1)]),!h&&![`else`,`elsif`,`end`].includes(n)&&C(`Expecting "else", "elsif", or "end"`),!h&&e===0&&(A(`end`),A(`if`),A(`;`)),t.unlabElse.length===0&&ai(t.unlabThen,t.unlabThen.length-1),t},N=()=>{k(`either`);let e={...H(),kind:`LabelEither`,col:a.column,line:a.line,clauses:[]};for(;;){let t={...H(),kind:`Clause`,unlabOr:h?fe():ue(),labOr:[]};if(t.unlabOr.length===0)throw new D("`either' statement with empty `or' clause",e);if(e.clauses.push(t),E(1)!==`or`)break;k(`or`)}if(h||(k(`end`),A(`either`),A(`;`)),e.clauses.length===1)throw new D("`either' statement has no `or'",e);return e},ge=e=>{e===0&&(A(`with`),h&&A(`(`));let t={...H(),kind:`With`,col:a.column,line:a.line,var:w(),isEq:!0,exp:ci(),Do:[]};t.isEq=j(),t.exp=O(),h&&E(1)===`)`||te(),t.exp.tokens.length===0&&C(`Empty with expression at `);let n=!h&&E(1)===`do`,r=h&&E(1)===`)`;if(n&&A(`do`),r&&k(`)`),t.Do=n?ue():r?fe():[ge(e+1)],n&&(A(`end`),A(`with`),A(`;`)),t.Do.length===0)throw new D(`Missing body of with statement`,t);return t},_e=()=>{let e=i.columns[0]+1,t=i.lines[0]+1,n={...H(),kind:`Lhs`,col:e,line:t,var:w(),sub:O()};A(`:=`,`≔`);let r=O();return r.tokens.length===0&&C(`Empty right-hand side of assignment at `),{...H(),kind:`SingleAssign`,col:e,line:t,lhs:n,rhs:r}},ve=()=>{let e={...H(),kind:`Assign`,col:i.columns[0]+1,line:i.lines[0]+1,ass:[_e()]};for(;E(1)===`||`||E(1)===`‖`;){w();try{e.ass.push(_e())}catch(e){if(!(e instanceof D))throw e;C(`Bad assignment statement at `)}}return A(`;`),e},ye=()=>{let e=[];if(ee(0)[0]!==`)`)for(;;){let t=O();if(e.push(t),t.tokens.length===0&&C(`Empty argument in call statement at `),E(1)===`)`)break;A(`,`)}return A(`)`),A(`;`),e},be=()=>{k(`call`);let e={...H(),kind:`Call`,col:a.column,line:a.line,returnTo:``,to:w(),args:[]};return A(`(`),e.args=ye(),v.includes(e.to)||v.push(e.to),e},P=()=>{let e=be();if(E(1)===`return`)return k(`return`),A(`;`),{...H(),kind:`CallReturn`,col:e.col,line:e.line,to:e.to,from:p,args:e.args};if(E(1)!==`goto`)return e;k(`goto`);let t={...H(),kind:`CallGoto`,col:e.col,line:e.line,to:e.to,after:w(),args:e.args};return y=!0,(t.to===`Done`||t.to===`"Done"`)&&(x=!0),A(`;`),t},xe=()=>{let e={...H(),kind:`MacroCall`,name:w(),col:a.column,line:a.line,args:[]};return k(`(`),e.args=ye(),e},Se=t=>{e.isInMacro=!0,k(`macro`);let n={...H(),kind:`Macro`,col:a.column,line:a.line,name:w(),params:[],body:[]};for(A(`(`);E(1)!==`)`;)n.params.length>0&&A(`,`),n.params.push(w());return k(`)`),M(),n.body=ue(),ne(`macro`),E(1)===`;`&&w(),Ne(n.body,t),e.isInMacro=!1,n},Ce=()=>{A(`procedure`);let e={...H(),kind:`Procedure`,col:a.column,line:a.line,name:w(),minusLabels:[],plusLabels:[],proceduresCalled:[],params:[],decls:[],body:[]};for(p=e.name,g=[],_=[],v=[],A(`(`);E(1)!==`)`;)e.params.length>0&&A(`,`),e.params.push(oe());return k(`)`),E(1)!==`begin`&&E(1)!==`{`&&(e.decls=se()),M(),e.body=ue(),ne(`procedure`),E(1)===`;`&&w(),p=void 0,e.plusLabels=g,e.minusLabels=_,e.proceduresCalled=v,e},we=()=>{A(`process`);let e=a.column,t=a.line;h&&A(`(`);let n=w(),r=j(),i=O();g=[],_=[],v=[],h&&A(`)`),i.tokens.length===0&&C(`Empty process id at `);let o=E(1)===`begin`||E(1)===`{`?[]:ae();M();let s=ue();return ne(`process`),E(1)===`;`&&w(),{...H(),kind:`Process`,col:e,line:t,name:n,fairness:0,minusLabels:_,plusLabels:g,proceduresCalled:v,isEq:r,id:i,decls:o,body:s}},Te=()=>{let e=`${r.labelRoot}${l}`;return l+=1,u.has(e)?Te():e},Ee=e=>{e.lbl===``&&(e.lbl=Te(),s.push(e.lbl),c.push(ri(e)))},De=(e,t,n,r,i)=>{Gi(r,i);let a=t,o=!1,s=e=>{Ee(e),o=!0,i.length=0};return e.forEach(e=>{if(e.lbl!==``&&(o=!0,i.length=0,n))throw new D("Label in `with' statement",e);if(a){if(n)throw new D("Statement follows `call' or `return' inside a `with' statement.",e);s(e),a=!1}switch(e.kind){case`LabelIf`:{let t=[],r=[],o=De(e.unlabThen,!1,n,i,t);a=De(e.unlabElse,!1,n,i,r)||o,Gi(Ui(t,r),i);return}case`LabelEither`:{let t=[];e.clauses.forEach(e=>{let r=[];a=De(e.unlabOr,!1,n,i,r)||a,Gi(Ui(r,t),t)}),Gi(t,i);return}case`While`:if(n)throw new D("`while' inside a `with' statement",e);s(e),De(e.unlabDo,!1,!1,i,[]),a=!1;return;case`With`:{let t=[];a=De(e.Do,!1,!0,n?[...r]:[],t),Gi(t,i),!n&&!Wi(r,i)&&s(e);return}}let t=e.kind===`Call`||e.kind===`CallGoto`,c=e.kind===`Return`||e.kind===`CallReturn`,l=e.kind===`Assign`?Ui([],e.ass.map(e=>e.lhs.var)):t||c?[`stack`,...c||e.to===p?m.flatMap(e=>[...e.params,...e.decls].map(e=>e.var)):[]]:[];if(a=t||c||e.kind===`Goto`,Wi(i,l))Gi(Ui(i,l),i);else{if(n)throw new D(e.kind===`Assign`?"Second assignment to same variable inside a `with' statement":"Call or return makes second assignment to a variable inside a `with' statement",e);s(e),Gi(l,i)}}),o||a},F=e=>{let t=e=>{let t=e.findIndex(e=>e.lbl!==``),n=t===-1?e:e.slice(0,t);return F(n),{unlabeled:n,labeled:Oe(t===-1?[]:e.slice(t))}};e.forEach(e=>{switch(e.kind){case`LabelIf`:{let n=t(e.unlabThen);e.unlabThen=n.unlabeled,e.labThen=n.labeled;let r=t(e.unlabElse);e.unlabElse=r.unlabeled,e.labElse=r.labeled;return}case`LabelEither`:e.clauses.forEach(e=>{let n=t(e.unlabOr);e.unlabOr=n.unlabeled,e.labOr=n.labeled});return;case`While`:{let n=t(e.unlabDo);e.unlabDo=n.unlabeled,e.labDo=n.labeled}}})},Oe=e=>{let t=[];return e.forEach(e=>{if(e.lbl===``&&t.length>0)t[t.length-1].stmts.push(e);else{if(e.lbl===``)throw new T(`Failure of assertion: Missing Label in MakeLabeledStmtSeq`);t.push({...H(),kind:`LabeledStmt`,col:e.col,line:e.line,macroCol:e.macroCol,macroLine:e.macroLine,label:e.lbl,stmts:[e]})}}),t.forEach(e=>F(e.stmts)),t},I=(e,t)=>{let n=e[t];switch(n.kind){case`LabelIf`:{let r=ke(n.unlabThen);n.labThen.forEach(e=>ke(e.stmts));let i=ke(n.unlabElse);return n.labElse.forEach(e=>ke(e.stmts)),n.labThen.length>0||n.labElse.length>0||r===2||i===2?2:(e[t]={...H(),kind:`If`,test:n.test,Then:n.unlabThen,Else:n.unlabElse},+(r+i>0))}case`LabelEither`:{let r=n.clauses.reduce((e,t)=>{let n=Math.max(e,ke(t.unlabOr));return t.labOr.forEach(e=>ke(e.stmts)),t.labOr.length>0?2:n},0);return r===2?2:(e[t]={...H(),kind:`Either`,ors:n.clauses.map(e=>e.unlabOr)},r)}case`With`:{let e=ke(n.Do);if(e===2)throw new D(`with statement at ${ri(n)} contains a labeled statement`);return e}case`While`:if(t!==0)throw new T("ParseAlgorithm.ClassifyStmtSeq encountered `while' not at beginning of StmtSeq.");return ke(n.unlabDo),n.labDo.forEach(e=>ke(e.stmts)),0;case`Call`:return e[t+1]?.kind===`Return`?0:1;case`Return`:case`CallReturn`:if(p===void 0)throw new D(`return statement not in a procedure at ${ri(n)}`);return 1;case`Goto`:case`CallGoto`:return 1;case`Assign`:case`When`:case`PrintS`:case`Assert`:case`Skip`:case`MacroCall`:return 0;default:throw new T(`ParseAlgorithm.ClassifyStmtSeq encountered the unexpected statement type ${n.kind}`)}},ke=e=>{for(let t=0;t<e.length;t++){let n=I(e,t);if(n!==0){if(t===e.length-1)return n;throw new T(`Translator discovered later than it should have that\n Statement at ${ri(e[t+1])} must have a label`)}}return 0},Ae=e=>{De(e,!0,!1,[],[]);let t=Oe(e);return t.forEach(e=>ke(e.stmts)),t},je=(e,t,n,r,i)=>{let a=e=>bi(e,t,n),o=e=>e.map(e=>je(e,t,n,r,i)),s=e=>e.map(e=>({...H(),kind:`LabeledStmt`,label:e.label,stmts:e.stmts.map(e=>je(e,t,n,-1,0))})),c={...H(),col:e.col,line:e.line,macroCol:r>0?i:e.macroCol,macroLine:r>0?r:e.macroLine};switch(e.kind){case`Assign`:return{...c,kind:`Assign`,ass:e.ass.map(e=>Me(e,t,n,r,i))};case`If`:return{...c,kind:`If`,test:a(e.test),Then:o(e.Then),Else:o(e.Else)};case`Either`:return{...c,kind:`Either`,ors:e.ors.map(o)};case`With`:return{...c,kind:`With`,var:e.var,isEq:e.isEq,exp:a(e.exp),Do:o(e.Do)};case`When`:case`Assert`:case`PrintS`:return{...c,kind:e.kind,exp:a(e.exp)};case`Skip`:return{...c,kind:`Skip`,macroCol:r>0?i:0,macroLine:r>0?r:-1};case`While`:return{...c,kind:`While`,test:a(e.test),unlabDo:o(e.unlabDo),labDo:s(e.labDo)};case`LabelIf`:return{...c,kind:`LabelIf`,test:a(e.test),unlabThen:o(e.unlabThen),labThen:s(e.labThen),unlabElse:o(e.unlabElse),labElse:s(e.labElse)};case`LabelEither`:return{...c,kind:`LabelEither`,clauses:e.clauses.map(e=>({...H(),kind:`Clause`,labOr:s(e.labOr),unlabOr:o(e.unlabOr)}))};case`Call`:return{...c,kind:`Call`,to:e.to,returnTo:e.returnTo,args:xi(e.args,t,n)};case`Return`:return{...c,kind:`Return`,from:e.from};case`CallReturn`:return{...c,kind:`CallReturn`,to:e.to,from:e.from,args:xi(e.args,t,n)};case`CallGoto`:return{...c,kind:`CallGoto`,to:e.to,after:e.after,args:xi(e.args,t,n)};case`Goto`:return{...c,kind:`Goto`,to:e.to};default:throw new T(`Found unexpected statement type in macro at${ri(e)}`)}},Me=(e,t,n,r,i)=>{let a=bi(e.rhs,t,n),o={...H(),kind:`Lhs`,var:e.lhs.var,sub:e.lhs.sub.tokens.length===0?e.lhs.sub:bi(e.lhs.sub,t,n)},s={...H(),kind:`SingleAssign`,col:e.col,line:e.line,macroCol:r>0?i:e.macroCol,macroLine:r>0?r:e.macroLine,lhs:o,rhs:a},c=n.indexOf(o.var);if(c===-1)return s;let l=t[c],u=hi(l,{line:0,item:0});if(u.type!==$r.ident)throw new D(`Macro expansion substitutes \`${u.string}' for assignment variable\n at ${ri(s)}`);if(o.var=u.string,gi(l,{line:0,item:0},1)===void 0)return s;let d=fi(l);return d.tokens[0].splice(0,1),li(d),o.sub.tokens.length===0?o.sub=d:pi(o.sub,d,0),s},Ne=(e,t)=>{let n=e.flatMap(e=>{switch(e.kind){case`LabelIf`:return Ne(e.unlabThen,t),Ne(e.unlabElse,t),[e];case`LabelEither`:return e.clauses.forEach(e=>Ne(e.unlabOr,t)),[e];case`With`:return Ne(e.Do,t),[e];case`While`:return Ne(e.unlabDo,t),[e];case`MacroCall`:return Pe(e,t);default:return[e]}});e.splice(0,e.length,...n)},Pe=(e,t)=>{let n=t.findLast(t=>t.name===e.name);if(n===void 0)throw new D(`Macro ${e.name} undefined,\n at ${ri(e)}`);if(n.params.length!==e.args.length)throw new D(`Macro ${e.name} called with wrong number of arguments at \n ${ri(e)}`);let r=n.body.map(t=>je(t,e.args,n.params,e.line,e.col));return r.length>0&&(r[0].lbl=e.lbl),r},Fe=e=>{e.forEach((t,n)=>{if(e.slice(n+1).some(e=>e.name===t.name))throw new D(`Multiple definitions of macro name \`${t.name}'`)})},Ie=e=>{if(e.length===0)return;let t=()=>{S=!1},n=e[0];if(e.length>1||n.kind!==`LabeledStmt`)return t();if(n.stmts.length===0)return;let r=n.stmts[0];if(n.stmts.length>1||r.kind!==`While`||!mi(r.test)||r.test.tokens[0][0].string!==`TRUE`)return t();r.labDo.length>0&&(S=!1),r.unlabDo.some(e=>[`LabelIf`,`LabelEither`,`LabeledStmt`].includes(e.kind))&&(S=!1)},Le=()=>{let e=s.length>1?`Missing labels at the following locations:`:`Missing label at the following location:`;throw new D([e,...c].join(`
31
+ `))},Re=e=>m.forEach(t=>{p=t.name,Ne(t.body,e),t.body=Ae(t.body)}),ze=()=>{n&&w()!==`algorithm`&&C("`--fair' not followed by `algorithm'");let t=w();h=E(1)===`{`,h&&k(`{`);let i=E(1)===`variable`||E(1)===`variables`?ae():[],a=ci();E(1)===`define`&&(k(`define`),h&&A(`{`),a=O(!0),ne(`define`),A(`;`));let o=[];for(;E(1)===`macro`;)o.push(Se(o));for(;E(1)===`procedure`;)m.push(Ce()),S=!1;if(E(1)===`fair`&&(E(2)===`process`||E(2)===`+`&&E(3)===`process`)||E(1)===`process`){let n=[];for(;E(1)===`fair`||E(1)===`process`;){let e=E(1)===`fair`;e&&k(`fair`);let t=e&&E(1)===`+`;t&&k(`+`);let i=t||!e&&r.fairnessOption===`sf`?2:e||r.fairnessOption===`wf`?1:0;n.push({...we(),fairness:i})}return ne(`algorithm`),Fe(o),n.forEach(e=>{Ne(e.body,o),e.body=Ae(e.body),Ie(e.body)}),Re(o),s.length>0&&(r.labelFlag||Le(),e.log(`Labels added.`)),(x||y)&&(S=!1),{...H(),kind:`Multiprocess`,name:t,decls:i,defs:a,macros:o,prcds:m,procs:n}}r.inputVersionNumber===1500&&E(1)===`fair`&&(A(`fair`),E(1)===`+`&&A(`+`),r.fairnessOption=`wf`),n&&([``,`wf`,`wfNext`].includes(r.fairnessOption)||e.log(`Warning: Option \`${r.fairnessOption}' specified for --fair algorithm.`),r.fairnessOption=`wf`),M();let c=ue();Fe(o),Ne(c,o),Re(o),h&&A(`}`),ne(`algorithm`);let l=Ae(c);return s.length>0&&(d&&!r.labelFlag&&Le(),e.log(`Labels added.`)),(y||x)&&(S=!1),Ie(l),{...H(),kind:`Uniprocess`,name:t,decls:i,defs:a,macros:o,prcds:m,body:l}};try{return{ast:ze(),shouldOmitPC:S,hasDefaultInitialization:f}}catch(e){if(!(e instanceof b))throw e;return C(`Unknown error at or before`)}},W={global:0,label:1,procedure:2,process:3,processVar:4,procedureVar:5,parameter:6},qi=[`Global variable`,`Label`,`Procedure`,`Process`,`Process variable`,`Procedure variable`,`Parameter`],Ji=/* @__PURE__ */ new Set([W.global,W.processVar,W.procedureVar,W.parameter]),Yi=(e,t,n,r)=>e.symbols.find(e=>e.id===n&&e.context===r&&e.type===t),Xi=(e,t,n)=>e.symbols.find(e=>e.id===t&&e.context===n),Zi=(e,t)=>{let n=e.procedures.findIndex(e=>e.name===t);return n===-1?e.procedures.length:n},Qi=(e,t,n,r)=>!(t===W.procedureVar||t===W.processVar||t===W.parameter?Yi(e,W.global,n,``)!==void 0||Xi(e,n,r)!==void 0:Yi(e,t,n,r)!==void 0)&&(e.symbols.push({type:t,id:n,context:r,useThis:n}),!0),$i=(e,t,n,r)=>Yi(e,t,n,r)?.useThis??n,ea=(e,t,n)=>{let r=Xi(e,t,n);return r===void 0?t:Ji.has(r.type)?r.useThis:t},ta=e=>{let t={symbols:[],procedures:[],processNames:[],errorReport:``},n=(e,n)=>{Qi(t,W.label,e.label,n)||(t.errorReport+=`\nLabel ${e.label} redefined at line ${e.line}, column ${e.col}`),e.stmts.forEach(e=>r(e,n))},r=(e,t)=>{let i=e=>e.forEach(e=>r(e,t)),a=e=>e.forEach(e=>n(e,t));switch(e.kind){case`While`:i(e.unlabDo),a(e.labDo);return;case`If`:i(e.Then),i(e.Else);return;case`With`:i(e.Do);return;case`LabelIf`:i(e.unlabThen),a(e.labThen),i(e.unlabElse),a(e.labElse);return;case`Either`:e.ors.forEach(i);return;case`LabelEither`:e.clauses.forEach(e=>{i(e.unlabOr),a(e.labOr)});return;case`Assign`:case`When`:case`PrintS`:case`Assert`:case`Skip`:case`Call`:case`Return`:case`CallReturn`:case`CallGoto`:case`Goto`:return;default:throw new T(`Unexpected AST type ${e.kind}`)}},i=(e,n,r=n===``?W.global:W.processVar)=>{Qi(t,r,e.var,n)||(t.errorReport+=`\n${qi[r]} ${e.var} redefined at line ${e.line}, column ${e.col}`)};if(Qi(t,W.global,`pc`,``),e.prcds.length>0&&Qi(t,W.global,`stack`,``),e.decls.forEach(e=>i(e,``)),e.prcds.forEach(e=>{let r=Zi(t,e.name)<t.procedures.length;r&&(t.errorReport+=`\nProcedure ${e.name} redefined at line ${e.line}, column ${e.col}`),r||t.procedures.push({name:e.name,params:e.params,decls:e.decls,initialPC:e.body.length===0?void 0:ii(e.body[0]).label}),Qi(t,W.procedure,e.name,``),e.decls.forEach(t=>i(t,e.name,W.procedureVar)),e.params.forEach(t=>i(t,e.name,W.parameter)),e.body.forEach(t=>n(ii(t),e.name))}),e.kind===`Multiprocess`&&e.procs.forEach(e=>{let r=t.processNames.includes(e.name);r&&(t.errorReport+=`\nProcess ${e.name} redefined at line ${e.line}, column ${e.col}`),r||t.processNames.push(e.name),Qi(t,W.process,e.name,``),e.decls.forEach(t=>i(t,e.name)),e.body.forEach(t=>n(ii(t),e.name))}),e.kind===`Uniprocess`&&e.body.forEach(e=>n(ii(e),``)),t.errorReport.length>0)throw new D(t.errorReport);return t},na=e=>{let t=t=>e.symbols.filter(e=>e.useThis===t).length>1,n=!1;for(let r=0;r<=7;r+=1)e.symbols.forEach(e=>{if(e.type===r){e.useThis=e.id;for(let n=1;r>0&&t(e.useThis);n+=1)e.useThis+=n===1?`_`:e.context[n-2]??String(r);e.id!==e.useThis&&(n=!0)}});return n},ra=e=>{let t=e.symbols.filter(e=>e.id===`defaultInitValue`).map(e=>`${qi[e.type]} name`);if(t.length>0)throw new D(`Cannot use \`defaultInitValue' as ${t.join(` or `)}`)},ia=(e,t,n)=>{let r=(e,n)=>{let r=[],i=[];e.tokens.forEach(e=>e.forEach(e=>{if(e.type!==$r.ident)return;let a=ea(t,e.string,n);r.includes(e.string)||a===e.string||(r.push(e.string),i.push(ui([[ca(a)]])))})),i.length>0&&yi(e,i,r,!1)},i=(e,n)=>{e.var=ea(t,e.var,n),r(e.val,n)},a=(e,n)=>e.forEach((r,i)=>{e[i]=$i(t,W.label,r,n)}),o=(e,n)=>e===void 0?void 0:$i(t,W.procedure,e,n),s=(e,n)=>{e.label=$i(t,W.label,e.label,n),e.stmts.forEach(e=>c(e,n))},c=(e,n)=>{let i=e=>e.forEach(e=>c(e,n)),a=e=>e.forEach(e=>s(e,n)),l=e=>e.forEach(e=>r(e,n));switch(e.kind){case`LabeledStmt`:s(e,n);return;case`While`:i(e.unlabDo),a(e.labDo),r(e.test,n);return;case`Assign`:e.ass.forEach(e=>{e.lhs.var=ea(t,e.lhs.var,n),r(e.lhs.sub,n),r(e.rhs,n)});return;case`If`:i(e.Then),i(e.Else),r(e.test,n);return;case`With`:r(e.exp,n),i(e.Do);return;case`When`:case`PrintS`:case`Assert`:r(e.exp,n);return;case`Skip`:return;case`LabelIf`:r(e.test,n),i(e.unlabThen),a(e.labThen),i(e.unlabElse),a(e.labElse);return;case`Call`:e.returnTo=$i(t,W.procedure,e.returnTo,n),e.to=$i(t,W.procedure,e.to,n),l(e.args);return;case`Return`:e.from=o(e.from,n);return;case`CallReturn`:e.from=o(e.from,n),e.to=$i(t,W.procedure,e.to,n),l(e.args);return;case`CallGoto`:e.after=$i(t,W.procedure,e.after,n),e.to=$i(t,W.procedure,e.to,n),l(e.args);return;case`Goto`:if(Yi(t,W.label,e.to,n)===void 0&&e.to!==`Done`)throw new D(`goto to non-existent label \`${e.to}' at line ${e.line}, column ${e.col}`);e.to=$i(t,W.label,e.to,n);return;case`Either`:e.ors.forEach(i);return;case`LabelEither`:e.clauses.forEach(e=>{i(e.unlabOr),a(e.labOr)});return;default:throw new T(`Unexpected AST type${e.kind}`)}},l=e=>{e.decls.forEach(t=>i(t,e.name)),e.params.forEach(t=>i(t,e.name)),e.body.forEach(t=>s(ii(t),e.name));let n=ai(t.procedures,Zi(t,e.name));a(e.plusLabels,e.name),a(e.minusLabels,e.name),n.initialPC!==void 0&&(n.initialPC=$i(t,W.label,n.initialPC,e.name)),e.name=$i(t,W.procedure,e.name,``),n.name=e.name},u=e=>{e.decls.forEach(t=>i(t,e.name)),e.body.forEach(t=>s(ii(t),e.name)),a(e.plusLabels,e.name),a(e.minusLabels,e.name),e.name=$i(t,W.process,e.name,``)};e.decls.forEach(e=>i(e,``)),e.kind===`Multiprocess`&&((e,t)=>{e.forEach(l);let r=e.map(e=>e.name),i=e.map(e=>r.map(t=>e.proceduresCalled.includes(t)));r.forEach((e,t)=>i.forEach(e=>e.forEach((n,r)=>{e[r]=n||e[t]&&i[t][r]}))),e.forEach((e,t)=>{e.proceduresCalled=r.filter((e,n)=>i[t][n])});for(let e of t){u(e);let t=e.proceduresCalled;for(let e=0;e<t.length;e+=1){let a=r.indexOf(t[e]);if(a===-1){n(`\nUnrecoverable error:\n -- Could not find procedure name \`${t[e]}'.\n`);return}r.forEach((e,n)=>{i[a][n]&&!t.includes(e)&&t.push(e)})}}})(e.prcds,e.procs),e.kind===`Uniprocess`&&(e.prcds.forEach(l),e.body.forEach(e=>s(ii(e),``)))},aa=e=>oi(e,0,$r.string),oa=e=>oi(e,0,$r.added),sa=e=>oi(e,0,$r.builtin),ca=e=>oi(e,0,$r.ident),la=(e,t)=>{let n=[];return e.forEach(e=>{let r=n.at(-1),i=r===void 0?0:r.column+si(r)+t;n.push(oi(e.string,i,e.type))}),ui([n])},ua=e=>e.tokens.forEach((t,n)=>{let r=n===0||n===e.tokens.length-1?1:6;t.forEach(e=>{if(e.column=r,r+=si(e),e.type===$r.builtin)switch(e.string){case`|->`:case`↦`:e.column=Math.max(16,e.column+1),r=e.column+5;return;case`[`:case`<<`:r+=1;return;case`]`:case`>>`:e.column+=1,r+=1;return;case`\\o`:e.column+=1,r+=2}})}),da=(e,t,n,r=0,i=0)=>({...H(),kind:`SingleAssign`,line:r,col:i,lhs:{...H(),kind:`Lhs`,var:e,sub:t},rhs:n}),fa=(e,t=0,n=0)=>({...H(),kind:`Assign`,line:t,col:n,ass:e}),pa=(e,t,n=0,r=0)=>fa([da(e,ui([]),t,n,r)],n,r),ma=e=>{if(e.tokens.length>1)return!1;let t=ai(e.tokens,0);return t.length===1?t[0].string===`TRUE`:t.length===3&&t[0].string===`(`&&t[1].string===`TRUE`&&t[2].string===`)`},ha=e=>({...H(),kind:`When`,exp:la([oa(`pc`),sa(`=`),aa(e)],1)}),ga=e=>pa(`pc`,ui([[aa(e??`null`)]])),_a=e=>[ca(`Head`),sa(`(`),oa(`stack`),sa(`)`),sa(`.`),ca(e)],va=()=>[ca(`Tail`),sa(`(`),oa(`stack`),sa(`)`)],ya=e=>ui([_a(e)]),ba=(e,t,n,r)=>{let i=[[sa(`<<`),sa(`[`),ca(`procedure`),sa(`|->`),aa(e),sa(`,`)],[ca(`pc`),sa(`|->`),...t]];n.forEach(e=>{i[i.length-1].push(sa(`,`)),i.push([ca(e.var),sa(`|->`),ca(e.var)])}),i[i.length-1].push(sa(`]`),sa(`>>`)),i.push(r);let a=ci(i);return ua(a),li(a),a},xa=(e,t,n)=>{if(t.params.length!==n.args.length)throw new D(`Procedure ${n.to} called with wrong number of arguments`,n);return t.params.forEach((t,r)=>e.ass.push(da(t.var,ui([]),n.args[r],n.line,n.col))),[e,...t.decls.map(e=>pa(e.var,e.val,n.line,n.col)),ga(t.initialPC)]},Sa=(e,t,n)=>{let r,i=(e,n)=>{let r=Zi(t,e.to);if(r===t.procedures.length)throw new D(`Call of non-existent procedure ${e.to}`,e);let i=t.procedures[r],a=ba(e.to,[aa(n)],[...i.decls,...i.params],[sa(`\\o`),oa(`stack`)]);return xa(pa(`stack`,a,e.line,e.col),i,e)},a=e=>{e.from??=r;let n=e.from;if(n===void 0)throw new D("`return' statement not in procedure",e);let i=Zi(t,n);if(i>=t.procedures.length)throw new D(`Error in procedure (perhaps name used elsewhere)`,e);let a=t.procedures[i],o=(t,n)=>fa([da(t,ci(),n,e.line,e.col)],e.line,e.col);return[o(`pc`,ya(`pc`)),...a.decls.map(e=>o(e.var,ya(e.var))),...a.params.map(e=>o(e.var,ya(e.var))),o(`stack`,ui([va()]))]},o=e=>{let n=e.from;if(n===void 0)throw new D(`\`return' statement following \`call' at ${ri(e)} not in a procedure`);let r=ai(t.procedures,Zi(t,n)),i=Zi(t,e.to);if(i===t.procedures.length)throw new D(`Call of non-existent procedure ${e.to}`,e);let a=t.procedures[i],o=fa([],e.line,e.col);if(n!==e.to){r.decls.forEach(t=>o.ass.push(da(t.var,ci(),ya(t.var),e.line,e.col)));let t=ba(e.to,_a(`pc`),[...a.decls,...a.params],[sa(`\\o`),...va()]);o.ass.push(da(`stack`,ui([]),t,e.line,e.col))}return xa(o,a,e)},s=(e,t)=>{if(e.length===0)return{stmts:[],labeledStmts:[],needsGoto:!n};let r={stmts:e,labeledStmts:[],needsGoto:!1},c=e[e.length-1];switch(c.kind){case`LabelIf`:case`LabelEither`:{let n=c.kind===`LabelIf`?f(c,t):p(c,t);e.pop(),e.push(n.stmt),r.labeledStmts=n.labeledStmts;break}case`Goto`:e.pop(),e.push(ga(c.to));break;case`Call`:e.pop(),e.push(...i(c,t));break;case`Return`:e.pop(),e.push(...a(c));break;case`CallReturn`:e.pop(),e.push(...o(c));break;case`CallGoto`:e.pop(),e.push(...i({...H(),kind:`Call`,returnTo:``,to:c.to,args:c.args,line:c.line,col:c.col},c.after));break;case`If`:{let e=s(c.Then,t),i=s(c.Else,t);r.labeledStmts.push(...e.labeledStmts,...i.labeledStmts),c.Then=e.stmts,c.Else=i.stmts,n||(r.needsGoto=e.needsGoto&&i.needsGoto,r.needsGoto||(e.needsGoto&&c.Then.push(ga(t)),i.needsGoto&&c.Else.push(ga(t))));break}case`Either`:{let e=c.ors.map((e,n)=>{let i=s(e,t);return c.ors[n]=i.stmts,r.labeledStmts.push(...i.labeledStmts),i});r.needsGoto=e.every(e=>e.needsGoto),!n&&!r.needsGoto&&e.forEach((e,n)=>{e.needsGoto&&c.ors[n].push(ga(t))});break}case`With`:{let e=s(c.Do,t);c.Do=e.stmts,r.labeledStmts.push(...e.labeledStmts),r.needsGoto=e.needsGoto;break}default:r.needsGoto=!0}return n&&(r.needsGoto=!1),r},c=(e,t)=>{let n=s(e,t);return n.needsGoto&&n.stmts.push(ga(t)),n},l=(e,t)=>{let r=e.stmts.at(0);if(r?.kind===`While`)return d(e,r,t);let i=c([...e.stmts],t),a=[];return n||(i.stmts.unshift(ha(e.label)),a.push({...H(),kind:`LabeledStmt`,col:e.col,line:e.line,label:e.label,stmts:i.stmts})),a.push(...i.labeledStmts),a},u=(e,t)=>e.flatMap((n,r)=>l(n,r<e.length-1?e[r+1].label:t)),d=(e,t,r)=>{let i=t.labDo.length===0?e.label:t.labDo[0].label,a=c([...t.unlabDo],i),o=c(e.stmts.slice(1),r),s=ma(t.test),l=s?a.stmts:[{...H(),kind:`If`,test:t.test,Then:a.stmts,Else:o.stmts}];return[{...H(),kind:`LabeledStmt`,col:e.col,line:e.line,label:e.label,stmts:[...n?[]:[ha(e.label)],...l]},...u(t.labDo,e.label),...a.labeledStmts,...s?[]:o.labeledStmts]},f=(e,t)=>{let n=c(e.unlabThen,e.labThen.length===0?t:e.labThen[0].label),r=c(e.unlabElse,e.labElse.length===0?t:e.labElse[0].label),i=u(e.labThen,t);return i.push(...u(e.labElse,t)),i.push(...n.labeledStmts,...r.labeledStmts),{stmt:{...H(),kind:`If`,col:e.col,line:e.line,test:e.test,Then:n.stmts,Else:r.stmts},labeledStmts:i}},p=(e,t)=>{let n=[],r=[];return e.clauses.forEach(e=>{let i=c(e.unlabOr,e.labOr.length>0?e.labOr[0].label:t);n.push(i.stmts),r.push(...i.labeledStmts),r.push(...u(e.labOr,t))}),{stmt:{...H(),kind:`Either`,col:e.col,line:e.line,ors:n},labeledStmts:r}},m=(e,t)=>u(e.map(ii),t),h=e=>{r=e.name;let n=m(e.body,$i(t,W.label,`Error`,``));return r=void 0,{...H(),kind:`Procedure`,col:e.col,line:e.line,name:e.name,minusLabels:[],plusLabels:[],proceduresCalled:[],params:e.params,decls:e.decls,body:n}},g=e=>({...H(),kind:`Process`,col:e.col,line:e.line,name:e.name,fairness:0,minusLabels:[],plusLabels:[],proceduresCalled:[],isEq:e.isEq,id:e.id,decls:e.decls,body:m(e.body,`Done`)}),_=e.prcds.map(h);return e.kind===`Uniprocess`?{...H(),kind:`Uniprocess`,col:e.col,line:e.line,name:e.name,decls:e.decls,defs:e.defs,macros:[],prcds:_,body:m(e.body,`Done`)}:{...H(),kind:`Multiprocess`,col:e.col,line:e.line,name:e.name,decls:e.decls,defs:e.defs,macros:[],prcds:_,procs:e.procs.map(g)}},Ca=(e,t)=>{let n=t?[]:[`pc`];if(n.push(...e.decls.map(e=>e.var)),e.prcds.length>0&&n.push(`stack`),e.prcds.forEach(e=>{n.push(...e.params.map(e=>e.var)),n.push(...e.decls.map(e=>e.var))}),e.kind===`Multiprocess`&&e.procs.forEach(e=>n.push(...e.decls.map(e=>e.var))),n.length===0)throw new D(`The algorithm has no variables.`);let r=(e,t)=>{let r=n.indexOf(t);return r===-1?0:(e[r]+=1,e[r])},i=(e,t)=>t.forEach((t,n)=>{e[n]=Math.max(e[n],t)}),a=e=>[...e].sort((e,t)=>e.lhs.var<t.lhs.var?-1:+(e.lhs.var>t.lhs.var)),o=(e,t)=>{let o=[...t];e.ass=a(e.ass),new Set(e.ass.map(e=>e.lhs.var)).forEach(t=>{let i=e.ass.filter(e=>e.lhs.var===t);if(!n.includes(t))throw new D(`Assignment to undeclared variable ${t}`,i[0]);let a=i.some(e=>e.lhs.sub.tokens.length===0);if(r(o,t)>1||i.length>1&&a)throw new D(`Multiple assignment to ${t}`,e)}),i(t,o)},s=(e,t)=>{switch(e.kind){case`Assign`:o(e,t);return;case`If`:{let n=[...t],r=[...t];e.Then.forEach(e=>s(e,n)),e.Else.forEach(e=>s(e,r)),i(t,n),i(t,r);return}case`Either`:{let n=[...t];e.ors.forEach(e=>{let r=[...t];e.forEach(e=>s(e,r)),i(n,r)}),i(t,n);return}case`With`:e.Do.forEach(e=>s(e,t));return;case`When`:case`PrintS`:case`Assert`:case`Skip`:return;default:throw new T(`Unexpected AST type ${e.kind}`)}},c=e=>e.forEach(e=>{let t=n.map(()=>0);ii(e).stmts.forEach(e=>s(e,t))});e.prcds.forEach(e=>c(e.body)),(e.kind===`Uniprocess`?[e.body]:e.procs.map(e=>e.body)).forEach(c)},wa=(e,t,n,r)=>{let i=ta(e);na(i)&&r(`Warning: symbols were renamed.`),ia(e,i,r),Ca(Sa(e,i,t),t),n&&ra(i)},Ta=`[ \\t\\n\\x0B\\f\\r]`,Ea=RegExp(`\\\\\\* BEGIN TRANSLATION${Ta}+\\(${Ta}*([cC][hH]([eE][cC])?[kK][sS][uU][mM]\\([pP]([lL][uU][sS])?[cC][aA][lL]\\))${Ta}*(=${Ta}*"(?<pcal>[0-9A-Fa-f]*)"|\\\\in${Ta}*STRING)${Ta}*\\/\\\\${Ta}*([cC][hH]([eE][cC])?[kK][sS][uU][mM]\\([tT][lL][aA]\\+?\\))${Ta}*(=${Ta}*"(?<tla>[0-9A-Fa-f]*)"|\\\\in${Ta}*STRING)${Ta}*\\)`),Da=e=>process.getBuiltinModule(`node:zlib`).crc32(Buffer.from(e,`utf8`)).toString(16),Oa=(e,t)=>e.log(`\nUnrecoverable error:\n -- ${t}.\n`),ka=(e,t)=>Oa(e,t.node===void 0||t.node.line===0?t.message:`${t.message}\n at ${ri(t.node)}`),Aa=e=>e.map(e=>`${Array.from(e).reduce((e,t)=>t===` `?e+` `.repeat(8-e.length%8):e+t,``)} `),ja=(e,t,n,r)=>{for(let i=Math.max(t,0);i<e.length;i++){let t=e[i],a=t.indexOf(n);if(a===-1)continue;let o=a+n.length,s=t.slice(o).search(/[^ ]/);if(s!==-1&&o+s===t.indexOf(r))return i}return-1},Ma=(e,t)=>{for(;t.line<e.length;){let n=e[t.line];for(;t.column<n.length&&n[t.column]===` `;)t.column+=1;if(t.column<n.length)return n;t.line+=1,t.column=0}return``},Na=(e,t,n)=>{let r=Array.from(e.slice(t)).findIndex(e=>n.includes(e));return r===-1?e.length:t+e.slice(t,t+r).length},Pa=e=>/^[\p{L}\p{Nd}_]$/u.test(e),Fa=(e,t,n)=>{for(;t.line<e.length;){let r=Ma(e,t);if(r.slice(t.column).startsWith(n)){let e=t.column+n.length;if(e>=r.length||!/^[\p{L}_]$/u.test(r[e]))return t.column=Na(r,e,` `),!0}t.column=Na(r,t.column,` `)}return!1},Ia=(e,t)=>Oa(e,`Command-line error: ${t}`),La=(e,t)=>{let n=e.params,r=!0,i=!1,a=t=>(r&&=(n.fairnessOption=``,!1),n.fairnessOption===``?(n.fairnessOption=t,!0):(Ia(e,`Can only have one of -wf, -sf, -wfNext, and -nof options`),!1));for(let r=0;r<t.length;r++){let o=t[r],s=t[r+1];switch(o){case`-spec`:case`spec`:case`-myspec`:case`myspec`:{let t=o.endsWith(`myspec`);if(n[t?`myspecOption`:`specOption`]=!0,n.specOption&&n.myspecOption){Ia(e,`
32
+ Can have at most one of the options -spec, -myspec, -spec2, -myspec2, writeAST`);return}if(s===void 0){Ia(e,`Specification name must follow \`-${t?`myspec`:`spec`}' option`);return}r+=1;continue}case`-termination`:case`termination`:n.checkTermination=!0;continue;case`-noold`:case`-nocfg`:case`-noDoneDisjunct`:case`noDoneDisjunct`:continue;case`-wf`:case`wf`:case`-sf`:case`sf`:case`-wfNext`:case`wfNext`:case`-nof`:case`nof`:if(!a(o.replace(/^-/,``)))return;o.endsWith(`nof`)&&(i=!0);continue;case`-label`:case`label`:n.labelFlag=!0;continue;case`-labelRoot`:case`labelRoot`:if(s===void 0){Ia(e,"Label root must follow `-labelRoot' option");return}if(!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(s)){Ia(e,`Label root must be a valid PlusCal identifier (must start with a letter and contain only letters, numbers, and underscores)`);return}n.labelRoot=s,r+=1;continue;case`-version`:case`version`:{if(s===void 0){Ia(e,"Version number must follow `-version' option");return}let t=ti(s);if(t<0||t>1903){Oa(e,t<0?`Illegal version ${s} specified.`:`Specified version ${s} later than current version 1.12`),Ia(e,`Bad version number`);return}n.inputVersionNumber=t,r+=1;continue}case`-lineWidth`:if(!/^[+-]?\d+$/.test(s??``)||Number(s)<60){Ia(e,"Integer value at least 60 must follow `-lineWidth' option");return}r+=1;continue;default:Ia(e,`Unknown or illegal option in options statement: ${o}`);return}}n.checkTermination&&n.fairnessOption===``&&!i&&(n.fairnessOption=`wf`)},Ra=(e,t,n)=>{if(Ma(t,n),n.column+=7,!Ma(t,n).slice(n.column).startsWith(`(`)){Oa(e,"`PlusCal options' not followed by '('");return}n.column+=1;let r=[];for(;;){let e=Ma(t,n);if(n.line>=t.length||e[n.column]===`)`)break;if(e[n.column]===`,`){n.column+=1;continue}let i=Na(e,n.column,` ,)`);r.push(e.slice(n.column,i)),n.column=i}n.line>=t.length?Oa(e,`No closing ')' found in options statement`):La(e,r)},za=(e,t,n)=>{let r=0,i=!1,a=!1;for(let o=t;!i&&o<e.length;o++){let s=e[o],c=o===t?n:0,l=[s.slice(0,c)];a=!1;for(let e=c;!i&&e<s.length;e++){let t=s[e],n=s.slice(e,e+2);if(n===`(*`&&!a)r+=1,l.push(` `),e+=1;else if(n===`*)`&&!a&&r===0)l.push(n),i=!0;else if(n===`*)`&&!a)--r,l.push(` `),e+=1;else if(r>0)l.push(` `);else if(a&&t===`\\`&&n.length===2)l.push(n),e+=1;else{if(!a&&n===`\\*`){l.push(` `);break}t===`"`&&(a=!a),l.push(t)}}if(a)return new D(`Unterminated string in line ${o+1}`);e[o]=l.join(``)}},Ba=(e,t)=>{let n=10*2**Math.max(0,Math.ceil(Math.log2(t/10)));throw new b(`java.lang.ArrayIndexOutOfBoundsException: Index ${e} out of bounds for length ${n}`)},Va=(e,t,n)=>{if(!t.some(e=>e.indexOf(`algorithm`)>0))return/* @__PURE__ */ new Set([`NO_PLUSCAL_EXISTS`]);let r=Aa(t),i={line:0,column:0};for(;Fa(r,i,`PlusCal`);){let t=Ma(r,i).slice(i.column),n=Array.from(t).findIndex(e=>!Pa(e));if(t.startsWith(`options`)&&(n===-1?t.length:n)===7){Ra(e,r,i);break}}let a=0,o=-1,s=!1;for(;a<r.length;a++){let e=r[a];if(/^=+$/.test(e))break;let t=e.indexOf(`--algorithm`),n=e.indexOf(`--fair`);if(t!==-1){o=t+11;break}if(n!==-1){o=n+6,s=!0;break}}let c=/* @__PURE__ */ new Set,l=ja(r,0,`BEGIN`,`TRANSLATION`);l===-1&&c.add(`NO_TRANSLATION_EXISTS`);let u=ja(r,l+1,`END`,`TRANSLATION`);if(u===-1&&c.add(`NO_TRANSLATION_EXISTS`),l===-1&&u===-1)return c;if(o===-1)return c.add(`NO_PLUSCAL_EXISTS`),c;let d=za(r,a,o);if(d!==void 0)return ka(e,d),/* @__PURE__ */ new Set([`ERROR_ENCOUNTERED`]);let f;try{let t=Ki(e,wi(r,a,o),s);f=t.ast,wa(t.ast,t.shouldOmitPC,t.hasDefaultInitialization,e.log)}catch(t){if(!(t instanceof D))throw t;ka(e,t)}l===-1&&Ba(-1,r.length);let p=Ea.exec(r[l]);if(p===null)return c.add(`NO_PCAL_CHECKSUMS_EXIST`),c;let m=p.groups?.pcal,h=s&&n!==`1.7.4`?`fair`:f===void 0?void 0:Ci(f,e.params.inputVersionNumber,n);m!==void 0&&(h===void 0||m!==Da(h))&&c.add(`PCAL_DIVERGENCE_EXISTS`);let g=p.groups?.tla;if(g!==void 0){if(u===-1)throw new b(`java.lang.IllegalArgumentException: fromIndex(${l+1}) > toIndex(-1)`);let e=t.slice(l+1,u).join(``);g!==Da(e)&&c.add(`TLA_DIVERGENCE_EXISTS`)}return c.size===0?/* @__PURE__ */ new Set([`NO_DIVERGENCE`]):c},Ha=[[`STRING`,0,0,[],[]],[`FALSE`,0,0,[],[]],[`TRUE`,0,0,[],[]],[`BOOLEAN`,0,0,[],[]],[`=`,2,0,[2,2],[1,1]],[`/=`,2,0,[2,2],[1,1]],[`.`,2,0,void 0,void 0],[`'`,1,2,[1],[0]],[`\\lnot`,1,0,[3],[1]],[`\\neg`,1,0,void 0,void 0],[`\\land`,2,0,[3,3],[1,1]],[`\\lor`,2,0,[3,3],[1,1]],[`\\equiv`,2,0,[3,3],[1,1]],[`=>`,2,0,[3,3],[1,1]],[`SUBSET`,1,0,[2],[1]],[`UNION`,1,0,[2],[1]],[`DOMAIN`,1,0,[2],[1]],[`\\subseteq`,2,0,[2,2],[1,1]],[`\\in`,2,0,[2,2],[1,1]],[`\\notin`,2,0,[2,2],[1,1]],[`\\`,2,0,[2,2],[1,1]],[`\\intersect`,2,0,[2,2],[1,1]],[`\\union`,2,0,[2,2],[1,1]],[`\\times`,2,0,[2,2],[1,1]],[`~>`,2,3,[3,3],[0,0]],[`[]`,1,3,[3],[0]],[`<>`,1,3,[3],[0]],[`ENABLED`,1,1,[2],[0]],[`UNCHANGED`,1,2,[1],[0]],[`\\cdot`,2,2,[2,2],[0,0]],[`-+->`,2,3,[3,3],[0,0]],[`$AngleAct`,2,2,[2,1],[0,0]],[`$BoundedChoose`,-1,0,[2],[1]],[`$BoundedExists`,-1,0,[3],[1]],[`$BoundedForall`,-1,0,[3],[1]],[`$CartesianProd`,-1,0,[2],[1]],[`$Case`,-1,0,[3],[1]],[`$ConjList`,-1,0,[3],[1]],[`$DisjList`,-1,0,[3],[1]],[`$Except`,-1,0,[2],[1]],[`$FcnApply`,2,0,[2,2],[1,1]],[`$FcnConstructor`,-1,0,[3],[1]],[`$IfThenElse`,3,0,[3,3,3],[1,1,1]],[`$NonRecursiveFcnSpec`,1,0,[3],[1]],[`$Pair`,2,0,[3,3],[1,1]],[`$RcdConstructor`,-1,0,[3],[1]],[`$RcdSelect`,2,0,[2,0],[1,1]],[`$RecursiveFcnSpec`,1,0,[3],[1]],[`$Seq`,-1,0,[2],[1]],[`$SetEnumerate`,-1,0,[2],[1]],[`$SetOfAll`,-1,0,[2],[1]],[`$SetOfFcns`,-1,0,[2],[1]],[`$SetOfRcds`,-1,0,[2],[1]],[`$SF`,2,3,[1,2],[0,0]],[`$SquareAct`,2,2,[2,1],[0,0]],[`$SubsetOf`,1,0,[2],[1]],[`$TemporalExists`,1,3,[3],[0]],[`$TemporalForall`,1,3,[3],[0]],[`$TemporalWhile`,2,3,[3,3],[0,0]],[`$Tuple`,-1,0,[2],[1]],[`$UnboundedChoose`,1,0,[2],[1]],[`$UnboundedExists`,1,0,[3],[1]],[`$UnboundedForall`,1,0,[3],[1]],[`$WF`,2,3,[1,2],[0,0]],[`$Nop`,1,0,[3],[1]],[`$Qed`,0,0,[],[]],[`$Pfcase`,1,0,[3],[1]],[`$Have`,1,0,[3],[1]],[`$Take`,1,0,[3],[1]],[`$Pick`,1,0,[3],[1]],[`$Witness`,-1,0,[2],[1]],[`$Suffices`,1,0,[3],[1]]],Ua={file:`--TLA+ BUILTINS--`,beginLine:0,beginColumn:0,endLine:0,endColumn:0},G=e=>({id:e,levelChecked:0,level:0,levelParams:/* @__PURE__ */ new Set,allParams:/* @__PURE__ */ new Set,nonLeibnizParams:/* @__PURE__ */ new Set,argLevelParams:/* @__PURE__ */ new Map,levelCorrect:!0,levelConstraints:/* @__PURE__ */ new Map,argLevelConstraints:/* @__PURE__ */ new Map}),Wa=e=>Ha.map(t=>{let n=e(),r=t[1]<0?void 0:Array.from({length:t[1]},(t,n)=>({...G(e()),kind:`FormalParam`,name:`Formal_${n}`,arity:0,location:void 0})),i=t[3]!==void 0&&t[4]!==void 0,a=t[4]?.map(e=>e>0);return{...G(n),levelChecked:i?99:0,level:t[2],kind:`OpDef`,defKind:`BuiltIn`,name:t[0],arity:t[1],params:r,body:void 0,isLocal:!1,location:Ua,module:void 0,source:void 0,preComments:[],isDefined:!0,inRecursive:!1,inRecursiveSection:!1,recursiveSection:-1,letInLevel:0,weights:t[1]<0?(t[4]??[]).slice(0,1):t[4]??[],isLeibnizArg:i?a:void 0,isLeibniz:a?.every(Boolean)??!0,opLevelCond:void 0,maxLevels:t[1]<0?(t[3]??[]).slice(0,1):t[3]??[],minMaxLevel:void 0,labels:/* @__PURE__ */ new Map,step:void 0}}),Ga=/* @__PURE__ */ new Map([[`$Qed`,`QED step`],[`$Pfcase`,`CASE`],[`$Have`,`HAVE`],[`$Take`,`TAKE`],[`$Pick`,`PICK`],[`$Witness`,`WITNESS`],[`$Suffices`,`SUFFICES`]]),Ka=e=>{if(e.length>3&&e.endsWith(`!!!`))return[...Ka(e.slice(0,-3)),`!!`];let t=e.split(`!`);return t.some(e=>e.length===0)?[e]:t},qa=e=>{switch(e.kind){case`Identifier`:return Ka(e.name).map(e=>({op:`Name`,name:e,args:void 0}));case`Apply`:{let t=Ka(e.operator),n=e.argumentCounts??t.map((n,r)=>r===t.length-1?e.args.length:0),r=0;return t.map((t,i)=>{let a=e.args.slice(r,r+n[i]);return r+=n[i],{op:`Name`,name:t,args:a.length>0?a:void 0}})}case`Subexpression`:return e.selectors.map(e=>{switch(e.kind){case`Name`:return{op:`Name`,name:e.name,args:e.args.length>0?e.args:void 0};case`Operand`:return{op:e.operand,name:String(e.operand),args:void 0};case`Bound`:return{op:`Null`,name:`!(...)`,args:e.args};case`At`:return{op:`@`,name:`@`,args:void 0};case`Colon`:return{op:`:`,name:`:`,args:void 0}}})}},Ja=e=>{let t=e[e.length-1];return t.op!==`Name`||t.args===void 0},Ya=e=>typeof e.op==`number`?`argument selector ${e.name}`:e.name,Xa=(e,t)=>typeof e==`number`?e>0&&e<=t?e:-1:e===`<<`?t>0?1:-1:e===`>>`&&t===2?2:-1,Za=e=>e.kind===`OpDecl`||e.kind===`FormalParam`||e.kind===`OpDef`&&(e.defKind===`BuiltIn`||e.defKind===`NumberedProofStep`),Qa=e=>e.kind===`FormalParam`||e.kind===`OpDecl`||e.kind===`OpDef`||e.kind===`ThmOrAssumpDef`||e.kind===`Module`,$a=e=>(e.bounded?.length??0)>0?(e.bounded??[]).flat():e.unbounded??[],eo=(e,t)=>e===void 0?t:{...e,endLine:t.endLine,endColumn:t.endColumn},to=e=>(t,n,r,i,a)=>{let o=[],s=[],c=[],l={name:void 0,nameLocation:void 0,node:void 0,index:0,mode:`FindingOpName`,previousMode:void 0,letInContext:void 0,definitionArityFound:0,definitionArgs:[],isInSuffices:!1},u=()=>t[l.index].location??a,d=e=>e.args??[];for(;l.index<t.length;){let f=t[l.index];if((f.op!==`Name`&&f.op!==`Null`||n!==0)&&f.args!==void 0)return e.addError(u(),`Selector \`${f.name}' should not have argument(s).`);switch(l.mode){case`FindingOpName`:{let f,p,m=[];for(;f===void 0&&l.index<t.length;){let n=t[l.index];if(p=n.op===`Name`?l.name===void 0?e.resolveSynonym(n.name):`${l.name}!${e.resolveSynonym(n.name)}`:void 0,l.name===void 0&&n.op!==`Name`)return e.addError(u(),`Need name or step number here, not \`${n.name}'.`);p!==void 0&&(f=l.letInContext===void 0?e.resolveSymbol(p):kt(l.letInContext,p)),f===void 0&&(p!==void 0&&(l.name=p,l.nameLocation=eo(l.nameLocation,u())),m.push(...d(n)),l.index++)}if(f===void 0&&e.version===`1.7.4`){let n=t.length-1;return e.addError(t[n].location??a,`Unknown operator: \`${Ya(t[n])}'.`)}if(f===void 0)return e.addError(l.nameLocation??a,`Unknown operator: \`${l.name}'.`);if(f.kind===`Module`)return e.addError(u(),`Module name (${t[l.index].name}) not allowed here.`);if(l.node=f,l.nameLocation=eo(l.nameLocation,u()),l.name=p,Za(f)&&t.length!==1)return e.addError(u(),`Cannot take subexpression of \`${l.name}'.`);let h=we(f);if(n===0){if(m.push(...d(t[l.index])),l.definitionArityFound+m.length!==h)return e.addError(t[l.index].argsLocation??a,`The operator ${l.name} requires ${h-l.definitionArityFound} arguments.`);m.forEach((t,n)=>l.definitionArgs.push(e.generateArgument(f,n+l.definitionArityFound,t,u())))}if(l.definitionArityFound=h,f.kind===`OpDef`&&f.defKind===`ModuleInstance`){if(l.index===t.length-1&&!(i||r))return e.addError(u(),`Operator name ${l.name} is incomplete.`)}else{let n=f.kind===`OpDef`&&f.defKind===`UserDefined`||f.kind===`ThmOrAssumpDef`?f:void 0;if(f.kind===`OpDef`&&f.defKind===`UserDefined`&&!f.isDefined&&t.length!==1)return e.addError(u(),`Subexpression of \`${l.name}' used inside the operator's definition.`);if(l.index!==t.length-1&&n!==void 0){s.push(...n.params??[]),l.name=void 0,l.nameLocation=void 0,l.mode=t[l.index+1].op===`Name`?`FollowingLabels`:`FindingSubExpr`,c.push(...l.definitionArgs),l.definitionArityFound=0,l.definitionArgs=[];let e=n.body;for(;e?.kind===`SubstIn`;)o.push(e),e=e.body;for(;e?.kind===`APSubstIn`;)o.push(e),e=e.body;l.mode===`FindingSubExpr`&&(l.node=e)}}l.previousMode=`FindingOpName`;break}case`FollowingLabels`:{let r=l.node,i=r?.kind===`OpDef`||r?.kind===`ThmOrAssumpDef`||r?.kind===`Label`?r.labels.get(f.name):void 0;if(i===void 0)return e.addError(u(),`Cannot find label \`${f.name}'.`);if(l.node=i,e.isOutOfLabelScope(i))return e.addError(u(),`Accessing subexpression labeled \`${f.name}' of ASSUME/PROVE clause within the scope of a declaration\n from outside that declaration's scope.`);if(n===0){if(i.params.length!==d(f).length)return e.addError(u(),`Label \`${f.name}' used with wrong number of arguments.`);c.push(...d(f).map(e.generateExpression))}s.push(...i.params),l.index<t.length-1&&t[l.index+1].op!==`Name`&&(l.mode=`FindingSubExpr`),l.mode===`FindingSubExpr`&&(l.node=i.body),l.previousMode=`FollowingLabels`;break}case`FindingSubExpr`:{let n=l.node,r=()=>e.addError(u(),`Nonexistent operand specified by \`${Ya(f)}'.`);if(f.op===`:`){if(!(l.previousMode!==`FindingSubExpr`&&(l.index===t.length-1&&l.previousMode===`FindingOpName`||l.index<t.length-1&&t[l.index+1].op===`Name`)))return e.addError(u(),`\`!:' can be used only after a name and either at the end after an
33
+ operator name or before an operator name.`)}else if(n===void 0||ne(n))return e.addError(u(),`Subexpression selection failed, probably due to an error in the selected expression.`);else if(n.kind===`LetIn`){if(Xa(f.op,1)!==1)return e.addError(u(),`A LET/IN expression has only one operand.`);l.node=n.body}else if(n.kind===`OpAppl`){let i=n.operator,a=n.operands,o=i.kind===`FormalParam`||i.kind===`OpDecl`&&i.declKind===2||i.kind===`OpDef`&&i.defKind===`UserDefined`,p=()=>e.addError(u(),`Internal error: Expecting $Pair and didn't find it.`),m=e=>e?.kind===`OpAppl`&&e.operator.name===`$Pair`,h=Xa(f.op,a.length);if(o){let e=Xa(f.op,i.arity);if(e===-1)return r();l.node=a[e-1]}else if(i.kind===`OpDef`&&i.defKind===`BuiltIn`&&n.nullKind!==`null`){if(i.name===`$RcdConstructor`||i.name===`$SetOfRcds`){if(h===-1)return r();let e=a[h-1];if(!m(e))return p();l.node=e.operands[1]}else if(i.name===`$Case`){if(l.index===t.length-1)return e.addError(u(),`Subexpression of CASE must have form !i!j.`);if(h===-1)return r();let n=a[h-1];if(!m(n))return p();l.index++;let i=Xa(t[l.index].op,2);if(i===-1)return e.addError(u(),`Second selector for CASE subexpression must specify one of two operands.`);if(l.node=n.operands[i-1],l.node===void 0||ne(l.node))return e.addError(u(),`Selecting OTHER in a CASE statement.`)}else if(i.name===`$Except`){if(h>1)return e.addError(u(),`Selecting subexpression of an EXCEPT not yet implemented.`);if(h===-1)return r();l.node=a[h-1]}else if((n.bounded?.length??0)===0&&(n.unbounded?.length??0)===0){if(h===-1)return r();l.node=a[h-1]}else if(f.op===`Null`||f.op===`@`){let t=$a(n);if(s.push(...t),f.op===`Null`){if(d(f).length!==t.length)return e.addError(u(),`Selector with ${d(f).length} argument(s) used for quantifier with ${t.length} bound identifier(s).`);c.push(...d(f).map(e.generateExpression))}l.node=a[0]}else{let e=Xa(f.op,n.ranges.length);if(e===-1)return r();l.node=n.ranges[e-1]}}else return e.addError(u(),`Choosing operand \`${Ya(f)}' of subexpression with no operands.`)}else if(n.kind===`AssumeProve`){if(n.isSuffices&&!l.isInSuffices){if(Xa(f.op,1)!==1)return e.addError(u(),`Accessing non-existent subexpression of a SUFFICES`);l.isInSuffices=!0}else{l.isInSuffices=!1;let i=Xa(f.op,1+n.assumptions.length);if(i===-1)return r();if(e.isOutOfClauseScope(n,i))return e.addError(u(),`Accessing ASSUME/PROVE clause within the scope of a declaration
34
+ from outside that declaration's scope.`);if(i<=n.assumptions.length){if(l.node=n.assumptions[i-1],l.node.kind===`NewSymb`&&l.index!==t.length-1)return e.addError(u(),`Selected a subexpression of a NEW clause of an ASSUME.`)}else l.node=n.goal}}else if(n.kind===`OpArg`){let t=n.op;if(t.kind!==`OpDef`||t.name!==`LAMBDA`)return e.addError(u(),`Trying to select subexpression of an operator argument.`);if(f.op!==`Null`&&f.op!==`@`)return e.addError(u(),`Cannot use !${f.name} to select subexpression of a LAMBDA.`);if(f.op===`Null`){if(t.arity!==d(f).length)return e.addError(u(),`Selector with ${d(f).length} arguments used for LAMBDA expression taking ${t.arity} arguments.`);c.push(...d(f).map(e.generateExpression))}s.push(...t.params??[]),l.node=t.body}else if(n.kind===`Label`)l.node=n.body,l.index--;else return e.addError(u(),`Selecting subexpression of expression that has none.`);if(l.node===void 0||ne(l.node))return e.addError(u(),`An unexpected null node specified by '${Ya(f)}'.\nThis is probably due to a previous error.`);if(l.index!==t.length-1){let n=t[l.index+1];if(n.op===`Name`){for(;l.node?.kind===`Label`;)l.node=l.node.body;if(l.node?.kind!==`LetIn`)return e.addError(u(),`A name selector here must be from a LET clause.`);l.letInContext=l.node.context,l.mode=`FindingOpName`}else if(n.op===`:`)return e.addError(u(),`!: should not follow an operand selector.`)}l.previousMode=`FindingSubExpr`;break}}l.index++}let f=l.node;if(f===void 0)return e.addError(a,`Subexpression selection failed, probably due to an error in the selected expression.`);if(f.kind===`AssumeProve`||f.kind===`NewSymb`)return r?f:e.addError(a,f.kind===`AssumeProve`?`Selected ASSUME/PROVE instead of expression.`:`Selected a NEW declaration as an expression or operator.`);if(n<0){let t=f.kind===`OpDef`&&(f.defKind===`UserDefined`||f.defKind===`NumberedProofStep`||f.defKind===`ModuleInstance`&&i)||f.kind===`ThmOrAssumpDef`;return l.previousMode!==`FindingOpName`||!t?e.addError(a,`DEF clause entry should describe a defined operator.`):f.kind===`OpDef`&&f.step!==void 0&&f.step.kind!==`DefStep`?e.addError(a,`DEF clause entry refers to a non-definition step.`):f}if(f.kind===`OpDef`&&f.defKind===`NumberedProofStep`)return e.addError(a,r?`Step number of non-fact used as a fact`:`Step number of non-expression step used as an expression.`);if(n>0){let t=s.length+(f.kind===`OpArg`?we(f.op):l.previousMode===`FindingOpName`&&Qa(f)?we(f):0);if(n!==t)return e.addError(a,`Expected arity ${n} but found operator of arity ${t}.`)}let p=f;if(l.previousMode===`FindingOpName`&&s.length+o.length>0){if(p.kind!==`OpDef`&&p.kind!==`ThmOrAssumpDef`)return e.addError(t[t.length-1].location??a,`Internal Error: Found unexpected node kind after FindingOpName`);c.push(...l.definitionArgs);let n=(p.params??[]).map(t=>{let n=e.createFormalParam(t.name,t.arity,t.location);return s.push(n),t.arity===0?e.createOpAppl(n,[],a):e.createOpArg(n,a)});p=e.createOpAppl(p,n,a)}if(p.kind===`OpArg`){if(n===0)return e.addError(a,`Selected operator argument when expression expected.`);if(s.length+o.length>0){let t=p.op;s.push(...Array.from({length:we(t)},(t,n)=>e.createFormalParam(`NewParam${n}`,0,void 0))),p=e.createOpAppl(t,l.definitionArgs,a)}}if(!r){if(p.kind===`ThmOrAssumpDef`&&p.body.kind===`AssumeProve`)return e.addError(a,`ASSUME/PROVE used where an expression is required.`);if(p.kind===`ThmOrAssumpDef`&&p.body.kind===`OpAppl`){let t=Ga.get(p.body.operator.name);if(t!==void 0)return e.addError(a,`${t} proof step selected instead of expression.`)}}if(p.kind===`FormalParam`||p.kind===`OpDecl`||p.kind===`ThmOrAssumpDef`||p.kind===`OpDef`&&(p.defKind===`UserDefined`||p.defKind===`BuiltIn`))return n>0?e.createOpArg(p,a):e.createOpAppl(p,l.definitionArgs,a);if(p.kind===`OpArg`)return p;if(p.kind===`OpDef`||p.kind===`Module`)return(r||i)&&p.kind===`OpDef`?p:e.addError(a,`Module instantiation selected instead of expression.`);let m=o.reduceRight((t,n)=>e.copySubstIn(n,t),p),h=s.length>0?e.createLambda(s,m,a):void 0;return n>0?h===void 0||s.length!==n?e.addError(a,`Expected operator argument with arity ${n} but found one of arity ${s.length}.`):e.createOpArg(h,a):s.length===c.length?h===void 0?e.createOpAppl(e.getBuiltin(`$Nop`),[m],a):e.createOpAppl(h,c,a):e.addError(a,`Expected ${s.length} arguments but found ${c.length}.`)},no=e=>e[e.length-1],ro=(e,t)=>{for(let n=e.length-1;n>=0;n--){let r=kt(e[n],t);if(r)return r}},io=e=>e.kind===`OpDecl`?`${e.kind}${e.declKind}`:e.kind===`OpDef`?e.defKind:e.kind,ao=(e,t)=>{if(e.kind===`OpDef`&&t.kind===`OpDef`){let n=e.source??e;return n===(t.source??t)?n.module===void 0||oo(n.module):!1}if(e.kind===`ThmOrAssumpDef`&&t.kind===`ThmOrAssumpDef`){let n=e.source??e;return n===(t.source??t)&&oo(n.module)}return!1},oo=e=>Ae(e,2).length===0&&Ae(e,3).length===0,so=(e,t)=>{let n=ro(e.contexts,t.name);if(n===t)return;if(n===void 0){qe(no(e.contexts),t);return}let r=t.kind===`FormalParam`||io(n)!==io(t)||we(n)!==we(t);n.kind===`OpDef`&&n.defKind===`BuiltIn`&&!(r&&e.version===`1.7.4`)?e.addError(t.location,`Symbol ${t.name} is a built-in operator, and cannot be redefined.`):r?e.addError(t.location,`Multiply-defined symbol '${t.name}': this definition or declaration conflicts \nwith the one at ${I(n.location)}.`):ao(t,n)||e.addWarning(t.location,`Multiple declarations or definitions for symbol ${t.name}. \nThis duplicates the one at ${I(n.location)}.`)},co=e=>e.labelScopes.push({labels:/* @__PURE__ */ new Map,params:[]}),lo=e=>e.labelScopes.pop()?.labels??/* @__PURE__ */ new Map,uo=(e,t)=>{let n=t.kind===`AssumeProve`?e.assumeProveScopes.get(t):void 0;n&&(n.isInProof=!1)},fo=(e,t)=>R(e,N(e,t)),po=(e,t)=>t.range?ye(e,t.range):{start:_e(e,t),end:_e(e,t)},mo=(e,t)=>R(e,po(e,t)),ho=(e,t)=>{for(let n=e.contexts.length-1;n>=0;n--){let r=oe(e.contexts[n],t);if(r?.kind===`Module`)return r}return e.externalModules.get(t)},go=(e,t)=>{let n=ho(e,t);if(n===void 0)throw new s(`Could not find module ${t}`);return n},_o=(e,t,n)=>{e.contexts.push(t);let r=n();return e.contexts.pop(),r},vo=(e,t,n,r,i)=>{let a={...G(e.getId()),kind:`FormalParam`,name:t,arity:n,location:r};return i&&so(e,a),a},yo=(e,t)=>({...G(e.getId()),kind:`OpDef`,defKind:`UserDefined`,arity:t.params?.length??0,params:[],body:void 0,isLocal:!1,module:e.currentModule,source:void 0,preComments:[],isDefined:!0,inRecursive:!1,inRecursiveSection:!1,recursiveSection:-1,letInLevel:0,weights:(t.params??[]).map(()=>0),isLeibnizArg:(t.params??[]).map(()=>!0),isLeibniz:!0,opLevelCond:void 0,maxLevels:(t.params??[]).map(()=>3),minMaxLevel:void 0,labels:/* @__PURE__ */ new Map,step:void 0,...t}),bo=(e,t)=>{t.letInLevel=e.curLevel,e.unresolvedSum>0&&(t.recursiveSection=e.recursiveSections.count,t.inRecursiveSection=e.unresolvedCount[e.curLevel]>0,e.currentModule.opDefsInRecursiveSection.push(t))},xo=(e,t,n,r,i={},a=e.getId())=>({...G(a),kind:`OpAppl`,operator:t,operands:n,unbounded:i.unbounded,bounded:i.bounded,tupleOrs:i.tupleOrs,ranges:i.ranges??[],location:r}),So=e=>({...xo(e,Co(e,`$Nop`),[],Ua,{},e.nullApplicationId),nullKind:`null`}),Co=(e,t)=>{let n=e.builtinsByName.get(t);if(!n)throw new g(`SANY has no builtin operator ${t}`);return n},K=(e,t,n,r,i={})=>xo(e,Co(e,t),n,r,i),wo=(e,t,n)=>({...G(e.getId()),kind:`String`,value:t,location:n}),To=(e,t,n)=>({...G(e.getId()),kind:`OpArg`,op:t,location:n}),Eo=(e,t,n)=>{let r=ro(e.contexts,Ct(t));if(r===void 0||r.kind===`Module`)throw new s(`Unknown operator: \`${t}' at line ${n.beginLine}, column ${n.beginColumn} of module ${n.file}`);return r},Do=(e,t,n,r)=>{if(t.kind!==`OpDef`||t.defKind!==`UserDefined`)return;let i=t.params??[];i.length===n.length?i.forEach((i,a)=>{let o=n[a];i.arity===0&&o.kind===`OpArg`&&e.addError(r,`Operator used in argument number ${a+1} has incorrect number of arguments.`);let s=o.kind===`OpArg`&&we(o.op)===i.arity&&!(o.op.kind===`OpDef`&&(o.op.params??[]).some(e=>e.arity>0));i.arity>0&&!s&&e.addError(r,`Argument number ${a+1} to operator '${t.name}' \nshould be a ${i.arity}-parameter operator.`)}):e.addError(r,`Wrong number of arguments (${n.length}) given to operator '${t.name}', \nwhich requires ${i.length} arguments.`)},Oo=e=>/^[A-Za-z0-9_]+$/.test(e),ko=e=>e!==`!!`&&e.includes(`!`),Ao=e=>BigInt(e.startsWith(`\\`)?`0${e.slice(1).replace(/^h/i,`x`)}`:e).toString(),jo=/* @__PURE__ */ new Set([`Identifier`,`Subexpression`,`OperatorReference`,`Lambda`]),Mo=e=>{let t=e.kind===`Apply`?qa(e):void 0;return jo.has(e.kind)||t!==void 0&&Ja(t)},No=(e,t,n)=>{let r=n.start;return t.map(t=>{let i=t.op===`Name`?t.name:t.op===`Null`?`(`:String(t.op),a=ie(e,r,n.end,i);if(a===-1)return t;if(t.op===`Null`){let n=Me(e,a);return r=n+1,{...t,location:R(e,{start:a,end:n})}}r=a+1;let o=L(e,a);if(t.args===void 0||!M(e,a+1,`(`))return{...t,location:o};let s=Me(e,a+1);return r=s+1,{...t,location:o,argsLocation:R(e,{start:a+1,end:s})}})},Po=(e,t,n,r,i,a=fo(e.file,t))=>{let o=qa(t);if(o===void 0)throw new s(`Expected a name, found ${t.kind}`);return e.selectorToNode(No(e.file,o,N(e.file,t)),n,r,i,a)},Fo=(e,t)=>{let n=Po(e,t,0,!1,!1);if(n.kind!==`OpAppl`)throw new s(`Expected an expression`);return n},Io=(e,t)=>{if(t.kind!==`OpAppl`)return;let n=e.functions.find(e=>e.name===t.operator.name);n&&(n.node.operator=Co(e,`$RecursiveFcnSpec`))},Lo=e=>e.reduce((e,t)=>{let n=e[e.length-1];return n!==void 0&&n[0].set===t.set&&t.pattern.kind===`Name`&&n[0].pattern.kind===`Name`?n.push(t):e.push([t]),e},[]),Ro=(e,t,n)=>is(e,t,n,Lo(t).map(t=>q(e,t[0].set))),zo=(e,t,n)=>{let r=e.labelScopes.at(-1);r?.params.push(t);let i=q(e,n);return r?.params.pop(),i},Bo=(e,t,n,r,i,a)=>_o(e,At(),()=>{let o=Ro(e,n,r),s=zo(e,o.bounded.flat(),i);return K(e,t,[s],a,o)}),Vo=(e,t)=>{let n=N(e.file,t),r=Mt(e.file,n.start,n.end,t.params);return _o(e,At(),()=>{let i=t.params.map((t,n)=>vo(e,t,0,L(e.file,r[n]),!0)),a=zo(e,i,t.body);return yo(e,{name:`LAMBDA`,params:i,body:a,location:R(e.file,n),preComments:me(e.file,n.start)})})},Ho=(e,t)=>t.kind===`OperatorReference`?t.operator:t.kind===`Lambda`&&t.body.kind===`Apply`?t.body.operator:e.tokens[_e(e,t.location)].text,Uo=(e,t,n)=>{let r=Ho(e.file,t),i=ro(e.contexts,Ct(r));return i===void 0?(e.addError(n,`Could not find declaration or definition of symbol '${r}'.`),So(e)):To(e,i,n)},Wo=(e,t,n)=>{let r=N(e.file,t),i=Le(e.file,r),a=R(e.file,i),o=i!==r;if(t.kind===`Lambda`&&!o)return t.location.range!==void 0&&t.operator===void 0?To(e,Vo(e,t),a):Uo(e,t,a);if(o||!Mo(t))return e.addError(a,`Arity ${n.arity} operator (not an expression) is expected \nto substitute for CONSTANT '${n.name}'.`),So(e);if(t.kind===`OperatorReference`)return Uo(e,t,a);let c=Po(e,t,n.arity,!1,!1);if(c.kind===`OpArg`||c.kind===`OpAppl`&&c.nullKind!==void 0)return c;throw new s(`Expected an operator argument at line ${a.beginLine}, column ${a.beginColumn}`)},Go=(e,t,n,r,i)=>{let a=t.kind===`OpDef`&&(t.defKind===`UserDefined`||t.defKind===`ModuleInstance`)?t.params??[]:void 0;if(a!==void 0&&a.length<=n)return So(e);let o=a?.[n]?.arity??0;if(o===0)return q(e,r);let c=N(e.file,r),l=R(e.file,c),u=`${n+1} (counting from 1)`,d=Pe(e.file,c);if(d!==c||!Mo(r))return e.addError(R(e.file,d),`An expression appears as argument number ${u} to operator '${t.name}', in a position an operator is required.`),So(e);if(r.kind===`Identifier`||r.kind===`Subexpression`||r.kind===`Apply`){let t=Po(e,r,o,!1,!1);if(t.kind===`OpArg`||t.kind===`OpAppl`)return t;throw new s(`Expected an operator argument at ${I(l)}`)}if(r.kind===`Lambda`&&r.location.range!==void 0&&r.operator===void 0){let a=Vo(e,r),s=we(a);return s===o?To(e,a,l):(e.addError(i,`Lambda expression with arity ${s} used as argument ${n+1} of operator \`${t.name}', \nbut an operator of arity ${o} is required.`),So(e))}let f=Ho(e.file,r),p=ro(e.contexts,Ct(f));if(p===void 0)return e.addError(l,`Could not find declaration or definition of symbol '${f}'.`),So(e);let m=we(p);return m===o?To(e,p,l):(e.addError(i,`Operator with incorrect arity passed as argument. \nOperator '${p.name}' of arity ${m} is argument number ${u} to operator \`${I(t.location)}', \nbut an operator of arity ${o} was expected.`),So(e))},Ko=(e,t)=>{let n=fo(e.file,t);if(t.isBulleted)return K(e,t.kind===`And`?`$ConjList`:`$DisjList`,t.operands.map(t=>q(e,t)),n);let r=N(e.file,t),i=t.kind===`And`?`\\land`:`\\lor`,[a,...o]=t.operands;return o.reduce((t,n,a)=>{let s=P(e.file,n),c=a===o.length-1?r.end:s.end;return K(e,i,[t,q(e,n)],R(e.file,{start:r.start,end:c}))},q(e,a))},qo=(e,t)=>{let n=N(e.file,t),r=t.arms.map((r,i)=>{let a=P(e.file,r.condition),o=i===t.arms.length-1&&t.other===void 0,s=P(e.file,r.body),c=[q(e,r.condition),q(e,r.body)];return K(e,`$Pair`,c,R(e.file,{start:a.start,end:o?n.end:s.end}))}),i=t.other;if(i){let t=P(e.file,i),a=Jo(e.file,t.start,`OTHER`);r.push(K(e,`$Pair`,[void 0,q(e,i)],R(e.file,{start:a,end:n.end})))}return K(e,`$Case`,r,R(e.file,n))},Jo=(e,t,n)=>{for(let r=t;r>=0;r--)if(M(e,r,n))return r;return t},Yo=(e,t)=>{let n=N(e.file,t),r=R(e.file,n),i=[q(e,t.function)],a=K(e,`$Except`,i,r),o=N(e.file,t.function),s=ie(e.file,o.end+1,n.end,`EXCEPT`)+1;return t.updates.forEach(t=>{let r=ie(e.file,s,n.end,`!`),o=P(e.file,t.value),c=R(e.file,{start:r,end:o.end}),l=r+1,u=t.path.map(t=>{if(t.kind===`Field`){let n=Xo(e.file,l,t.name);return l=n+1,wo(e,t.name,L(e.file,n))}let r=ie(e.file,l,n.end,`[`);return l=Me(e.file,r)+1,t.args.length===1?q(e,t.args[0]):K(e,`$Tuple`,t.args.map(t=>q(e,t)),R(e.file,ye(e.file,t.tupleRange)))}),d=K(e,`$Seq`,u,c),f=K(e,`$Pair`,[d],c);e.exceptSpecStack.push(f),e.exceptStack.push(a),f.operands.push(q(e,t.value)),e.exceptSpecStack.pop(),e.exceptStack.pop(),i.push(f),s=o.end+1}),a},Xo=(e,t,n)=>{for(let r=t;r<e.tokens.length;r++)if(e.tokens[r].text===n&&e.tokens[r].kind!==`String`)return r;return t},Zo=(e,t,n)=>{let r=N(e.file,n),i=r.start+1,a=n.fields.map((t,r)=>{let a=Xo(e.file,i,t.name),o=P(e.file,t.value);return i=o.end+1,n.fields.slice(0,r).some(e=>e.name===t.name)&&e.addError(L(e.file,a),`Non-unique fields in constructor.`),K(e,`$Pair`,[wo(e,t.name,L(e.file,a)),q(e,t.value)],R(e.file,{start:a,end:o.end}))}),o=K(e,t,a,R(e.file,r));return e.currentModule.records.push(o),o},Qo=(e,t)=>({line:e.tokens[t].line,column:e.tokens[t].column}),$o=(e,t)=>{let n=[],r=t;for(;e.tokens[r]?.kind===`Identifier`;){let t=M(e,r+1,`(`)?Me(e,r+1):r,i=e.tokens.slice(r+1,t).filter(e=>e.text===`_`).length;if(n.push({name:e.tokens[r].text,arity:i,location:{...Qo(e,r),range:{module:e.name,start:Qo(e,r),end:Qo(e,t)}}}),!M(e,t+1,`,`))break;r=t+2}return n},es=(e,t)=>{let n=[...t.definitions.map(t=>({unit:{kind:`Definition`,definition:t},span:cs(e,t)})),...(t.instances??[]).map(t=>({unit:{kind:`Instance`,instance:t},span:cs(e,t)}))],r=N(e,t).start,i=P(e,t.body).start,a=[];for(let t=r+1;t<i;t++){let r=n.some(e=>e.span.start<=t&&t<=e.span.end);M(e,t,`RECURSIVE`)&&!r&&a.push({unit:{kind:`Recursive`,declarations:$o(e,t+1)},span:{start:t,end:t}})}return[...n,...a].toSorted((e,t)=>e.span.start-t.span.start).map(e=>e.unit)},ts=(e,t)=>{let n=At();return _o(e,n,()=>{e.curLevel++,e.unresolvedCount[e.curLevel]=0;let r=[],i=[];es(e.file,t).forEach(t=>{t.kind===`Recursive`?fs(e,t.declarations):t.kind===`Instance`?gs(e,t.instance,r,i):t.definition.kind===`Function`?ds(e,t.definition,r):ls(e,t.definition,r)}),ps(e),e.curLevel=Math.max(e.curLevel-1,0);let a=q(e,t.body);return{...G(e.getId()),kind:`LetIn`,opDefs:r,instances:i,body:a,context:n,location:fo(e.file,t)}})},ns=(e,t)=>{let n=N(e.file,t),r=R(e.file,n);return _o(e,At(),()=>{let i=t.pattern,a=i.kind===`Name`?[i.name]:i.names;if(t.set===void 0){let o=Mt(e.file,n.start,n.end,a),s=a.map((t,r)=>vo(e,t,0,L(e.file,i.kind===`Name`?n.start:o[r]),!0)),c=zo(e,s,t.body);return K(e,`$UnboundedChoose`,[c],r,{unbounded:s})}let o=q(e,t.set),s=N(e.file,t.set),c=Mt(e.file,n.start,s.start,a),l=a.map((t,n)=>vo(e,t,0,L(e.file,c[n]),!0)),u=zo(e,l,t.body);return K(e,`$BoundedChoose`,[u],r,{bounded:[l],tupleOrs:[i.kind===`Tuple`],ranges:[o]})})},rs=(e,t)=>{if(Oo(t.operator)||ko(t.operator)||t.args.length>2||ro(e.contexts,Ct(t.operator))!==void 0)return;let n=N(e.file,t);if(e.file.tokens[n.start].text===t.operator&&M(e.file,n.start+1,`(`))return;let r=P(e.file,t.args[0]),i=t.args.length===1&&r.start!==n.start,a=i?n.start:r.end+1,o=ze(e.file,a);return{index:a,name:i&&o===`-`?`-.`:o,fixity:i?`prefix`:t.args.length===2?`infix`:`postfix`}},q=(e,t)=>{let n=fo(e.file,t);switch(t.kind){case`Number`:return{...G(e.getId()),kind:`Numeral`,value:Ao(t.text??String(t.value)),location:n};case`Decimal`:{let[r,i]=t.text.split(`.`),a=BigInt(r+i),o=a<=9223372036854775807n;return{...G(e.getId()),kind:`Decimal`,mantissa:a.toString(),exponent:String(o?-i.length:i.length),integralPart:r,fractionalPart:i,location:n}}case`String`:return wo(e,t.value,n);case`Identifier`:{let n=Fo(e,t);return Io(e,n),n}case`Apply`:{let r=rs(e,t);if(r!==void 0)return e.addError(L(e.file,r.index),`Could not find declaration or definition of symbol '${r.name}'.`),e.addError(n,`Couldn't resolve ${r.fixity} operator symbol \`${r.name}'.`),{...So(e),nullKind:`absent`};let i=Fo(e,t);return(ko(t.operator)||Oo(t.operator))&&Io(e,i),i}case`Bracket`:return e.addError(L(e.file,N(e.file,t).start),"Unsupported expression type `['."),{...So(e),nullKind:`absent`};case`OperatorReference`:case`Lambda`:{let r=e.file.tokens[N(e.file,t).start],i=t.operator??r.text,a=ro(e.contexts,Ct(i));return e.addError(n,r.text===`LAMBDA`?`LAMBDA expression used where an expression is required.`:a===void 0?`Could not find declaration or definition of symbol '${r.spelling??i}'.`:`The operator ${Ct(i)} requires ${we(a)} arguments.`),{...So(e),nullKind:`absent`}}case`And`:case`Or`:return Ko(e,t);case`Prime`:return K(e,`'`,[q(e,t.expression)],n);case`Unchanged`:return K(e,`UNCHANGED`,[q(e,t.expression)],n);case`Enabled`:return K(e,`ENABLED`,[q(e,t.expression)],n);case`Always`:return K(e,`[]`,[q(e,t.expression)],n);case`Eventually`:return K(e,`<>`,[q(e,t.expression)],n);case`If`:return K(e,`$IfThenElse`,[q(e,t.condition),q(e,t.consequent),q(e,t.alternative)],n);case`Case`:return qo(e,t);case`Let`:return ts(e,t);case`Forall`:case`Exists`:return Bo(e,t.kind===`Forall`?`$BoundedForall`:`$BoundedExists`,t.bounds,N(e.file,t).start,t.body,n);case`UnboundedQuantifier`:{let r=N(e.file,t),i=N(e.file,t.body),a=Mt(e.file,r.start,i.start,t.names),o=t.isTemporal?t.quantifier===`Forall`?`$TemporalForall`:`$TemporalExists`:t.quantifier===`Forall`?`$UnboundedForall`:`$UnboundedExists`;return _o(e,At(),()=>{let r=t.names.map((t,n)=>vo(e,t,0,L(e.file,a[n]),!0)),i=zo(e,r,t.body);return K(e,o,[i],n,{unbounded:r})})}case`Choose`:return ns(e,t);case`SetEnumeration`:return K(e,`$SetEnumerate`,t.elements.map(t=>q(e,t)),n);case`Tuple`:return K(e,`$Tuple`,t.elements.map(t=>q(e,t)),n);case`SetFilter`:{let r=q(e,t.bound.set),i=N(e.file,t);return _o(e,At(),()=>{let a=is(e,[t.bound],i.start,[r]),o=zo(e,a.bounded.flat(),t.predicate);return K(e,`$SubsetOf`,[o],n,a)})}case`SetMap`:return Bo(e,`$SetOfAll`,t.bounds,N(e.file,t.expression).end+1,t.expression,n);case`FunctionConstruction`:return Bo(e,`$FcnConstructor`,t.bounds,N(e.file,t).start,t.body,n);case`FunctionSet`:return K(e,`$SetOfFcns`,[q(e,t.domain),q(e,t.range)],n);case`Record`:return Zo(e,`$RcdConstructor`,t);case`RecordSet`:return Zo(e,`$SetOfRcds`,t);case`Except`:return Yo(e,t);case`ExceptAt`:{let t=e.exceptStack[e.exceptStack.length-1],r=e.exceptSpecStack[e.exceptSpecStack.length-1];return t===void 0||r===void 0?(e.addError(n,`@ used where its meaning is not defined.`),So(e)):{...G(e.getId()),kind:`At`,except:t,component:r,location:r.location}}case`FunctionApplication`:{let r=q(e,t.function);if(ne(r))return r;Io(e,r);let i=r.kind===`OpAppl`?r.operator:void 0,a=i?.kind===`OpDef`&&i.defKind===`UserDefined`?i.body:void 0;if(a?.kind===`OpAppl`&&(a.operator.name===`$NonRecursiveFcnSpec`||a.operator.name===`$RecursiveFcnSpec`)){let r=(a.bounded??[]).reduce((e,t,n)=>e+(a.tupleOrs?.[n]?1:t.length),0);if(t.args.length>=2&&r!==t.args.length)return e.addError(n,`Function '${i?.name}' is defined with ${r} parameters, but is applied to ${t.args.length} arguments.`),So(e)}let o=t.args.length===1?q(e,t.args[0]):K(e,`$Tuple`,t.args.map(t=>q(e,t)),n);return K(e,`$FcnApply`,[r,o],n)}case`FieldAccess`:{let r=q(e,t.record),i=N(e.file,t);return K(e,`$RcdSelect`,[r,wo(e,t.field,L(e.file,i.end))],n)}case`Product`:return K(e,`$CartesianProd`,t.factors.map(t=>q(e,t)),n);case`BoxAction`:case`AngleAction`:return K(e,t.kind===`BoxAction`?`$SquareAct`:`$AngleAct`,[q(e,t.action),q(e,t.subscript)],n);case`WeakFairness`:case`StrongFairness`:return K(e,t.kind===`WeakFairness`?`$WF`:`$SF`,[q(e,t.subscript),q(e,t.action)],n);case`Label`:return os(e,t);case`Subexpression`:return Fo(e,t);case`Selection`:return q(e,t.expression)}},is=(e,t,n,r)=>{let i=Lo(t),a=n;return{bounded:i.map(t=>{let n=N(e.file,t[0].set),r=t.flatMap(e=>e.pattern.kind===`Name`?[e.pattern.name]:e.pattern.names),i=Mt(e.file,a,n.start,r);return a=n.end+1,r.map((t,n)=>vo(e,t,0,L(e.file,i[n]),!0))}),tupleOrs:i.map(e=>e[0].pattern.kind===`Tuple`),ranges:r}},as=e=>{let t=So(e);return{...G(t.id),kind:`Label`,name:`nullLabelNode`,params:[],body:t,labels:/* @__PURE__ */ new Map,isAssumeProve:!1,location:t.location}},os=(e,t)=>{let n=fo(e.file,t),r=e.labelScopes.at(-1);if(r===void 0)return e.addError(n,`Label not in definition or proof step.`),as(e);if(e.assumeProveState.isDeclared.slice(2,e.assumeProveState.depth+1).some(Boolean))return e.addError(n,`Label not allowed within scope of declaration in nested ASSUME/PROVE.`),as(e);if(e.exceptStack.length>0&&e.exceptSpecStack.length>0)return e.addError(n,`Labels inside EXCEPT clauses are not yet implemented.`),as(e);co(e);let i=q(e,t.body),a=lo(e),o=Mt(e.file,N(e.file,t).start,N(e.file,t.body).start,t.params),s=t.params.map((n,r)=>{let i=ro(e.contexts,n);if(i?.kind===`FormalParam`)return i;let a=L(e.file,o[r]);return e.addError(a,`Illegal parameter ${n} of label \`${t.name}'.`),vo(e,n,0,a,!1)}),c={...G(e.getId()),kind:`Label`,name:t.name,params:s,body:i,labels:a,isAssumeProve:!1,location:n},l=/* @__PURE__ */ new Set;if(s.forEach(t=>{l.has(t)&&e.addError(n,`Repeated formal parameter ${t.name} \nin label \`${c.name}'.`),l.add(t)}),r.params.flat().forEach(t=>{l.delete(t)||e.addError(n,`Label ${c.name} must contain formal parameter \`${t.name}'.`)}),l.size>0){let t=[...l].map(e=>`${e.name} `).join(``);e.addError(n,`Label ${c.name} declares extra parameter(s) ${t}`)}r.labels.has(c.name)?e.addError(n,`Duplicate label \`${c.name}'.`):r.labels.set(c.name,c);let u=e.assumeProveState.goal;return u&&e.labelGoals.set(c,{scope:u,clause:e.assumeProveState.goalClause}),c},ss=(e,t,n,r)=>{let i=n.start;return t.params.map(t=>{let n=t.location?_e(e.file,t.location):Xo(e.file,i,t.name),a=ys(e.file,n,t.arity);i=a.end+1;let o=t.arity===1&&M(e.file,n+1,`_`);return vo(e,o?e.file.tokens[n].spelling??t.name:Ct(t.name),t.arity,R(e.file,a),r)})},cs=(e,t)=>{let n=po(e,t.location);return t.isLocal&&!M(e,n.start,`LOCAL`)&&M(e,n.start-1,`LOCAL`)?{start:n.start-1,end:n.end}:n},ls=(e,t,n)=>{let r=cs(e.file,t),i=R(e.file,r),a=Ct(t.name),o={start:t.isLocal?r.start+1:r.start,end:r.end},s=_o(e,At(),()=>{let n=ss(e,t,o,!0),r=ro(e.contexts,a);if(r?.kind===`OpDef`&&r.inRecursive&&!r.isDefined){let t=r.params?.length===n.length&&n.every(e=>e.arity===0);r.letInLevel===e.curLevel?(t||e.addError(i,`Definition of ${r.name} has different arity than its RECURSIVE declaration.`),r.params=n):e.addError(i,`Recursive operator ${a} defined at wrong LET/IN level.`)}else r!==void 0&&e.addError(i,`Operator ${a} already defined or declared.`);return co(e),{params:n,body:q(e,t.body),existing:r}}),c=lo(e),l=s.existing,u=s.params,d=me(e.file,r.start);if(l?.kind===`OpDef`&&l.inRecursive&&!l.isDefined&&l.letInLevel===e.curLevel){l.weights=u.map(()=>0),l.maxLevels=u.map(()=>3),l.isLeibnizArg=u.map(()=>!0),l.labels=c,us(e,l,s.body,i,d),e.currentModule.definitions.push(l),n?.push(l);return}let f=yo(e,{name:a,params:u,body:s.body,isLocal:t.isLocal,location:i,preComments:d,labels:c});so(e,f),bo(e,f),e.currentModule.definitions.push(f),n?.push(f)},us=(e,t,n,r,i)=>{t.isDefined=!0,t.body=n,t.location=r,t.preComments=i,t.inRecursive&&(e.unresolvedCount[e.curLevel]--,e.unresolvedSum--)},ds=(e,t,n)=>{let r=cs(e.file,t),i=R(e.file,r),a=At(),o=t.isLocal?r.start+1:r.start,s=_o(e,a,()=>Ro(e,t.bounds,o+1)),c=_o(e,a,()=>ro(e.contexts,t.name)),l=_o(e,a,()=>vo(e,t.name,0,i,c===void 0)),u=K(e,`$NonRecursiveFcnSpec`,[],i,{unbounded:[l],...s}),d=c?.kind===`OpDef`&&c.inRecursive&&!c.isDefined,f=d&&c.letInLevel===e.curLevel;f?c.arity!==0&&e.addError(i,`Function ${c.name} has operator arguments in its RECURSIVE declaration.`):d?e.addError(i,`Recursive function ${t.name} defined at wrong LET/IN level.`):c!==void 0&&e.addError(i,`Function name \`${t.name}' already defined or declared.`);let p=me(e.file,r.start),m=c===void 0?yo(e,{name:t.name,params:[],body:u,isLocal:t.isLocal,location:i,preComments:p}):c.kind===`OpDef`&&(f||!d)?c:void 0;f?c.arity===0&&us(e,c,u,i,p):c===void 0&&m!==void 0&&(so(e,m),bo(e,m)),m!==void 0&&(e.currentModule.definitions.push(m),n?.push(m)),e.functions.unshift({name:t.name,node:u}),co(e);let h=()=>zo(e,s.bounded.flat(),t.body),g=m===void 0?h():_o(e,a,h),_=lo(e);m!==void 0&&(m.labels=_),e.functions.shift(),u.operands=[g],u.operator.name===`$NonRecursiveFcnSpec`&&(u.unbounded=void 0)},fs=(e,t)=>{e.unresolvedSum===0&&e.recursiveSections.count++,e.unresolvedCount[e.curLevel]+=t.length,e.unresolvedSum+=t.length,t.forEach(t=>{let n=bs(e.file,t);e.getId();let r=Array.from({length:t.arity},()=>vo(e,``,0,void 0,!1)),i=yo(e,{name:Ct(t.name),params:r,location:R(e.file,n),isDefined:!1,inRecursive:!0,inRecursiveSection:!0,recursiveSection:e.recursiveSections.count,letInLevel:e.curLevel});so(e,i),e.recursiveDeclarations.push(i),e.currentModule.opDefsInRecursiveSection.push(i)})},ps=e=>{e.unresolvedCount[e.curLevel]!==0&&(e.recursiveDeclarations.filter(t=>t.letInLevel===e.curLevel&&!t.isDefined).forEach(t=>e.addError(t.location,`Symbol ${t.name} declared in RECURSIVE statement but not defined.`)),e.unresolvedSum-=e.unresolvedCount[e.curLevel])},ms=(e,t,n,r)=>{e.getId();let i=le(n.table).filter(e=>e.kind===`OpDecl`),a=i.flatMap(t=>{let n=ro(e.contexts,t.name);if(n===void 0)return[];let i=t.declKind===3||t.declKind===2&&t.arity===0;return i&&Do(e,n,[],r),[{op:t,expr:i?xo(e,n,[],r):To(e,n,r),isImplicit:!0}]}),o=(t,n)=>{(n.kind===`OpArg`?we(n.op):0)!==t.arity&&e.addError(n.location,`An operator must be substituted for symbol '${t.name}', and it must have arity ${t.arity}.`)},s=cs(e.file,t),c=ie(e.file,s.start,s.end,`WITH`)+1;return t.substitutions.forEach(t=>{let i=ie(e.file,c,s.end,t.name);i!==-1&&(c=N(e.file,t.expression).end+1);let l=kt(n,Ct(t.name));if(l?.kind!==`OpDecl`){e.addError(i===-1?r:L(e.file,i),`Identifier '${i===-1?t.name:ze(e.file,i)}' is not a legal target of a substitution. \nA legal target must be a declared CONSTANT or VARIABLE in the module being instantiated. \n(Also, check for warnings about multiple declarations of this same identifier.)`);return}let u=l.arity===0?q(e,t.expression):Wo(e,t.expression,l);o(l,u);let d=a.find(e=>e.op.name===l.name);d&&!d.isImplicit?e.addError(fo(e.file,t.expression),`Multiple substitutions for symbol '${l.name}' in substitution.`):d?(d.expr=u,d.isImplicit=!1):a.push({op:l,expr:u,isImplicit:!1})}),a.filter(t=>t.isImplicit&&e.version!==`1.7.4`).forEach(e=>o(e.op,e.expr)),i.filter(e=>!a.some(t=>t.op.name===e.name)).forEach(t=>e.addError(r,`Substitution missing for symbol ${t.name} declared at ${I(t.location)} \nand instantiated in module ${e.currentModule.name}.`)),a},hs=(e,t,n,r,i,a,o=e.currentModule)=>(ne(r)&&e.addError(a,t===`SubstIn`?`Substitution error, probably due to error
35
+ in module being instantiated.`:`Substitution error, probably due to error in module being instantiated.`),{...G(e.getId()),kind:t,substs:n,body:r,instantiatingModule:o,instantiatedModule:i,location:a}),gs=(e,t,n,r)=>{let i=cs(e.file,t),a=R(e.file,i),o=me(e.file,i.start),s=t.name??``,c=At(),l=t.isLocal?i.start+1:i.start;t.params.length>0&&e.contexts.push(c);let u=ss(e,t,{start:l,end:i.end},t.params.length>0),d=go(e,t.module),f=d.context,p=ms(e,t,f,a);t.params.length>0&&e.contexts.pop(),le(f.table).forEach(r=>{if(r.kind!==`OpDef`||r.isLocal||r.defKind!==`UserDefined`&&r.defKind!==`ModuleInstance`)return;let i=[...u,...r.params??[]],c=`${s}!${r.name}`,l=r.defKind===`UserDefined`?yo(e,{name:c,params:i,body:p.length>0&&r.body?hs(e,`SubstIn`,p,r.body,d,a):r.body,isLocal:t.isLocal,location:a,source:r.source??r,preComments:o,labels:r.labels}):yo(e,{defKind:`ModuleInstance`,name:c,params:i,isLocal:t.isLocal,location:a,module:r.module,source:r.source??r,preComments:o});so(e,l),r.defKind===`UserDefined`&&bo(e,l),(n??e.currentModule.definitions).push(l)}),le(f.table).forEach(r=>{if(r.kind!==`ThmOrAssumpDef`||r.isLocal)return;let i=p.length>0?hs(e,`APSubstIn`,p,r.body,d,a):r.body,o={...G(e.getId()),kind:`ThmOrAssumpDef`,name:`${s}!${r.name}`,isTheorem:r.isTheorem,body:i,params:[...u,...r.params],isLocal:t.isLocal,location:a,module:e.currentModule,source:r.source??r,labels:r.labels,isLeibnizArg:[],isLeibniz:!1,opLevelCond:[],maxLevels:[],minMaxLevel:[]};so(e,o),(n??e.currentModule.definitions).push(o)});let m={...G(e.getId()),kind:`Instance`,name:s,isLocal:t.isLocal,params:u,module:d,substs:p,location:a};(r??e.currentModule.topLevel).push(m);let h=yo(e,{defKind:`ModuleInstance`,name:s,params:u,isLocal:t.isLocal,location:a,preComments:o});so(e,h),e.version!==`1.7.4`&&n?.push(h)},_s=(e,t)=>(so(e,t),t),vs=(e,t,n=!0,r)=>{let i=cs(e.file,t),a=r??R(e.file,i),o=me(e.file,i.start),s=go(e,t.module),c=s.context,l=ms(e,t,c,a),u=t.isLocal,d=oo(s);le(c.table).forEach(t=>{if(t.kind!==`OpDef`||t.defKind!==`UserDefined`||t.isLocal)return;let n=(n,r)=>{let i=yo(e,{name:t.name,params:t.params,body:r,isLocal:u,location:a,module:n,source:t.source??t,preComments:o,labels:t.labels});return so(e,i),i},r=t.module===void 0||oo(t.module),i=d||r?u?n(t.module,t.body):_s(e,t):n(e.currentModule,t.body&&hs(e,`SubstIn`,l,t.body,s,a));e.currentModule.definitions.push(i),bo(e,i)}),le(c.table).forEach(t=>{if(t.kind!==`ThmOrAssumpDef`||t.isLocal)return;let r=(n,r)=>{let i={...t,...G(e.getId()),body:r,isLocal:u,location:a,module:n,source:t.source??t};return so(e,i),i},i=d?u?r(t.module,t.body):_s(e,t):oo(t.module)?u?r(e.currentModule,t.body):t:r(e.currentModule,hs(e,`APSubstIn`,l,t.body,s,a));n&&e.currentModule.definitions.push(i)});let f={...G(e.getId()),kind:`Instance`,name:void 0,isLocal:u,params:[],module:s,substs:l,location:a};return n&&e.currentModule.topLevel.push(f),f},ys=(e,t,n)=>n===0?{start:t,end:t}:M(e,t,`_`)?{start:t,end:M(e,t+2,`_`)?t+2:t+1}:M(e,t+1,`(`)?{start:t,end:Me(e,t+1)}:{start:t,end:M(e,t+1,`_`)?t+1:t},bs=(e,t)=>ys(e,po(e,t.location).start,t.arity),xs=(e,t,n)=>{let r=bs(e.file,t);t.name===`@`&&n===3&&e.addError(R(e.file,r),`Attempted to declare '@' as a variable.`);let i={...G(e.getId()),levelChecked:1,level:+(n===3),kind:`OpDecl`,name:Ct(t.name),arity:t.arity,declKind:n,location:R(e.file,r),module:e.currentModule};return n===2&&(i.levelParams.add(i),i.allParams.add(i)),so(e,i),i},Ss=(e,t,n)=>{e.unresolvedSum!==0&&e.addError(mo(e.file,t),`${n} may not appear within a recursive definition section.`)},Cs={Constant:{declKind:24,level:0},Variable:{declKind:25,level:1},State:{declKind:26,level:1},Action:{declKind:27,level:2},Temporal:{declKind:28,level:3}},ws=(e,t)=>{let n=ho(e,t.name)??(t.name===e.currentModule.name?e.currentModule:void 0);return n===void 0?(e.addError(L(e.file,_e(e.file,t.location)+1),`Module \`${t.name}' used without being extended or instantiated.`),[]):[n]},Ts=(e,t)=>t.flatMap(t=>{if(t.kind===`ModuleFact`)return ws(e,t);let n=t.kind===`ExceptAt`?{kind:`Identifier`,name:`@`,location:t.location}:t,r=qa(n);if(r===void 0||!Ja(r))return[q(e,t)];let i=Po(e,n,0,!0,!1);if(i.kind===`ThmOrAssumpDef`)throw new s(`Expected a fact`);return[i]}),Es=(e,t)=>t.flatMap(t=>{if(t.kind===`ModuleFact`)return ws(e,t);let n=ct.get(t)??[];if(n.forEach(t=>e.addError(t.location,t.message)),n.length>0)return[];let r=fo(e.file,t),i=Po(e,Ce(t)??(t.kind===`OperatorReference`?{kind:`Identifier`,name:t.operator,location:t.location}:t),-1,!1,!0,r);return i.kind===`OpDef`||i.kind===`ThmOrAssumpDef`&&!i.name.startsWith(`<`)?[i]:(e.addError(r,`DEF clause entry should describe a defined operator.`),[])}),Ds=(e,t,n)=>{t.isOnly||t.facts.length+t.defs.length>0||e.addError(n,`Empty BY, USE, or HIDE`)},Os=(e,t)=>{let n=mo(e.file,t.location);Ds(e,t,n);let r=Ts(e,t.facts),i=Es(e,t.defs);return r.length+i.length===0&&e.addError(n,`Empty USE or HIDE statement.`),t.kind===`Hide`&&r.filter(e=>e.kind===`OpAppl`&&e.operator.kind!==`ThmOrAssumpDef`).forEach(t=>e.addError(t.location,`The only expression allowed as a fact in a HIDE is
36
+ the name of a theorem, assumption, or step.`)),{...G(e.getId()),kind:`UseOrHide`,facts:r,defs:i,isOnly:t.isOnly,isHide:t.kind===`Hide`,location:n}},ks=(e,t)=>{let n=po(e.file,t.location),r=t.set&&q(e,t.set),i=Xo(e.file,n.start,t.name),a=Cs[t.level],o={...G(e.getId()),levelChecked:1,level:a.level,kind:`OpDecl`,name:Ct(t.name),arity:t.arity,declKind:a.declKind,location:R(e.file,ys(e.file,i,t.arity)),module:e.currentModule};return so(e,o),{...G(e.getId()),kind:`NewSymb`,declaration:o,set:r,location:R(e.file,n)}},As=(e,t,n,r)=>{let i=po(e.file,t.location),a=De(e.file,i.start-1),o=N(e.file,t.conclusion).start,s=e.file.tokens.findLastIndex((e,t)=>t<o&&e.kind===`Keyword`&&e.text===`PROVE`),c=R(e.file,{start:a?i.start-1:i.start,end:i.start});a!==De(e.file,s-1)&&e.addError(c,a?`[]ASSUME matched by PROVE instead of []PROVE`:`ASSUME matched by []PROVE instead of PROVE`);let l=e.getId();n>1&&e.contexts.push(At()),a&&e.contexts.some(t=>e.assumeContexts.has(t))&&e.addError(c,`[]ASSUME used within the scope of an ordinary ASSUME's assumptions`),a||e.assumeContexts.add(no(e.contexts));let u={isDeclaredBefore:[!1],hasGoal:r!==void 0,isSuffices:r?.isSuffices??!1,isInProof:!0};e.assumeProveState.depth=n,e.assumeProveState.isDeclared[n]=!1,n===1&&(e.assumeProveState.goal=r&&u,e.assumeProveState.goalClause=0);let d=t.assumptions.map((t,r)=>{let i=t.kind===`NewSymbol`,a=t.kind===`AssumeProve`?As(e,t,n+1):i?ks(e,t):q(e,t);return e.assumeProveState.depth=n,i&&(e.assumeProveState.isDeclared[n]=!0),u.isDeclaredBefore.push(u.isDeclaredBefore[r]||i),n===1&&e.assumeProveState.goalClause++,a}),f=q(e,t.conclusion);n>1&&e.contexts.pop(),e.assumeProveState.depth=n-1,n===1&&(e.assumeProveState.goal=void 0);let p={...G(l),kind:`AssumeProve`,assumptions:d,goal:f,isSuffices:u.isSuffices,isBoxed:a,location:R(e.file,{start:a?i.start-1:i.start,end:i.end})};return e.assumeProveScopes.set(p,u),p},js=(e,t,n,r,i,a,o=!0)=>({...G(t),kind:`ThmOrAssumpDef`,name:n,isTheorem:o,body:r,params:[],isLocal:!1,location:i,module:e.currentModule,source:void 0,labels:a,isLeibnizArg:[],isLeibniz:!1,opLevelCond:[],maxLevels:[],minMaxLevel:[]}),Ms=(e,t)=>{let n=mo(e.file,t.location);t.kind===`By`&&Ds(e,t,n);let r=t.kind===`By`?Ts(e,t.facts):[],i=t.kind===`By`?Es(e,t.defs):[];return t.kind===`By`&&e.getId(),t.kind===`By`&&r.length+i.length===0&&e.addError(n,`Empty BY`),{...G(e.getId()),kind:`LeafProof`,facts:r,defs:i,isOmitted:t.kind===`Omitted`,isOnly:t.kind===`By`&&t.isOnly,location:n}},Ns=(e,t,n)=>{let r=R(e.file,n);switch(t.kind){case`Have`:return K(e,`$Have`,[q(e,t.expression)],r);case`Case`:return K(e,`$Pfcase`,[q(e,t.expression)],r);case`Witness`:return K(e,`$Witness`,t.expressions.map(t=>q(e,t)),r);case`Qed`:return K(e,`$Qed`,[],r);case`Take`:case`Pick`:{let i=t.kind===`Pick`,a=i?`$Pick`:`$Take`;i&&e.contexts.push(At());let o=n=>t.kind===`Pick`?[zo(e,n,t.body)]:[];if(t.bounds.length>0){let i=Ro(e,t.bounds,n.start),s=o(i.bounded.flat());return K(e,a,s,r,i)}let s=Mt(e.file,n.start,n.end+1,t.names),c=t.names.map((t,n)=>vo(e,t,0,L(e.file,s[n]),!0)),l=o(c);return K(e,a,l,r,{unbounded:c})}}},Ps=(e,t)=>{if((t.kind===`And`||t.kind===`Or`)&&!t.isBulleted)return!0;if(t.kind!==`Apply`||t.args.length!==2)return!1;let n=P(e,t.args[0]),r=N(e,t).start;return n.start===r&&!M(e,n.end+1,`(`)},Fs=(e,t)=>{if(t.kind!==`Steps`)return Ms(e,t);let n=At();e.contexts.push(n);let r=[],i=[],a,o=(t,n,i)=>{if(t.kind===`Define`){let n=t.definitions.map(t=>{let n=[];t.kind===`Instance`?gs(e,t,n,r):t.kind===`Function`?ds(e,t,n):ls(e,t,n);let i=n[t.kind===`Instance`?n.length-1:0];if(i?.kind!==`OpDef`)throw new s(`A DEFINE step defines no operator`);return i});return{...G(e.getId()),kind:`DefStep`,defs:n,location:R(e.file,i)}}if(t.kind===`Use`||t.kind===`Hide`)return{...Os(e,t),location:R(e.file,n)};if(t.kind===`Instance`)return vs(e,t,!1,R(e.file,i))},c=t.steps.map(t=>{let n=po(e.file,t.location),r=ye(e.file,t.head),c={start:r.start+1,end:r.end},l=t.body;t.name!==void 0&&/^<[*+]>/.test(t.token)&&e.addError(L(e.file,n.start),`<*> and <+> cannot be used for a named step.`),t.name!==void 0&&co(e);let u=t.name===void 0?void 0:e.getId();l.kind!==`Assert`&&(a=void 0);let d=o(l,n,c);if(d!==void 0)return t.name!==void 0&&so(e,yo(e,{defKind:`NumberedProofStep`,name:t.name,location:R(e.file,n),labels:lo(e),step:d})),d;let f=l.kind===`Assert`&&l.statement.kind===`AssumeProve`;f&&(a=void 0);let p=l.kind===`Assert`&&l.isSuffices,m=At(),h=l.kind===`Assert`?(n=>{if(n.kind===`AssumeProve`){let r=_o(e,m,()=>As(e,n,1,t.name===void 0?void 0:{isSuffices:p}));return r.isSuffices=p,r}if(p){let t=q(e,n);return K(e,`$Suffices`,[t],R(e.file,c))}let r=a!==void 0&&n.kind===`Apply`&&Ps(e.file,n)&&n.args[0].kind===`ExceptAt`,i=r?q(e,n.args[1]):void 0,o=r?xo(e,Eo(e,n.operator,fo(e.file,n)),[K(e,`$Nop`,[a],fo(e.file,n.args[0])),i],fo(e.file,n)):q(e,n),s=o.kind===`OpAppl`?o.operands[1]:void 0;return a=Ps(e.file,n)?s:void 0,o})(l.statement):Ns(e,l,c);if(h===void 0)throw new s(`Unexpected proof step ${l.kind}`);let g=l.kind===`Pick`?e.contexts.pop():void 0,_=t.name===void 0||u===void 0?void 0:js(e,u,t.name,h,L(e.file,_e(e.file,t.location)),lo(e));_&&so(e,_);let v=f&&!p;v&&e.contexts.push(m);let y=t.proof&&Fs(e,t.proof);return v&&e.contexts.pop(),uo(e,h),f&&p&&(i.push(m),e.contexts.push(m)),g?.symbols.forEach(t=>so(e,t)),{...G(e.getId()),kind:`Theorem`,definition:_,body:h,proof:y,isSuffices:p,location:R(e.file,n)}});return i.forEach(()=>{e.contexts.pop()?.symbols.forEach(e=>qe(n,e))}),e.contexts.pop(),{...G(e.getId()),kind:`NonLeafProof`,steps:c,instances:r,proofLevel:t.level,location:mo(e.file,t.location)}},Is=(e,t)=>{let n=mo(e.file,t.location),r=t.statement,i=At();t.name!==void 0&&co(e);let a=t.name===void 0?void 0:e.getId();r.kind===`AssumeProve`&&e.contexts.push(i);let o=r.kind===`AssumeProve`?As(e,r,1,t.name===void 0?void 0:{isSuffices:!1}):q(e,r),s=t.name===void 0||a===void 0?void 0:js(e,a,t.name,o,n,lo(e));s&&(r.kind===`AssumeProve`&&e.contexts.pop(),so(e,s),e.currentModule.definitions.push(s),r.kind===`AssumeProve`&&e.contexts.push(i));let c=t.proof&&Fs(e,t.proof);r.kind===`AssumeProve`&&e.contexts.pop(),uo(e,o);let l={...G(e.getId()),kind:`Theorem`,definition:s,body:o,proof:c,isSuffices:!1,location:n};e.currentModule.topLevel.push(l)},Ls=(e,t)=>{let n=mo(e.file,t.location);t.name!==void 0&&co(e);let r=q(e,t.expression),i=t.name===void 0?void 0:js(e,e.getId(),t.name,r,n,lo(e),!1);i&&(so(e,i),e.currentModule.definitions.push(i));let a={...G(e.getId()),kind:`Assume`,definition:i,body:r,location:n};e.currentModule.topLevel.push(a)},Rs=e=>e.kind===`OpDef`||e.kind===`FormalParam`?`definition`:`declaration`,zs=e=>[...e.kind===`Let`?e.instances??[]:[],...$e(e).flatMap(zs)],Bs=e=>e.kind===`AssumeProve`?[...e.assumptions,e.conclusion].flatMap(e=>e.kind===`NewSymbol`?[]:Bs(e)):zs(e),Vs=e=>e?.kind===`Steps`?e.steps.flatMap(e=>[...e.body.kind===`Instance`?[e.body]:[],...e.body.kind===`Define`?e.body.definitions.flatMap(e=>e.kind===`Instance`?[e]:[]):[],...Vs(e.proof)]):[],Hs=(e,t)=>{let n=/* @__PURE__ */ new Set;for(let r of e.units)if(r.kind===`Module`&&n.add(r.module.name),r.kind===`Instance`&&r.instance.module===t.module)return n.has(t.module);return e.modules.some(e=>e.name===t.module&&Dt(e.location,t.location))},Us=e=>{let t=[],n=[],r=/* @__PURE__ */ new Map,i=(a,o)=>{let s=a===e,c=(e,t)=>e.forEach(e=>{t.push(e),r.has(e)||r.set(e,a.name)}),l=e=>!o.has(e);c(a.extends.filter(l),t),c(a.units.flatMap(e=>e.kind===`Instance`?[e.instance]:e.kind===`Definition`?zs(e.definition.body):e.kind===`Theorem`&&s?[...Bs(e.theorem.statement),...Vs(e.theorem.proof)]:e.kind===`Assumption`&&s?zs(e.assumption.expression):[]).filter(e=>l(e.module)&&!Hs(a,e)).map(e=>e.module),n);let u=new Map(o);a.modules.forEach(e=>{let t=new Map(u),n=/* @__PURE__ */ new Set,r=e=>{n.has(e)||(n.add(e),e.extends.forEach(e=>{let n=t.get(e);n!==void 0&&(n.modules.forEach(e=>{t.has(e.name)||t.set(e.name,e)}),r(n))}))};r(e),i(e,t),u.set(e.name,e)})};return i(e,/* @__PURE__ */ new Map),{extendees:t,instancees:n,importers:r}},Ws=(e,t,n={})=>{let r=[],i=(e,t)=>jt(r,{location:e,text:t,isWarning:!1}),a=(e,t)=>jt(r,{location:e,text:t,isWarning:!0}),o=n.version===`1.7.4`?-1:0,c=()=>++o,l=0;n.version!==`1.7.4`&&Wa(c);let u=Wa(c);c();let f=new Map(u.map(e=>[e.name,e])),p=/* @__PURE__ */ new Map,m=/* @__PURE__ */ new Map,h=(e,t)=>{let r=e===n.rootFileName&&n.rootFilePath||`${e}.tla`,i=t=>new d(`Could not parse module ${e} from file ${r}`,e,t),a=n.version===`1.7.4`?bt(t):void 0;if(a!==void 0)throw i(a);try{return de(He(t))}catch(e){throw e instanceof s?i(Qe(t)??`***Parse Error***\n${e.message}`):e}},g=(e,t,r)=>{let i=m.get(e);if(i)return i;if(t===void 0)throw new C(e,r,n.version!==`1.7.4`);n.onParse?.(e);let a=h(e,t);if(a.name!==e)throw new d(`File name '${e}' does not match the name '${a.name}' of the top level module it contains.`,void 0);let o={file:Oe(a.name,t),module:a};return m.set(e,o),o},_=[],v=/* @__PURE__ */ new Set,y=[],b=(e,n,r)=>{let i=y.indexOf(e);if(i!==-1)throw new d(`Circular dependency among .tla files; dependency cycle is:\n\n ${[...y.slice(i),e].map(e=>`${e}.tla`).join(` --> `)}`,void 0);if(v.has(e))return;v.add(e),y.push(e);let a=D(e,g(e,n,r).module);[...a.extendees,...a.instancees].forEach(n=>b(n,t(n),e)),y.pop(),_.push(e)},x=/* @__PURE__ */ new Set,S=(e,t)=>x.has(`${e} ${t}`),w=(e,t,n)=>{let r=m.get(e);if(!r||n.has(e))return;n.add(e);let i=D(e,r.module),a=i[t].find(t=>!S(e,t));if(a!==void 0)return{name:a,importer:e,namingModule:i.importers.get(a)??e};for(let r of[...i.extendees,...i.instancees]){let i=S(e,r)?w(r,t,n):void 0;if(i)return i}},T=n=>{g(n,e);let r=()=>w(n,`extendees`,/* @__PURE__ */ new Set)??w(n,`instancees`,/* @__PURE__ */ new Set);for(let e=r();e!==void 0;e=r())m.has(e.name)||g(e.name,t(e.name),e.namingModule),x.add(`${e.importer} ${e.name}`)},E=n.rootFileName??h(``,e).name,D=(e,t)=>{let r=Us(t);return e!==E||n.rootExtendees===void 0||(r.extendees.splice(t.extends.length,0,...n.rootExtendees),n.rootExtendees.forEach(t=>{r.importers.has(t)||r.importers.set(t,e)})),r};T(E),b(E,e);let ee=(e,t,r,o,s={count:0})=>{let u={kind:`Module`,id:c(),name:e.name,location:mo(t,e.location),extendees:[],context:no(o),topLevel:[],definitions:[],opDefsInRecursiveSection:[],isLevelChecked:!1,levelCorrect:!0,argLevelParams:/* @__PURE__ */ new Map,levelConstraints:/* @__PURE__ */ new Map,argLevelConstraints:/* @__PURE__ */ new Map,records:[]};r&&r.definitions.push(u);let d={version:n.version,addError:i,addWarning:a,getId:c,builtinsByName:f,externalModules:p,nullApplicationId:l,file:t,contexts:o,currentModule:u,curLevel:0,unresolvedCount:[0],unresolvedSum:0,recursiveSections:s,functions:[],exceptStack:[],exceptSpecStack:[],labelScopes:[],assumeContexts:/* @__PURE__ */ new WeakSet,assumeProveState:{depth:0,isDeclared:[],goal:void 0,goalClause:0},assumeProveScopes:/* @__PURE__ */ new WeakMap,labelGoals:/* @__PURE__ */ new WeakMap,recursiveDeclarations:[],selectorToNode:to({version:n.version,resolveSymbol:e=>ro(o,e),resolveSynonym:Ct,generateExpression:e=>q(d,e),generateArgument:(e,t,n,r)=>Go(d,e,t,n,r),createOpAppl:(e,t,n)=>{let r=xo(d,e,t,n);return Do(d,e,t,n),r},createOpArg:(e,t)=>To(d,e,t),createFormalParam:(e,t,n)=>vo(d,e,t,n,!1),createLambda:(e,n,r)=>yo(d,{name:`LAMBDA`,params:e,body:n,location:r,preComments:me(t,_e(t,{line:r.beginLine,column:r.beginColumn}))}),copySubstIn:(e,t)=>hs(d,`SubstIn`,e.substs,t,e.instantiatedModule,e.location,e.instantiatingModule),getBuiltin:e=>Co(d,e),addError:(e,t)=>(i(e,t),So(d)),isOutOfLabelScope:e=>{let t=d.labelGoals.get(e);return t!==void 0&&t.scope.isDeclaredBefore[t.clause]&&t.scope.isSuffices===t.scope.isInProof},isOutOfClauseScope:(e,t)=>{let n=d.assumeProveScopes.get(e);return n!==void 0&&n.isDeclaredBefore[t-1]&&(!n.hasGoal||n.isSuffices===n.isInProof)}})};return e.extends.forEach(e=>{let t=go(d,e);u.extendees.push(t);let n=no(o);t.context.symbols.forEach(e=>{if(e.kind!==`Module`&&e.kind!==`FormalParam`&&e.kind!==`OpDecl`&&e.isLocal)return;let t=e.kind===`Module`?oe(n,e.name):kt(n,e.name);t===void 0?qe(n,e):t!==e&&t.kind!==e.kind?i(e.location,`The ${Rs(e)} of '${e.name}' conflicts with \nits ${Rs(t)} at ${I(t.location)}.`):t!==e&&!ao(t,e)&&a(e.location,`Warning: the ${Rs(t)} of '${e.name}' conflicts with \nits ${Rs(t)} at ${I(t.location)}.`)}),u.topLevel.push(...t.topLevel)}),e.units.forEach(e=>{switch(e.kind){case`Variables`:Ss(d,e.location,`A VARIABLE declaration`),e.declarations.forEach(e=>xs(d,e,3));break;case`Constants`:Ss(d,e.location,`A declaration`),e.declarations.forEach(e=>xs(d,e,2));break;case`Recursive`:fs(d,e.declarations);break;case`Definition`:e.definition.kind===`Function`?ds(d,e.definition,void 0):ls(d,e.definition,void 0);break;case`Instance`:e.instance.name===void 0?vs(d,e.instance):gs(d,e.instance,void 0,void 0);break;case`Assumption`:Ss(d,e.assumption.location,`An ASSUME`),Ls(d,e.assumption);break;case`Theorem`:Ss(d,e.theorem.location,`A THEOREM`),Is(d,e.theorem);break;case`Use`:Ss(d,e.use.location,`A USE or HIDE`),u.topLevel.push(Os(d,e.use));break;case`Module`:{Ss(d,e.module.location,`A MODULE `);let n=ee(e.module,t,u,[...o,At()],d.recursiveSections);u.opDefsInRecursiveSection.push(...n.opDefsInRecursiveSection);let r=ho(d,n.name);r===void 0?qe(no(o),n):r!==n&&i(n.location,`Multiply-defined module '${n.name}': this definition or declaration conflicts \nwith the one at ${I(r.location)}.`);break}}}),ps(d),u},O=_.map(e=>{n.onAnalyze?.(e),l=Array.from({length:4},c)[1];let t=g(e,void 0),i=At();u.toReversed().forEach(e=>qe(i,e));let a=ee(t.module,t.file,void 0,[i]);return p.set(e,a),n.onModule?.(a,r),a});return{root:O[O.length-1],modules:O,messages:r}},Gs=(e,t,n,r)=>jt(e.messages,{location:t,text:n,isWarning:!1,...r!==void 0&&!e.isTlc174&&{code:r}}),J=(e,t)=>{for(let n of t)e.add(n)},Ks=(e,t,n)=>`${e.id}:${t}:${n.id}`,qs=(e,t,n,r)=>{e.set(Ks(t,n,r),{op:t,index:n,param:r})},Js=(e,t,n=()=>!0)=>{t.forEach((t,r)=>{n(t)&&e.set(r,t)})},Ys=(e,t,n)=>{e.set(t,Math.min(n,e.get(t)??3))},Xs=(e,t,n=()=>!0)=>{t.forEach((t,r)=>{n(r)&&Ys(e,r,t)})},Zs=(e,t)=>`${e.id}:${t}`,Qs=(e,t,n,r)=>{let i=Zs(t,n),a=e.get(i)?.level??0;e.set(i,{param:t,position:n,level:Math.max(r,a)})},$s=(e,t,n=()=>!0)=>{t.forEach(t=>{n(t)&&Qs(e,t.param,t.position,t.level)})},ec=(e,t)=>{e.levelParams=t.levelParams,e.allParams=t.allParams,e.levelConstraints=t.levelConstraints,e.argLevelConstraints=t.argLevelConstraints,e.argLevelParams=t.argLevelParams},tc=(e,t)=>{J(e.levelParams,t.levelParams),J(e.allParams,t.allParams),Xs(e.levelConstraints,t.levelConstraints),$s(e.argLevelConstraints,t.argLevelConstraints),Js(e.argLevelParams,t.argLevelParams)},nc=(e,t)=>t.includes(e.op)||t.includes(e.param),rc=e=>e.kind===`OpDecl`||e.kind===`FormalParam`,ic=e=>e.kind!==`Module`,ac=e=>e.kind===`OpDef`||e.kind===`ThmOrAssumpDef`,oc=(e,t)=>e.kind===`OpDef`&&e.arity<0?0:t,sc=(e,t)=>e.kind===`OpDef`?e.weights[oc(e,t)]??0:0,cc=(e,t)=>e.maxLevels[oc(e,t)]??3,lc=(e,t,n)=>e.minMaxLevel?.[t]?.[n]??0,uc=(e,t)=>e.kind===`OpDef`?e.isLeibnizArg?.[oc(e,t)]??!0:e.isLeibnizArg[t]??!0,dc=(e,t,n,r)=>e.opLevelCond?.[t]?.[n]?.[r]??!1,fc=e=>[...e.unbounded??[],...(e.bounded??[]).flat()],pc=(e,t)=>t.find(t=>t.op===e)?.expr,mc=(e,t,n)=>{let r=pc(e,t);return r===void 0?/* @__PURE__ */ new Set([e]):n?r.allParams:r.levelParams},hc=(e,t)=>{let n=/* @__PURE__ */ new Map;return e.forEach((e,r)=>{let i=pc(e.op,t);if(i===void 0){n.set(r,e);return}if(i.kind!==`OpArg`||!rc(i.op))return;let a=i.op;mc(e.param,t,!1).forEach(t=>qs(n,a,e.index,t))}),n},gc=(e,t,n,r,i)=>{let a=/* @__PURE__ */ new Map;return e.levelConstraints.forEach((e,r)=>{let i=n||r.kind!==`OpDecl`?e:r.declKind===2?0:r.declKind===3?1:e;mc(r,t,!1).forEach(e=>Ys(a,e,i))}),e.argLevelParams.forEach(e=>{let n=pc(e.op,t);if(n?.kind!==`OpArg`||n.op.kind!==`OpDef`)return;Y(n.op,r,i);let o=cc(n.op,e.index);mc(e.param,t,!1).forEach(e=>Ys(a,e,o))}),a},_c=(e,t,n,r)=>{let i=/* @__PURE__ */ new Map;return e.argLevelConstraints.forEach(e=>{let n=pc(e.param,t);n===void 0?Qs(i,e.param,e.position,e.level):n.kind===`OpArg`&&rc(n.op)&&Qs(i,n.op,e.position,e.level)}),e.argLevelParams.forEach(e=>{let a=pc(e.param,t);if(a===void 0)return;let o=pc(e.op,t),s=o===void 0?e.op:o.kind===`OpArg`?o.op:void 0;s!==void 0&&rc(s)&&(Y(a,n,r),Qs(i,s,e.index,a.level))}),i},vc=(e,t)=>Ae(e,3).length>0||(Dc(e,t),ce(e).some(e=>(e.body?.level??0)!==0))?!1:e.topLevel.every(e=>e.kind!==`Theorem`||e.level===0),yc=(e,t,n)=>{e.minMaxLevel=t.map(e=>Array.from({length:e.arity},(t,r)=>n.argLevelConstraints.get(Zs(e,r))?.level??0)),e.opLevelCond=t.map(e=>t.map(t=>Array.from({length:e.arity},(r,i)=>n.argLevelParams.has(Ks(e,i,t))))),J(e.levelParams,n.levelParams),J(e.allParams,n.allParams),J(e.nonLeibnizParams,n.nonLeibnizParams),t.forEach((t,n)=>{e.levelParams.delete(t),e.allParams.delete(t),e.nonLeibnizParams.has(t)&&(e.nonLeibnizParams.delete(t),e.isLeibnizArg&&(e.isLeibnizArg[n]=!1),e.isLeibniz=!1)}),e.levelConstraints=new Map(n.levelConstraints),t.forEach(t=>e.levelConstraints.delete(t)),e.argLevelConstraints=new Map(n.argLevelConstraints),t.forEach(t=>{for(let n=0;n<t.arity;n++)e.argLevelConstraints.delete(Zs(t,n))}),Js(e.argLevelParams,n.argLevelParams,e=>!t.some(t=>t===e.op)||!t.some(t=>t===e.param))},bc=(e,t,n,r,i)=>{e.operands.forEach((a,o)=>{if(a===void 0||(a.level>cc(t,o)&&(n&&Y(a,r,i)&&Gs(i,e.location,`Level error in applying operator ${t.name}:\nThe level of argument ${o+1} exceeds the maximum level allowed by the operator.`),e.levelCorrect=!1),a.kind!==`OpArg`||!ac(a.op)))return;let s=a.op;Y(s,r,i);let c=we(s);for(let l=0;l<c;l++){let c=lc(t,o,l);cc(s,l)>=c||(n&&Y(a,r,i)&&Gs(i,e.location,`Level error in applying operator ${t.name}:\nThe permitted level of argument ${l+1} of the operator argument ${o+1} \nmust be at least ${c}.`),e.levelCorrect=!1)}e.operands.forEach((n,l)=>{for(let u=0;u<c;u++)n===void 0||!dc(t,o,l,u)||n.level<=cc(s,u)||(Y(a,r,i)&&Y(n,r,i)&&Gs(i,e.location,`Level error in applying operator ${t.name}:\nThe level of argument ${l+1} exceeds the maximum level allowed by the operator.`,`HIGHER_ORDER_OPERATOR_COPARAMETER_LEVEL_CONSTRAINTS_EXCEEDED`),e.levelCorrect=!1)})}),e.ranges.forEach((n,a)=>{let o=Y(n,r,i);n.level<=2||(o&&Gs(i,e.location,`Level error in applying operator ${t.name}:\nThe level of the range for the bounded variable ${I(e.bounded?.[a]?.[0]?.location)} \nexceeds the maximum level allowed by the operator.`),e.levelCorrect=!1)})},xc=(e,t,n,r,i)=>{let a=t.params??[],o=t=>e.operands.find((e,n)=>a[n]===t);Xs(e.levelConstraints,t.levelConstraints),e.operands.forEach(t=>{t!==void 0&&Xs(e.levelConstraints,t.levelConstraints,e=>!n.has(e))}),e.ranges.forEach(t=>Xs(e.levelConstraints,t.levelConstraints)),e.operands.forEach((n,r)=>{let i=cc(t,r);n?.levelParams.forEach(t=>Ys(e.levelConstraints,t,i))}),e.operands.forEach((n,a)=>{if(n?.kind!==`OpArg`||!ac(n.op))return;let o=n.op;Y(o,r,i);let s=we(o);e.operands.forEach((n,r)=>{for(let i=0;i<s;i++){if(!dc(t,a,r,i))continue;let s=cc(o,i);n?.levelParams.forEach(t=>Ys(e.levelConstraints,t,s)),!o.isLeibniz&&!uc(o,i)&&n&&J(e.nonLeibnizParams,n.allParams)}})}),t.argLevelParams.forEach(t=>{let n=o(t.op);n?.kind===`OpArg`&&ac(n.op)&&(Y(n.op,r,i),Ys(e.levelConstraints,t.param,cc(n.op,t.index)))}),$s(e.argLevelConstraints,t.argLevelConstraints),e.operands.forEach(t=>{t&&$s(e.argLevelConstraints,t.argLevelConstraints)}),e.ranges.forEach(t=>$s(e.argLevelConstraints,t.argLevelConstraints)),e.operands.forEach((n,r)=>{if(n?.kind!==`OpArg`||!rc(n.op))return;let i=n.op;for(let n=0;n<i.arity;n++)Qs(e.argLevelConstraints,i,n,lc(t,r,n));e.operands.forEach((n,a)=>{for(let o=0;o<i.arity;o++)n!==void 0&&dc(t,r,a,o)&&Qs(e.argLevelConstraints,i,o,n.level)})}),t.argLevelParams.forEach(t=>{let n=o(t.op);n!==void 0&&(Y(n,r,i),Qs(e.argLevelConstraints,t.op,t.index,n.level))}),e.operands.forEach(t=>{t!==void 0&&Js(e.argLevelParams,t.argLevelParams,e=>!n.has(e.param))}),e.ranges.forEach(t=>Js(e.argLevelParams,t.argLevelParams)),t.argLevelParams.forEach((t,n)=>{let a=o(t.op);if(a===void 0){let a=o(t.param);a===void 0?e.argLevelParams.set(n,t):(Y(a,r,i),a.levelParams.forEach(n=>qs(e.argLevelParams,t.op,t.index,n)))}else a.kind===`OpArg`&&rc(a.op)&&qs(e.argLevelParams,a.op,t.index,t.param)}),e.operands.forEach((n,r)=>{if(n?.kind!==`OpArg`||!rc(n.op))return;let i=n.op;e.operands.forEach((n,a)=>{for(let o=0;o<i.arity;o++)n!==void 0&&dc(t,r,a,o)&&n.levelParams.forEach(t=>qs(e.argLevelParams,i,o,t))})})},Sc=/* @__PURE__ */ new Map([[`\\land`,`\\land`],[`\\lor`,`\\lor`],[`=>`,`=>`],[`\\equiv`,`\\equiv`],[`$ConjList`,`Conjunction list`],[`$DisjList`,`Disjunction list`]]),Cc=(e,t)=>{let n=(n,r)=>{Gs(t,n,r),t.isTlc174||(e.levelCorrect=!1)},r=e.operator.name,i=e.operands[0];if((r===`[]`||r===`<>`)&&i?.level===2&&i.kind===`OpAppl`){let t=r===`[]`;i.operator.name!==(t?`$SquareAct`:`$AngleAct`)&&n(e.location,t?`[] followed by action not of form [A]_v.`:`<> followed by action not of form <<A>>_v.`)}r!==`~>`&&r!==`-+->`||i?.level!==2&&e.operands[1]?.level!==2||n(e.location,`Action used where only temporal formula or state predicate allowed.`);let a=Sc.get(r);a!==void 0&&e.operands.some(e=>e?.level===3)&&e.operands.some(e=>e?.level===2)&&n(e.location,`${a} has both temporal formula and action as arguments.`),e.level===3&&(r===`$BoundedExists`||r===`$BoundedForall`)&&e.ranges.forEach(e=>{e.level===2&&n(e.location,`Action-level bound of quantified temporal formula.`)})},wc=(e,t,n)=>{if(e.levelChecked>=t)return e.levelCorrect;e.levelChecked=t,e.levelCorrect=!0;let r=e.operands.filter(e=>e!==void 0);r.forEach(r=>{Y(r,t,n)||(e.levelCorrect=!1)}),e.ranges.forEach(r=>{Y(r,t,n)||(e.levelCorrect=!1)});let i=e.operator;if(ac(i)){let r=Y(i,t,n);bc(e,i,r,t,n),e.level=e.operands.reduce((e,t,n)=>t!==void 0&&sc(i,n)===1?Math.max(e,t.level):e,i.level),e.ranges.forEach(t=>{e.level=Math.max(e.level,t.level)}),J(e.levelParams,i.levelParams),J(e.allParams,i.allParams),J(e.nonLeibnizParams,i.nonLeibnizParams),e.operands.forEach((t,n)=>{t!==void 0&&(sc(i,n)===1&&J(e.levelParams,t.levelParams),J(e.allParams,t.allParams),J(e.nonLeibnizParams,t.nonLeibnizParams),uc(i,n)||J(e.nonLeibnizParams,t.allParams))}),e.ranges.forEach(t=>{J(e.levelParams,t.levelParams),J(e.allParams,t.allParams),J(e.nonLeibnizParams,t.nonLeibnizParams)});let a=new Set(fc(e));a.forEach(t=>{e.levelParams.delete(t),e.allParams.delete(t),e.nonLeibnizParams.delete(t)}),xc(e,i,a,t,n)}else Y(i,t,n),e.level=r.reduce((e,t)=>Math.max(e,t.level),i.kind===`Module`?0:i.level),e.levelParams=/* @__PURE__ */ new Set([i]),e.allParams.add(i),r.forEach((t,n)=>{J(e.levelParams,t.levelParams),J(e.allParams,t.allParams),J(e.nonLeibnizParams,t.nonLeibnizParams),Xs(e.levelConstraints,t.levelConstraints),Qs(e.argLevelConstraints,i,n,t.level),$s(e.argLevelConstraints,t.argLevelConstraints),t.levelParams.forEach(t=>qs(e.argLevelParams,i,n,t)),Js(e.argLevelParams,t.argLevelParams)});return Cc(e,n),e.levelCorrect},Tc=(e,t,n)=>{if(e.levelChecked>=t||!e.inRecursiveSection&&e.levelChecked>0)return e.levelCorrect;e.levelChecked=t;let r=e.body;if(r===void 0)return e.levelCorrect=e.step===void 0||Y(e.step,t,n),e.levelCorrect;e.levelCorrect=Y(r,t,n),e.level=Math.max(e.level,r.level);let i=e.params??[];return i.forEach((t,n)=>{let i=r.levelConstraints.get(t);i!==void 0&&(e.maxLevels[n]=Math.min(e.maxLevels[n],i)),r.levelParams.has(t)&&(e.weights[n]=Math.max(e.weights[n],1))}),yc(e,i,r),e.levelCorrect},Ec=(e,t,n)=>(e.levelChecked>=t||(e.levelChecked=t,e.maxLevels=e.params.map(()=>3),e.isLeibnizArg=e.params.map((t,n)=>n===e.params.length-1),e.params.length>0&&(e.isLeibniz=!0),e.levelCorrect=Y(e.body,t,n),e.level=e.body.level,e.params.forEach((t,n)=>{let r=e.body.levelConstraints.get(t);r!==void 0&&(e.maxLevels[n]=r)}),yc(e,e.params,e.body)),e.levelCorrect),Dc=(e,t)=>{if(e.isLevelChecked)return e.levelCorrect;e.isLevelChecked=!0;let n=e.opDefsInRecursiveSection,r=0;for(;r<n.length;){let e=n[r].recursiveSection,i=r;for(;i<n.length&&n[i].recursiveSection===e;){let e=n[i];e.inRecursive?(e.levelChecked=1,e.maxLevels=e.maxLevels.map(()=>2),e.weights=e.weights.map(()=>1)):e.levelChecked=0,i++}let a=n.slice(r,i),o=/* @__PURE__ */ new Set,s=/* @__PURE__ */ new Set,c=0;a.forEach(e=>{e.inRecursive&&(e.levelChecked=0),Tc(e,1,t),e.inRecursive&&(e.maxLevels.forEach((n,r)=>{n>=2||Gs(t,e.location,`Argument ${r+1} of recursive operator ${e.name} is primed`)}),c=Math.max(c,e.level),J(o,e.levelParams),J(s,e.allParams))}),a.forEach(e=>{e.inRecursive&&(e.levelChecked=2),e.level=Math.max(e.level,c),J(e.levelParams,o),J(e.allParams,s)}),a.forEach(e=>{e.inRecursive&&(e.levelChecked=1),Tc(e,2,t)}),r=i}e.levelCorrect=!0;let i=t=>{t||(e.levelCorrect=!1)};e.definitions.filter(e=>e.kind===`Module`).forEach(e=>i(Dc(e,t)));let a=ce(e);return a.forEach(e=>i(Tc(e,1,t))),ut(e).forEach(e=>i(Ec(e,1,t))),e.topLevel.forEach(e=>i(Y(e,1,t))),vc(e,t)||Ae(e,2).forEach(t=>Ys(e.levelConstraints,t,0)),a.forEach(t=>{Xs(e.levelConstraints,t.levelConstraints),$s(e.argLevelConstraints,t.argLevelConstraints),Js(e.argLevelParams,t.argLevelParams,e=>!nc(e,t.params??[]))}),e.topLevel.forEach(t=>{Xs(e.levelConstraints,t.levelConstraints),$s(e.argLevelConstraints,t.argLevelConstraints),Js(e.argLevelParams,t.argLevelParams)}),e.levelCorrect},Oc=(e,t,n,r)=>(e.levelChecked>=n||(e.levelChecked=n,t.forEach(t=>{ic(t)&&(t.kind!==`OpDef`||t.defKind!==`ModuleInstance`)&&(e.levelCorrect=Y(t,n,r)&&e.levelCorrect,e.level=Math.max(e.level,t.level),tc(e,t),J(e.nonLeibnizParams,t.nonLeibnizParams))})),e.levelCorrect),kc=(e,t)=>{e?.kind===`NonLeafProof`&&e.steps.forEach(e=>{if(e.kind!==`Theorem`||e.body.kind!==`OpAppl`)return;let n=e.body.operator.name;n===`$Take`||n===`$Witness`||n===`$Have`?e.body.level!==0&&Gs(t,e.body.location,`Non-constant TAKE, WITNESS, or HAVE for temporal goal.`):n===`$Pfcase`?(e.body.level!==0&&Gs(t,e.body.location,`Non-constant CASE for temporal goal.`),kc(e.proof,t)):n===`$Qed`&&kc(e.proof,t)})},Ac=(e,t,n)=>{if(e.levelChecked>=t)return e.levelCorrect;e.levelChecked=t,e.levelParams=/* @__PURE__ */ new Set,e.levelCorrect=!0;let r=e.module;Dc(r,n)||(e.levelCorrect=!1),e.substs.forEach(r=>{Y(r.expr,t,n)||(e.levelCorrect=!1)});let i=vc(r,n);e.substs.forEach(a=>{!i&&a.expr.level>a.op.level&&(Y(a.expr,t,n)&&Gs(n,e.location,`Level error in instantiating module '${r.name}':\nThe level of the expression or operator substituted for '${a.op.name}' \nmust be at most ${a.op.level}.`),e.levelCorrect=!1),a.expr.kind!==`OpArg`||a.expr.op.kind!==`OpDef`||a.expr.op.defKind!==`UserDefined`&&a.expr.op.defKind!==`BuiltIn`||a.expr.op.isLeibniz||Gs(n,e.location,`Error in instantiating module '${r.name}':\n A non-Leibniz operator substituted for '${a.op.name}'.`)}),e.substs.forEach(i=>{let a=r.levelConstraints.get(i.op);if(a!==void 0&&i.expr.level>a&&(Y(i.expr,t,n)&&Gs(n,e.location,`Level error in instantiating module '${r.name}':\nThe level of the expression or operator substituted for '${i.op.name}' \nmust be at most ${a}.`),e.levelCorrect=!1),i.op.arity<=0||i.expr.kind!==`OpArg`||i.expr.op.kind!==`OpDef`)return;let o=i.expr.op,s=Y(o,t,n);for(let t=0;t<i.op.arity;t++){let a=r.argLevelConstraints.get(Zs(i.op,t))?.level;a===void 0||cc(o,t)>=a||(s&&Gs(n,e.location,`Level error in instantiating module '${r.name}':\nThe level of the argument ${t+1} of the operator ${o.name} \nmust be at least ${a}.`),e.levelCorrect=!1)}}),r.argLevelParams.forEach(i=>{e.substs.forEach(a=>{e.substs.forEach(o=>{if(i.op!==a.op||i.param!==o.op||a.expr.kind!==`OpArg`)return;let s=a.expr.op,c=Y(s,t,n);if(s.kind!==`OpDef`)return;let l=cc(s,i.index);o.expr.level<=l||(c&&Y(o.expr,t,n)&&Gs(n,e.location,`Level error when instantiating module '${r.name}':\nThe level of the argument ${i.index} of the operator ${a.op.name}' \nmust be at most ${l}.`),e.levelCorrect=!1)})})});let a=t=>!e.params.some(e=>e===t);return Xs(e.levelConstraints,gc(r,e.substs,i,t,n),a),e.substs.forEach(t=>Xs(e.levelConstraints,t.expr.levelConstraints,a)),$s(e.argLevelConstraints,_c(r,e.substs,t,n),e=>a(e.param)),e.substs.forEach(t=>$s(e.argLevelConstraints,t.expr.argLevelConstraints,e=>a(e.param))),Js(e.argLevelParams,hc(r.argLevelParams,e.substs),t=>!nc(t,e.params)),e.substs.forEach(t=>Js(e.argLevelParams,t.expr.argLevelParams,t=>!nc(t,e.params))),e.levelCorrect},Y=(e,t,n)=>{if(!ic(e))return Dc(e,n);switch(e.kind){case`OpAppl`:return wc(e,t,n);case`OpDef`:return Tc(e,t,n);case`ThmOrAssumpDef`:return Ec(e,t,n);case`FormalParam`:return e.levelChecked===0&&(e.levelChecked=t,e.levelParams.add(e),e.allParams.add(e)),!0;case`OpDecl`:return!0;case`Numeral`:case`String`:case`Decimal`:return e.levelChecked<t&&(e.levelChecked=t),!0;case`OpArg`:{if(e.levelChecked>=t)return e.levelCorrect;e.levelChecked=t;let r=e.op;return e.levelCorrect=Y(r,t,n),r.kind===`Module`||(e.level=r.level,ec(e,r)),e.levelCorrect}case`LetIn`:{if(e.levelChecked>=t)return e.levelCorrect;e.levelChecked=t,e.levelCorrect=!0;let r=e.opDefs.filter(e=>e.kind!==`OpDef`||e.defKind!==`ModuleInstance`);return r.forEach(r=>{Y(r,t,n)||(e.levelCorrect=!1)}),Y(e.body,t,n)||(e.levelCorrect=!1),e.instances.forEach(r=>{Y(r,t,n)||(e.levelCorrect=!1)}),e.level=e.body.level,e.levelParams=new Set(e.body.levelParams),e.allParams=new Set(e.body.allParams),Xs(e.levelConstraints,e.body.levelConstraints),r.forEach(t=>Xs(e.levelConstraints,t.levelConstraints)),$s(e.argLevelConstraints,e.body.argLevelConstraints),r.forEach(t=>$s(e.argLevelConstraints,t.argLevelConstraints)),Js(e.argLevelParams,e.body.argLevelParams),r.forEach(t=>{let n=t.kind===`OpDef`?t.params??[]:[];Js(e.argLevelParams,t.argLevelParams,e=>!nc(e,n))}),e.instances.forEach(t=>Js(e.argLevelParams,t.argLevelParams)),e.levelCorrect}case`Label`:{if(e.levelChecked>=t)return!0;e.levelChecked=t,e.params.forEach(e=>Y(e,t,n));let r=Y(e.body,t,n);return e.level=e.body.level,ec(e,e.body),r}case`At`:{if(e.levelChecked>=t)return!0;e.levelChecked=t;let r=e.except.operands,i=r[0];if(i===void 0)return!0;Y(i,t,n),e.level=i.level;let a=[i];for(let i of r.slice(1))if(i!==void 0){if(Y(i,t,n),i===e.component)break;e.level=Math.max(e.level,i.level),a.push(i)}return a.forEach(t=>tc(e,t)),!0}case`SubstIn`:case`APSubstIn`:{if(e.levelChecked>=t)return e.levelCorrect;e.levelChecked=t,e.levelCorrect=!0;let r=e.body;Y(r,t,n)||(e.levelCorrect=!1),e.substs.forEach(r=>{Y(r.expr,t,n)||(e.levelCorrect=!1)}),e.level=e.substs.reduce((e,t)=>r.levelParams.has(t.op)?Math.max(e,t.expr.level):e,r.level),r.levelParams.forEach(t=>J(e.levelParams,mc(t,e.substs,!1))),e.kind===`APSubstIn`?r.allParams.forEach(t=>J(e.allParams,mc(t,e.substs,!0))):(e.allParams=new Set(r.allParams),e.nonLeibnizParams=new Set(r.nonLeibnizParams),e.substs.forEach(t=>{e.allParams.has(t.op)&&(e.allParams.delete(t.op),J(e.allParams,t.expr.allParams),J(e.nonLeibnizParams,t.expr.nonLeibnizParams),e.nonLeibnizParams.has(t.op)&&(e.nonLeibnizParams.delete(t.op),J(e.nonLeibnizParams,t.expr.allParams)))}));let i=vc(e.instantiatedModule,n);return e.levelConstraints=gc(r,e.substs,i,t,n),e.argLevelConstraints=_c(r,e.substs,t,n),e.argLevelParams=hc(r.argLevelParams,e.substs),e.levelCorrect}case`Instance`:return Ac(e,t,n);case`Assume`:{if(e.levelChecked>=t)return!0;e.levelChecked=t;let r=Y(e.body,t,n),i=!e.definition||Y(e.definition,t,n);return e.level=e.body.level,ec(e,e.body),e.level!==0&&Gs(n,e.location,`Level error: assumptions must be level 0 (Constant), \nbut this one has level ${e.level}.`),r&&i}case`Theorem`:{if(e.levelChecked>=t)return!0;let r=Oc(e,[e.definition??e.body,...e.proof?[e.proof]:[]],t,n),i=e.body;return i.kind===`OpAppl`&&i.operator.name===`$Pick`&&i.level===3&&i.ranges.forEach(e=>{e.level!==0&&Gs(n,e.location,`Non-constant bound of temporal PICK.`)}),i.level===3&&kc(e.proof,n),r}case`LeafProof`:case`UseOrHide`:return Oc(e,e.facts,t,n);case`NonLeafProof`:return Oc(e,[...e.steps,...e.instances],t,n);case`DefStep`:return Oc(e,e.defs,t,n);case`NewSymb`:return e.levelChecked>=t||(e.levelChecked=t,e.level=e.declaration.level,e.set===void 0)||(e.levelCorrect=Y(e.set,t,n),e.level=Math.max(e.level,e.set.level),e.level===3&&(e.levelCorrect=!1,Gs(n,e.location,`Level error:
37
+ Temporal formula used as set.`)),ec(e,e.set)),e.levelCorrect;case`AssumeProve`:return e.levelChecked>=t||(e.levelChecked=t,e.levelCorrect=!0,e.assumptions.forEach(r=>{Y(r,t,n)||(e.levelCorrect=!1)}),Y(e.goal,t,n),e.level=e.assumptions.reduce((e,t)=>Math.max(e,t.level),e.goal.level),[e.goal,...e.assumptions].forEach(t=>tc(e,t)),e.levelCorrect&&e.levelParams.forEach(t=>{t.kind===`OpDecl`&&t.declKind===2&&Ys(e.levelConstraints,t,2)})),e.levelCorrect}},jc=e=>{switch(e.kind){case`OpAppl`:return[...e.ranges,...e.operands];case`OpDef`:case`ThmOrAssumpDef`:case`Label`:return[e.body];case`LetIn`:return[...e.opDefs,...e.instances,e.body];case`SubstIn`:case`APSubstIn`:return[e.body,...e.substs.map(e=>e.expr)];case`Instance`:return e.substs.map(e=>e.expr);case`AssumeProve`:return[...e.assumptions,e.goal];case`NewSymb`:return[e.set];default:return[]}},Mc=/* @__PURE__ */ new Map([[`Integers`,`Int`],[`Naturals`,`Nat`],[`Reals`,`Reals`]]),Nc=e=>{let t=/* @__PURE__ */ new Set,n=e=>{if(e===void 0||t.has(e))return!1;if(t.add(e),e.kind===`OpAppl`){let t=e.operator;if(t.kind===`OpDecl`||t.kind===`FormalParam`)return!0;if(t.kind===`OpDef`){if(t.name===`BOOLEAN`)return!0;let e=t.module?.name;if(e!==void 0&&Mc.get(e)===t.name||n(t))return!0}}return jc(e).some(n)};return n(e)},Pc=e=>e.operands.filter(e=>e?.kind===`OpAppl`),Fc=e=>{let t=e.operands[0];return t?.kind===`String`?t:void 0},Ic=e=>JSON.stringify([e.operands.length,...Pc(e).map(e=>Fc(e)?.value).sort()]),Lc=(e,t=/* @__PURE__ */ new Set)=>(e.extendees.forEach(e=>{t.has(e)||(t.add(e),Lc(e,t))}),t),Rc=e=>{let t=e.records.map(t=>({domain:Ic(t),warnings:Pc(t).flatMap(t=>{let n=Fc(t),r=n&&kt(e.context,n.value);return n===void 0||r===void 0?[]:[{location:n.location,text:`The field name "${n.value}" in the record constructor is identical to the existing definition or declaration\nnamed ${n.value}, located at ${I(r.location)}.\nThe field in the record will not take the value of the ${n.value} definition or declaration.\nIn TLA+, field names in records are strings, regardless of any similarly named declarations or definitions.\nTherefore, DOMAIN [${n.value} |-> ...] = {"${n.value}"} holds true.`,isWarning:!0}]})})),n=new Set(t.flatMap(e=>e.warnings.length>0?[e.domain]:[])),r=/* @__PURE__ */ new Set;return[...[...Lc(e)].flatMap(e=>e.records),...e.records].forEach(e=>{let t=Ic(e);n.has(t)&&!r.has(t)&&Pc(e).some(Nc)&&r.add(t)}),t.flatMap(e=>r.has(e.domain)?[]:e.warnings)},zc=e=>`${I(e.location)}\n\n${e.text}`,Bc=e=>{let t=e.filter(e=>!e.isWarning),n=e.filter(e=>e.isWarning);return[t.length>0?`*** Errors: ${t.length}\n\n`:``,...t.map(e=>`${zc(e)}\n\n\n`),n.length>0?`*** Warnings: ${n.length}\n\n`:``,...n.map(e=>`${zc(e)}\n\n\n`)].join(``)},Vc=4802,Hc=/* @__PURE__ */ new Set([`FiniteSets`,`Sequences`,`Bags`,`Naturals`,`Integers`,`Reals`,`RealTime`,`Randomization`,`TLC`]),Uc=e=>{let t=/* @__PURE__ */ new Set,n=[],r=e=>{t.add(e.name),n.push(...e.extends),e.modules.forEach(r)};return r(e),n.filter(e=>!t.has(e))},Wc=e=>{try{return de(He(e))}catch(e){if(e instanceof s)return;throw e}},Gc=(e,t)=>t===`1.7.4`&&bt(e)!==void 0?void 0:Wc(e)?.name,Kc=(e,t,n={})=>{let r=en(e,`.tla`),i=Et(n.version),a=n.fileName??r,o=B(e),s=o?pn(e,`utf8`):i.get(r),c=[],l=e=>{c.push(e),n.onPrint?.(e)},u=e=>l(`${e}\n`),f=n.version===`1.7.4`,p=f&&n.isXmlExport,m=e=>{n.isXmlExport||u(e)},h=n.describeFile,g=/* @__PURE__ */ new Map([[r,o?`file`:`standard`]]),_=!1,v=[],y=!1,x=!1,S=Vi(ei(),u),C=/* @__PURE__ */ new Map,w=[],T=()=>w.splice(0).forEach(e=>e.isError?n.onPrintError?.(`${e.text}\n`):u(e.text)),E=e=>{let t=C.get(e),r=t?.module.location.range;if(t===void 0||r===void 0)return;let i=t.text.split(/\r\n|\r|\n/),a=Va(S,i.slice(r.start.line-1,r.end.line),n.version),o=a.has(`TLA_DIVERGENCE_EXISTS`),s=a.has(`PCAL_DIVERGENCE_EXISTS`),c=o===s?void 0:`The ${o?`TLA+ translation`:`PlusCal algorithm`} in module ${e} has changed since its last translation.`;if(f){let t=o&&s?`The PlusCal algorithm and its TLA+ translation in module ${e} filename since the last translation.`:c;t===void 0?a.has(`ERROR_ENCOUNTERED`)&&w.push({text:`A unexpected problem was encountered attempting to validate the specification for ${e}`,isError:!0}):w.push({text:`!! WARNING: ${t}`,isError:!1});return}let l=o&&s?`Both the PlusCal algorithm and its TLA+ translation in module ${e} have changed since the last translation.`:c??(a.has(`ERROR_ENCOUNTERED`)?`An unexpected problem was encountered attempting to validate the specification for ${e}`:void 0);if(l===void 0)return;let u=!a.has(`ERROR_ENCOUNTERED`)||o||s;v.some(e=>e.text===l)||v.push({location:e,text:l,isWarning:u})},D=(e,t)=>{if(n.isXmlExport||C.has(e))return;let r=Wc(t);if(r===void 0||r.name!==e)return;let i=[...C.values()].filter(t=>Uc(t.module).includes(e));C.set(e,{text:t,module:r}),i.forEach(()=>E(e)),Uc(r).filter(t=>t!==e&&C.has(t)).forEach(E)},ee=()=>{if(T(),y)return;y=!0;let e=v.filter(e=>e.isWarning);e.length>0&&(m(`Warnings (${e.length}) during syntax parsing of ${a}:\n\n`),e.forEach(e=>m(`${zc(e)}\n\n\n`))),e.length!==v.length&&(u(Bc(v)),_=!0,x=!0)},O=e=>{let n=i.get(e),r=t(e),a=r===void 0&&n===void 0&&s!==void 0&&!f?xe(s,e):void 0,o=r??a;return g.set(e,r===void 0?a===void 0?`standard`:`root file`:`file`),o!==void 0&&D(e,o),o??n},k=(()=>{try{if(s===void 0)throw new d(`Cannot find source file for module ${a}`,void 0);return D(r,s),Ws(s,O,{rootFileName:r,rootFilePath:n.isXmlExport?`${a.replace(/\.tla$/,``)}.tla`:void 0,version:n.version,rootExtendees:n.rootExtendees,onParse:e=>{h&&u(`Parsing file ${h(e,g.get(e)??`file`)}`),e===r&&E(r),T()},onAnalyze:e=>{ee(),(h||p)&&!x&&u(`Semantic processing of module ${e}`)},onModule:(e,t)=>{if(x||(t.every(e=>e.isWarning)&&Dc(e,{messages:t,isTlc174:f}),t.length===0))return;if(t.some(e=>!e.isWarning)&&(_=!0),f)return u(`Semantic errors:\n\n${Bc(t)}`);let n=t.filter(e=>e.isWarning);n.length>0&&(m(`*** Warnings: ${n.length}\n`),n.forEach(e=>m(`${zc(e)}\n\n\n`)));let r=t.filter(e=>!e.isWarning);r.length!==0&&(u(`Semantic errors:\n\n*** Errors: ${r.length}\n`),r.forEach(e=>u(`${zc(e)}\n\n`)))}})}catch(e){if(_=!0,e instanceof b){u(`\nFatal errors while parsing TLA+ spec in file ${a}\n`),u(e.message),u(Bc(v));return}if(!(e instanceof d))throw e;let t={location:e.location,text:e.message,isWarning:!1},n=f&&e.parseError?.includes(` and token "" `);if(e.parseError!==void 0&&!n&&!p&&u(e.parseError),u(`\nFatal errors while parsing TLA+ spec in file ${a}\n`),n){u(`java.lang.NullPointerException: Cannot invoke "String.length()" because "str" is null`);return}if(f){u(`tla2sany.semantic.AbortException`),l(`*** Abort messages: 1\n\n${zc(t)}\n\n\n`);return}u(zc(t)),u(Bc(y?[t]:[...v,t]))}})();if(k!==void 0&&ee(),k!==void 0&&!_&&!n.isXmlExport&&!f){let e=k.modules.filter(e=>!Hc.has(e.name));h&&e.forEach(e=>u(`Linting of module ${e.name}`));let t=n.suppressedCodes?.includes(Vc)?[]:e.flatMap(Rc),r=n.errorCodes?.includes(Vc)?`Warning treated as error: `:``;t.forEach(e=>u(`${r}${zc(e)}\n\n\n`)),r&&t.length>0&&(_=!0)}return{text:c.join(``),isFailed:_,specification:x?void 0:k}},qc=e=>e.kind===`OpDef`&&e.defKind!==`BuiltIn`&&e.defKind!==`ModuleInstance`,Jc=(e,t)=>e.context.symbols.find(e=>qc(e)&&e.name===t),Yc=e=>v(new j(`Parsing or semantic analysis failed.Parsing or semantic analysis failed.${e}`),w.specParseError),Xc=(e,t,n,r,i,a)=>{let o=e=>Yc(`Unknown location\n\n${e} while parsing breakpoint expression "${r}"`);try{Te(e)}catch(e){throw e instanceof s?Yc(`Syntax error while parsing breakpoint expression "${r}"`):e}let c=!1,l=!1,u=(()=>{try{return Ws(e,i,{version:a,onModule:(e,n)=>{let r=()=>n.every(e=>e.isWarning);if(!r())return;let i=Dc(e,{messages:n,isTlc174:a===`1.7.4`});e.name===t&&(c=!0,l=i&&r())}})}catch(e){throw e instanceof s?o(`Semantic error`):e}})();if(!c)throw o(`Semantic error`);if(!l)throw o(`Level-checking error`);let d=Jc(u.root,n)?.level??0;if(d===3)throw Yc(`Unknown location\n\nDebug expressions must be action-level or below; actual level: ${d} (Temporal)`)},Zc=(e,t,n,r,i)=>{let a=n=>n===t.name?e:r(n),o=Date.now();return n.map((e,n)=>{if(Jc(t,e.expression))return{name:e.expression,module:void 0,source:void 0};let r=`__DebuggerModule__${o+n}`,s=`__DebuggerExpr__${o+n}`,c=`---- MODULE ${r} ----\nEXTENDS ${t.name}\n\n${s} == ${e.expression}\n====`;return Xc(c,r,s,e.expression,a,i),{name:s,module:r,source:c}})},Qc=(1n<<63n)-1n,$c=[[-123456,-123456],[-1,0],[1e3,1003],[1005,1005],[1101,1102],[2e3,2001],[2100,2149],[2154,2274],[2279,2287],[2300,2301],[2400,2405],[2501,2502],[2772,2780],[3e3,3002],[3100,3114],[4e3,4002],[5001,5007],[7e3,7010],[2e4,2e4]],el=[[4003,4005],[4200,4206],[4220,4224],[4240,4247],[4260,4262],[4270,4275],[4290,4294],[4310,4315],[4330,4337],[4350,4357]],tl=/* @__PURE__ */ new Map([[4800,`EXTENDED_MODULES_SYMBOL_UNIFICATION_AMBIGUITY`],[4801,`INSTANCED_MODULES_SYMBOL_UNIFICATION_AMBIGUITY`],[4802,`RECORD_CONSTRUCTOR_FIELD_NAME_CLASH`],[4803,`PLUSCAL_ALGORITHM_AND_TRANSLATION_CHANGED_SINCE_LAST_TRANSLATION`],[4804,`PLUSCAL_ALGORITHM_CHANGED_SINCE_LAST_TRANSLATION`],[4805,`PLUSCAL_TRANSLATION_CHANGED_SINCE_LAST_TRANSLATION`]]),nl=(e,t,n)=>({module:e,constant:n,operators:[{kind:`postcondition`,operator:t}]}),rl={json:nl(`_JsonTrace`,`_JsonTrace`,`_JsonTraceFile`),tla:nl(`_TLAPlusCounterExample`,`_TLAPlusCounterExample`,`_TLAPlusCounterExampleFile`),tlc:nl(`_TLCTrace`,`_TLCTrace`,`_TLCTraceFile`),tlcplain:nl(`_TLCTracePlain`,`_TLCTrace`,`_TLCTraceFile`),tlctespec:nl(`_TLCTESpec`,`_TLCTrace`,`_TLCTraceFile`),tlcaction:nl(`_TLCActionTrace`,`_TLCTrace`,`_TLCTraceFile`),dot:nl(`_DotTrace`,`_DotTrace`,`_DotTraceFile`)},il=(e,t)=>({module:e,constant:`${t}InputFile`,operators:[{kind:`constraint`,operator:`${t}Constraint`},{kind:`view`,operator:`${t}View`}]}),al={tlc:il(`_TLCTrace`,`_TLCTrace`),json:il(`_JsonTrace`,`_JsonTrace`)},ol=(e,t)=>e.some(e=>t>=e[0]&&t<=e[1]),sl=(e,t)=>{if(e===``)return[e];let n=e.split(t);for(;n.at(-1)===``;)n.pop();return n},cl=(e,t)=>[...new Set(e.filter(e=>t.includes(e)))].sort((e,t)=>e-t),ll=(e,t)=>{if(!/^[+-]?\d+$/.test(e))return;let n=BigInt(e);return BigInt.asIntN(t,n)===n?n:void 0},ul=e=>/^[+-]?(NaN|Infinity|(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?[fFdD]?)$/.test(e.trim())?Number.parseFloat(e.trim().replace(/[fFdD]$/,``)):void 0,dl=()=>({specs:[],configPath:void 0,seed:0n,aril:0n,workers:1,coverage:void 0,livenessCheck:`default`,dump:void 0,fingerprintIndex:0,maxSetSize:void 0,isLazyValueExpanded:!0,isViewPrinted:!1,metadir:void 0,recoverDirectory:void 0,mode:`model-check`,dfidDepth:void 0,traceDepth:100,traceCount:void 0,scheduler:`random`,isTool:!1,isContinued:!1,isDeadlockChecked:!0,isWarningEnabled:!0,isTraceSpecForced:!1,isTraceSpecDisabled:!1,isTraceBinaryDisabled:!1,traceSpecPath:void 0,isDiffTrace:!1,suppressedCodes:[],errorCodes:[],userFile:void 0,invariants:[],moduleOperators:[]}),fl={"-modelcheck":()=>{},"-difftrace":e=>{e.isDiffTrace=!0},"-deadlock":e=>{e.isDeadlockChecked=!1},"-cleanup":()=>{},"-nowarning":e=>{e.isWarningEnabled=!1},"-gzip":()=>{},"-terse":e=>{e.isLazyValueExpanded=!1},"-continue":e=>{e.isContinued=!0},"-view":e=>{e.isViewPrinted=!0},"-debug":()=>{},"-tool":e=>{e.isTool=!0}},pl=(e,t,n)=>(r,i)=>{let a=ll(i,e);return a===void 0?`${t} But encountered ${i}`:n(r,a,i)},ml=(e,t,n,r)=>({missing:t,apply:pl(32,n,(t,n)=>{let i=BigInt.asIntN(32,n*60000n);if(i<0n)return`Error: expect a nonnegative integer for -${e} option.`;r(t,Number(i)/6e4)})}),hl={"-teSpecOutDir":{missing:`Error: expected a path for -teSpecOutDir option.`,apply:(e,t)=>{e.traceSpecPath=t}},"-userFile":{missing:`Error: need to specify the full qualified file.`,apply:(e,t)=>{try{cn(fn(t,`w`))}catch{return`Error: Failed to create user output log file.`}e.userFile=t}},"-lncheck":{missing:`Error: expect a strategy such as final for -lncheck option.`,apply:(e,t)=>{e.livenessCheck=t.toLowerCase()}},"-config":{missing:`Error: expect a file name for -config option.`,apply:(e,t)=>{let n=t.replace(/\.cfg$/,``);e.configPath=n.endsWith(`.tla`)?n:`${n}.cfg`}},"-coverage":ml(`coverage`,`Error: coverage report interval required.`,`Error: An integer for coverage report interval required.`,(e,t)=>{e.coverage=t}),"-checkpoint":ml(`checkpoint`,`Error: checkpoint interval required.`,`Error: An integer for checkpoint interval is required.`,()=>{}),"-depth":{missing:`Error: trace length required.`,apply:pl(32,`Error: An integer for trace length required.`,(e,t)=>{e.traceDepth=Number(t)})},"-seed":{missing:`Error: seed required.`,apply:pl(64,`Error: An integer for seed required.`,(e,t)=>{e.seed=t})},"-aril":{missing:`Error: aril required.`,apply:pl(64,`Error: An integer for aril required.`,(e,t)=>{e.aril=t})},"-maxSetSize":{missing:`Error: maxSetSize required.`,apply:pl(32,`Error: An integer for maxSetSize required.`,(e,t,n)=>{if(t<1n)return`Error: Value in interval [0, ${Xe}] for maxSetSize required. But encountered ${n}`;e.maxSetSize=Number(t)})},"-recover":{missing:`Error: need to specify the metadata directory for recovery.`,apply:(e,t)=>{e.recoverDirectory=t}},"-metadir":{missing:`Error: need to specify the metadata directory.`,apply:(e,t)=>{e.metadir=t}},"-workers":{missing:`Error: expect an integer or 'auto' for -workers option.`,apply:(e,t)=>{let n=t.trim().toLowerCase()===`auto`?BigInt(wn()):ll(t,32);if(n===void 0)return`Error: worker number or 'auto' required. But encountered ${t}`;if(n<1n)return`Error: at least one worker required.`;e.workers=Number(n)}},"-dfid":{missing:`Error: expect a nonnegative integer for -dfid option.`,apply:pl(32,`Error: expect a nonnegative integer for -dfid option.`,(e,t)=>{if(t<0n)return`Error: expect a nonnegative integer for -dfid option.`;e.dfidDepth=Number(t)})},"-fp":{missing:`Error: expect an integer for -fp option.`,apply:pl(32,`Error: A number for -fp is required.`,(e,t)=>{if(t<0n||t>=131)return`Error: The number for -fp must be between 0 and 130 (inclusive).`;e.fingerprintIndex=Number(t)})},"-fpmem":{missing:`Error: fpset memory size required.`,apply:(e,t)=>{let n=ul(t);if(n===void 0||n<0)return`Error: An positive integer or a fraction for fpset memory size/percentage required. But encountered ${t}`;n>1&&process.stdout.write(`Using -fpmem with an abolute memory value has been deprecated. Please allocate memory for the TLC process via the JVM mechanisms and use -fpmem to set the fraction to be used for fingerprint storage.
38
+ `)}},"-fpbits":{missing:`Error: fpbits required.`,apply:pl(32,`Error: An integer for fpbits required.`,(e,t,n)=>t<0n||t>30n?`Error: Value in interval [0, 30] for fpbits required. But encountered ${n}`:void 0)}},gl={"-loadtrace":{name:`-loadTrace`,missing:`Error: A format and a file name for loading traces required.`,formats:al},"-dumptrace":{name:`-dumpTrace`,missing:`Error: A format and a file name for dumping traces required.`,formats:rl}},_l=e=>{let t=dl(),n=0,r=e=>({kind:`command-line`,error:e,isTool:t.isTool}),i=()=>({kind:`uncaught`,error:`java.lang.ArrayIndexOutOfBoundsException: Index ${e.length} out of bounds for length ${e.length}`,isTool:t.isTool}),a={tlc:[],sany:[]},o={tlc:[],sany:[]},s=()=>e[n],c=()=>e[n++];for(;n<e.length;){let l=c();if(Object.hasOwn(fl,l))fl[l](t);else if(Object.hasOwn(hl,l)){let e=c();if(e===void 0)return r(hl[l].missing);let n=hl[l].apply(t,e);if(n!==void 0)return r(n)}else if(l===`-simulate`||l===`-generate`){t.mode=l===`-generate`?`generate`:`simulate`;let e=s();if(e===void 0||![`stats=`,`file=`,`num=`,`sched`].some(t=>e.includes(t)))continue;n++;let i=e.split(`,`).some(e=>e.startsWith(`file=`));t.scheduler=e.split(`,`).includes(`sched=rl`)?`rl`:e.split(`,`).includes(`sched=rlaction`)?`rlaction`:`random`;for(let n of e.split(`,`).filter(e=>e.startsWith(`num=`))){let e=n.replace(`num=`,``);if(t.traceCount=ll(e,64),t.traceCount===void 0)return{kind:`uncaught`,error:`java.lang.NumberFormatException: For input string: "${e}"`,isTool:t.isTool}}if((t.traceCount??Qc)===Qc&&i)return r(`Error: You need to specify a 'num' argument when using the 'file' argument, for example: '"num=5,file=test.txt"'.`)}else if(l===`-suppressMessages`||l===`-messagesAsErrors`){let e=c();if(e===void 0)return r(`Error: ${l} requires a comma-separated list of message codes.`);let t=l===`-suppressMessages`?a:o;for(let n of sl(e,`,`)){let e=n.replace(/^[^!-\uffff]+|[^!-\uffff]+$/g,``),i=ll(e,32);if(i===void 0)return r(`Error: For input string: "${e}"`);let o=Number(i);if(ol($c,o))t.tlc.push(o);else{if(!tl.has(o)&&!ol(el,o))return r(`Error: unknown message code: ${o}`);if(t===a&&!tl.has(o))return r(`Error: code ${o} is an error and cannot be suppressed.`);t.sany.push(o)}}}else if(l===`-inv`){let e=c();if(e===void 0)return i();t.invariants.push({modules:[...new Set([...e.matchAll(/INSTANCE\s+(\w+)/g)].map(e=>e[1]))],expression:e})}else if(l===`-invlevel`){let e=c();if(e===void 0)return i();if(ll(e,32)===void 0)return r(`Error: An integer for -invlevel required. But encountered ${e}`);t.invariants.push({modules:[`TLC`,`Naturals`],expression:`LET _T == INSTANCE TLC _N == INSTANCE Naturals IN _N!<(_T!TLCGet("level"), ${e})`})}else if(l===`-debugger`){let e=s();e!==void 0&&[`port=`,`nosuspend`,`nohalt`,`suspend`,`halt`].some(t=>e.includes(t))&&n++}else if(l===`-generateSpecTE`)t.isTraceSpecForced=!0,s()===`nomonolith`&&n++;else if(l===`-noGenerateSpecTE`||l.toLowerCase()===`-note`)t.isTraceSpecDisabled=!0;else if(l===`-noGenerateSpecTEBin`||l.toLowerCase()===`-notebin`)t.isTraceBinaryDisabled=!0;else{if(l===`-help`||l===`-h`)return`usage`;if(l===`-dump`){let i=s();if(i?.startsWith(`class,`))return r(`Trying to instantiate a custom IStateWriter implementation ${i.replaceAll(`class,`,``)}.`);let a=i?.startsWith(`dot`)&&n+1<e.length?2:1;if(t.dump=e.slice(n,n+a),n+=a,t.dump.length===0)return r(`Error: A file name for dumping states required.`)}else if(Object.hasOwn(gl,l.toLowerCase())){let i=gl[l.toLowerCase()];if(n+1>=e.length)return r(i.missing);let a=c(),o=c();if(!Object.hasOwn(i.formats,a.toLowerCase()))return r(`Error: Unknown format ${a} given to ${i.name}.`);let s=i.formats[a.toLowerCase()];t.moduleOperators.push(...s.operators.map(e=>({...e,module:s.module,constants:{[s.constant]:o}})))}else if(l.toLowerCase()===`-postcondition`){let e=c();if(e===void 0)return r(`Error: Module!Operator for postCondition required.`);if(!e.includes(`!`))return r(`Module!Operator for postCondition required. Encountered: ${e}`);let n=sl(e,`!`);if(n.length!==2)return r(`Module!Operator for postCondition must be of the form module!operator. Encountered: ${e}`);if(n[0]===``)return r(`Module name for postCondition required. Encountered: ${e}`);if(n[0].includes(`.`))return r(`Module name for postCondition must not contain a dot. Encountered: ${n[0]}`);if(n[1].includes(`.`))return r(`Operator name for postCondition must not contain a dot. Encountered: ${n[1]}`);t.moduleOperators.push({kind:`postcondition`,module:n[0],operator:n[1]})}else{if(l.startsWith(`-`))return r(`Error: unrecognized option: ${l}`);t.specs.push(l)}}}if(!t.isWarningEnabled&&a.tlc.length+a.sany.length>0)return r(`Error: -nowarning already suppresses all warnings, making -suppressMessages redundant. Remove -nowarning to suppress only the specified messages, or remove -suppressMessages to suppress all warnings.`);let l=cl(a.tlc,o.tlc),u=l.length>0?l.map(String):cl(a.sany,o.sany).map(e=>tl.get(e)??String(e));return u.length>0?r(`Error: The following codes were set to both -suppressMessages and -messagesAsErrors: [${u.join(`, `)}]`):(t.suppressedCodes=[...a.tlc,...a.sany],t.errorCodes=[...o.tlc,...o.sany],t)},vl=(e,t)=>e.print(F.computingInitProgress,z.none,`Computed ${t} initial states...`),yl=(e,t)=>e===`invariant-violation`?{code:F.invariantViolatedInitial,text:`Invariant ${t} is violated by the initial state:`}:{code:F.propertyViolatedInitial,text:`Property ${t} is violated by the initial state:`},bl=(e,t)=>t?.forEach(t=>{if(typeof t==`string`)return console.log(t);if(t.kind===`initial-states-progress`)return vl(e,t.count);let n=yl(t.status,t.name);e.print(n.code,z.error,`${n.text}\n${ae(t.state)}`)}),xl={code:F.behaviorUpToThisPoint,text:`The behavior up to this point is:`},Sl={code:F.counterExample,text:`The following behavior constitutes a counter-example:
39
+ `},Cl={"error-trace":{heading:xl,isLastDiffed:!1},simulation:{heading:xl,isLastDiffed:!0},"counter-example":{heading:Sl,isLastDiffed:!0}},wl=(e,t,n)=>{let r=Cl[n].heading,i=n===`counter-example`&&e.version===`1.7.4`;t.length>0&&e.print(r.code,z.error,r.text);try{t.forEach((r,a)=>{(a>0||i)&&bl(e,r.output);let o=e.isDiffTrace&&a>0&&(Cl[n].isLastDiffed||a<t.length-1);e.print(F.statePrint2,z.state,`${a+1}: <${r.label??r.action??`Initial predicate`}>\n${ae(r.state,o?t[a-1].state:void 0)}`)})}catch(t){if(!(t instanceof _))throw t;e.print(F.general,z.error,t.message)}},Tl=(e,t)=>t===`1.7.4`||e.length===0?`Temporal properties were violated.
40
+ `:e.length===1?`Temporal property ${e[0]} was violated.\n`:`Temporal properties ${e.slice(0,-1).join(`, `)}${e.length>2?`,`:``} and ${e[e.length-1]} were violated.\n`,El=e=>e.filter((t,n)=>t!==e[n-1]).map((e,t)=>`${t}) ${fe(e)}\n`).toReversed().join(``),Dl=e=>{if(e.length===0)return` The error call stack is empty.
41
+ `;let t=[];return e.forEach((n,r)=>{let i=n.location.range;n!==e[r-1]&&i&&t.push(`${t.length}. Line ${i.start.line}, column ${i.start.column} to line ${i.end.line}, column ${i.end.column} in ${i.module}\n`)}),`${t.join(``)}\n`},Ol=(e,t)=>{let n=t.generated,r=t.distinct,i=je(/* @__PURE__ */ new Date);n===r?e.print(F.initGenerated1,z.none,`Finished computing initial states: ${r} distinct state${r===1?``:`s`} generated at ${i}.`):e.print(F.initGenerated2,z.none,`Finished computing initial states: ${n} state${n===1?``:`s`} generated, with ${r} of them distinct at ${i}.`)},kl=(e,t,n)=>{let r=Math.max(Date.now()-(n??0),1)/6e4,i=e=>e.toLocaleString(`en-US`),a=(e,t)=>n===void 0?``:` (${i(Math.floor(e/r))} ${t}/min)`;e.print(F.progress,z.none,`Progress(${Math.max(t.depth,1)}) at ${je(/* @__PURE__ */ new Date)}: ${i(t.generatedStates)} states generated${a(t.generatedStates,`s`)}, ${i(t.distinctStates)} distinct states found${a(t.distinctStates,`ds`)}, ${i(t.queuedStates)} states left on queue.`)},Al={init:F.coverageInit,next:F.coverageNext,invariant:F.coverageProperty,implied:F.coverageProperty,constraint:F.coverageConstraint},jl=(e,t,n)=>{let r=(t,n)=>e.print(t,z.none,n);r(F.coverageStart,`The coverage statistics at ${je(/* @__PURE__ */ new Date)} (see https://explain.tlapl.us/module-coverage-statistics for how to interpret the following statistics).`),t.variables.forEach(e=>r(F.coverageVariable,`<${e.label}>: ${e.distinct}`)),t.relations.forEach(e=>{let t=Al[e.kind];r(t,t===F.coverageProperty?`<${e.label}>`:`<${e.label}>: ${e.distinct}:${e.generated}`),e.expressions.forEach(e=>{let t=` ${`|`.repeat(e.depth)}${e.location}`;e.cost>0?r(F.coverageValueCost,`${t}: ${e.count}:${e.cost}`):r(F.coverageValue,`${t}: ${e.count}`)})}),Date.now()-n>3e5?r(F.coverageEndOverhead,`End of statistics (please note that for performance reasons large models
42
+ are best checked with coverage and cost statistics disabled).`):r(F.coverageEnd,`End of statistics.`)},Ml=(e,t)=>an(e,`${t}.class`),Nl=(e,t,n,r)=>{let i=e.print;switch(t.kind){case`parsed`:n.isParsed=!0,e.isTool&&i(F.sanyFinished,z.none,`SANY finished.`),i(F.starting,z.none,`Starting... (${je(/* @__PURE__ */ new Date)})`);return;case`constant-level-invariant`:if(e.version===`1.7.4`)return;i(F.constantLevelInvariant,z.warning,`The invariant ${t.name} is a constant-level formula (i.e., it contains no variables, primes, or temporal operators) and evaluates to TRUE. To assert constant-level formulas in your spec, use ASSUME ConstInv. If you optionally want to give the assumption a name, write ASSUME YourAssumption == ConstInv instead. See https://explain.tlapl.us/assumptions-and-invariants for additional details.`);return;case`state-level-property`:if(e.version===`1.7.4`)return;i(F.stateLevelProperty,z.warning,`The formula ${t.name} is a state-level formula, but it was used as a PROPERTY (or PROPERTIES), where a temporal formula is typically expected. State-level formulas used as PROPERTY or PROPERTIES are only checked in the initial state. To verify that the formula ${t.name} holds in all states of every behavior, use INVARIANT ${t.name} instead. Alternatively, applying the "always" temporal operator ([]) to the state-level formula ${t.name} changes it into a temporal formula, asserting that ${t.name} holds in all states of every behavior. See https://explain.tlapl.us/invariants-and-properties for additional details.`);return;case`liveness-initializing`:t.isSymmetric&&i(F.livenessSymmetry,z.warning,`Declaring symmetry during liveness checking is dangerous. It might cause TLC to miss violations of the stated liveness properties. Please check liveness without symmetry defined.`),t.isConstrained&&e.version===`1.7.4`&&i(F.livenessConstraints,z.warning,`Declaring state or action constraints during liveness checking is dangerous: Please read section 14.3.5 on page 247 of Specifying Systems (https://lamport.azurewebsites.net/tla/book.html) and optionally the discussion at https://discuss.tlapl.us/msg00994.html for more details.`);return;case`liveness-prepared`:i(F.temporalBranches,z.none,`Implied-temporal checking--satisfiability problem has ${t.branches} branches.`);return;case`java-override`:{let e=xn(on(Ml(r,t.module))).href;i(t.isMatched?F.javaOverrideLoaded:F.javaOverrideMismatch,t.isMatched?z.none:z.warning,`${t.isMatched?`Loading`:`Failed to match`} ${t.operator} operator override from ${e.replace(`file:///`,`file:/`)} with signature: <Java Method: ${t.signature}>.`);return}case`initial-states-started`:i(F.computingInit,z.none,`Computing initial states...`);return;case`initial-states-progress`:vl(e,t.count);return;case`initial-states-computed`:Ol(e,t.initialStates);return;case`progress`:kl(e,t.statistics,n.startTime),t.statistics.coverage&&jl(e,t.statistics.coverage,n.startTime);return;case`liveness-started`:{n.livenessStartTime=Date.now(),t.isComplete&&kl(e,t.statistics);let r=t.branches>1?`${t.branches} branches of `:``;i(F.checkingTemporal,z.none,`Checking ${r}temporal properties for the ${t.isComplete?`complete`:`current`} state space with ${t.states} total distinct states at (${je(/* @__PURE__ */ new Date)})`);return}case`liveness-finished`:Pl(e,n);return;case`sequential-fallback`:process.stderr.write(`Warning: the search ordered the string ${JSON.stringify(t.string)} against another string it created, so tla-ts checks the model again with one worker. Workers don't agree on the order of strings the search creates.\n`);return;case`warning`:i(t.code,z.warning,t.text);return;case`violation`:Il(t.status,t.violation,e)}},Pl=(e,t)=>{t.livenessStartTime!==void 0&&(e.print(F.checkingTemporalEnd,z.none,`Finished checking temporal properties in ${Ie(Date.now()-t.livenessStartTime)} at ${je(/* @__PURE__ */ new Date)}`),t.livenessStartTime=void 0)},Fl=(e,t)=>{t&&(t.counts&&console.log(t.counts),e.print(t.code,z.error,Ne(t.code,t.message,e.isTool)))},Il=(e,t,n)=>{let r=n.print,i=t.name,a=t.loopStart,o=a===void 0&&t.trace.length===1&&(e===`invariant-violation`||e===`liveness-violation`),s={code:F.temporalPropertyViolated,text:Tl(t.properties??[i],n.version)},c={success:void 0,error:void 0,"assumption-violation":t.message?{code:F.assumptionEvaluationError,text:Ne(F.assumptionEvaluationError,`Evaluating assumption ${i} failed.\n${t.message}`,n.isTool)}:{code:F.assumptionFalse,text:`Assumption ${i} is false.`},deadlock:{code:F.deadlockReached,text:`Deadlock reached.`},"invariant-violation":o?yl(`invariant-violation`,i):{code:F.invariantViolatedBehavior,text:`Invariant ${i} is violated.`},"property-violation":s,"liveness-violation":a===void 0?o?yl(`liveness-violation`,i):{code:F.actionPropertyViolatedBehavior,text:`Action property ${i} is violated.`}:s,"postcondition-violation":{code:t.postcondition?.code??F.general,text:Ne(t.postcondition?.code??F.general,t.message??`Postcondition ${i} is false.`,n.isTool)}}[e],l=e===`property-violation`,u=a!==void 0&&!l,d=l||u;if(d&&n.version!==`1.7.4`&&bl(n,t.trace[0]?.output),t.counts&&console.log(t.counts),c){let e=o?`${c.text}\n${ae(t.trace[0].state)}`:c.text;r(c.code,z.error,e)}if(o||(d||bl(n,t.trace[0]?.output),wl(n,t.trace,d?`counter-example`:`error-trace`)),bl(n,t.traceOutput),u){let e=t.loopLabel;a===t.trace.length-1?r(F.statePrint3,z.state,`${a+2}: Stuttering`):n.isTool?r(F.backToState,z.state,`${a+1}: Back to state${e?`: <${e}>\n`:``}`):console.log(`Back to state ${a+1}${e?`: <${e}>\n`:``}`)}t.warning&&n.version!==`1.7.4`&&r(t.warning.code,z.warning,t.warning.text);let f=t.unwitnessed??(e===`postcondition-violation`?void 0:t.postcondition);return bl(n,t.postconditionOutput),Fl(n,f),!o&&e!==`assumption-violation`},Ll=(e,t)=>e.print(F.nestedExpression,z.error,`The error occurred when TLC was evaluating the nested\nexpressions at the following positions:\n${Dl(t)}`),Rl=(e,t,n)=>e.print(F.success,z.none,[`Model checking completed. No error has been found.`,` Estimates of the probability that TLC did not check all reachable states`,` because two distinct states had the same fingerprint:`,` calculated (optimistic): val = ${yt(t)}`,...n===void 0?[]:[` based on the actual fingerprints: val = ${yt(n)}`]].join(`
43
+ `)),zl=(e,t,n)=>{switch(t.kind){case`message`:e.print(t.code,t.isError?z.error:z.none,e.isTool?t.toolMessage:t.message);return;case`coverage`:jl(e,t.coverage,n);return;case`behavior`:t.states.forEach((n,r)=>t.isInvariant?e.print(F.statePrint2,z.state,`${r+1}: \n${ae(n,e.isDiffTrace?t.states[r-1]:void 0)}`):e.print(F.statePrint1,z.state,`${r+1}:\n${ae(n)}`));return;case`nested-expressions`:Ll(e,t.callStack);return;case`success`:Rl(e,t.optimistic,t.actual)}},Bl=(e,t,n)=>{let r=t.print;if(e.failure){let n=e.failure,i=t.isTool?n.toolMessage:n.message,a=()=>{let e=n.fingerprint;if(e){let i=n.callStack?.length&&t.version!==`1.7.4`?Dl(n.callStack):El(e.sources);r(F.fingerprintFailed,z.error,`TLC was unable to fingerprint.\n\nFingerprint Stack Trace:\n${i}\nReason:\n${he(e.reason,t.isTool)}`)}else n.callStack&&Ll(t,n.callStack)};n.isCallStackFirst&&a();let o=n.initialState&&(()=>{try{return`While working on the initial state:\n${ae(n.initialState)}`}catch(e){throw e instanceof j?v(new j(`${c}${e.message}`),w.error):e}})();r(o?F.initialState:n.code,z.error,o?`${i}\n${o}`:i),bl(t,n.trace[0]?.output),wl(t,n.trace,`error-trace`);let s=n.traceFailure;s&&(bl(t,s.output),r(s.code,z.error,t.isTool?s.toolMessage:s.message)),bl(t,n.traceOutput),Fl(t,n.postcondition),n.isCallStackFirst||a()}else if(e.violation){if(!Il(e.status,e.violation,t))return;let n=e.additionalViolation;n&&Il(`property-violation`,n,t),e.liveCallStack&&Ll(t,e.liveCallStack)}else e.status===`success`&&(Pl(t,n),Rl(t,ht(e.distinctStates,e.generatedStates),e.fingerprintDistance===void 0?void 0:ot(e.fingerprintDistance)));if(e.failure?.isWithoutStatistics)return;e.status!==`success`&&Pl(t,n),e.coverage&&jl(t,e.coverage,n.startTime),t.isTool&&kl(t,e,n.startTime),r(F.stats,z.none,`${e.generatedStates} states generated, ${e.distinctStates} distinct states found, ${e.queuedStates} states left on queue.`);let i=t.version===`1.7.4`,a=i?e.outDegrees??e.violationOutDegrees:e.outDegrees;(!i||a)&&r(F.searchDepth,z.none,`The depth of the complete state graph search is ${i?Math.max(e.depth,1):e.depth}.`);let o=a&&xt(a);o&&r(F.stateGraphOutdegree,z.none,o)},Vl=e=>e.print(F.version,z.none,`TLC2 Version ${Wn} (rev: tla-ts)`),Hl=(e,t,n)=>{let r=re({isTool:e,version:t});return Vl(r),r.print(F.commandLineError,z.error,`${n}\nUsage: java tlc2.TLC [-help] [-option] inputfile`),1},Ul=(e,t)=>{let n=`${t.workers} worker${t.workers===1?``:`s`} on ${wn()} cores with ${Math.floor(On().heap_size_limit/1024/1024)}MB heap and 64MB offheap memory [pid: ${process.pid}] (${Dn()} ${Tn()} ${Cn()}, Node.js ${process.versions.node} ${process.arch.endsWith(`64`)?64:32}bit`;t.mode===`model-check`&&t.dfidDepth!==void 0?e.print(F.depthFirstModelChecking,z.none,`Running depth-first search Model-Checking with fp ${t.fingerprintIndex} and seed ${t.seed} with ${n}).`):t.mode===`model-check`?e.print(F.modelChecking,z.none,`Running breadth-first search Model-Checking with fp ${t.fingerprintIndex} and seed ${t.seed} with ${n}, MSBDiskFPSet, DiskStateQueue).`):e.print(F.simulating,z.none,`Running ${t.scheduler===`rl`?`RL`:`Random`} Simulation with seed ${t.seed} with ${n}).`)},Wl=(e,t,n)=>{let r=e.print;switch(t.kind){case`message`:r(t.code,t.isError?z.error:z.none,e.isTool?t.toolMessage:t.message);return;case`coverage`:jl(e,t.coverage,n);return;case`behavior`:{let n=t.trace[t.trace.length-1];if(!t.isLastStateOnly){wl(e,t.trace,`simulation`);return}r(F.errorState,z.none,`The error state is:
44
+ `),r(F.statePrint1,z.state,`:\n${ae(n.state)}`);return}case`progress`:{let n=t.statistics;if(e.isTool){Gl(e,n);return}let i=n.levelM2/(n.traces+1);r(F.simulationProgress,z.none,`Progress: ${n.generatedStates} states checked, ${n.traces} traces generated (trace length: mean=${n.levelMean}, var(x)=${Math.round(i)}, sd=${Math.round(Math.sqrt(i))})`);return}case`summary`:e.isTool&&Gl(e,t.statistics),r(F.simulationStats,z.none,`The number of states generated: ${t.statistics.generatedStates}\nSimulation using seed ${t.statistics.seed} and aril ${t.statistics.aril}`)}},Gl=(e,t)=>e.print(F.simulationProgress,z.none,`Progress(${t.traces}) at ${je(/* @__PURE__ */ new Date)}: ${t.generatedStates} states generated, -1 distinct states found, -1 states left on queue.`),Kl=[{name:`-checkpoint`,sampleValue:`minutes`,description:`interval between check point; defaults to 30`,isOptional:!0},{name:`-cleanup`,description:`clean up the states directory`,isOptional:!0},{name:`-config`,sampleValue:`file`,description:`provide the configuration file; defaults to SPEC.cfg`,isOptional:!0},{name:`-continue`,description:`continue running even when an invariant is violated; default
49
45
  behavior is to halt on first violation`,isOptional:!0},{name:`-coverage`,sampleValue:`minutes`,description:`interval between the collection of coverage information;
50
46
  if not specified, no coverage will be collected`,isOptional:!0},{name:`-deadlock`,description:`if specified DO NOT CHECK FOR DEADLOCK. Setting the flag is
51
47
  the same as setting CHECK_DEADLOCK to FALSE in config
@@ -126,20 +122,20 @@ terminates. The optional parameter 'port=1274' makes the
126
122
  debugger listen on port 1274 instead of on the standard
127
123
  port 4712, and 'port=0' lets the debugger choose a port.
128
124
  Multiple optional parameters must be comma-separated.
129
- Specifying '-debugger' implies '-workers 1'.`,isOptional:!1,subOptions:`nosuspend`},{name:`SPEC`,isOptional:!1}],ru=[[...nu,{name:`-dfid`,sampleValue:`num`,description:`run the model check in depth-first iterative deepening
130
- starting with an initial depth of 'num'`,isOptional:!0},{name:`-view`,description:`apply VIEW (if provided) when printing out states`,isOptional:!0}],[...nu,{name:`-depth`,sampleValue:`num`,description:`specifies the depth of random simulation; defaults to 100`,isOptional:!0},{name:`-seed`,sampleValue:`num`,description:`provide the seed for random simulation; defaults to a
125
+ Specifying '-debugger' implies '-workers 1'.`,isOptional:!1,subOptions:`nosuspend`},{name:`SPEC`,isOptional:!1}],ql=[[...Kl,{name:`-dfid`,sampleValue:`num`,description:`run the model check in depth-first iterative deepening
126
+ starting with an initial depth of 'num'`,isOptional:!0},{name:`-view`,description:`apply VIEW (if provided) when printing out states`,isOptional:!0}],[...Kl,{name:`-depth`,sampleValue:`num`,description:`specifies the depth of random simulation; defaults to 100`,isOptional:!0},{name:`-seed`,sampleValue:`num`,description:`provide the seed for random simulation; defaults to a
131
127
  random long pulled from a pseudo-RNG`,isOptional:!0},{name:`-aril`,sampleValue:`num`,description:`adjust the seed for random simulation; defaults to 0`,isOptional:!0},{name:`-simulate`,description:`run in simulation mode; optional parameters may be specified
132
128
  comma delimited: 'num=X' where X is the maximum number of
133
129
  total traces to generate and/or 'file=Y' where Y is the
134
130
  absolute-pathed prefix for trace file modules to be written
135
131
  by the simulation workers; for example Y='/a/b/c/tr' would
136
- produce, e.g, '/a/b/c/tr_1_15'`,isOptional:!1,subOptions:`file=X,num=Y`}]],iu=[`When using the '-generateSpecTE' you can version the generated specification by doing:
132
+ produce, e.g, '/a/b/c/tr_1_15'`,isOptional:!1,subOptions:`file=X,num=Y`}]],Jl=[`When using the '-generateSpecTE' you can version the generated specification by doing:
137
133
  ./tla2tools.jar -generateSpecTE MySpec.tla && NAME="SpecTE-$(date +%s)" && sed -e "s/MODULE SpecTE/MODULE $NAME/g" SpecTE.tla > $NAME.tla`,`If, while checking a SpecTE created via '-generateSpecTE', you get an error message concerning
138
134
  CONSTANT declaration and you've previous used 'integers' as model values, rename your
139
135
  model values to start with a non-numeral and rerun the model check to generate a new SpecTE.`,`If, while checking a SpecTE created via '-generateSpecTE', you get a warning concerning
140
136
  duplicate operator definitions, this is likely due to the 'monolith' specification
141
137
  creation. Try re-running TLC adding the 'nomonolith' option to the '-generateSpecTE'
142
- parameter.`,`When using more than one worker, the reported depth might differ across runs. For small models, use a single worker. For large models, the diameter will almost always appear deterministic.`],X=e=>`\u001b[1m${e}\u001b[0m`,au=e=>`\u001b[3m${e}\u001b[0m`,ou=e=>e.name.startsWith(`-`)&&!e.name.startsWith(`--`),su=(e,t)=>e.name<t.name?-1:+(e.name>t.name),cu=e=>e.subOptions===void 0?``:` [${e.subOptions}]`,lu=e=>{let t=[...e].sort(su),n=t.filter(e=>e.sampleValue===void 0&&e.isOptional&&ou(e)),r=n.filter(e=>e.name.length===2).map(e=>e.name.slice(1)).join(``),i=t.filter(e=>e.sampleValue===void 0&&!e.isOptional).sort((e,t)=>ou(e)===ou(t)?su(e,t):ou(e)?-1:1);return[X(`TLC`),...r===``?[]:[`[${X(`-${r}`)}]`],...n.filter(e=>e.name.length!==2).map(e=>`[${X(e.name)}${cu(e)}]`),...t.filter(e=>e.sampleValue===void 0&&e.isOptional&&e.name.startsWith(`--`)).map(e=>`[${X(e.name)}${cu(e)}]`),...t.filter(e=>e.sampleValue!==void 0&&e.isOptional).map(e=>`[${X(e.name)} ${e.subOptions===void 0?``:`[${e.subOptions}] `}${au(e.sampleValue??``)}]`),...t.filter(e=>e.sampleValue!==void 0&&!e.isOptional).map(e=>`${X(e.name)} ${au(e.sampleValue??``)}`),...i.map(e=>`${e.name}${cu(e)}`)].join(` `)},uu=()=>(/* @__PURE__ */ new Date()).toISOString().replace(/^(\d+)-(\d+)-(\d+)T(\d+):(\d+):(\d+).*$/,`Version $1.$2.$3.$4$5$6`),du=()=>{let e=[...new Map(ru.flat().map(e=>[e.name,e])).values()].sort(su).filter(e=>e.sampleValue!==void 0||e.isOptional||ou(e)),t=(e,t)=>e.replace(/\r\n|\r|\n/g,`\n${t}`);return[``,`${X(`NAME`)}\n`,`\tTLC - provides model checking and simulation of TLA+ specifications - ${uu()}\n\n`,`${X(`SYNOPSIS`)}\n`,...ru.map(e=>`\t${lu(e)}`),``,`${X(`DESCRIPTION`)}\n`,`\t${t(`The model checker (TLC) provides the functionalities of model checking
138
+ parameter.`,`When using more than one worker, the reported depth might differ across runs. For small models, use a single worker. For large models, the diameter will almost always appear deterministic.`],X=e=>`\u001b[1m${e}\u001b[0m`,Yl=e=>`\u001b[3m${e}\u001b[0m`,Xl=e=>e.name.startsWith(`-`)&&!e.name.startsWith(`--`),Zl=(e,t)=>e.name<t.name?-1:+(e.name>t.name),Ql=e=>e.subOptions===void 0?``:` [${e.subOptions}]`,$l=e=>{let t=[...e].sort(Zl),n=t.filter(e=>e.sampleValue===void 0&&e.isOptional&&Xl(e)),r=n.filter(e=>e.name.length===2).map(e=>e.name.slice(1)).join(``),i=t.filter(e=>e.sampleValue===void 0&&!e.isOptional).sort((e,t)=>Xl(e)===Xl(t)?Zl(e,t):Xl(e)?-1:1);return[X(`TLC`),...r===``?[]:[`[${X(`-${r}`)}]`],...n.filter(e=>e.name.length!==2).map(e=>`[${X(e.name)}${Ql(e)}]`),...t.filter(e=>e.sampleValue===void 0&&e.isOptional&&e.name.startsWith(`--`)).map(e=>`[${X(e.name)}${Ql(e)}]`),...t.filter(e=>e.sampleValue!==void 0&&e.isOptional).map(e=>`[${X(e.name)} ${e.subOptions===void 0?``:`[${e.subOptions}] `}${Yl(e.sampleValue??``)}]`),...t.filter(e=>e.sampleValue!==void 0&&!e.isOptional).map(e=>`${X(e.name)} ${Yl(e.sampleValue??``)}`),...i.map(e=>`${e.name}${Ql(e)}`)].join(` `)},eu=()=>(/* @__PURE__ */ new Date()).toISOString().replace(/^(\d+)-(\d+)-(\d+)T(\d+):(\d+):(\d+).*$/,`Version $1.$2.$3.$4$5$6`),tu=()=>{let e=[...new Map(ql.flat().map(e=>[e.name,e])).values()].sort(Zl).filter(e=>e.sampleValue!==void 0||e.isOptional||Xl(e)),t=(e,t)=>e.replace(/\r\n|\r|\n/g,`\n${t}`);return[``,`${X(`NAME`)}\n`,`\tTLC - provides model checking and simulation of TLA+ specifications - ${eu()}\n\n`,`${X(`SYNOPSIS`)}\n`,...ql.map(e=>`\t${$l(e)}`),``,`${X(`DESCRIPTION`)}\n`,`\t${t(`The model checker (TLC) provides the functionalities of model checking
143
139
  or simulation of TLA+ specifications. It may be invoked from the command
144
140
  line, or via the model checking functionality of the Toolbox.
145
141
 
@@ -148,13 +144,13 @@ approach for the state space exploration.
148
144
 
149
145
  A pretty-printed and in-depth description of TLC can be found at:
150
146
 
151
- https://lamport.azurewebsites.net/tla/current-tools.pdf`.replace(/TLC(\)|\s|$)/g,`${X(`TLC`)}$1`),` `)}`,``,`${X(`OPTIONS`)}\n`,...e.map(e=>`\t${X(e.name)}${e.sampleValue===void 0?``:` ${au(e.sampleValue)}`}\n\t\t${t(e.description??``,` `)}`),``,`${X(`TIPS`)}\n`,...iu.map(e=>`\t${t(e,` `)}\n`)].join(`
152
- `)},fu=async e=>{let t=(await import(`./compile.js`)).compile(kt(e,`utf8`),e),n=`\\* Generated by tla-ts from ${_t(e)}. Edit ${_t(e)} instead.`,r=xt(yt(e),`${t.name}.tla`),i=xt(yt(e),`${t.name}.cfg`);for(let t of[r,i])if(I(t)&&!kt(t,`utf8`).startsWith(n))throw new l(`${t} already exists, and tla-ts didn't generate it from ${e}`);return It(r,`${n}\n${t.source}\n`),It(i,`${n}\n${t.config}\n`),r},pu={success:T.success,"assumption-violation":T.assumptionViolation,deadlock:T.deadlock,"invariant-violation":T.safetyViolation,"property-violation":T.safetyViolation,"liveness-violation":T.livenessViolation,"postcondition-violation":T.assumptionViolation,error:T.error},mu=e=>{if(Ft(e,{throwIfNoEntry:!1})?.isDirectory())throw new y(`${e} (Is a directory)`)},hu=(e,t)=>e.endsWith(t)?e:`${e}${t}`,gu=e=>{if(e.length===1)return{path:hu(e[0],`.dump`)};let t=e[0].toLowerCase();return{path:hu(e[1],`.dot`),dot:!0,colorize:t.includes(`colorize`),actionLabels:t.includes(`actionlabels`),snapshot:t.includes(`snapshot`),constrained:t.includes(`constrained`),stuttering:t.includes(`stuttering`),strict:t.includes(`strict`)}},_u=e=>Oe([e]).toString(),vu=(e,t,n,r,i)=>{let a=n.temporaryDirectory??Ht(),o=I(a)?Mt(a):St(a),s=xt(o,`tlc-${_u(St(e))}`),c=on(n);return(n,a)=>{let l=`${n}.tla`;if(a===`file`)return Mt(Yt(t,n)??e);if(i===`1.7.4`)return xt(o,l);if(a===`root file`){let t=r===void 0?o:St(r),i=Mt(e);return`${xt(t,_u(`${i} ${n}`),l)} (${i})`}let u=xt(s,l);return c===void 0?u:`${u} (${Qt(c)}${l})`}},yu=(e,t)=>{let n=e.split(/\r?\n/),r=n.findIndex(e=>e.match(/^-----*\s*CONFIG\s+(\S+?)\s*-----*$/)?.[1]===t);if(r===-1)return`
147
+ https://lamport.azurewebsites.net/tla/current-tools.pdf`.replace(/TLC(\)|\s|$)/g,`${X(`TLC`)}$1`),` `)}`,``,`${X(`OPTIONS`)}\n`,...e.map(e=>`\t${X(e.name)}${e.sampleValue===void 0?``:` ${Yl(e.sampleValue)}`}\n\t\t${t(e.description??``,` `)}`),``,`${X(`TIPS`)}\n`,...Jl.map(e=>`\t${t(e,` `)}\n`)].join(`
148
+ `)},nu=async e=>{let t=(await import(`./compile.js`)).compile(pn(e,`utf8`),e),n=`\\* Generated by tla-ts from ${en(e)}. Edit ${en(e)} instead.`,r=an(nn(e),`${t.name}.tla`),i=an(nn(e),`${t.name}.cfg`);for(let t of[r,i])if(B(t)&&!pn(t,`utf8`).startsWith(n))throw new m(`${t} already exists, and tla-ts didn't generate it from ${e}`);return bn(r,`${n}\n${t.source}\n`),bn(i,`${n}\n${t.config}\n`),r},ru={success:w.success,"assumption-violation":w.assumptionViolation,deadlock:w.deadlock,"invariant-violation":w.safetyViolation,"property-violation":w.safetyViolation,"liveness-violation":w.livenessViolation,"postcondition-violation":w.assumptionViolation,error:w.error},iu=e=>{if(yn(e,{throwIfNoEntry:!1})?.isDirectory())throw new j(`${e} (Is a directory)`)},au=(e,t)=>e.endsWith(t)?e:`${e}${t}`,ou=e=>{if(e.length===1)return{path:au(e[0],`.dump`)};let t=e[0].toLowerCase();return{path:au(e[1],`.dot`),dot:!0,colorize:t.includes(`colorize`),actionLabels:t.includes(`actionlabels`),snapshot:t.includes(`snapshot`),constrained:t.includes(`constrained`),stuttering:t.includes(`stuttering`),strict:t.includes(`strict`)}},su=e=>Tt([e]).toString(),cu=(e,t,n,r,i)=>{let a=n.temporaryDirectory??En(),o=B(a)?gn(a):on(a),s=an(o,`tlc-${su(on(e))}`),c=Un(n);return(n,a)=>{let l=`${n}.tla`;if(a===`file`)return gn(Nn(t,n)??e);if(i===`1.7.4`)return an(o,l);if(a===`root file`){let t=r===void 0?o:on(r),i=gn(e);return`${an(t,su(`${i} ${n}`),l)} (${i})`}let u=an(s,l);return c===void 0?u:`${u} (${In(c)}${l})`}},lu=(e,t)=>{let n=e.split(/\r?\n/),r=n.findIndex(e=>e.match(/^-----*\s*CONFIG\s+(\S+?)\s*-----*$/)?.[1]===t);if(r===-1)return`
153
149
  `;let i=n.findIndex((e,t)=>t>r&&e.startsWith(`====`));return`${n.slice(r+1,i===-1?void 0:i).join(`
154
- `).trim()}\n`},bu=e=>e.replace(/\/+/g,`/`).replace(/(.)\/$/,`$1`),xu=e=>{let t=bu(e),n=t.lastIndexOf(`/`);return n===-1?`.`:t.slice(0,Math.max(n,1))},Su=(e,t)=>e.endsWith(`/`)?`${e}${t}`:`${e}/${t}`,Cu=(e,t,n,r)=>{if(t===`1.7.4`||!e.isTraceSpecForced&&(e.isTraceSpecDisabled||e.isTool||e.isContinued||_t(n).includes(`_TTrace`)))return;let i=e.traceSpecPath,a=`${_t(n)}_TTrace_${Math.floor(r/1e3)}`,o=i===void 0?{directory:xu(n),module:a}:i.toLowerCase().endsWith(`.tla`)?{directory:xu(i),module:_t(i).replace(/\.tla$/,``)}:{directory:bu(i),module:a};return{...o,traceFile:e.isTraceBinaryDisabled?void 0:Su(o.directory,`${o.module}.bin`)}},wu={ENOENT:`No such file or directory`,ENOTDIR:`Not a directory`,EISDIR:`Is a directory`,EACCES:`Permission denied`},Tu=(e,t)=>{try{It(e,t)}catch(t){let n=t instanceof Error&&`code`in t?wu[String(t.code)]:void 0;throw n===void 0?t:new y(`${e} (${n})`)}},Eu=e=>{try{Dt(e,{recursive:!0})}catch{}},Du=e=>{let t=/* @__PURE__ */ new Date,n=`${Ie(t.getFullYear()%100)}-${Ie(t.getMonth()+1)}-${Ie(t.getDate())}-${Ie(t.getHours())}-${Ie(t.getMinutes())}-${Ie(t.getSeconds())}.${Ie(t.getMilliseconds(),3)}`,r=xt(e.metadir??`states`,n);return Dt(r,{recursive:!0}),r},Ou=async(e,n,r,i,s)=>{let c=n.livenessCheck,l=s.version;Zl(s);let d=n.recoverDirectory;if(d!==void 0)throw I(xt(d,`vars.chkpt`))?new k(`tla-ts can't recover a model check from the checkpoint in ${d}.`):new a(d);$l(s,n);let f=n.configPath??e.replace(/\.tla$/,`.cfg`);if(!I(f))return s.print(M.configFileError,F.error,`TLC encountered the following error when trying to read the configuration file ${f}:\nFile not found.`),T.configParseError;let p=_t(e,`.tla`),m={startTime:Date.now(),livenessStartTime:void 0,isParsed:!1},h=()=>{let e=Date.now()-m.startTime;s.print(M.finished,F.none,`Finished in ${s.isTool?`${e}ms`:P(e)} at (${me(/* @__PURE__ */ new Date)})`)},g=()=>s.print(M.parsingFailed,F.error,`Parsing or semantic analysis failed.`),v=e=>(e instanceof o?g():en(e,s),h(),$t(e)),b=(()=>{try{let e=kt(f,`utf8`);return Se(f.endsWith(`.tla`)?yu(e,f.replaceAll(`.tla`,``)):e,l)}catch(e){if(!(e instanceof _))throw e;return e}})();if(b instanceof _&&l===`1.7.4`)return s.print(M.general,F.error,`${t(`tlc2.tool.ConfigFileException`)}${De(b.message,s.isTool)}`),h(),T.error;if(b instanceof _)return v(b);n.isDeadlockChecked||(b.checkDeadlock=!1);let x=yt(e),S=[x,...i.libraries],C=Xt(S),w=Cu(n,l,e.replace(/\.tla$/,``),m.startTime),E=e=>n.moduleOperators.filter(t=>t.kind===e).map(e=>e.module);s.isTool&&s.print(M.startingSany,F.none,`Starting SANY...`);let ee=bt(e),D=ee?p:e.replace(/\.tla$/,``),O=on(i),te=l===`1.7.4`?Mu(e,i,O):void 0;te?!I(e)&&!ve.has(p)&&te(`${p}.tla`):!I(e)&&!ke.has(p)&&Zt(ee?x:process.cwd(),ee?`${p}.tla`:`./${D}.tla`,[...ee||x===`.`?[]:[x],...i.libraries]);let ne=nl(e,te?an(C,te):C,{fileName:D,describeFile:vu(e,S,i,n.metadir,l),version:l,rootExtendees:[...E(`postcondition`),...w?.traceFile===void 0?[]:[`_TLCTrace`],...n.invariants.flatMap(e=>e.modules),...E(`constraint`),...E(`view`).slice(0,1)],suppressedCodes:n.suppressedCodes,errorCodes:n.errorCodes,onPrint:e=>process.stdout.write(e),onPrintError:e=>process.stderr.write(e)}),re=ne.specification;if(ne.isFailed||re===void 0)return Ul(s,{kind:`parsed`},m,x),g(),h(),T.specParseError;try{let t=kt(e,`utf8`),i=Je(t).name;if(i!==p)throw new u(`File name '${p}' does not match the name '${i}' of the top level module it contains.`,void 0);let a=n.userFile,o=We(l),d=sl(t,re.root,n.invariants,e=>C(e)??o.get(e)??he(t,e),l);b.invariants.push(...d.names);let f={workers:n.workers,livenessCheck:c===`off`?`off`:[`final`,`seqfinal`].includes(c)?`final`:`default`,seed:n.seed,fingerprintPolynomial:n.fingerprintIndex,maxSetSize:n.maxSetSize,isLazyValueExpanded:n.isLazyValueExpanded,isViewPrinted:n.isViewPrinted,dump:r,isTool:s.isTool,isContinued:n.isContinued,moduleOperators:n.moduleOperators,traceSpec:w,coverage:n.coverage,isSanyReported:!0,isWarningEnabled:n.isWarningEnabled,version:l,onProgress:e=>Ul(s,e,m,x),onPrint:a===void 0?void 0:e=>Ct(a,`${e}\n`),source:d.source,config:b,onPause:()=>At(0,Buffer.alloc(1)),readLine:ku,loadModule:C,loadClass:e=>{let t=Hl(x,e);return I(t)?kt(t):void 0},readFile:e=>(mu(e),I(e)?kt(e,`utf8`):void 0),writeFile:Tu,makeDirectory:Eu};if(n.mode!==`model-check`){let e=pr({...f,traceDepth:n.traceDepth,traceCount:n.traceCount,aril:n.aril,isGenerating:n.mode===`generate`,scheduler:n.scheduler,onSimulation:e=>eu(s,e)});return h(),e}if(n.dfidDepth!==void 0){let e=or({...f,maxDepth:n.dfidDepth,onOutput:e=>Yl(s,e)});return h(),e}let g=await Xe(f);if(Xl(g,s,m),h(),w&&g.traceSpec!==void 0){let e=Su(w.directory,`${w.module}.tla`);Eu(w.directory);let t=(()=>{try{Tu(e,g.traceSpec);return}catch(e){if(!(e instanceof y))throw e;return e}})();s.print(t?M.traceSpecFailed:M.traceSpecWritten,F.none,t?`Failed to generate trace exploration spec; error message: ${t.message}`:`Trace exploration spec path: ${e}`)}return g.failure?.exitCode??pu[g.status]}catch(e){if(!(e instanceof A))throw e;return e instanceof o&&console.log(Au(e,p)),m.isParsed||Ul(s,{kind:`parsed`},m,x),v(e)}},ku=()=>{let e=[],t=Buffer.alloc(1),n=!1;for(;At(0,t)===1&&(n=!0,t[0]!==10);)e.push(t[0]);return n?Buffer.from(e).toString().replace(/\r$/,``):void 0},Au=(e,t)=>{let n=e instanceof u;if(!n&&!e.failure)return`Semantic errors:\n\n*** Errors: 1\n\n${e.message}\n\n`;let r=n?e.location===void 0?`Unknown location\n\n${e.message}`:`In module ${e.location}\n\n${e.message}`:`In module ${t}\n\nCould not parse module ${t} from file ${t}.tla`;return`${e.failure?`***Parse Error***\n${e.message}\n\n`:``}\nFatal errors while parsing TLA+ spec in file ${t}\n\n${r}\n*** Errors: 1\n\n${r}\n\n\n`},ju=async(e,t)=>{let n=t.tlcVersion??`master`,r=Dl(e);if(r===`usage`)return console.log(du()),1;if(`error`in r)return r.kind===`uncaught`?(console.error(`Exception in thread "main" ${r.error}`),1):Ql(r.isTool,n,r.error);let i=r.dump&&gu(r.dump);i?.path.startsWith("${metadir}")&&(i.path=i.path.replaceAll("${metadir}",Du(r)));let a=i?.path;if(a!==void 0)try{wt(Ot(a,`w`))}catch{return console.log(`Error: Unable to write to file ${a}`),Ql(r.isTool,n,`Error: Given file name ${a} for dumping states invalid.`)}let o=r.configPath!==void 0;if(o&&r.specs.length>1)return Ql(r.isTool,n,`Error: more than one input files: ${r.specs[0].replace(/\.tla$/,``)} and ${r.specs[1]}`);let s=Jt(r.specs).map(e=>({...e,path:e.isGlobbed||/\.(tla|cfg|ts)$/.test(e.path)?e.path.replace(/\.cfg$/,`.tla`):`${e.path}.tla`})).filter(e=>e.path.endsWith(`.ts`)||e.path.endsWith(`.tla`)&&(!e.isGlobbed||o||I(e.path.replace(/\.tla$/,`.cfg`)))).map(e=>e.path);if(s.length===0)return Ql(r.isTool,n,`Error: Missing input TLA+ module.`);if(o&&s.length>1)return console.error(`Error: -config applies to one specification, but several were given.`),1;let c=[...new Set(s.map(e=>I(e)||bt(e)?e:t.libraries.map(t=>xt(t,e)).find(I)??e))],l=[];for(let[e,a]of c.entries()){e>0&&console.log(``);let o=N({isTool:r.isTool,isWarningEnabled:r.isWarningEnabled,isDiffTrace:r.isDiffTrace,version:n,suppressedCodes:r.suppressedCodes,errorCodes:r.errorCodes});l.push(await tn(async()=>{let e=a.endsWith(`.ts`)?await fu(a):a;return c.length>1&&console.log(`Checking ${_t(e)} with ${_t(e,`.tla`)}.cfg`),Ou(e,r,i,t,o)},o))}return l.find(e=>e!==T.success)??T.success},Mu=(e,t,n)=>{let r=e.slice(0,e.lastIndexOf(`/`)+1),i=(!bt(e)&&r!==``?[r]:t.libraries).map(rn),a=i.length>0?i[i.length-1]:bt(e)?r:``;return e=>nn(`${a}${e}`,i,n)},Nu={uncaughtException:1,argsParsingFailure:1,specParsingFailure:2,unrepresentableCharacter:7},Pu=e=>`java.lang.IllegalArgumentException: unsupported kind: ${e} in xml export`,Z=(e,t=[])=>({tag:e,children:t}),Q=(e,t)=>({tag:e,text:String(t),children:[]}),Fu={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,"\r":`&#13;`},Iu=e=>e.replace(/[&<>\r]|[\u{10000}-\u{10FFFF}]/gu,e=>e.length===2?`&#${e.codePointAt(0)};`:Fu[e]),Lu=/[^\t\n\r\u0020-\uD7FF\uE000-\uFFFD\u{10000}-\u{10FFFF}]/u,Ru=e=>{let t=(e.cdata??e.text)?.match(Lu)?.[0];if(t!==void 0)return{tag:e.tag,character:t};for(let t of e.children){let e=Ru(t);if(e)return e}},zu=(e,t,n,r)=>{let i=` `.repeat(t*n);if(e.cdata){let t=e.cdata.replaceAll(`]]>`,`]]]]><![CDATA[>`);r.push(`${i}<${e.tag}><![CDATA[${t}]]></${e.tag}>`)}else if(e.text)r.push(`${i}<${e.tag}>${Iu(e.text)}</${e.tag}>`);else if(e.children.length===0)r.push(`${i}<${e.tag}/>`);else{r.push(`${i}<${e.tag}>`);for(let i of e.children)zu(i,t+1,n,r);r.push(`${i}</${e.tag}>`)}},Bu=e=>Z(`location`,[Z(`column`,[Q(`begin`,e.beginColumn),Q(`end`,e.endColumn)]),Z(`line`,[Q(`begin`,e.beginLine),Q(`end`,e.endLine)]),Q(`filename`,e.file)]),Vu=e=>{switch(e.kind){case`FormalParam`:return`FormalParamNodeRef`;case`OpDecl`:return`OpDeclNodeRef`;case`Module`:return`ModuleNodeRef`;case`Theorem`:return`TheoremNodeRef`;case`Assume`:return`AssumeNodeRef`;case`ThmOrAssumpDef`:return e.isTheorem?`TheoremDefRef`:`AssumeDefRef`;case`OpDef`:return e.defKind===`UserDefined`?`UserDefinedOpKindRef`:e.defKind===`BuiltIn`?`BuiltInKindRef`:`ModuleInstanceKindRef`}},$={main:{at:`xml.XMLExporter.main(XMLExporter.java:145)`},constant:{at:`semantic.ModuleNode.getSymbolElement(ModuleNode.java:1228)`},variable:{at:`semantic.ModuleNode.getSymbolElement(ModuleNode.java:1236)`},definition:{at:`semantic.ModuleNode.getSymbolElement(ModuleNode.java:1244)`},topLevel:{at:`semantic.ModuleNode.getSymbolElement(ModuleNode.java:1268)`},body:{at:`semantic.OpDefNode.getSymbolElement(OpDefNode.java:1392)`,nullType:`ExprNode`,nullValue:`"this.body"`},param:{at:`semantic.OpDefNode.getSymbolElement(OpDefNode.java:1397)`},builtInParam:{at:`semantic.OpDefNode.getSymbolElement(OpDefNode.java:1413)`},theoremDefinitionBody:{at:`semantic.ThmOrAssumpDefNode.getSymbolElement(ThmOrAssumpDefNode.java:663)`,nullType:`LevelNode`,nullValue:`"this.body"`},theoremDefinition:{at:`semantic.TheoremNode.getLevelElement(TheoremNode.java:439)`},theorem:{at:`semantic.TheoremNode.getLevelElement(TheoremNode.java:444)`,nullType:`LevelNode`,nullValue:`the return value of "tla2sany.semantic.TheoremNode.getTheorem()"`},proof:{at:`semantic.TheoremNode.getLevelElement(TheoremNode.java:447)`},assumeDefinition:{at:`semantic.AssumeNode.getLevelElement(AssumeNode.java:249)`},assume:{at:`semantic.AssumeNode.getLevelElement(AssumeNode.java:254)`,nullType:`ExprNode`,nullValue:`the return value of "tla2sany.semantic.AssumeNode.getAssume()"`},operator:{at:`semantic.OpApplNode.getLevelElement(OpApplNode.java:1315)`},operand:{at:`semantic.OpApplNode.getLevelElement(OpApplNode.java:1326)`,nullType:`ExprOrOpArgNode`,nullValue:`"this.operands[i]"`},unbound:{at:`semantic.OpApplNode.getLevelElement(OpApplNode.java:1337)`},bound:{at:`semantic.OpApplNode.getLevelElement(OpApplNode.java:1347)`},range:{at:`semantic.OpApplNode.getLevelElement(OpApplNode.java:1349)`,nullType:`ExprNode`,nullValue:`"this.ranges[i]"`},letBody:{at:`semantic.LetInNode.getLevelElement(LetInNode.java:301)`,nullType:`ExprNode`,nullValue:`"this.body"`},letDefinition:{at:`semantic.LetInNode.getLevelElement(LetInNode.java:303)`},labelBody:{at:`semantic.LabelNode.getLevelElement(LabelNode.java:341)`,nullType:`LevelNode`,nullValue:`"this.body"`},labelParam:{at:`semantic.LabelNode.getLevelElement(LabelNode.java:343)`},argument:{at:`semantic.OpArgNode.getLevelElement(OpArgNode.java:150)`},exceptObject:{at:`semantic.AtNode.getLevelElement(AtNode.java:180)`},exceptComponents:{at:`semantic.AtNode.getLevelElement(AtNode.java:181)`},substOperator:{at:`semantic.Subst.export(Subst.java:258)`},substExpression:{at:`semantic.Subst.export(Subst.java:259)`,nullType:`ExprOrOpArgNode`,nullValue:`"this.expr"`},instanceSubst:{at:`semantic.InstanceNode.getLevelElement(InstanceNode.java:447)`},instanceParam:{at:`semantic.InstanceNode.getLevelElement(InstanceNode.java:452)`},useFact:{at:`semantic.UseOrHideNode.getLevelElement(UseOrHideNode.java:175)`,nullType:`LevelNode`,nullValue:`"this.facts[i]"`},useDefinition:{at:`semantic.UseOrHideNode.getLevelElement(UseOrHideNode.java:176)`},newDeclaration:{at:`semantic.NewSymbNode.getLevelElement(NewSymbNode.java:202)`},newSet:{at:`semantic.NewSymbNode.getLevelElement(NewSymbNode.java:204)`},assumption:{at:`semantic.AssumeProveNode.getLevelElement(AssumeProveNode.java:404)`,nullType:`SemanticNode`,nullValue:`"assumes[i]"`},goal:{at:`semantic.AssumeProveNode.getLevelElement(AssumeProveNode.java:406)`,nullType:`ExprNode`,nullValue:`the return value of "tla2sany.semantic.AssumeProveNode.getProve()"`},byFact:{at:`semantic.LeafProofNode.getLevelElement(LeafProofNode.java:154)`,nullType:`LevelNode`,nullValue:`"this.facts[i]"`},byDefinition:{at:`semantic.LeafProofNode.getLevelElement(LeafProofNode.java:155)`},step:{at:`semantic.NonLeafProofNode.getLevelElement(NonLeafProofNode.java:228)`,nullType:`LevelNode`,nullValue:`"this.steps[i]"`},defStep:{at:`semantic.DefStepNode.getLevelElement(DefStepNode.java:99)`}},Hu={SubstIn:{subst:{at:`semantic.SubstInNode.getLevelElement(SubstInNode.java:530)`},body:{at:`semantic.SubstInNode.getLevelElement(SubstInNode.java:533)`,nullType:`ExprNode`,nullValue:`"this.body"`},from:{at:`semantic.SubstInNode.getLevelElement(SubstInNode.java:536)`},to:{at:`semantic.SubstInNode.getLevelElement(SubstInNode.java:540)`}},APSubstIn:{subst:{at:`semantic.APSubstInNode.getLevelElement(APSubstInNode.java:460)`},body:{at:`semantic.APSubstInNode.getLevelElement(APSubstInNode.java:463)`,nullType:`LevelNode`,nullValue:`"this.body"`},from:{at:`semantic.APSubstInNode.getLevelElement(APSubstInNode.java:466)`},to:{at:`semantic.APSubstInNode.getLevelElement(APSubstInNode.java:470)`}}},Uu={at:`semantic.OpDefNode.getSymbolElement(OpDefNode.java:1424)`},Wu=la(`--TLA+ BUILTINS--`),Gu=(e,t)=>{let[n,r,i]=e===`Theorem`?[`TheoremNode.export(TheoremNode.java:456)`,70,`TheoremNode.exportDefinition(TheoremNode.java:404)`]:e===`Assume`?[`AssumeNode.export(AssumeNode.java:263)`,80,`AssumeNode.exportDefinition(AssumeNode.java:207)`]:[e===`ThmOrAssumpDef`?`ThmOrAssumpDefNode.export(ThmOrAssumpDefNode.java:671)`:`SymbolNode.export(SymbolNode.java:177)`,60,`SymbolNode.exportDefinition(SymbolNode.java:138)`];return[{at:`semantic.${n}`},{at:`xml.SymbolContext.put(SymbolContext.java:${r})`},{at:`semantic.${i}`,failedFor:t}]},Ku=(e,t=16)=>e>t*.75?Ku(e,t*2):t,qu=(e,t)=>(e^e>>>16)&t-1,Ju=e=>{let t=e.split(/\r?\n/);for(;t.at(-1)===``;)t.pop();return t},Yu=e=>e.replace(/^[\0-\x20]+|[\0-\x20]+$/g,``),Xu=/[\t-\r\x1C-\x20\u1680\u2000-\u2006\u2008-\u200A\u2028\u2029\u205F\u3000]+$/,Zu=e=>{let t=e.indexOf(`(**`),n=e.lastIndexOf(`**)`);if(t<0||n<=t)return e;let r=Ju(e),i=r.findIndex(e=>e.includes(`(**`)),a=r.findLastIndex(e=>e.includes(`**)`));return i<0||i>=a?e:r.slice(i+1,a).map(e=>{let t=e.indexOf(`(*`),n=e.indexOf(`*)`);return t<0||n<=t?e:e.slice(t+3,Math.max(t+3,n)).replace(Xu,``)}).join(`
155
- `)},Qu=e=>{let t=Ju(e),n=e=>Yu(e).startsWith(`\\*`);return t.filter(n).length<Math.floor(t.length/2)?e:t.map(e=>{if(!n(e))return e;let t=e.indexOf(`\\*`)+2;return e.slice(e[t]===` `?t+1:t)}).join(`
156
- `)},$u=(e,t,n)=>{let i=n.version===`1.7.4`,a=/* @__PURE__ */ new Set,o=/* @__PURE__ */ new Map,s=!1,c=[],l=(e,t)=>{if(!i)return t();c.push(...e);let n=t();return c.length-=e.length,n},u=(e,t)=>{let n=[...c,...t].reverse(),r=[e,...n.map(e=>`\tat tla2sany.${e.at}`)].join(`
157
- `),i=n.filter(e=>e.failedFor!==void 0).map(e=>`failed for node.toString(): ${e.failedFor}\n with error \n${r}\n`).join(``);return v(new m(r,i),Nu.uncaughtException)},d=e=>u(`java.lang.NullPointerException: Cannot invoke "tla2sany.semantic.${e.nullType}.export(org.w3c.dom.Document, tla2sany.xml.SymbolContext)" because ${e.nullValue} is null`,[e]),f=(e,t)=>(a.has(e.id)||(a.add(e.id),o.set(e.id,l([...t?[t]:[],...Gu(e.kind,la(e.location))],()=>_(e)))),Z(Vu(e),[Q(`UID`,e.id)])),p=(e,t)=>{let n=t.levelChecked===0?[]:[Q(`level`,t.level)],r=t.location?[Bu(t.location),...n]:n;return{...e,children:[...r,...e.children]}},h=(e,t,n)=>Z(`params`,e.map((e,r)=>Z(`leibnizparam`,[f(e,n),...t?.[r]?[Z(`leibniz`)]:[]]))),g=e=>{let t=e.map(e=>e.trimEnd()).filter(e=>e.length>0).join(`
158
- `),r=n.isUncommented?Qu(Zu(t)):t;return e.length>0?[{tag:`pre-comments`,cdata:r,children:[]}]:[]},_=e=>{switch(e.kind){case`FormalParam`:return p(Z(`FormalParamNode`,[Q(`uniquename`,e.name),Q(`arity`,e.arity)]),e);case`OpDecl`:return p(Z(`OpDeclNode`,[Q(`uniquename`,e.name),Q(`arity`,e.arity),Q(`kind`,e.declKind)]),e);case`OpDef`:{if(e.defKind===`NumberedProofStep`)throw i?u(Pu(37),[Uu]):v(new r(Pu(37)),Nu.uncaughtException);if(e.defKind===`ModuleInstance`)return p(Z(`ModuleInstanceKind`,[Q(`uniquename`,e.name),...e.isLocal&&!i?[Z(`local`)]:[]]),e);let t=e.params??[];if(e.defKind===`BuiltIn`)return p(Z(`BuiltInKind`,[Q(`uniquename`,e.name),Q(`arity`,e.arity),...e.params?[h(t,e.isLeibnizArg,$.builtInParam)]:[]]),e);let n=e.body,a=e.module;if(n===void 0&&i)throw d($.body);if(n===void 0||a===void 0)throw Error(`The definition of ${e.name} has no body`);return p(Z(`UserDefinedOpKind`,[Q(`uniquename`,e.name),Q(`arity`,e.arity),...i?[]:[Z(`originalOperator`,[f(e.source??e)]),Z(`originallyDefinedInModule`,[f(a)])],Z(`body`,[C(n,$.body)]),...e.params||!i?[h(t,e.isLeibnizArg,$.param)]:[],...i?[]:g(e.preComments),...e.inRecursive?[Z(`recursive`)]:[],...e.recursiveSection>=0&&!i?[Q(`recursiveSection`,e.recursiveSection)]:[],...e.isLocal&&!i?[Z(`local`)]:[]]),e)}case`ThmOrAssumpDef`:return p(Z(e.isTheorem?`TheoremDefNode`:`AssumeDef`,[Q(`uniquename`,e.name),C(e.body,$.theoremDefinitionBody)]),e);case`Module`:return Z(`ModuleNode`,[Bu(e.location),...y(e)]);case`Theorem`:return p(Z(`TheoremNode`,[...e.definition?[Z(`definition`,[f(e.definition,$.theoremDefinition)])]:[],Z(`body`,[C(e.body,$.theorem)]),...e.proof?[C(e.proof,$.proof)]:[],...e.isSuffices?[Z(`suffices`)]:[]]),e);case`Assume`:return Z(`AssumeNode`,[Bu(e.location),...e.body.levelChecked===0?[]:[Q(`level`,e.body.level)],...e.definition?[Z(`definition`,[f(e.definition,$.assumeDefinition)])]:[],Z(`body`,[C(e.body,$.assume)])])}},y=e=>{let t=t=>!n.isRestricted||t.module===e;return[Q(`uniquename`,e.name),...i?[]:[Z(`extends`,[...new Set(e.extendees.map(e=>e.name))].toSorted().map(e=>Q(`uniquename`,e)))],...Ta(e,2).filter(t).map(e=>f(e,$.constant)),...Ta(e,3).filter(t).map(e=>f(e,$.variable)),...wa(e).filter(t).map(e=>f(e,$.definition)),...e.topLevel.map(e=>e.kind===`Instance`||e.kind===`UseOrHide`?C(e,$.topLevel):f(e,$.topLevel)),...e.definitions.filter(e=>!i&&e.kind===`Module`).map(e=>f(e))]},b=(e,t)=>l([t],()=>Z(`Subst`,[f(e.op,$.substOperator),C(e.expr,$.substExpression)])),x=e=>{if(e.nullKind!==void 0&&i)throw u(Pu(0),[$.operator,...Gu(`OpDef`,Wu),Uu]);let t=e.operands[e.operands.length-1];e.operator.name===`$Case`&&e.operands.length>1&&t?.kind===`OpAppl`&&t.operator.name===`$Pair`&&t.operands[0]===void 0&&(s=!0);let n=f(e.operator,$.operator),r=e.operands.map((e,t)=>e===void 0||t===0&&s&&ua(e)?i?Q(`StringNode`,`$Other`):Z(`StringNode`,[Q(`StringValue`,`$Other`)]):C(e,$.operand)),a=e.tupleOrs,o=e.unbounded===void 0&&e.bounded===void 0?[]:[Z(`boundSymbols`,[...(e.unbounded??[]).map((e,t)=>Z(`unbound`,[f(e,$.unbound),...a?.[t]?[Z(`tuple`)]:[]])),...(e.bounded??[]).map((t,n)=>Z(`bound`,[...t.map(e=>f(e,$.bound)),...a?.[n]?[Z(`tuple`)]:[],C(e.ranges[n],$.range)]))])];return Z(`OpApplNode`,[Z(`operator`,[n]),Z(`operands`,r),...o])},S=(e,t)=>e.kind===`Module`||e.kind===`OpDef`?f(e,t):C(e,t),C=(e,t)=>{if(!i)return w(e);if(e.kind===`OpAppl`&&e.nullKind===`absent`&&`nullType`in t)throw d(t);return l([t,{at:`semantic.SemanticNode.export(SemanticNode.java:379)`,failedFor:la(e.location)},{at:`semantic.LevelNode.getSemanticElement(LevelNode.java:333)`}],()=>w(e))},w=e=>{switch(e.kind){case`OpAppl`:return p(x(e),e);case`Numeral`:return p(Z(`NumeralNode`,[Q(`IntValue`,e.value)]),e);case`String`:return p(Z(`StringNode`,[Q(`StringValue`,e.value)]),e);case`Decimal`:return p(Z(`DecimalNode`,[Q(`mantissa`,e.mantissa),Q(`exponent`,e.exponent),...i?[]:[Q(`integralPart`,e.integralPart),Q(`fractionalPart`,e.fractionalPart)]]),e);case`LetIn`:{let t=C(e.body,$.letBody);return p(Z(`LetInNode`,[Z(`body`,[t]),Z(`opDefs`,e.opDefs.map(e=>f(e,$.letDefinition)))]),e)}case`Label`:return p(Z(`LabelNode`,[Q(`uniquename`,e.name),Q(`arity`,e.params.length),Z(`body`,[C(e.body,$.labelBody)]),Z(`params`,e.params.map(e=>f(e,$.labelParam)))]),e);case`OpArg`:return p(Z(`OpArgNode`,[Z(`argument`,[f(e.op,$.argument)])]),e);case`At`:{let t=e.except.operands[0],n=e.component.operands[0];if(t===void 0||n===void 0)throw Error(`An @ refers to an incomplete EXCEPT`);return p(Z(`AtNode`,[C(t,$.exceptObject),C(n,$.exceptComponents)]),e)}case`SubstIn`:case`APSubstIn`:{let t=Hu[e.kind],n=e.substs.map(e=>b(e,t.subst)),r=C(e.body,t.body);return p(Z(e.kind===`SubstIn`?`SubstInNode`:`APSubstInNode`,[Z(`substs`,n),Z(`body`,[r]),Z(`instFrom`,[f(e.instantiatingModule,t.from)]),Z(`instTo`,[f(e.instantiatedModule,t.to)])]),e)}case`Instance`:{let t=e.substs.map(e=>b(e,$.instanceSubst)),n=e.params.map(e=>f(e,$.instanceParam));return Z(`InstanceNode`,[Bu(e.location),Q(`level`,0),...e.name===void 0?[]:[Q(`uniquename`,e.name)],Q(`module`,e.module.name),Z(`substs`,t),Z(`params`,n),...e.isLocal&&!i?[Z(`local`)]:[]])}case`UseOrHide`:return p(Z(`UseOrHideNode`,[Z(`facts`,e.facts.map(e=>S(e,$.useFact))),Z(`defs`,e.defs.map(e=>f(e,$.useDefinition))),...e.isOnly?[Z(`only`)]:[],...e.isHide?[Z(`hide`)]:[]]),e);case`NewSymb`:return p(Z(`NewSymbNode`,[f(e.declaration,$.newDeclaration),...e.set&&!(i&&ua(e.set))?[C(e.set,$.newSet)]:[]]),e);case`AssumeProve`:return p(Z(`AssumeProveNode`,[Z(`assumes`,e.assumptions.map(e=>C(e,$.assumption))),Z(`prove`,[C(e.goal,$.goal)]),...e.isSuffices?[Z(`suffices`)]:[],...e.isBoxed?[Z(`boxed`)]:[]]),e);case`LeafProof`:{let t=e.facts.length===0&&e.defs.length===0,n=e.isOmitted?Z(`omitted`):t?Z(`obvious`):Z(`by`,[Z(`facts`,e.facts.map(e=>S(e,$.byFact))),Z(`defs`,e.defs.map(e=>f(e,$.byDefinition))),...e.isOnly?[Z(`only`)]:[]]);return p(n,e)}case`NonLeafProof`:return p(Z(`steps`,[...i?[]:[Q(`proofLevel`,e.proofLevel)],...e.steps.map(e=>e.kind===`Theorem`?f(e,$.step):C(e,$.step))]),e);case`DefStep`:return p(Z(`DefStepNode`,e.defs.map(e=>f(e,$.defStep))),e)}},T=(n.isRestricted?[t]:e).map(e=>f(e,$.main)),E=Ku(o.size),ee=Z(`context`,[...o.entries()].toSorted(([e],[t])=>qu(e,E)-qu(t,E)).map(([e,t])=>Z(`entry`,[Q(`UID`,e),t])));return Z(`modules`,[Q(`RootModule`,t.name),ee,...T])},ed=(e,t={version:`master`,isRestricted:!1,isUncommented:!1,isTerse:!1})=>{let n=$u(e.modules,e.root,t),i=Ru(n);if(i){let e=i.character.codePointAt(0)??0;throw v(new r(`The spec contains the character U+${e.toString(16).toUpperCase().padStart(4,`0`)} in the ${i.tag} element. XML 1.0 cannot represent that character in character data, not even as a numeric character reference, so the spec cannot be exported until the character is removed from it.`),Nu.unrepresentableCharacter)}let a=[`<?xml version="1.0" encoding="UTF-8" standalone="no"?>`];return zu(n,0,t.isTerse?0:2,a),t.isTerse?a.join(``):`${a.join(`
159
- `)}\n`},td=(()=>{let e=[[`-I`,`Include; use given directory path to resolve module dependencies.`],[`-help`,`Print this usage information.`],[`-o`,`Offline mode; skip XML schema validation step.`],[`-r`,`Restrict mode; include only declarations and definitions of the specified module, excluding extended or instantiated modules.`],[`-t`,`Terse; format XML output without tabs or newlines.`],[`-u`,`Uncomment; process boxed comments and single-line comments (\\*) in pre-comments to extract their content.`]],t=[`Only one root TLA+ file can be parsed per run.`,`Multiple directory search paths can be given by providing multiple -I arguments.`,`XML schema validation does not require network access.`];return[``,X(`NAME`),``,` tla2sany.xml.XMLExporter - Emit SANY's parse tree as XML - Version 2.2 created 08 July 2020`,``,``,X(`SYNOPSIS`),``,`\t${X(`tla2sany.xml.XMLExporter`)} [${X(`-Iortu`)}] [${X(`-help`)}] FILE`,``,X(`DESCRIPTION`),``,` Given a TLA+ file, parse that file with SANY then translate the module's semantic parse tree to XML, including all the modules depended on. The XML is printed to stdout and its output format is given by an XML Schema file (.xsd) found at https://proofs.tlapl.us/doc/web/sany.xsd.`,``,X(`OPTIONS`),``,...e.map(([e,t])=>`\t${X(e)}\n\t\t${t}`),``,X(`TIPS`),``,...t.flatMap(e=>[`\t${e}`,``]),``].join(`
160
- `)})(),nd=e=>(process.stderr.write(`ERROR: ${e}\n${td}`),Nu.argsParsingFailure),rd=(e,t)=>{try{return process.stdout.write(ed(e,t)),T.success}catch(e){if(!(e instanceof r))throw e;let t=p(e),n=e instanceof m?e.unwound:``;return console.error(t===Nu.uncaughtException?`${n}Exception in thread "main" ${e.message}`:`ERROR: ${e.message}`),t}},id={"no-file":{message:`at least one .tla file must be given`,line174:59},"missing-include":{message:`the -I flag must be followed by a directory and at least one .tla file`,line174:71},"several-files":{message:`Only one TLA file to check allowed!`,line174:83}},ad=(e,t)=>{let n={flags:/* @__PURE__ */ new Set,includes:[],error:void 0};if(e.length===0)return{...n,error:`no-file`};let r=-1;for(let i=0;i<e.length-1;i++)if(t.has(e[i]))n.flags.add(e[i]),r=i;else if(e[i]===`-I`){if(i++,i>e.length-2)return{...n,error:`missing-include`};n.includes.push(e[i]),r=i}return r===e.length-2?n:{...n,error:`several-files`}},od=e=>{let t=ad(e,/* @__PURE__ */ new Set([`-o`,`-t`,`-r`,`-u`]));if(t.error)return nd(id[t.error].message);let n=e[e.length-1];if(n===`-help`)return process.stdout.write(td),T.success;let r=n.endsWith(`.tla`)?n:`${n}.tla`,i=[`.`,...t.includes],a=i.map(e=>St(e,r)).find(I);a===void 0&&!ke.has(r.slice(0,-4))&&Zt(process.cwd(),`./${r}`,t.includes);let o=nl(a??r,Xt(i),{fileName:n,isXmlExport:!0});return process.stderr.write(o.text),o.isFailed||o.specification===void 0?(console.error(`ERROR: Failed to parse module.`),Nu.specParsingFailure):rd(o.specification,{version:`master`,isRestricted:t.flags.has(`-r`),isUncommented:t.flags.has(`-u`),isTerse:t.flags.has(`-t`)})},sd=(e,t)=>(console.error(`Exception in thread "main" ${e}\n\tat tla2sany.xml.XMLExporter.main(XMLExporter.java:${t})`),Nu.uncaughtException),cd=(e,t)=>{let n=ad(e,/* @__PURE__ */ new Set([`-o`]));if(n.error)return sd(`java.lang.IllegalArgumentException: ${id[n.error].message}`,id[n.error].line174);let r=e[e.length-1],i=`${r.replace(/\.tla$/i,``)}.tla`,a=(n.includes.length===0?[`/`]:n.includes).map(rn),o=[`.`,...a],s=e=>nn(`${a[a.length-1]}${e}`,a,t),c=o.map(e=>St(e,i)).find(I);if(c===void 0&&!ve.has(_t(i,`.tla`)))return s(i),T.success;let l=nl(c??i,an(Xt(o),s),{fileName:r,isXmlExport:!0,version:`1.7.4`});return process.stderr.write(l.text),l.specification===void 0?sd(`tla2sany.xml.XMLExportingException: spec ${(c&&tl(kt(c,`utf8`),`1.7.4`))??`null`} is malformed - does not have a root module`,110):rd(l.specification,{version:`1.7.4`,isRestricted:!1,isUncommented:!1,isTerse:!0})},ld=[`tlc2.TLC`,`tla2sany.xml.XMLExporter`],ud=e=>{let t={libraries:[]};for(let n=0;n<e.length;n++){let r=e[n];if(r===`-cp`||r===`-classpath`||r===`--class-path`)n++,t.classPath=e[n];else if(r===`-jar`)return t.classPath=e[n+1],{mainClass:`tlc2.TLC`,args:e.slice(n+2),java:t};else if(r.startsWith(`-DTLA-Library=`))t.libraries.push(...r.slice(14).split(vt));else if(r.startsWith(`-Djava.io.tmpdir=`))t.temporaryDirectory=r.slice(17);else if(r.startsWith(`-Dtla-ts.tlc=`))t.tlcVersion=r.slice(13)===`1.7.4`?`1.7.4`:`master`;else if(!r.startsWith(`-D`)&&!r.startsWith(`-X`))return n>0||ld.includes(r)?{mainClass:r,args:e.slice(n+1),java:t}:void 0}},dd=async e=>{if(e[0]===`tlapm`)return tn(()=>tr(e.slice(1)));let t=ud(e);return t===void 0?ju(e,{libraries:[]}):(t.java.tlcVersion??=await Kt(on(t.java)),t.mainClass===`tlc2.TLC`?ju(t.args,t.java):t.mainClass===`tla2sany.xml.XMLExporter`?tn(()=>t.java.tlcVersion===`1.7.4`?cd(t.args,on(t.java)):od(t.args)):(console.error(`Error: tla-ts runs the Java classes ${ld.join(` and `)}, not ${t.mainClass}.`),1))},fd=async()=>{process.exitCode=await dd(process.argv.slice(2))};export{fd as runCli};
150
+ `).trim()}\n`},uu=e=>e.replace(/\/+/g,`/`).replace(/(.)\/$/,`$1`),du=e=>{let t=uu(e),n=t.lastIndexOf(`/`);return n===-1?`.`:t.slice(0,Math.max(n,1))},fu=(e,t)=>e.endsWith(`/`)?`${e}${t}`:`${e}/${t}`,pu=(e,t,n,r)=>{if(t===`1.7.4`||!e.isTraceSpecForced&&(e.isTraceSpecDisabled||e.isTool||e.isContinued||en(n).includes(`_TTrace`)))return;let i=e.traceSpecPath,a=`${en(n)}_TTrace_${Math.floor(r/1e3)}`,o=i===void 0?{directory:du(n),module:a}:i.toLowerCase().endsWith(`.tla`)?{directory:du(i),module:en(i).replace(/\.tla$/,``)}:{directory:uu(i),module:a};return{...o,traceFile:e.isTraceBinaryDisabled?void 0:fu(o.directory,`${o.module}.bin`)}},mu={ENOENT:`No such file or directory`,ENOTDIR:`Not a directory`,EISDIR:`Is a directory`,EACCES:`Permission denied`},hu=(e,t)=>{try{bn(e,t)}catch(t){let n=t instanceof Error&&`code`in t?mu[String(t.code)]:void 0;throw n===void 0?t:new j(`${e} (${n})`)}},gu=e=>{try{dn(e,{recursive:!0})}catch{}},_u=e=>{let t=/* @__PURE__ */ new Date,n=`${Ve(t.getFullYear()%100)}-${Ve(t.getMonth()+1)}-${Ve(t.getDate())}-${Ve(t.getHours())}-${Ve(t.getMinutes())}-${Ve(t.getSeconds())}.${Ve(t.getMilliseconds(),3)}`,r=an(e.metadir??`states`,n);return dn(r,{recursive:!0}),r},vu=async(e,n,r,i,a)=>{let o=n.livenessCheck,c=a.version;Vl(a);let l=n.recoverDirectory;if(l!==void 0)throw B(an(l,`vars.chkpt`))?new h(`tla-ts can't recover a model check from the checkpoint in ${l}.`):new f(l);Ul(a,n);let u=n.configPath??e.replace(/\.tla$/,`.cfg`);if(!B(u))return a.print(F.configFileError,z.error,`TLC encountered the following error when trying to read the configuration file ${u}:\nFile not found.`),w.configParseError;let p=en(e,`.tla`),m={startTime:Date.now(),livenessStartTime:void 0,isParsed:!1},g=()=>{let e=Date.now()-m.startTime;a.print(F.finished,z.none,`Finished in ${a.isTool?`${e}ms`:Ie(e)} at (${je(/* @__PURE__ */ new Date)})`)},_=()=>a.print(F.parsingFailed,z.error,`Parsing or semantic analysis failed.`),v=e=>{e instanceof s?_():Rn(e,a);let t=Ln(e);return t!==w.abort&&g(),t},b=(()=>{try{let e=pn(u,`utf8`);return wt(u.endsWith(`.tla`)?lu(e,u.replaceAll(`.tla`,``)):e,c)}catch(e){if(!(e instanceof k))throw e;return e}})();if(b instanceof k&&c===`1.7.4`)return a.print(F.general,z.error,`${t(`tlc2.tool.ConfigFileException`)}${he(b.message,a.isTool)}`),g(),w.error;if(b instanceof k)return v(b);n.isDeadlockChecked||(b.checkDeadlock=!1);let x=nn(e),S=[x,...i.libraries],C=Pn(S),T=pu(n,c,e.replace(/\.tla$/,``),m.startTime),E=e=>n.moduleOperators.filter(t=>t.kind===e).map(e=>e.module);a.isTool&&a.print(F.startingSany,z.none,`Starting SANY...`);let D=rn(e),ee=D?p:e.replace(/\.tla$/,``),O=Un(i),A=c===`1.7.4`?Su(e,i,O):void 0;A?!B(e)&&!Ye.has(p)&&A(`${p}.tla`):!B(e)&&!ft.has(p)&&Fn(D?x:process.cwd(),D?`${p}.tla`:`./${ee}.tla`,[...D||x===`.`?[]:[x],...i.libraries]);let te=Kc(e,A?Hn(C,A):C,{fileName:ee,describeFile:cu(e,S,i,n.metadir,c),version:c,rootExtendees:[...E(`postcondition`),...T?.traceFile===void 0?[]:[`_TLCTrace`],...n.invariants.flatMap(e=>e.modules),...E(`constraint`),...E(`view`).slice(0,1)],suppressedCodes:n.suppressedCodes,errorCodes:n.errorCodes,onPrint:e=>process.stdout.write(e),onPrintError:e=>process.stderr.write(e)}),M=te.specification;if(te.isFailed||M===void 0)return Nl(a,{kind:`parsed`},m,x),_(),g(),w.specParseError;try{let t=pn(e,`utf8`),i=Te(t).name;if(i!==p)throw new d(`File name '${p}' does not match the name '${i}' of the top level module it contains.`,void 0);let s=n.userFile,l=Et(c),u=Zc(t,M.root,n.invariants,e=>C(e)??l.get(e)??xe(t,e),c),f={workers:n.workers,livenessCheck:o===`off`?`off`:[`final`,`seqfinal`].includes(o)?`final`:`default`,seed:n.seed,fingerprintPolynomial:n.fingerprintIndex,maxSetSize:n.maxSetSize,isLazyValueExpanded:n.isLazyValueExpanded,isViewPrinted:n.isViewPrinted,dump:r,isTool:a.isTool,isContinued:n.isContinued,moduleOperators:n.moduleOperators,traceSpec:T,coverage:n.coverage,isSanyReported:!0,isWarningEnabled:n.isWarningEnabled,version:c,onProgress:e=>Nl(a,e,m,x),onPrint:s===void 0?void 0:e=>sn(s,`${e}\n`),source:t,config:b,onPause:()=>mn(0,Buffer.alloc(1)),readLine:yu,runtimeInvariants:u.map(e=>({name:e.name,module:e.module})),loadModule:e=>u.find(t=>t.module===e)?.source??C(e),loadClass:e=>{let t=Ml(x,e);return B(t)?pn(t):void 0},readFile:e=>(iu(e),B(e)?pn(e,`utf8`):void 0),writeFile:hu,makeDirectory:gu};if(n.mode!==`model-check`){let e=Xr({...f,traceDepth:n.traceDepth,traceCount:n.traceCount,aril:n.aril,isGenerating:n.mode===`generate`,scheduler:n.scheduler,onSimulation:e=>Wl(a,e,m.startTime)});return g(),e}if(n.dfidDepth!==void 0){let e=Ur({...f,maxDepth:n.dfidDepth,onOutput:e=>zl(a,e,m.startTime)});return g(),e}let h=await Nt(f);if(Bl(h,a,m),g(),T&&h.traceSpec!==void 0){let e=fu(T.directory,`${T.module}.tla`);gu(T.directory);let t=(()=>{try{hu(e,h.traceSpec);return}catch(e){if(!(e instanceof j))throw e;return e}})();a.print(t?F.traceSpecFailed:F.traceSpecWritten,z.none,t?`Failed to generate trace exploration spec; error message: ${t.message}`:`Trace exploration spec path: ${e}`)}return h.failure?.exitCode??ru[h.status]}catch(e){if(!(e instanceof y))throw e;return e instanceof s&&console.log(bu(e,p)),m.isParsed||Nl(a,{kind:`parsed`},m,x),v(e)}},yu=()=>{let e=[],t=Buffer.alloc(1),n=!1;for(;mn(0,t)===1&&(n=!0,t[0]!==10);)e.push(t[0]);return n?Buffer.from(e).toString().replace(/\r$/,``):void 0},bu=(e,t)=>{let n=e instanceof d;if(!n&&!e.failure)return`Semantic errors:\n\n*** Errors: 1\n\n${e.message}\n\n`;let r=n?e.location===void 0?`Unknown location\n\n${e.message}`:`In module ${e.location}\n\n${e.message}`:`In module ${t}\n\nCould not parse module ${t} from file ${t}.tla`;return`${e.failure?`***Parse Error***\n${e.message}\n\n`:``}\nFatal errors while parsing TLA+ spec in file ${t}\n\n${r}\n*** Errors: 1\n\n${r}\n\n\n`},xu=async(e,t)=>{let n=t.tlcVersion??`master`,r=_l(e);if(r===`usage`)return console.log(tu()),1;if(`error`in r)return r.kind===`uncaught`?(console.error(`Exception in thread "main" ${r.error}`),1):Hl(r.isTool,n,r.error);let i=r.dump&&ou(r.dump);i?.path.startsWith("${metadir}")&&(i.path=i.path.replaceAll("${metadir}",_u(r)));let a=i?.path;if(a!==void 0)try{cn(fn(a,`w`))}catch{return console.log(`Error: Unable to write to file ${a}`),Hl(r.isTool,n,`Error: Given file name ${a} for dumping states invalid.`)}let o=r.configPath!==void 0;if(o&&r.specs.length>1)return Hl(r.isTool,n,`Error: more than one input files: ${r.specs[0].replace(/\.tla$/,``)} and ${r.specs[1]}`);let s=Mn(r.specs).map(e=>({...e,path:e.isGlobbed||/\.(tla|cfg|ts)$/.test(e.path)?e.path.replace(/\.cfg$/,`.tla`):`${e.path}.tla`})).filter(e=>e.path.endsWith(`.ts`)||e.path.endsWith(`.tla`)&&(!e.isGlobbed||o||B(e.path.replace(/\.tla$/,`.cfg`)))).map(e=>e.path);if(s.length===0)return Hl(r.isTool,n,`Error: Missing input TLA+ module.`);if(o&&s.length>1)return console.error(`Error: -config applies to one specification, but several were given.`),1;let c=[...new Set(s.map(e=>B(e)||rn(e)?e:t.libraries.map(t=>an(t,e)).find(B)??e))],l=[];for(let[e,a]of c.entries()){e>0&&console.log(``);let o=re({isTool:r.isTool,isWarningEnabled:r.isWarningEnabled,isDiffTrace:r.isDiffTrace,version:n,suppressedCodes:r.suppressedCodes,errorCodes:r.errorCodes});l.push(await zn(async()=>{let e=a.endsWith(`.ts`)?await nu(a):a;return c.length>1&&console.log(`Checking ${en(e)} with ${en(e,`.tla`)}.cfg`),vu(e,r,i,t,o)},o))}return l.find(e=>e!==w.success)??w.success},Su=(e,t,n)=>{let r=e.slice(0,e.lastIndexOf(`/`)+1),i=(!rn(e)&&r!==``?[r]:t.libraries).map(Vn),a=i.length>0?i[i.length-1]:rn(e)?r:``;return e=>Bn(`${a}${e}`,i,n)},Cu={uncaughtException:1,argsParsingFailure:1,specParsingFailure:2,unrepresentableCharacter:7},wu=e=>`java.lang.IllegalArgumentException: unsupported kind: ${e} in xml export`,Z=(e,t=[])=>({tag:e,children:t}),Q=(e,t)=>({tag:e,text:String(t),children:[]}),Tu={"&":`&amp;`,"<":`&lt;`,">":`&gt;`,"\r":`&#13;`},Eu=e=>e.replace(/[&<>\r]|[\u{10000}-\u{10FFFF}]/gu,e=>e.length===2?`&#${e.codePointAt(0)};`:Tu[e]),Du=/[^\t\n\r\u0020-\uD7FF\uE000-\uFFFD\u{10000}-\u{10FFFF}]/u,Ou=e=>{let t=(e.cdata??e.text)?.match(Du)?.[0];if(t!==void 0)return{tag:e.tag,character:t};for(let t of e.children){let e=Ou(t);if(e)return e}},ku=(e,t,n,r)=>{let i=` `.repeat(t*n);if(e.cdata){let t=e.cdata.replaceAll(`]]>`,`]]]]><![CDATA[>`);r.push(`${i}<${e.tag}><![CDATA[${t}]]></${e.tag}>`)}else if(e.text)r.push(`${i}<${e.tag}>${Eu(e.text)}</${e.tag}>`);else if(e.children.length===0)r.push(`${i}<${e.tag}/>`);else{r.push(`${i}<${e.tag}>`);for(let i of e.children)ku(i,t+1,n,r);r.push(`${i}</${e.tag}>`)}},Au=e=>Z(`location`,[Z(`column`,[Q(`begin`,e.beginColumn),Q(`end`,e.endColumn)]),Z(`line`,[Q(`begin`,e.beginLine),Q(`end`,e.endLine)]),Q(`filename`,e.file)]),ju=e=>{switch(e.kind){case`FormalParam`:return`FormalParamNodeRef`;case`OpDecl`:return`OpDeclNodeRef`;case`Module`:return`ModuleNodeRef`;case`Theorem`:return`TheoremNodeRef`;case`Assume`:return`AssumeNodeRef`;case`ThmOrAssumpDef`:return e.isTheorem?`TheoremDefRef`:`AssumeDefRef`;case`OpDef`:return e.defKind===`UserDefined`?`UserDefinedOpKindRef`:e.defKind===`BuiltIn`?`BuiltInKindRef`:`ModuleInstanceKindRef`}},$={main:{at:`xml.XMLExporter.main(XMLExporter.java:145)`},constant:{at:`semantic.ModuleNode.getSymbolElement(ModuleNode.java:1228)`},variable:{at:`semantic.ModuleNode.getSymbolElement(ModuleNode.java:1236)`},definition:{at:`semantic.ModuleNode.getSymbolElement(ModuleNode.java:1244)`},topLevel:{at:`semantic.ModuleNode.getSymbolElement(ModuleNode.java:1268)`},body:{at:`semantic.OpDefNode.getSymbolElement(OpDefNode.java:1392)`,nullType:`ExprNode`,nullValue:`"this.body"`},param:{at:`semantic.OpDefNode.getSymbolElement(OpDefNode.java:1397)`},builtInParam:{at:`semantic.OpDefNode.getSymbolElement(OpDefNode.java:1413)`},theoremDefinitionBody:{at:`semantic.ThmOrAssumpDefNode.getSymbolElement(ThmOrAssumpDefNode.java:663)`,nullType:`LevelNode`,nullValue:`"this.body"`},theoremDefinition:{at:`semantic.TheoremNode.getLevelElement(TheoremNode.java:439)`},theorem:{at:`semantic.TheoremNode.getLevelElement(TheoremNode.java:444)`,nullType:`LevelNode`,nullValue:`the return value of "tla2sany.semantic.TheoremNode.getTheorem()"`},proof:{at:`semantic.TheoremNode.getLevelElement(TheoremNode.java:447)`},assumeDefinition:{at:`semantic.AssumeNode.getLevelElement(AssumeNode.java:249)`},assume:{at:`semantic.AssumeNode.getLevelElement(AssumeNode.java:254)`,nullType:`ExprNode`,nullValue:`the return value of "tla2sany.semantic.AssumeNode.getAssume()"`},operator:{at:`semantic.OpApplNode.getLevelElement(OpApplNode.java:1315)`},operand:{at:`semantic.OpApplNode.getLevelElement(OpApplNode.java:1326)`,nullType:`ExprOrOpArgNode`,nullValue:`"this.operands[i]"`},unbound:{at:`semantic.OpApplNode.getLevelElement(OpApplNode.java:1337)`},bound:{at:`semantic.OpApplNode.getLevelElement(OpApplNode.java:1347)`},range:{at:`semantic.OpApplNode.getLevelElement(OpApplNode.java:1349)`,nullType:`ExprNode`,nullValue:`"this.ranges[i]"`},letBody:{at:`semantic.LetInNode.getLevelElement(LetInNode.java:301)`,nullType:`ExprNode`,nullValue:`"this.body"`},letDefinition:{at:`semantic.LetInNode.getLevelElement(LetInNode.java:303)`},labelBody:{at:`semantic.LabelNode.getLevelElement(LabelNode.java:341)`,nullType:`LevelNode`,nullValue:`"this.body"`},labelParam:{at:`semantic.LabelNode.getLevelElement(LabelNode.java:343)`},argument:{at:`semantic.OpArgNode.getLevelElement(OpArgNode.java:150)`},exceptObject:{at:`semantic.AtNode.getLevelElement(AtNode.java:180)`},exceptComponents:{at:`semantic.AtNode.getLevelElement(AtNode.java:181)`},substOperator:{at:`semantic.Subst.export(Subst.java:258)`},substExpression:{at:`semantic.Subst.export(Subst.java:259)`,nullType:`ExprOrOpArgNode`,nullValue:`"this.expr"`},instanceSubst:{at:`semantic.InstanceNode.getLevelElement(InstanceNode.java:447)`},instanceParam:{at:`semantic.InstanceNode.getLevelElement(InstanceNode.java:452)`},useFact:{at:`semantic.UseOrHideNode.getLevelElement(UseOrHideNode.java:175)`,nullType:`LevelNode`,nullValue:`"this.facts[i]"`},useDefinition:{at:`semantic.UseOrHideNode.getLevelElement(UseOrHideNode.java:176)`},newDeclaration:{at:`semantic.NewSymbNode.getLevelElement(NewSymbNode.java:202)`},newSet:{at:`semantic.NewSymbNode.getLevelElement(NewSymbNode.java:204)`},assumption:{at:`semantic.AssumeProveNode.getLevelElement(AssumeProveNode.java:404)`,nullType:`SemanticNode`,nullValue:`"assumes[i]"`},goal:{at:`semantic.AssumeProveNode.getLevelElement(AssumeProveNode.java:406)`,nullType:`ExprNode`,nullValue:`the return value of "tla2sany.semantic.AssumeProveNode.getProve()"`},byFact:{at:`semantic.LeafProofNode.getLevelElement(LeafProofNode.java:154)`,nullType:`LevelNode`,nullValue:`"this.facts[i]"`},byDefinition:{at:`semantic.LeafProofNode.getLevelElement(LeafProofNode.java:155)`},step:{at:`semantic.NonLeafProofNode.getLevelElement(NonLeafProofNode.java:228)`,nullType:`LevelNode`,nullValue:`"this.steps[i]"`},defStep:{at:`semantic.DefStepNode.getLevelElement(DefStepNode.java:99)`}},Mu={SubstIn:{subst:{at:`semantic.SubstInNode.getLevelElement(SubstInNode.java:530)`},body:{at:`semantic.SubstInNode.getLevelElement(SubstInNode.java:533)`,nullType:`ExprNode`,nullValue:`"this.body"`},from:{at:`semantic.SubstInNode.getLevelElement(SubstInNode.java:536)`},to:{at:`semantic.SubstInNode.getLevelElement(SubstInNode.java:540)`}},APSubstIn:{subst:{at:`semantic.APSubstInNode.getLevelElement(APSubstInNode.java:460)`},body:{at:`semantic.APSubstInNode.getLevelElement(APSubstInNode.java:463)`,nullType:`LevelNode`,nullValue:`"this.body"`},from:{at:`semantic.APSubstInNode.getLevelElement(APSubstInNode.java:466)`},to:{at:`semantic.APSubstInNode.getLevelElement(APSubstInNode.java:470)`}}},Nu={at:`semantic.OpDefNode.getSymbolElement(OpDefNode.java:1424)`},Pu=I(`--TLA+ BUILTINS--`),Fu=(e,t)=>{let[n,r,i]=e===`Theorem`?[`TheoremNode.export(TheoremNode.java:456)`,70,`TheoremNode.exportDefinition(TheoremNode.java:404)`]:e===`Assume`?[`AssumeNode.export(AssumeNode.java:263)`,80,`AssumeNode.exportDefinition(AssumeNode.java:207)`]:[e===`ThmOrAssumpDef`?`ThmOrAssumpDefNode.export(ThmOrAssumpDefNode.java:671)`:`SymbolNode.export(SymbolNode.java:177)`,60,`SymbolNode.exportDefinition(SymbolNode.java:138)`];return[{at:`semantic.${n}`},{at:`xml.SymbolContext.put(SymbolContext.java:${r})`},{at:`semantic.${i}`,failedFor:t}]},Iu=(e,t=16)=>e>t*.75?Iu(e,t*2):t,Lu=(e,t)=>(e^e>>>16)&t-1,Ru=e=>{let t=e.split(/\r?\n/);for(;t.at(-1)===``;)t.pop();return t},zu=e=>e.replace(/^[\0-\x20]+|[\0-\x20]+$/g,``),Bu=/[\t-\r\x1C-\x20\u1680\u2000-\u2006\u2008-\u200A\u2028\u2029\u205F\u3000]+$/,Vu=e=>{let t=e.indexOf(`(**`),n=e.lastIndexOf(`**)`);if(t<0||n<=t)return e;let r=Ru(e),i=r.findIndex(e=>e.includes(`(**`)),a=r.findLastIndex(e=>e.includes(`**)`));return i<0||i>=a?e:r.slice(i+1,a).map(e=>{let t=e.indexOf(`(*`),n=e.indexOf(`*)`);return t<0||n<=t?e:e.slice(t+3,Math.max(t+3,n)).replace(Bu,``)}).join(`
151
+ `)},Hu=e=>{let t=Ru(e),n=e=>zu(e).startsWith(`\\*`);return t.filter(n).length<Math.floor(t.length/2)?e:t.map(e=>{if(!n(e))return e;let t=e.indexOf(`\\*`)+2;return e.slice(e[t]===` `?t+1:t)}).join(`
152
+ `)},Uu=(e,t,n)=>{let i=n.version===`1.7.4`,a=/* @__PURE__ */ new Set,o=/* @__PURE__ */ new Map,s=!1,c=[],l=(e,t)=>{if(!i)return t();c.push(...e);let n=t();return c.length-=e.length,n},u=(e,t)=>{let n=[...c,...t].reverse(),i=[e,...n.map(e=>`\tat tla2sany.${e.at}`)].join(`
153
+ `),a=n.filter(e=>e.failedFor!==void 0).map(e=>`failed for node.toString(): ${e.failedFor}\n with error \n${i}\n`).join(``);return v(new r(i,a),Cu.uncaughtException)},d=e=>u(`java.lang.NullPointerException: Cannot invoke "tla2sany.semantic.${e.nullType}.export(org.w3c.dom.Document, tla2sany.xml.SymbolContext)" because ${e.nullValue} is null`,[e]),f=(e,t)=>(a.has(e.id)||(a.add(e.id),o.set(e.id,l([...t?[t]:[],...Fu(e.kind,I(e.location))],()=>_(e)))),Z(ju(e),[Q(`UID`,e.id)])),p=(e,t)=>{let n=t.levelChecked===0?[]:[Q(`level`,t.level)],r=t.location?[Au(t.location),...n]:n;return{...e,children:[...r,...e.children]}},m=(e,t,n)=>Z(`params`,e.map((e,r)=>Z(`leibnizparam`,[f(e,n),...t?.[r]?[Z(`leibniz`)]:[]]))),h=e=>{let t=e.map(e=>e.trimEnd()).filter(e=>e.length>0).join(`
154
+ `),r=n.isUncommented?Hu(Vu(t)):t;return e.length>0?[{tag:`pre-comments`,cdata:r,children:[]}]:[]},_=e=>{switch(e.kind){case`FormalParam`:return p(Z(`FormalParamNode`,[Q(`uniquename`,e.name),Q(`arity`,e.arity)]),e);case`OpDecl`:return p(Z(`OpDeclNode`,[Q(`uniquename`,e.name),Q(`arity`,e.arity),Q(`kind`,e.declKind)]),e);case`OpDef`:{if(e.defKind===`NumberedProofStep`)throw i?u(wu(37),[Nu]):v(new g(wu(37)),Cu.uncaughtException);if(e.defKind===`ModuleInstance`)return p(Z(`ModuleInstanceKind`,[Q(`uniquename`,e.name),...e.isLocal&&!i?[Z(`local`)]:[]]),e);let t=e.params??[];if(e.defKind===`BuiltIn`)return p(Z(`BuiltInKind`,[Q(`uniquename`,e.name),Q(`arity`,e.arity),...e.params?[m(t,e.isLeibnizArg,$.builtInParam)]:[]]),e);let n=e.body,r=e.module;if(n===void 0&&i)throw d($.body);if(n===void 0||r===void 0)throw Error(`The definition of ${e.name} has no body`);return p(Z(`UserDefinedOpKind`,[Q(`uniquename`,e.name),Q(`arity`,e.arity),...i?[]:[Z(`originalOperator`,[f(e.source??e)]),Z(`originallyDefinedInModule`,[f(r)])],Z(`body`,[C(n,$.body)]),...e.params||!i?[m(t,e.isLeibnizArg,$.param)]:[],...i?[]:h(e.preComments),...e.inRecursive?[Z(`recursive`)]:[],...e.recursiveSection>=0&&!i?[Q(`recursiveSection`,e.recursiveSection)]:[],...e.isLocal&&!i?[Z(`local`)]:[]]),e)}case`ThmOrAssumpDef`:return p(Z(e.isTheorem?`TheoremDefNode`:`AssumeDef`,[Q(`uniquename`,e.name),C(e.body,$.theoremDefinitionBody)]),e);case`Module`:return Z(`ModuleNode`,[Au(e.location),...y(e)]);case`Theorem`:return p(Z(`TheoremNode`,[...e.definition?[Z(`definition`,[f(e.definition,$.theoremDefinition)])]:[],Z(`body`,[C(e.body,$.theorem)]),...e.proof?[C(e.proof,$.proof)]:[],...e.isSuffices?[Z(`suffices`)]:[]]),e);case`Assume`:return Z(`AssumeNode`,[Au(e.location),...e.body.levelChecked===0?[]:[Q(`level`,e.body.level)],...e.definition?[Z(`definition`,[f(e.definition,$.assumeDefinition)])]:[],Z(`body`,[C(e.body,$.assume)])])}},y=e=>{let t=t=>!n.isRestricted||t.module===e;return[Q(`uniquename`,e.name),...i?[]:[Z(`extends`,[...new Set(e.extendees.map(e=>e.name))].toSorted().map(e=>Q(`uniquename`,e)))],...Ae(e,2).filter(t).map(e=>f(e,$.constant)),...Ae(e,3).filter(t).map(e=>f(e,$.variable)),...ce(e).filter(t).map(e=>f(e,$.definition)),...e.topLevel.map(e=>e.kind===`Instance`||e.kind===`UseOrHide`?C(e,$.topLevel):f(e,$.topLevel)),...e.definitions.filter(e=>!i&&e.kind===`Module`).map(e=>f(e))]},b=(e,t)=>l([t],()=>Z(`Subst`,[f(e.op,$.substOperator),C(e.expr,$.substExpression)])),x=e=>{if(e.nullKind!==void 0&&i)throw u(wu(0),[$.operator,...Fu(`OpDef`,Pu),Nu]);let t=e.operands[e.operands.length-1];e.operator.name===`$Case`&&e.operands.length>1&&t?.kind===`OpAppl`&&t.operator.name===`$Pair`&&t.operands[0]===void 0&&(s=!0);let n=f(e.operator,$.operator),r=e.operands.map((e,t)=>e===void 0||t===0&&s&&ne(e)?i?Q(`StringNode`,`$Other`):Z(`StringNode`,[Q(`StringValue`,`$Other`)]):C(e,$.operand)),a=e.tupleOrs,o=e.unbounded===void 0&&e.bounded===void 0?[]:[Z(`boundSymbols`,[...(e.unbounded??[]).map((e,t)=>Z(`unbound`,[f(e,$.unbound),...a?.[t]?[Z(`tuple`)]:[]])),...(e.bounded??[]).map((t,n)=>Z(`bound`,[...t.map(e=>f(e,$.bound)),...a?.[n]?[Z(`tuple`)]:[],C(e.ranges[n],$.range)]))])];return Z(`OpApplNode`,[Z(`operator`,[n]),Z(`operands`,r),...o])},S=(e,t)=>e.kind===`Module`||e.kind===`OpDef`?f(e,t):C(e,t),C=(e,t)=>{if(!i)return w(e);if(e.kind===`OpAppl`&&e.nullKind===`absent`&&`nullType`in t)throw d(t);return l([t,{at:`semantic.SemanticNode.export(SemanticNode.java:379)`,failedFor:I(e.location)},{at:`semantic.LevelNode.getSemanticElement(LevelNode.java:333)`}],()=>w(e))},w=e=>{switch(e.kind){case`OpAppl`:return p(x(e),e);case`Numeral`:return p(Z(`NumeralNode`,[Q(`IntValue`,e.value)]),e);case`String`:return p(Z(`StringNode`,[Q(`StringValue`,e.value)]),e);case`Decimal`:return p(Z(`DecimalNode`,[Q(`mantissa`,e.mantissa),Q(`exponent`,e.exponent),...i?[]:[Q(`integralPart`,e.integralPart),Q(`fractionalPart`,e.fractionalPart)]]),e);case`LetIn`:{let t=C(e.body,$.letBody);return p(Z(`LetInNode`,[Z(`body`,[t]),Z(`opDefs`,e.opDefs.map(e=>f(e,$.letDefinition)))]),e)}case`Label`:return p(Z(`LabelNode`,[Q(`uniquename`,e.name),Q(`arity`,e.params.length),Z(`body`,[C(e.body,$.labelBody)]),Z(`params`,e.params.map(e=>f(e,$.labelParam)))]),e);case`OpArg`:return p(Z(`OpArgNode`,[Z(`argument`,[f(e.op,$.argument)])]),e);case`At`:{let t=e.except.operands[0],n=e.component.operands[0];if(t===void 0||n===void 0)throw Error(`An @ refers to an incomplete EXCEPT`);return p(Z(`AtNode`,[C(t,$.exceptObject),C(n,$.exceptComponents)]),e)}case`SubstIn`:case`APSubstIn`:{let t=Mu[e.kind],n=e.substs.map(e=>b(e,t.subst)),r=C(e.body,t.body);return p(Z(e.kind===`SubstIn`?`SubstInNode`:`APSubstInNode`,[Z(`substs`,n),Z(`body`,[r]),Z(`instFrom`,[f(e.instantiatingModule,t.from)]),Z(`instTo`,[f(e.instantiatedModule,t.to)])]),e)}case`Instance`:{let t=e.substs.map(e=>b(e,$.instanceSubst)),n=e.params.map(e=>f(e,$.instanceParam));return Z(`InstanceNode`,[Au(e.location),Q(`level`,0),...e.name===void 0?[]:[Q(`uniquename`,e.name)],Q(`module`,e.module.name),Z(`substs`,t),Z(`params`,n),...e.isLocal&&!i?[Z(`local`)]:[]])}case`UseOrHide`:return p(Z(`UseOrHideNode`,[Z(`facts`,e.facts.map(e=>S(e,$.useFact))),Z(`defs`,e.defs.map(e=>f(e,$.useDefinition))),...e.isOnly?[Z(`only`)]:[],...e.isHide?[Z(`hide`)]:[]]),e);case`NewSymb`:return p(Z(`NewSymbNode`,[f(e.declaration,$.newDeclaration),...e.set&&!(i&&ne(e.set))?[C(e.set,$.newSet)]:[]]),e);case`AssumeProve`:return p(Z(`AssumeProveNode`,[Z(`assumes`,e.assumptions.map(e=>C(e,$.assumption))),Z(`prove`,[C(e.goal,$.goal)]),...e.isSuffices?[Z(`suffices`)]:[],...e.isBoxed?[Z(`boxed`)]:[]]),e);case`LeafProof`:{let t=e.facts.length===0&&e.defs.length===0,n=e.isOmitted?Z(`omitted`):t?Z(`obvious`):Z(`by`,[Z(`facts`,e.facts.map(e=>S(e,$.byFact))),Z(`defs`,e.defs.map(e=>f(e,$.byDefinition))),...e.isOnly?[Z(`only`)]:[]]);return p(n,e)}case`NonLeafProof`:return p(Z(`steps`,[...i?[]:[Q(`proofLevel`,e.proofLevel)],...e.steps.map(e=>e.kind===`Theorem`?f(e,$.step):C(e,$.step))]),e);case`DefStep`:return p(Z(`DefStepNode`,e.defs.map(e=>f(e,$.defStep))),e)}},T=(n.isRestricted?[t]:e).map(e=>f(e,$.main)),E=Iu(o.size),D=Z(`context`,[...o.entries()].toSorted((e,t)=>Lu(e[0],E)-Lu(t[0],E)).map(e=>Z(`entry`,[Q(`UID`,e[0]),e[1]])));return Z(`modules`,[Q(`RootModule`,t.name),D,...T])},Wu=(e,t={version:`master`,isRestricted:!1,isUncommented:!1,isTerse:!1})=>{let n=Uu(e.modules,e.root,t),r=Ou(n);if(r){let e=r.character.codePointAt(0)??0;throw v(new g(`The spec contains the character U+${e.toString(16).toUpperCase().padStart(4,`0`)} in the ${r.tag} element. XML 1.0 cannot represent that character in character data, not even as a numeric character reference, so the spec cannot be exported until the character is removed from it.`),Cu.unrepresentableCharacter)}let i=[`<?xml version="1.0" encoding="UTF-8" standalone="no"?>`];return ku(n,0,t.isTerse?0:2,i),t.isTerse?i.join(``):`${i.join(`
155
+ `)}\n`},Gu=(()=>{let e=[[`-I`,`Include; use given directory path to resolve module dependencies.`],[`-help`,`Print this usage information.`],[`-o`,`Offline mode; skip XML schema validation step.`],[`-r`,`Restrict mode; include only declarations and definitions of the specified module, excluding extended or instantiated modules.`],[`-t`,`Terse; format XML output without tabs or newlines.`],[`-u`,`Uncomment; process boxed comments and single-line comments (\\*) in pre-comments to extract their content.`]],t=[`Only one root TLA+ file can be parsed per run.`,`Multiple directory search paths can be given by providing multiple -I arguments.`,`XML schema validation does not require network access.`];return[``,X(`NAME`),``,` tla2sany.xml.XMLExporter - Emit SANY's parse tree as XML - Version 2.2 created 08 July 2020`,``,``,X(`SYNOPSIS`),``,`\t${X(`tla2sany.xml.XMLExporter`)} [${X(`-Iortu`)}] [${X(`-help`)}] FILE`,``,X(`DESCRIPTION`),``,` Given a TLA+ file, parse that file with SANY then translate the module's semantic parse tree to XML, including all the modules depended on. The XML is printed to stdout and its output format is given by an XML Schema file (.xsd) found at https://proofs.tlapl.us/doc/web/sany.xsd.`,``,X(`OPTIONS`),``,...e.map(e=>`\t${X(e[0])}\n\t\t${e[1]}`),``,X(`TIPS`),``,...t.flatMap(e=>[`\t${e}`,``]),``].join(`
156
+ `)})(),Ku=e=>(process.stderr.write(`ERROR: ${e}\n${Gu}`),Cu.argsParsingFailure),qu=(e,t)=>{try{return process.stdout.write(Wu(e,t)),w.success}catch(e){if(!(e instanceof g))throw e;let t=p(e),n=e instanceof r?e.unwound:``;return console.error(t===Cu.uncaughtException?`${n}Exception in thread "main" ${e.message}`:`ERROR: ${e.message}`),t}},Ju={"no-file":{message:`at least one .tla file must be given`,line174:59},"missing-include":{message:`the -I flag must be followed by a directory and at least one .tla file`,line174:71},"several-files":{message:`Only one TLA file to check allowed!`,line174:83}},Yu=(e,t)=>{let n={flags:/* @__PURE__ */ new Set,includes:[],error:void 0};if(e.length===0)return{...n,error:`no-file`};let r=-1;for(let i=0;i<e.length-1;i++)if(t.has(e[i]))n.flags.add(e[i]),r=i;else if(e[i]===`-I`){if(i++,i>e.length-2)return{...n,error:`missing-include`};n.includes.push(e[i]),r=i}return r===e.length-2?n:{...n,error:`several-files`}},Xu=e=>{let t=Yu(e,/* @__PURE__ */ new Set([`-o`,`-t`,`-r`,`-u`]));if(t.error)return Ku(Ju[t.error].message);let n=e[e.length-1];if(n===`-help`)return process.stdout.write(Gu),w.success;let r=n.endsWith(`.tla`)?n:`${n}.tla`,i=[`.`,...t.includes],a=i.map(e=>on(e,r)).find(B);a===void 0&&!ft.has(r.slice(0,-4))&&Fn(process.cwd(),`./${r}`,t.includes);let o=Kc(a??r,Pn(i),{fileName:n,isXmlExport:!0});return process.stderr.write(o.text),o.isFailed||o.specification===void 0?(console.error(`ERROR: Failed to parse module.`),Cu.specParsingFailure):qu(o.specification,{version:`master`,isRestricted:t.flags.has(`-r`),isUncommented:t.flags.has(`-u`),isTerse:t.flags.has(`-t`)})},Zu=(e,t)=>(console.error(`Exception in thread "main" ${e}\n\tat tla2sany.xml.XMLExporter.main(XMLExporter.java:${t})`),Cu.uncaughtException),Qu=(e,t)=>{let n=Yu(e,/* @__PURE__ */ new Set([`-o`]));if(n.error)return Zu(`java.lang.IllegalArgumentException: ${Ju[n.error].message}`,Ju[n.error].line174);let r=e[e.length-1],i=`${r.replace(/\.tla$/i,``)}.tla`,a=(n.includes.length===0?[`/`]:n.includes).map(Vn),o=[`.`,...a],s=e=>Bn(`${a[a.length-1]}${e}`,a,t),c=o.map(e=>on(e,i)).find(B);if(c===void 0&&!Ye.has(en(i,`.tla`)))return s(i),w.success;let l=Kc(c??i,Hn(Pn(o),s),{fileName:r,isXmlExport:!0,version:`1.7.4`});return process.stderr.write(l.text),l.specification===void 0?Zu(`tla2sany.xml.XMLExportingException: spec ${(c&&Gc(pn(c,`utf8`),`1.7.4`))??`null`} is malformed - does not have a root module`,110):qu(l.specification,{version:`1.7.4`,isRestricted:!1,isUncommented:!1,isTerse:!0})},$u=[`tlc2.TLC`,`tla2sany.xml.XMLExporter`],ed=e=>{let t={libraries:[]};for(let n=0;n<e.length;n++){let r=e[n];if(r===`-cp`||r===`-classpath`||r===`--class-path`)n++,t.classPath=e[n];else if(r===`-jar`)return t.classPath=e[n+1],{mainClass:`tlc2.TLC`,args:e.slice(n+2),java:t};else if(r.startsWith(`-DTLA-Library=`))t.libraries.push(...r.slice(14).split(tn));else if(r.startsWith(`-Djava.io.tmpdir=`))t.temporaryDirectory=r.slice(17);else if(r.startsWith(`-Dtla-ts.tlc=`))t.tlcVersion=r.slice(13)===`1.7.4`?`1.7.4`:`master`;else if(!r.startsWith(`-D`)&&!r.startsWith(`-X`))return n>0||$u.includes(r)?{mainClass:r,args:e.slice(n+1),java:t}:void 0}},td=async e=>{if(e[0]===`tlapm`)return zn(()=>Rr(e.slice(1)));let t=ed(e);return t===void 0?xu(e,{libraries:[]}):(t.java.tlcVersion??=await An(Un(t.java)),t.mainClass===`tlc2.TLC`?xu(t.args,t.java):t.mainClass===`tla2sany.xml.XMLExporter`?zn(()=>t.java.tlcVersion===`1.7.4`?Qu(t.args,Un(t.java)):Xu(t.args)):(console.error(`Error: tla-ts runs the Java classes ${$u.join(` and `)}, not ${t.mainClass}.`),1))},nd=async()=>{process.exitCode=await td(process.argv.slice(2))};export{nd as runCli};